2
0
forked from Wavyzz/dolibarr

code syntax m... directories

This commit is contained in:
Frédéric FRANCE
2021-02-26 18:26:44 +01:00
parent c4e98486f7
commit f73c0abec1
62 changed files with 3649 additions and 2832 deletions

View File

@@ -77,8 +77,7 @@ class MailmanSpip
*/ */
public function isSpipEnabled() public function isSpipEnabled()
{ {
if (defined("ADHERENT_USE_SPIP") && (ADHERENT_USE_SPIP == 1)) if (defined("ADHERENT_USE_SPIP") && (ADHERENT_USE_SPIP == 1)) {
{
return true; return true;
} }
@@ -92,10 +91,8 @@ class MailmanSpip
*/ */
public function checkSpipConfig() public function checkSpipConfig()
{ {
if (defined('ADHERENT_SPIP_SERVEUR') && defined('ADHERENT_SPIP_USER') && defined('ADHERENT_SPIP_PASS') && defined('ADHERENT_SPIP_DB')) if (defined('ADHERENT_SPIP_SERVEUR') && defined('ADHERENT_SPIP_USER') && defined('ADHERENT_SPIP_PASS') && defined('ADHERENT_SPIP_DB')) {
{ if (ADHERENT_SPIP_SERVEUR != '' && ADHERENT_SPIP_USER != '' && ADHERENT_SPIP_PASS != '' && ADHERENT_SPIP_DB != '') {
if (ADHERENT_SPIP_SERVEUR != '' && ADHERENT_SPIP_USER != '' && ADHERENT_SPIP_PASS != '' && ADHERENT_SPIP_DB != '')
{
return true; return true;
} }
} }
@@ -112,8 +109,7 @@ class MailmanSpip
{ {
$resource = getDoliDBInstance('mysql', ADHERENT_SPIP_SERVEUR, ADHERENT_SPIP_USER, ADHERENT_SPIP_PASS, ADHERENT_SPIP_DB, ADHERENT_SPIP_PORT); $resource = getDoliDBInstance('mysql', ADHERENT_SPIP_SERVEUR, ADHERENT_SPIP_USER, ADHERENT_SPIP_PASS, ADHERENT_SPIP_DB, ADHERENT_SPIP_PORT);
if ($resource->ok) if ($resource->ok) {
{
return $resource; return $resource;
} }
@@ -165,8 +161,7 @@ class MailmanSpip
dol_syslog('result curl_exec='.$result); dol_syslog('result curl_exec='.$result);
//An error was found, we store it in $this->error for later //An error was found, we store it in $this->error for later
if ($result === false || curl_errno($ch) > 0) if ($result === false || curl_errno($ch) > 0) {
{
$this->error = curl_errno($ch).' '.curl_error($ch); $this->error = curl_errno($ch).' '.curl_error($ch);
dol_syslog('Error using curl '.$this->error, LOG_ERR); dol_syslog('Error using curl '.$this->error, LOG_ERR);
} }
@@ -188,14 +183,11 @@ class MailmanSpip
// phpcs:enable // phpcs:enable
dol_syslog(get_class($this)."::add_to_spip"); dol_syslog(get_class($this)."::add_to_spip");
if ($this->isSpipEnabled()) if ($this->isSpipEnabled()) {
{ if ($this->checkSpipConfig()) {
if ($this->checkSpipConfig())
{
$mydb = $this->connectSpip(); $mydb = $this->connectSpip();
if ($mydb) if ($mydb) {
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$mdpass = dol_hash($object->pass); $mdpass = dol_hash($object->pass);
$htpass = crypt($object->pass, makesalt()); $htpass = crypt($object->pass, makesalt());
@@ -205,13 +197,20 @@ class MailmanSpip
$mydb->close(); $mydb->close();
if ($result) if ($result) {
{
return 1; return 1;
} else $this->error = $mydb->lasterror(); } else {
} else $this->error = 'Failed to connect to SPIP'; $this->error = $mydb->lasterror();
} else $this->error = 'BadSPIPConfiguration'; }
} else $this->error = 'SPIPNotEnabled'; } else {
$this->error = 'Failed to connect to SPIP';
}
} else {
$this->error = 'BadSPIPConfiguration';
}
} else {
$this->error = 'SPIPNotEnabled';
}
return 0; return 0;
} }
@@ -228,27 +227,31 @@ class MailmanSpip
// phpcs:enable // phpcs:enable
dol_syslog(get_class($this)."::del_to_spip"); dol_syslog(get_class($this)."::del_to_spip");
if ($this->isSpipEnabled()) if ($this->isSpipEnabled()) {
{ if ($this->checkSpipConfig()) {
if ($this->checkSpipConfig())
{
$mydb = $this->connectSpip(); $mydb = $this->connectSpip();
if ($mydb) if ($mydb) {
{
$query = "DELETE FROM spip_auteurs WHERE login='".$object->login."'"; $query = "DELETE FROM spip_auteurs WHERE login='".$object->login."'";
$result = $mydb->query($query); $result = $mydb->query($query);
$mydb->close(); $mydb->close();
if ($result) if ($result) {
{
return 1; return 1;
} else $this->error = $mydb->lasterror(); } else {
} else $this->error = 'Failed to connect to SPIP'; $this->error = $mydb->lasterror();
} else $this->error = 'BadSPIPConfiguration'; }
} else $this->error = 'SPIPNotEnabled'; } else {
$this->error = 'Failed to connect to SPIP';
}
} else {
$this->error = 'BadSPIPConfiguration';
}
} else {
$this->error = 'SPIPNotEnabled';
}
return 0; return 0;
} }
@@ -263,22 +266,17 @@ class MailmanSpip
public function is_in_spip($object) public function is_in_spip($object)
{ {
// phpcs:enable // phpcs:enable
if ($this->isSpipEnabled()) if ($this->isSpipEnabled()) {
{ if ($this->checkSpipConfig()) {
if ($this->checkSpipConfig())
{
$mydb = $this->connectSpip(); $mydb = $this->connectSpip();
if ($mydb) if ($mydb) {
{
$query = "SELECT login FROM spip_auteurs WHERE login='".$object->login."'"; $query = "SELECT login FROM spip_auteurs WHERE login='".$object->login."'";
$result = $mydb->query($query); $result = $mydb->query($query);
if ($result) if ($result) {
{ if ($mydb->num_rows($result)) {
if ($mydb->num_rows($result))
{
// nous avons au moins une reponse // nous avons au moins une reponse
$mydb->close($result); $mydb->close($result);
return 1; return 1;
@@ -291,9 +289,15 @@ class MailmanSpip
$this->error = $mydb->lasterror(); $this->error = $mydb->lasterror();
$mydb->close(); $mydb->close();
} }
} else $this->error = 'Failed to connect to SPIP'; } else {
} else $this->error = 'BadSPIPConfiguration'; $this->error = 'Failed to connect to SPIP';
} else $this->error = 'SPIPNotEnabled'; }
} else {
$this->error = 'BadSPIPConfiguration';
}
} else {
$this->error = 'SPIPNotEnabled';
}
return -1; return -1;
} }
@@ -316,36 +320,32 @@ class MailmanSpip
$this->mladded_ok = array(); $this->mladded_ok = array();
$this->mladded_ko = array(); $this->mladded_ko = array();
if (!function_exists("curl_init")) if (!function_exists("curl_init")) {
{
$langs->load("errors"); $langs->load("errors");
$this->error = $langs->trans("ErrorFunctionNotAvailableInPHP", "curl_init"); $this->error = $langs->trans("ErrorFunctionNotAvailableInPHP", "curl_init");
return -1; return -1;
} }
if ($conf->adherent->enabled) // Synchro for members if ($conf->adherent->enabled) { // Synchro for members
{ if (!empty($conf->global->ADHERENT_MAILMAN_URL)) {
if (!empty($conf->global->ADHERENT_MAILMAN_URL)) if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) {
{ $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS);
if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS); } else {
else $lists = explode(',', $listes); $lists = explode(',', $listes);
}
$categstatic = new Categorie($this->db); $categstatic = new Categorie($this->db);
foreach ($lists as $list) foreach ($lists as $list) {
{
// Filter on type something (ADHERENT_MAILMAN_LISTS = "mailinglist0,TYPE:typevalue:mailinglist1,CATEG:categvalue:mailinglist2") // Filter on type something (ADHERENT_MAILMAN_LISTS = "mailinglist0,TYPE:typevalue:mailinglist1,CATEG:categvalue:mailinglist2")
$tmp = explode(':', $list); $tmp = explode(':', $list);
if (!empty($tmp[2])) if (!empty($tmp[2])) {
{
$list = $tmp[2]; $list = $tmp[2];
if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) // Filter on member type label if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) { // Filter on member type label
{
dol_syslog("We ignore list ".$list." because object member type ".$object->type." does not match ".$tmp[1], LOG_DEBUG); dol_syslog("We ignore list ".$list." because object member type ".$object->type." does not match ".$tmp[1], LOG_DEBUG);
continue; continue;
} }
if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) // Filter on member category if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) { // Filter on member category
{
dol_syslog("We ignore list ".$list." because object member is not into category ".$tmp[1], LOG_DEBUG); dol_syslog("We ignore list ".$list." because object member is not into category ".$tmp[1], LOG_DEBUG);
continue; continue;
} }
@@ -354,11 +354,12 @@ class MailmanSpip
//We call Mailman to subscribe the user //We call Mailman to subscribe the user
$result = $this->callMailman($object, $conf->global->ADHERENT_MAILMAN_URL, $list); $result = $this->callMailman($object, $conf->global->ADHERENT_MAILMAN_URL, $list);
if ($result === false) if ($result === false) {
{
$this->mladded_ko[$list] = $object->email; $this->mladded_ko[$list] = $object->email;
return -2; return -2;
} else $this->mladded_ok[$list] = $object->email; } else {
$this->mladded_ok[$list] = $object->email;
}
} }
return count($lists); return count($lists);
} else { } else {
@@ -387,36 +388,32 @@ class MailmanSpip
$this->mlremoved_ok = array(); $this->mlremoved_ok = array();
$this->mlremoved_ko = array(); $this->mlremoved_ko = array();
if (!function_exists("curl_init")) if (!function_exists("curl_init")) {
{
$langs->load("errors"); $langs->load("errors");
$this->error = $langs->trans("ErrorFunctionNotAvailableInPHP", "curl_init"); $this->error = $langs->trans("ErrorFunctionNotAvailableInPHP", "curl_init");
return -1; return -1;
} }
if ($conf->adherent->enabled) // Synchro for members if ($conf->adherent->enabled) { // Synchro for members
{ if (!empty($conf->global->ADHERENT_MAILMAN_UNSUB_URL)) {
if (!empty($conf->global->ADHERENT_MAILMAN_UNSUB_URL)) if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) {
{ $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS);
if ($listes == '' && !empty($conf->global->ADHERENT_MAILMAN_LISTS)) $lists = explode(',', $conf->global->ADHERENT_MAILMAN_LISTS); } else {
else $lists = explode(',', $listes); $lists = explode(',', $listes);
}
$categstatic = new Categorie($this->db); $categstatic = new Categorie($this->db);
foreach ($lists as $list) foreach ($lists as $list) {
{
// Filter on type something (ADHERENT_MAILMAN_LISTS = "mailinglist0,TYPE:typevalue:mailinglist1,CATEG:categvalue:mailinglist2") // Filter on type something (ADHERENT_MAILMAN_LISTS = "mailinglist0,TYPE:typevalue:mailinglist1,CATEG:categvalue:mailinglist2")
$tmp = explode(':', $list); $tmp = explode(':', $list);
if (!empty($tmp[2])) if (!empty($tmp[2])) {
{
$list = $tmp[2]; $list = $tmp[2];
if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) // Filter on member type label if ($object->element == 'member' && $tmp[0] == 'TYPE' && $object->type != $tmp[1]) { // Filter on member type label
{
dol_syslog("We ignore list ".$list." because object member type ".$object->type." does not match ".$tmp[1], LOG_DEBUG); dol_syslog("We ignore list ".$list." because object member type ".$object->type." does not match ".$tmp[1], LOG_DEBUG);
continue; continue;
} }
if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) // Filter on member category if ($object->element == 'member' && $tmp[0] == 'CATEG' && !in_array($tmp[1], $categstatic->containing($object->id, 'member', 'label'))) { // Filter on member category
{
dol_syslog("We ignore list ".$list." because object member is not into category ".$tmp[1], LOG_DEBUG); dol_syslog("We ignore list ".$list." because object member is not into category ".$tmp[1], LOG_DEBUG);
continue; continue;
} }
@@ -425,11 +422,12 @@ class MailmanSpip
//We call Mailman to unsubscribe the user //We call Mailman to unsubscribe the user
$result = $this->callMailman($object, $conf->global->ADHERENT_MAILMAN_UNSUB_URL, $list); $result = $this->callMailman($object, $conf->global->ADHERENT_MAILMAN_UNSUB_URL, $list);
if ($result === false) if ($result === false) {
{
$this->mlremoved_ko[$list] = $object->email; $this->mlremoved_ko[$list] = $object->email;
return -2; return -2;
} else $this->mlremoved_ok[$list] = $object->email; } else {
$this->mlremoved_ok[$list] = $object->email;
}
} }
return count($lists); return count($lists);
} else { } else {

View File

@@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php";
$langs->loadLangs(array("admin", "bills", "margins", "stocks")); $langs->loadLangs(array("admin", "bills", "margins", "stocks"));
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@@ -40,11 +42,9 @@ $action = GETPOST('action', 'aZ09');
* Action * Action
*/ */
if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) {
{
$code = $reg[1]; $code = $reg[1];
if (dolibarr_set_const($db, $code, 1, 'yesno', 0, '', $conf->entity) > 0) if (dolibarr_set_const($db, $code, 1, 'yesno', 0, '', $conf->entity) > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} else { } else {
@@ -52,11 +52,9 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg))
} }
} }
if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) {
{
$code = $reg[1]; $code = $reg[1];
if (dolibarr_del_const($db, $code, $conf->entity) > 0) if (dolibarr_del_const($db, $code, $conf->entity) > 0) {
{
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
exit; exit;
} else { } else {
@@ -64,30 +62,24 @@ if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg))
} }
} }
if ($action == 'remises') if ($action == 'remises') {
{ if (dolibarr_set_const($db, 'MARGIN_METHODE_FOR_DISCOUNT', $_POST['MARGIN_METHODE_FOR_DISCOUNT'], 'chaine', 0, '', $conf->entity) > 0) {
if (dolibarr_set_const($db, 'MARGIN_METHODE_FOR_DISCOUNT', $_POST['MARGIN_METHODE_FOR_DISCOUNT'], 'chaine', 0, '', $conf->entity) > 0)
{
setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
} else { } else {
dol_print_error($db); dol_print_error($db);
} }
} }
if ($action == 'typemarges') if ($action == 'typemarges') {
{ if (dolibarr_set_const($db, 'MARGIN_TYPE', $_POST['MARGIN_TYPE'], 'chaine', 0, '', $conf->entity) > 0) {
if (dolibarr_set_const($db, 'MARGIN_TYPE', $_POST['MARGIN_TYPE'], 'chaine', 0, '', $conf->entity) > 0)
{
setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
} else { } else {
dol_print_error($db); dol_print_error($db);
} }
} }
if ($action == 'contact') if ($action == 'contact') {
{ if (dolibarr_set_const($db, 'AGENT_CONTACT_TYPE', $_POST['AGENT_CONTACT_TYPE'], 'chaine', 0, '', $conf->entity) > 0) {
if (dolibarr_set_const($db, 'AGENT_CONTACT_TYPE', $_POST['AGENT_CONTACT_TYPE'], 'chaine', 0, '', $conf->entity) > 0)
{
setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
} else { } else {
dol_print_error($db); dol_print_error($db);
@@ -126,18 +118,23 @@ print '<tr class="oddeven">';
print '<td>'.$langs->trans("MARGIN_TYPE").'</td>'; print '<td>'.$langs->trans("MARGIN_TYPE").'</td>';
print '<td>'; print '<td>';
print ' <input type="radio" name="MARGIN_TYPE" value="1" '; print ' <input type="radio" name="MARGIN_TYPE" value="1" ';
if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == '1') if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == '1') {
print 'checked '; print 'checked ';
}
print '/> '; print '/> ';
print $langs->trans('MargeType1'); print $langs->trans('MargeType1');
print '<br>'; print '<br>';
print ' <input type="radio" name="MARGIN_TYPE" value="pmp" '; print ' <input type="radio" name="MARGIN_TYPE" value="pmp" ';
if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') print 'checked '; if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp') {
print 'checked ';
}
print '/> '; print '/> ';
print $langs->trans('MargeType2'); print $langs->trans('MargeType2');
print '<br>'; print '<br>';
print ' <input type="radio" name="MARGIN_TYPE" value="costprice" '; print ' <input type="radio" name="MARGIN_TYPE" value="costprice" ';
if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') print 'checked '; if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice') {
print 'checked ';
}
print '/> '; print '/> ';
print $langs->trans('MargeType3'); print $langs->trans('MargeType3');
print '</td>'; print '</td>';
@@ -153,12 +150,10 @@ print '</form>';
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("DisplayMarginRates").'</td>'; print '<td>'.$langs->trans("DisplayMarginRates").'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print ajax_constantonoff('DISPLAY_MARGIN_RATES'); print ajax_constantonoff('DISPLAY_MARGIN_RATES');
} else { } else {
if (empty($conf->global->DISPLAY_MARGIN_RATES)) if (empty($conf->global->DISPLAY_MARGIN_RATES)) {
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_DISPLAY_MARGIN_RATES&amp;token='.newToken().'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_DISPLAY_MARGIN_RATES&amp;token='.newToken().'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
} else { } else {
print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_DISPLAY_MARGIN_RATES&amp;token='.newToken().'">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_DISPLAY_MARGIN_RATES&amp;token='.newToken().'">'.img_picto($langs->trans("Enabled"), 'on').'</a>';
@@ -172,12 +167,10 @@ print '</tr>';
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("DisplayMarkRates").'</td>'; print '<td>'.$langs->trans("DisplayMarkRates").'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print ajax_constantonoff('DISPLAY_MARK_RATES'); print ajax_constantonoff('DISPLAY_MARK_RATES');
} else { } else {
if (empty($conf->global->DISPLAY_MARK_RATES)) if (empty($conf->global->DISPLAY_MARK_RATES)) {
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_DISPLAY_MARK_RATES">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_DISPLAY_MARK_RATES">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
} else { } else {
print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_DISPLAY_MARK_RATES">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_DISPLAY_MARK_RATES">'.img_picto($langs->trans("Enabled"), 'on').'</a>';
@@ -191,12 +184,10 @@ print '</tr>';
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("ForceBuyingPriceIfNull").'</td>'; print '<td>'.$langs->trans("ForceBuyingPriceIfNull").'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print ajax_constantonoff('ForceBuyingPriceIfNull'); print ajax_constantonoff('ForceBuyingPriceIfNull');
} else { } else {
if (empty($conf->global->ForceBuyingPriceIfNull)) if (empty($conf->global->ForceBuyingPriceIfNull)) {
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_ForceBuyingPriceIfNull&amp;token='.newToken().'">'.img_picto($langs->trans("Disabled"), 'off').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=set_ForceBuyingPriceIfNull&amp;token='.newToken().'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
} else { } else {
print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_ForceBuyingPriceIfNull&amp;token='.newToken().'">'.img_picto($langs->trans("Enabled"), 'on').'</a>'; print '<a href="'.$_SERVER['PHP_SELF'].'?action=del_ForceBuyingPriceIfNull&amp;token='.newToken().'">'.img_picto($langs->trans("Enabled"), 'on').'</a>';

View File

@@ -39,16 +39,21 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortorder = "ASC";
{ }
if ($agentid > 0) if (!$sortfield) {
if ($agentid > 0) {
$sortfield = "s.nom"; $sortfield = "s.nom";
else $sortfield = "u.lastname"; } else {
$sortfield = "u.lastname";
}
} }
$startdate = $enddate = ''; $startdate = $enddate = '';
@@ -60,10 +65,12 @@ $enddateday = GETPOST('enddateday', 'int');
$enddatemonth = GETPOST('enddatemonth', 'int'); $enddatemonth = GETPOST('enddatemonth', 'int');
$enddateyear = GETPOST('enddateyear', 'int'); $enddateyear = GETPOST('enddateyear', 'int');
if (!empty($startdatemonth)) if (!empty($startdatemonth)) {
$startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear); $startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear);
if (!empty($enddatemonth)) }
if (!empty($enddatemonth)) {
$enddate = dol_mktime(23, 59, 59, $enddatemonth, $enddateday, $enddateyear); $enddate = dol_mktime(23, 59, 59, $enddatemonth, $enddateday, $enddateyear);
}
// Security check // Security check
if ($user->rights->margins->read->all) { if ($user->rights->margins->read->all) {
@@ -154,23 +161,31 @@ $sql .= " WHERE f.fk_soc = s.rowid";
$sql .= ' AND f.entity IN ('.getEntity('invoice').')'; $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
$sql .= " AND sc.fk_soc = f.fk_soc"; $sql .= " AND sc.fk_soc = f.fk_soc";
$sql .= " AND (d.product_type = 0 OR d.product_type = 1)"; $sql .= " AND (d.product_type = 0 OR d.product_type = 1)";
if (!empty($conf->global->AGENT_CONTACT_TYPE)) if (!empty($conf->global->AGENT_CONTACT_TYPE)) {
$sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = u.rowid) OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = u.rowid))"; $sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = u.rowid) OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = u.rowid))";
else $sql .= " AND sc.fk_user = u.rowid"; } else {
$sql .= " AND sc.fk_user = u.rowid";
}
$sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")";
$sql .= ' AND s.entity IN ('.getEntity('societe').')'; $sql .= ' AND s.entity IN ('.getEntity('societe').')';
$sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_facture = f.rowid";
if ($agentid > 0) { if ($agentid > 0) {
if (!empty($conf->global->AGENT_CONTACT_TYPE)) if (!empty($conf->global->AGENT_CONTACT_TYPE)) {
$sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = ".$agentid.") OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = ".$agentid."))"; $sql .= " AND ((e.fk_socpeople IS NULL AND sc.fk_user = ".$agentid.") OR (e.fk_socpeople IS NOT NULL AND e.fk_socpeople = ".$agentid."))";
else $sql .= " AND sc.fk_user = ".$agentid; } else {
$sql .= " AND sc.fk_user = ".$agentid;
}
}
if (!empty($startdate)) {
$sql .= " AND f.datef >= '".$db->idate($startdate)."'";
}
if (!empty($enddate)) {
$sql .= " AND f.datef <= '".$db->idate($enddate)."'";
} }
if (!empty($startdate))
$sql .= " AND f.datef >= '".$db->idate($startdate)."'";
if (!empty($enddate))
$sql .= " AND f.datef <= '".$db->idate($enddate)."'";
$sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) {
$sql .= " AND d.buy_price_ht <> 0";
}
//if ($agentid > 0) $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname"; //if ($agentid > 0) $sql.= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname";
//else $sql.= " GROUP BY u.rowid, u.login, u.lastname, u.firstname"; //else $sql.= " GROUP BY u.rowid, u.login, u.lastname, u.firstname";
$sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname"; $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, u.rowid, u.login, u.lastname, u.firstname";
@@ -183,28 +198,42 @@ print '<br>';
print img_info('').' '.$langs->trans("MarginPerSaleRepresentativeWarning").'<br>'; print img_info('').' '.$langs->trans("MarginPerSaleRepresentativeWarning").'<br>';
$param = ''; $param = '';
if (!empty($agentid)) $param .= "&amp;agentid=".urlencode($agentid); if (!empty($agentid)) {
if (!empty($startdateday)) $param .= "&amp;startdateday=".urlencode($startdateday); $param .= "&amp;agentid=".urlencode($agentid);
if (!empty($startdatemonth)) $param .= "&amp;startdatemonth=".urlencode($startdatemonth); }
if (!empty($startdateyear)) $param .= "&amp;startdateyear=".urlencode($startdateyear); if (!empty($startdateday)) {
if (!empty($enddateday)) $param .= "&amp;enddateday=".urlencode($enddateday); $param .= "&amp;startdateday=".urlencode($startdateday);
if (!empty($enddatemonth)) $param .= "&amp;enddatemonth=".urlencode($enddatemonth); }
if (!empty($enddateyear)) $param .= "&amp;enddateyear=".urlencode($enddateyear); if (!empty($startdatemonth)) {
$param .= "&amp;startdatemonth=".urlencode($startdatemonth);
}
if (!empty($startdateyear)) {
$param .= "&amp;startdateyear=".urlencode($startdateyear);
}
if (!empty($enddateday)) {
$param .= "&amp;enddateday=".urlencode($enddateday);
}
if (!empty($enddatemonth)) {
$param .= "&amp;enddatemonth=".urlencode($enddatemonth);
}
if (!empty($enddateyear)) {
$param .= "&amp;enddateyear=".urlencode($enddateyear);
}
dol_syslog('margin::agentMargins.php', LOG_DEBUG); dol_syslog('margin::agentMargins.php', LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
print '<br>'; print '<br>';
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1); print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
if ($conf->global->MARGIN_TYPE == "1") if ($conf->global->MARGIN_TYPE == "1") {
$labelcostprice = 'BuyingPrice'; $labelcostprice = 'BuyingPrice';
else // value is 'costprice' or 'pmp' } else { // value is 'costprice' or 'pmp'
$labelcostprice = 'CostPrice'; $labelcostprice = 'CostPrice';
}
$moreforfilter = ''; $moreforfilter = '';
@@ -213,21 +242,24 @@ if ($result)
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if ($agentid > 0) if ($agentid > 0) {
print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder);
else print_liste_field_titre("SalesRepresentative", $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); } else {
print_liste_field_titre("SalesRepresentative", $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder);
}
print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", $param, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", $param, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", $param, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'right ');
}
print "</tr>\n"; print "</tr>\n";
if ($num > 0) if ($num > 0) {
{
$group_list = array(); $group_list = array();
while ($objp = $db->fetch_object($result)) { while ($objp = $db->fetch_object($result)) {
if ($agentid > 0) { if ($agentid > 0) {
@@ -295,10 +327,12 @@ if ($result)
print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>';
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@@ -319,10 +353,12 @@ if ($result)
print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
}
print '</tr>'; print '</tr>';
print '</table>'; print '</table>';

View File

@@ -44,12 +44,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = 'f.ref'; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = 'f.ref';
}
$startdate = $enddate = ''; $startdate = $enddate = '';
@@ -73,15 +79,20 @@ if (GETPOST("button_search_x") || GETPOST("button_search")) {
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
@@ -108,23 +119,22 @@ if (empty($reshook))
} }
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_ref = ''; $search_ref = '';
$search_array_options = array(); $search_array_options = array();
} }
// Mass actions // Mass actions
/* /*
$objectclass='Product'; $objectclass='Product';
if ((string) $type == '1') { $objectlabel='Services'; } if ((string) $type == '1') { $objectlabel='Services'; }
if ((string) $type == '0') { $objectlabel='Products'; } if ((string) $type == '0') { $objectlabel='Products'; }
$permissiontoread = $user->rights->produit->lire; $permissiontoread = $user->rights->produit->lire;
$permissiontodelete = $user->rights->produit->supprimer; $permissiontodelete = $user->rights->produit->supprimer;
$uploaddir = $conf->product->dir_output; $uploaddir = $conf->product->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
*/ */
} }
@@ -146,12 +156,24 @@ llxHeader('', $title);
// print load_fiche_titre($text); // print load_fiche_titre($text);
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; $param .= '&contextpage='.$contextpage;
if ($search_ref != '') $param .= '&search_ref='.urlencode($search_ref); }
if (!empty($startdate)) $param .= '&startdatemonth='.GETPOST('startdatemonth', 'int').'&startdateday='.GETPOST('startdateday', 'int').'&startdateyear='.GETPOST('startdateyear', 'int'); if ($limit > 0 && $limit != $conf->liste_limit) {
if (!empty($enddate)) $param .= '&enddatemonth='.GETPOST('enddatemonth', 'int').'&enddateday='.GETPOST('enddateday', 'int').'&enddateyear='.GETPOST('enddateyear', 'int'); $param .= '&limit='.$limit;
if ($optioncss != '') $param .= '&optioncss='.$optioncss; }
if ($search_ref != '') {
$param .= '&search_ref='.urlencode($search_ref);
}
if (!empty($startdate)) {
$param .= '&startdatemonth='.GETPOST('startdatemonth', 'int').'&startdateday='.GETPOST('startdateday', 'int').'&startdateyear='.GETPOST('startdateyear', 'int');
}
if (!empty($enddate)) {
$param .= '&enddatemonth='.GETPOST('enddatemonth', 'int').'&enddateday='.GETPOST('enddateday', 'int').'&enddateyear='.GETPOST('enddateyear', 'int');
}
if ($optioncss != '') {
$param .= '&optioncss='.$optioncss;
}
// Show tabs // Show tabs
$head = marges_prepare_head($user); $head = marges_prepare_head($user);
@@ -194,9 +216,15 @@ $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as d ON d.fk_facture = f.rowi
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
$sql .= " WHERE f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= " WHERE f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")";
$sql .= " AND f.entity IN (".getEntity('invoice').") "; $sql .= " AND f.entity IN (".getEntity('invoice').") ";
if (!empty($startdate)) $sql .= " AND f.datef >= '".$db->idate($startdate)."'"; if (!empty($startdate)) {
if (!empty($enddate)) $sql .= " AND f.datef <= '".$db->idate($enddate)."'"; $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
if ($search_ref) $sql .= natural_search('f.ref', $search_ref); }
if (!empty($enddate)) {
$sql .= " AND f.datef <= '".$db->idate($enddate)."'";
}
if ($search_ref) {
$sql .= natural_search('f.ref', $search_ref);
}
$sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= " AND d.buy_price_ht IS NOT NULL";
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
@@ -205,8 +233,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
dol_syslog(__FILE__, LOG_DEBUG); dol_syslog(__FILE__, LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@@ -221,10 +248,11 @@ if ($result) {
print '<br>'; print '<br>';
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit); print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
if ($conf->global->MARGIN_TYPE == "1") if ($conf->global->MARGIN_TYPE == "1") {
$labelcostprice = 'BuyingPrice'; $labelcostprice = 'BuyingPrice';
else // value is 'costprice' or 'pmp' } else { // value is 'costprice' or 'pmp'
$labelcostprice = 'CostPrice'; $labelcostprice = 'CostPrice';
}
$moreforfilter = ''; $moreforfilter = '';
@@ -260,8 +288,7 @@ if ($result) {
print "</tr>\n"; print "</tr>\n";
$i = 0; $i = 0;
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
print '<tr class="oddeven">'; print '<tr class="oddeven">';

View File

@@ -36,7 +36,9 @@ $socid = GETPOST('socid', 'int');
$TSelectedProducts = GETPOST('products', 'array'); $TSelectedProducts = GETPOST('products', 'array');
$TSelectedCats = GETPOST('categories', 'array'); $TSelectedCats = GETPOST('categories', 'array');
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'societe', '', ''); $result = restrictedArea($user, 'societe', '', '');
$result = restrictedArea($user, 'margins'); $result = restrictedArea($user, 'margins');
@@ -48,19 +50,27 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = "s.nom"; // Set here default search field if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "s.nom"; // Set here default search field
}
if (!$sortorder) {
$sortorder = "ASC";
}
$startdate = $enddate = ''; $startdate = $enddate = '';
if (!empty($_POST['startdatemonth'])) if (!empty($_POST['startdatemonth'])) {
$startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']); $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
if (!empty($_POST['enddatemonth'])) }
$enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); if (!empty($_POST['enddatemonth'])) {
$enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$object = new Societe($db); $object = new Societe($db);
@@ -98,16 +108,19 @@ if ($socid > 0) {
$soc = new Societe($db); $soc = new Societe($db);
$soc->fetch($socid); $soc->fetch($socid);
if ($soc->client) if ($soc->client) {
{
print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>'; print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
print '<td class="maxwidthonsmartphone" colspan="4">'; print '<td class="maxwidthonsmartphone" colspan="4">';
print img_picto('', 'company').$form->select_company($socid, 'socid', '(client=1 OR client=3)', 1, 0, 0); print img_picto('', 'company').$form->select_company($socid, 'socid', '(client=1 OR client=3)', 1, 0, 0);
print '</td></tr>'; print '</td></tr>';
$client = true; $client = true;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "f.datef"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "f.datef";
}
} }
} else { } else {
print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>'; print '<tr><td class="titlefield">'.$langs->trans('ThirdPartyName').'</td>';
@@ -118,11 +131,11 @@ if ($socid > 0) {
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortorder = "ASC";
{ }
if ($client) if (!$sortfield) {
{ if ($client) {
$sortfield = "f.datef"; $sortfield = "f.datef";
$sortorder = "DESC"; $sortorder = "DESC";
} else { } else {
@@ -202,7 +215,9 @@ $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABAND
$sql = "SELECT"; $sql = "SELECT";
$sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,"; $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.client,";
if ($client) $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,"; if ($client) {
$sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
}
$sql .= " sum(d.total_ht) as selling_price,"; $sql .= " sum(d.total_ht) as selling_price,";
// Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this) // Note: qty and buy_price_ht is always positive (if not, your database may be corrupted, you can update this)
$sql .= " sum(".$db->ifsql('d.total_ht < 0', 'd.qty * d.buy_price_ht * -1 * (d.situation_percent / 100)', 'd.qty * d.buy_price_ht * (d.situation_percent / 100)').") as buying_price,"; $sql .= " sum(".$db->ifsql('d.total_ht < 0', 'd.qty * d.buy_price_ht * -1 * (d.situation_percent / 100)', 'd.qty * d.buy_price_ht * (d.situation_percent / 100)').") as buying_price,";
@@ -214,10 +229,16 @@ if (!empty($TSelectedCats)) {
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=d.fk_product';
} }
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " WHERE f.fk_soc = s.rowid";
if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; if ($socid > 0) {
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;
}
$sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")";
$sql .= ' AND s.entity IN ('.getEntity('societe').')'; $sql .= ' AND s.entity IN ('.getEntity('societe').')';
$sql .= ' AND f.entity IN ('.getEntity('invoice').')'; $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
@@ -229,32 +250,38 @@ if (!empty($TSelectedProducts)) {
if (!empty($TSelectedCats)) { if (!empty($TSelectedCats)) {
$sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')'; $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')';
} }
if (!empty($startdate)) if (!empty($startdate)) {
$sql .= " AND f.datef >= '".$db->idate($startdate)."'"; $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
if (!empty($enddate)) }
$sql .= " AND f.datef <= '".$db->idate($enddate)."'"; if (!empty($enddate)) {
$sql .= " AND f.datef <= '".$db->idate($enddate)."'";
}
$sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) {
$sql .= " AND d.buy_price_ht <> 0"; $sql .= " AND d.buy_price_ht <> 0";
if ($client) $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut"; }
else $sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client"; if ($client) {
$sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
} else {
$sql .= " GROUP BY s.rowid, s.nom, s.code_client, s.client";
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// TODO: calculate total to display then restore pagination // TODO: calculate total to display then restore pagination
//$sql.= $db->plimit($conf->liste_limit +1, $offset); //$sql.= $db->plimit($conf->liste_limit +1, $offset);
dol_syslog('margin::customerMargins.php', LOG_DEBUG); dol_syslog('margin::customerMargins.php', LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
print '<br>'; print '<br>';
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1); print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
if ($conf->global->MARGIN_TYPE == "1") if ($conf->global->MARGIN_TYPE == "1") {
$labelcostprice = 'BuyingPrice'; $labelcostprice = 'BuyingPrice';
else // value is 'costprice' or 'pmp' } else { // value is 'costprice' or 'pmp'
$labelcostprice = 'CostPrice'; $labelcostprice = 'CostPrice';
}
$moreforfilter = ''; $moreforfilter = '';
@@ -264,33 +291,34 @@ if ($result)
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($client)) { if (!empty($client)) {
print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$socid, '', $sortfield, $sortorder); print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$socid, '', $sortfield, $sortorder);
print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$socid, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$socid, 'align="center"', $sortfield, $sortorder);
} else print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;socid=".$socid, '', $sortfield, $sortorder); } else {
print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "s.nom", "", "&amp;socid=".$socid, '', $sortfield, $sortorder);
}
print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder); print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$socid, 'align="right"', $sortfield, $sortorder);
}
print "</tr>\n"; print "</tr>\n";
$cumul_achat = 0; $cumul_achat = 0;
$cumul_vente = 0; $cumul_vente = 0;
if ($num > 0) if ($num > 0) {
{ while ($i < $num /*&& $i < $conf->liste_limit*/) {
while ($i < $num /*&& $i < $conf->liste_limit*/)
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$pa = $objp->buying_price; $pa = $objp->buying_price;
$pv = $objp->selling_price; $pv = $objp->selling_price;
$marge = $objp->marge; $marge = $objp->marge;
if ($marge < 0) if ($marge < 0) {
{
$marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : ''; $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
$markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : ''; $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
} else { } else {
@@ -307,20 +335,22 @@ if ($result)
print '</td>'; print '</td>';
print '<td class="center">'; print '<td class="center">';
print dol_print_date($db->jdate($objp->datef), 'day').'</td>'; print dol_print_date($db->jdate($objp->datef), 'day').'</td>';
} else { } else {
$companystatic->id = $objp->socid; $companystatic->id = $objp->socid;
$companystatic->name = $objp->name; $companystatic->name = $objp->name;
$companystatic->client = $objp->client; $companystatic->client = $objp->client;
print '<td>'.$companystatic->getNomUrl(1, 'margin').'</td>'; print '<td>'.$companystatic->getNomUrl(1, 'margin').'</td>';
} }
print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>';
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@@ -344,17 +374,21 @@ if ($result)
//} //}
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($client) if ($client) {
print '<td colspan=2>'; print '<td colspan=2>';
else print '<td>'; } else {
print $langs->trans('TotalMargin')."</td>"; print '<td>';
}
print $langs->trans('TotalMargin')."</td>";
print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
}
print '</tr>'; print '</tr>';
print '</table>'; print '</table>';

View File

@@ -124,8 +124,7 @@ function getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localta
if ($fk_pa > 0 && empty($paht)) { if ($fk_pa > 0 && empty($paht)) {
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
$product = new ProductFournisseur($db); $product = new ProductFournisseur($db);
if ($product->fetch_product_fournisseur_price($fk_pa)) if ($product->fetch_product_fournisseur_price($fk_pa)) {
{
$paht_ret = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100); $paht_ret = $product->fourn_unitprice * (1 - $product->fourn_remise_percent / 100);
} else { } else {
$paht_ret = $paht; $paht_ret = $paht;
@@ -141,16 +140,20 @@ function getMarginInfos($pvht, $remise_percent, $tva_tx, $localtax1_tx, $localta
$pu_ht_remise = price2num($pu_ht_remise, 'MU'); $pu_ht_remise = price2num($pu_ht_remise, 'MU');
// calcul marge // calcul marge
if ($pu_ht_remise < 0) if ($pu_ht_remise < 0) {
$marge = -1 * (abs($pu_ht_remise) - $paht_ret); $marge = -1 * (abs($pu_ht_remise) - $paht_ret);
else $marge = $pu_ht_remise - $paht_ret; } else {
$marge = $pu_ht_remise - $paht_ret;
}
// calcul taux marge // calcul taux marge
if ($paht_ret != 0) if ($paht_ret != 0) {
$marge_tx_ret = (100 * $marge) / $paht_ret; $marge_tx_ret = (100 * $marge) / $paht_ret;
}
// calcul taux marque // calcul taux marque
if ($pu_ht_remise != 0) if ($pu_ht_remise != 0) {
$marque_tx_ret = (100 * $marge) / $pu_ht_remise; $marque_tx_ret = (100 * $marge) / $pu_ht_remise;
}
return array($paht_ret, $marge_tx_ret, $marque_tx_ret); return array($paht_ret, $marge_tx_ret, $marque_tx_ret);
} }

View File

@@ -41,9 +41,13 @@ $TSelectedCats = GETPOST('categories', 'array');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
if (empty($user->rights->margins->liretous)) accessforbidden(); if (empty($user->rights->margins->liretous)) {
accessforbidden();
}
$mesg = ''; $mesg = '';
@@ -52,14 +56,14 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) if (!$sortfield) {
{ if ($id > 0) {
if ($id > 0)
{
$sortfield = "f.datef"; $sortfield = "f.datef";
$sortorder = "DESC"; $sortorder = "DESC";
} else { } else {
@@ -70,10 +74,12 @@ if (!$sortfield)
$startdate = $enddate = ''; $startdate = $enddate = '';
if (!empty($_POST['startdatemonth'])) if (!empty($_POST['startdatemonth'])) {
$startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']); $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
if (!empty($_POST['enddatemonth'])) }
$enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']); if (!empty($_POST['enddatemonth'])) {
$enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$object = new Product($db); $object = new Product($db);
@@ -169,8 +175,12 @@ print '</form>';
$invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED); $invoice_status_except_list = array(Facture::STATUS_DRAFT, Facture::STATUS_ABANDONED);
$sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,"; $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,";
if ($id > 0) $sql .= " d.fk_product,"; if ($id > 0) {
if ($id > 0) $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,"; $sql .= " d.fk_product,";
}
if ($id > 0) {
$sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
}
$sql .= " SUM(d.total_ht) as selling_price,"; $sql .= " SUM(d.total_ht) as selling_price,";
// Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this) // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
$sql .= " SUM(d.qty) as product_qty,"; $sql .= " SUM(d.qty) as product_qty,";
@@ -187,38 +197,45 @@ $sql .= " WHERE f.fk_soc = s.rowid";
$sql .= ' AND f.entity IN ('.getEntity('invoice').')'; $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
$sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")"; $sql .= " AND f.fk_statut NOT IN (".implode(', ', $invoice_status_except_list).")";
$sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_facture = f.rowid";
if ($id > 0) if ($id > 0) {
$sql .= " AND d.fk_product =".$id; $sql .= " AND d.fk_product =".$id;
}
if (!empty($TSelectedCats)) { if (!empty($TSelectedCats)) {
$sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')'; $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')';
} }
if (!empty($startdate)) if (!empty($startdate)) {
$sql .= " AND f.datef >= '".$db->idate($startdate)."'"; $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
if (!empty($enddate)) }
$sql .= " AND f.datef <= '".$db->idate($enddate)."'"; if (!empty($enddate)) {
$sql .= " AND f.datef <= '".$db->idate($enddate)."'";
}
$sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) {
$sql .= " AND d.buy_price_ht <> 0"; $sql .= " AND d.buy_price_ht <> 0";
if ($id > 0) $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut"; }
else $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity"; if ($id > 0) {
$sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
} else {
$sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// TODO: calculate total to display then restore pagination // TODO: calculate total to display then restore pagination
//$sql.= $db->plimit($conf->liste_limit +1, $offset); //$sql.= $db->plimit($conf->liste_limit +1, $offset);
dol_syslog('margin::productMargins.php', LOG_DEBUG); dol_syslog('margin::productMargins.php', LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
print '<br>'; print '<br>';
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=".$id, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1); print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=".$id, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
//var_dump($conf->global->MARGIN_TYPE); //var_dump($conf->global->MARGIN_TYPE);
if ($conf->global->MARGIN_TYPE == "1") if ($conf->global->MARGIN_TYPE == "1") {
$labelcostprice = 'BuyingPrice'; $labelcostprice = 'BuyingPrice';
else // value is 'costprice' or 'pmp' } else { // value is 'costprice' or 'pmp'
$labelcostprice = 'CostPrice'; $labelcostprice = 'CostPrice';
}
$moreforfilter = ''; $moreforfilter = '';
@@ -228,37 +245,36 @@ if ($result)
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if ($id > 0) { if ($id > 0) {
print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder); print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder);
print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center ');
} else { } else {
print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder); print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder);
} }
print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "product_qty", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "product_qty", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'center ');
print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, '', $sortfield, $sortorder, 'right ');
}
print "</tr>\n"; print "</tr>\n";
$cumul_achat = 0; $cumul_achat = 0;
$cumul_vente = 0; $cumul_vente = 0;
$cumul_qty = 0; $cumul_qty = 0;
if ($num > 0) if ($num > 0) {
{ while ($i < $num /*&& $i < $conf->liste_limit*/) {
while ($i < $num /*&& $i < $conf->liste_limit*/)
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$qty = $objp->product_qty; $qty = $objp->product_qty;
$pa = $objp->buying_price; $pa = $objp->buying_price;
$pv = $objp->selling_price; $pv = $objp->selling_price;
$marge = $objp->marge; $marge = $objp->marge;
if ($marge < 0) if ($marge < 0) {
{
$marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : ''; $marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
$markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : ''; $markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
} else { } else {
@@ -277,8 +293,7 @@ if ($result)
print dol_print_date($db->jdate($objp->datef), 'day')."</td>"; print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
} else { } else {
print '<td>'; print '<td>';
if ($objp->rowid > 0) if ($objp->rowid > 0) {
{
$product_static->type = $objp->fk_product_type; $product_static->type = $objp->fk_product_type;
$product_static->id = $objp->rowid; $product_static->id = $objp->rowid;
$product_static->ref = $objp->ref; $product_static->ref = $objp->ref;
@@ -296,10 +311,12 @@ if ($result)
print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pv, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($pa, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($marge, 'MT')).'</td>';
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@@ -317,18 +334,22 @@ if ($result)
$markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : ''; $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
print '<tr class="liste_total">'; print '<tr class="liste_total">';
if ($id > 0) if ($id > 0) {
print '<td colspan=2>'; print '<td colspan=2>';
else print '<td>'; } else {
print '<td>';
}
print $langs->trans('TotalMargin').'</td>'; print $langs->trans('TotalMargin').'</td>';
print '<td class="center">'.$cumul_qty.'</td>'; print '<td class="center">'.$cumul_qty.'</td>';
print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_vente, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($cumul_achat, 'MT')).'</td>';
print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>'; print '<td class="nowrap right">'.price(price2num($totalMargin, 'MT')).'</td>';
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%").'</td>';
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>'; print '<td class="nowrap right">'.(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%").'</td>';
}
print "</tr>\n"; print "</tr>\n";
print "</table>"; print "</table>";

View File

@@ -36,9 +36,13 @@ $confirm = GETPOST('confirm', 'alpha');
// Security check // Security check
$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); $result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
if (empty($user->rights->margins->liretous)) accessforbidden(); if (empty($user->rights->margins->liretous)) {
accessforbidden();
}
$object = new Product($db); $object = new Product($db);
@@ -46,12 +50,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "f.datef"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "f.datef";
}
/* /*
@@ -62,20 +72,17 @@ $invoicestatic = new Facture($db);
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$result = $object->fetch($id, $ref); $result = $object->fetch($id, $ref);
$title = $langs->trans('ProductServiceCard'); $title = $langs->trans('ProductServiceCard');
$helpurl = ''; $helpurl = '';
$shortlabel = dol_trunc($object->label, 16); $shortlabel = dol_trunc($object->label, 16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) {
{
$title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card'); $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Card');
$helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos'; $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';
} }
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) {
{
$title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card'); $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Card');
$helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios'; $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';
} }
@@ -85,8 +92,7 @@ if ($id > 0 || !empty($ref))
/* /*
* En mode visu * En mode visu
*/ */
if ($result > 0) if ($result > 0) {
{
$head = product_prepare_head($object); $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'); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
@@ -133,7 +139,9 @@ if ($id > 0 || !empty($ref))
$sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,"; $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client,";
$sql .= " f.rowid as facid, f.ref, f.total as total_ht,"; $sql .= " f.rowid as facid, f.ref, f.total as total_ht,";
$sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,"; $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " sc.fk_soc, sc.fk_user,";
}
$sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
$sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty) as qty,"; // not always positive in case of Credit note
$sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // not always positive in case of Credit note $sql .= " ".$db->ifsql('f.type = 2', -1, 1)." * sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // not always positive in case of Credit note
@@ -141,18 +149,28 @@ if ($id > 0 || !empty($ref))
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."facture as f";
$sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; $sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " WHERE f.fk_soc = s.rowid";
$sql .= " AND f.fk_statut > 0"; $sql .= " AND f.fk_statut > 0";
$sql .= " AND f.entity IN (".getEntity('invoice').")"; $sql .= " AND f.entity IN (".getEntity('invoice').")";
$sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_facture = f.rowid";
$sql .= " AND d.fk_product =".$object->id; $sql .= " AND d.fk_product =".$object->id;
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if (!empty($socid)) $sql .= " AND f.fk_soc = $socid"; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if (!empty($socid)) {
$sql .= " AND f.fk_soc = $socid";
}
$sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) {
$sql .= " AND d.buy_price_ht <> 0";
}
$sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type"; $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", sc.fk_soc, sc.fk_user";
}
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// TODO: calculate total to display then restore pagination // TODO: calculate total to display then restore pagination
//$sql.= $db->plimit($conf->liste_limit +1, $offset); //$sql.= $db->plimit($conf->liste_limit +1, $offset);
@@ -177,10 +195,12 @@ if ($id > 0 || !empty($ref))
print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("BuyingPrice", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Qty", $_SERVER["PHP_SELF"], "d.qty", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
}
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;id=".$object->id, '', $sortfield, $sortorder, 'right ');
print "</tr>\n"; print "</tr>\n";
@@ -209,10 +229,12 @@ if ($id > 0 || !empty($ref))
print "<td class=\"right\">".price(price2num($objp->buying_price, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($objp->buying_price, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($objp->qty, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($objp->qty, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($objp->marge, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($objp->marge, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
}
print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>'; print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@@ -225,8 +247,7 @@ if ($id > 0 || !empty($ref))
// affichage totaux marges // affichage totaux marges
$totalMargin = $cumul_vente - $cumul_achat; $totalMargin = $cumul_vente - $cumul_achat;
if ($totalMargin < 0) if ($totalMargin < 0) {
{
$marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : ''; $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
$markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : ''; $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
} else { } else {
@@ -239,10 +260,12 @@ if ($id > 0 || !empty($ref))
print '<td class="right">'.price(price2num($cumul_achat, 'MT'))."</td>\n"; print '<td class="right">'.price(price2num($cumul_achat, 'MT'))."</td>\n";
print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n"; print '<td class="right">'.price(price2num($cumul_qty, 'MT'))."</td>\n";
print '<td class="right">'.price(price2num($totalMargin, 'MT'))."</td>\n"; print '<td class="right">'.price(price2num($totalMargin, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n"; print '<td class="right">'.(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
}
print '<td class="right">&nbsp;</td>'; print '<td class="right">&nbsp;</td>';
print "</tr>\n"; print "</tr>\n";
print "</table>"; print "</table>";

View File

@@ -30,7 +30,9 @@ $langs->loadLangs(array("companies", "bills", "products", "margins"));
// Security check // Security check
$socid = GETPOST('socid', 'int'); $socid = GETPOST('socid', 'int');
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'societe', '', ''); $result = restrictedArea($user, 'societe', '', '');
@@ -38,15 +40,23 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "DESC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "f.datef"; $sortorder = "DESC";
}
if (!$sortfield) {
$sortfield = "f.datef";
}
$object = new Societe($db); $object = new Societe($db);
if ($socid > 0) $object->fetch($socid); if ($socid > 0) {
$object->fetch($socid);
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('thirdpartymargins', 'globalcard')); $hookmanager->initHooks(array('thirdpartymargins', 'globalcard'));
@@ -58,7 +68,9 @@ $hookmanager->initHooks(array('thirdpartymargins', 'globalcard'));
$parameters = array('id'=>$socid); $parameters = array('id'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
@@ -70,18 +82,19 @@ $invoicestatic = new Facture($db);
$form = new Form($db); $form = new Form($db);
$title = $langs->trans("ThirdParty").' - '.$langs->trans("Margins"); $title = $langs->trans("ThirdParty").' - '.$langs->trans("Margins");
if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name.' - '.$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'; $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url); llxHeader('', $title, $help_url);
if ($socid > 0) if ($socid > 0) {
{
$object = new Societe($db); $object = new Societe($db);
$object->fetch($socid); $object->fetch($socid);
/* /*
* Affichage onglets * Affichage onglets
*/ */
$head = societe_prepare_head($object); $head = societe_prepare_head($object);
@@ -96,27 +109,25 @@ if ($socid > 0)
print '<div class="underbanner clearboth"></div>'; print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">'; print '<table class="border tableforfield" width="100%">';
if ($object->client) if ($object->client) {
{ print '<tr><td class="titlefield">';
print '<tr><td class="titlefield">'; print $langs->trans('CustomerCode').'</td><td colspan="3">';
print $langs->trans('CustomerCode').'</td><td colspan="3">'; print $object->code_client;
print $object->code_client; $tmpcheck = $object->check_codeclient();
$tmpcheck = $object->check_codeclient(); if ($tmpcheck != 0 && $tmpcheck != -5) {
if ($tmpcheck != 0 && $tmpcheck != -5) { print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>'; }
} print '</td></tr>';
print '</td></tr>'; }
}
if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) {
{
print '<tr><td class="titlefield">'; print '<tr><td class="titlefield">';
print $langs->trans('SupplierCode').'</td><td colspan="3">'; print $langs->trans('SupplierCode').'</td><td colspan="3">';
print $object->code_fournisseur; print $object->code_fournisseur;
$tmpcheck = $object->check_codefournisseur(); $tmpcheck = $object->check_codefournisseur();
if ($tmpcheck != 0 && $tmpcheck != -5) { if ($tmpcheck != 0 && $tmpcheck != -5) {
print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
} }
print '</td></tr>'; print '</td></tr>';
} }
@@ -163,7 +174,9 @@ if ($socid > 0)
$sql .= " AND d.fk_facture = f.rowid"; $sql .= " AND d.fk_facture = f.rowid";
$sql .= " AND f.fk_soc = $socid"; $sql .= " AND f.fk_soc = $socid";
$sql .= " AND d.buy_price_ht IS NOT NULL"; $sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) {
$sql .= " AND d.buy_price_ht <> 0";
}
$sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type"; $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type";
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
// TODO: calculate total to display then restore pagination // TODO: calculate total to display then restore pagination
@@ -171,8 +184,7 @@ if ($socid > 0)
dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG); dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$num = $db->num_rows($result); $num = $db->num_rows($result);
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;socid=".$object->id, $sortfield, $sortorder, '', $num, $num, ''); print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;socid=".$object->id, $sortfield, $sortorder, '', $num, $num, '');
@@ -187,20 +199,20 @@ if ($socid > 0)
print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
}
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print "</tr>\n"; print "</tr>\n";
$cumul_achat = 0; $cumul_achat = 0;
$cumul_vente = 0; $cumul_vente = 0;
if ($num > 0) if ($num > 0) {
{ while ($i < $num /*&& $i < $conf->liste_limit*/) {
while ($i < $num /*&& $i < $conf->liste_limit*/)
{
$objp = $db->fetch_object($result); $objp = $db->fetch_object($result);
$marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : ''; $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
@@ -222,10 +234,12 @@ if ($socid > 0)
print "<td class=\"right\">".price(price2num($objp->selling_price, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($objp->selling_price, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."</td>\n";
print "<td class=\"right\">".$sign.price(price2num($objp->marge, 'MT'))."</td>\n"; print "<td class=\"right\">".$sign.price(price2num($objp->marge, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
}
print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>'; print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@@ -237,8 +251,7 @@ if ($socid > 0)
// affichage totaux marges // affichage totaux marges
$totalMargin = $cumul_vente - $cumul_achat; $totalMargin = $cumul_vente - $cumul_achat;
if ($totalMargin < 0) if ($totalMargin < 0) {
{
$marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : ''; $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
$markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : ''; $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
} else { } else {
@@ -252,10 +265,12 @@ if ($socid > 0)
print "<td class=\"right\">".price(price2num($cumul_vente, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($cumul_vente, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($cumul_achat, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($cumul_achat, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($totalMargin, 'MT'))."</td>\n"; print "<td class=\"right\">".price(price2num($totalMargin, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES)) }
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n"; print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
}
print '<td class="right">&nbsp;</td>'; print '<td class="right">&nbsp;</td>';
print "</tr>\n"; print "</tr>\n";
} else { } else {

View File

@@ -26,8 +26,9 @@ 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")); $langs->loadLangs(array("admin", "other", "modulebuilder"));
if (!$user->admin || empty($conf->modulebuilder->enabled)) if (!$user->admin || empty($conf->modulebuilder->enabled)) {
accessforbidden(); accessforbidden();
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
@@ -35,8 +36,7 @@ $backtopage = GETPOST('backtopage', 'alpha');
/* /*
* Actions * Actions
*/ */
if ($action == "update") if ($action == "update") {
{
$res1 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_README', GETPOST('MODULEBUILDER_SPECIFIC_README', 'restricthtml'), 'chaine', 0, '', $conf->entity); $res1 = dolibarr_set_const($db, 'MODULEBUILDER_SPECIFIC_README', GETPOST('MODULEBUILDER_SPECIFIC_README', 'restricthtml'), 'chaine', 0, '', $conf->entity);
$res2 = dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTOR', GETPOST('MODULEBUILDER_ASCIIDOCTOR', 'nohtml'), '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); $res3 = dolibarr_set_const($db, 'MODULEBUILDER_ASCIIDOCTORPDF', GETPOST('MODULEBUILDER_ASCIIDOCTORPDF', 'nohtml'), 'chaine', 0, '', $conf->entity);
@@ -58,8 +58,9 @@ $reg = array();
if (preg_match('/set_(.*)/', $action, $reg)) { if (preg_match('/set_(.*)/', $action, $reg)) {
$code = $reg[1]; $code = $reg[1];
$values = GETPOST($code); $values = GETPOST($code);
if (is_array($values)) if (is_array($values)) {
$values = implode(',', $values); $values = implode(',', $values);
}
if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) { if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) {
header("Location: ".$_SERVER["PHP_SELF"]); header("Location: ".$_SERVER["PHP_SELF"]);
@@ -112,8 +113,7 @@ print '<td>'.$langs->trans("Value").'</td>';
print "</tr>\n"; print "</tr>\n";
if ($conf->global->MAIN_FEATURES_LEVEL >= 2) if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
{
// What is use case of this 2 options ? // What is use case of this 2 options ?
print '<tr class="oddeven">'; print '<tr class="oddeven">';

File diff suppressed because it is too large Load Diff

View File

@@ -25,16 +25,30 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; $res = @include "../../main.inc.php";
if (!$res) die("Include of main fails"); }
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
// Libraries // Libraries
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';

View File

@@ -29,16 +29,30 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; $res = @include "../../main.inc.php";
if (!$res) die("Include of main fails"); }
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
require_once '../lib/mymodule.lib.php'; require_once '../lib/mymodule.lib.php';

View File

@@ -25,16 +25,30 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; $res = @include "../../main.inc.php";
if (!$res) die("Include of main fails"); }
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
global $langs, $user; global $langs, $user;

View File

@@ -99,9 +99,8 @@ class ActionsMyModule
$error = 0; // Error counter $error = 0; // Error counter
/* print_r($parameters); print_r($object); echo "action: " . $action; */ /* print_r($parameters); print_r($object); echo "action: " . $action; */
if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2'
{ // Do what you want here...
// Do what you want here...
// You can for example call global vars like $fieldstosearchall to overwrite them, or update database depending on $action and $_POST values. // You can for example call global vars like $fieldstosearchall to overwrite them, or update database depending on $action and $_POST values.
} }
@@ -132,10 +131,8 @@ class ActionsMyModule
$error = 0; // Error counter $error = 0; // Error counter
/* print_r($parameters); print_r($object); echo "action: " . $action; */ /* print_r($parameters); print_r($object); echo "action: " . $action; */
if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2'
{ foreach ($parameters['toselect'] as $objectid) {
foreach ($parameters['toselect'] as $objectid)
{
// Do action on each object id // Do action on each object id
} }
} }
@@ -168,8 +165,7 @@ class ActionsMyModule
$disabled = 1; $disabled = 1;
/* print_r($parameters); print_r($object); echo "action: " . $action; */ /* print_r($parameters); print_r($object); echo "action: " . $action; */
if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2'
{
$this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("MyModuleMassAction").'</option>'; $this->resprints = '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("MyModuleMassAction").'</option>';
} }
@@ -204,8 +200,7 @@ class ActionsMyModule
dol_syslog(get_class($this).'::executeHooks action='.$action); dol_syslog(get_class($this).'::executeHooks action='.$action);
/* print_r($parameters); print_r($object); echo "action: " . $action; */ /* print_r($parameters); print_r($object); echo "action: " . $action; */
if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) // do something only for the context 'somecontext1' or 'somecontext2' if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2'
{
} }
return $ret; return $ret;

View File

@@ -119,29 +119,42 @@ class MyModuleApi extends DolibarrApi
// If the internal user must only see his customers, force searching by him // If the internal user must only see his customers, force searching by him
$search_sale = 0; $search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid"; $sql = "SELECT t.rowid";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
}
$sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
}
$sql .= " WHERE 1 = 1"; $sql .= " WHERE 1 = 1";
// Example of use $mode // Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; if ($tmpobject->ismultientitymanaged) {
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid; }
if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql .= " AND t.fk_soc = sc.fk_soc";
}
if ($restrictonsocid && $socid) {
$sql .= " AND t.fk_soc = ".$socid;
}
if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
}
// Insert sale filter // Insert sale filter
if ($restrictonsocid && $search_sale > 0) { if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
if ($sqlfilters) if ($sqlfilters) {
{
if (!DolibarrApi::_checkFilters($sqlfilters)) { if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
} }
@@ -161,11 +174,9 @@ class MyModuleApi extends DolibarrApi
$result = $this->db->query($sql); $result = $this->db->query($sql);
$i = 0; $i = 0;
if ($result) if ($result) {
{
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$tmp_object = new MyObject($this->db); $tmp_object = new MyObject($this->db);
if ($tmp_object->fetch($obj->rowid)) { if ($tmp_object->fetch($obj->rowid)) {
@@ -236,12 +247,13 @@ class MyModuleApi extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->myobject->$field = $value; $this->myobject->$field = $value;
} }
if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) if ($this->myobject->update(DolibarrApiAccess::$user, false) > 0) {
{
return $this->get($id); return $this->get($id);
} else { } else {
throw new RestException(500, $this->myobject->error); throw new RestException(500, $this->myobject->error);
@@ -272,8 +284,7 @@ class MyModuleApi extends DolibarrApi
throw new RestException(401, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access to instance id='.$this->myobject->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
} }
if (!$this->myobject->delete(DolibarrApiAccess::$user)) if (!$this->myobject->delete(DolibarrApiAccess::$user)) {
{
throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error); throw new RestException(500, 'Error when deleting MyObject : '.$this->myobject->error);
} }
@@ -338,8 +349,7 @@ class MyModuleApi extends DolibarrApi
// If object has lines, remove $db property // If object has lines, remove $db property
if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines); $nboflines = count($object->lines);
for ($i = 0; $i < $nboflines; $i++) for ($i = 0; $i < $nboflines; $i++) {
{
$this->_cleanObjectDatas($object->lines[$i]); $this->_cleanObjectDatas($object->lines[$i]);
unset($object->lines[$i]->lines); unset($object->lines[$i]->lines);
@@ -362,9 +372,12 @@ class MyModuleApi extends DolibarrApi
{ {
$myobject = array(); $myobject = array();
foreach ($this->myobject->fields as $field => $propfield) { foreach ($this->myobject->fields as $field => $propfield) {
if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
if (!isset($data[$field])) continue; // Not a mandatory field
}
if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$myobject[$field] = $data[$field]; $myobject[$field] = $data[$field];
} }
return $myobject; return $myobject;

View File

@@ -232,8 +232,12 @@ class MyObject extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Example to show how to set values of fields definition dynamically // Example to show how to set values of fields definition dynamically
/*if ($user->rights->mymodule->myobject->read) { /*if ($user->rights->mymodule->myobject->read) {
@@ -242,23 +246,17 @@ class MyObject extends CommonObject
}*/ }*/
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
if (is_object($langs)) if (is_object($langs)) {
{ foreach ($this->fields as $key => $val) {
foreach ($this->fields as $key => $val) if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
{ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@@ -298,7 +296,9 @@ class MyObject extends CommonObject
// Load source object // Load source object
$result = $object->fetchCommon($fromid); $result = $object->fetchCommon($fromid);
if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); if ($result > 0 && !empty($object->table_element_line)) {
$object->fetchLines();
}
// get lines so they will be clone // get lines so they will be clone
//foreach($this->lines as $line) //foreach($this->lines as $line)
@@ -310,21 +310,28 @@ class MyObject extends CommonObject
unset($object->import_key); unset($object->import_key);
// Clear fields // Clear fields
if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; if (property_exists($object, 'ref')) {
if (property_exists($object, 'label')) $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'];
if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } }
if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } if (property_exists($object, 'label')) {
if (property_exists($object, 'date_modification')) { $object->date_modification = null; } $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
}
if (property_exists($object, 'status')) {
$object->status = self::STATUS_DRAFT;
}
if (property_exists($object, 'date_creation')) {
$object->date_creation = dol_now();
}
if (property_exists($object, 'date_modification')) {
$object->date_modification = null;
}
// ... // ...
// Clear extrafields that are unique // Clear extrafields that are unique
if (is_array($object->array_options) && count($object->array_options) > 0) if (is_array($object->array_options) && count($object->array_options) > 0) {
{
$extrafields->fetch_name_optionals_label($this->table_element); $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); $shortkey = preg_replace('/options_/', '', $key);
if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
{
//var_dump($key); var_dump($clonedObj->array_options[$key]); exit; //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
unset($object->array_options[$key]); unset($object->array_options[$key]);
} }
@@ -340,22 +347,19 @@ class MyObject extends CommonObject
$this->errors = $object->errors; $this->errors = $object->errors;
} }
if (!$error) if (!$error) {
{
// copy internal contacts // copy internal contacts
if ($this->copy_linked_contact($object, 'internal') < 0) if ($this->copy_linked_contact($object, 'internal') < 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
// copy external contacts if same company // copy external contacts if same company
if (property_exists($this, 'socid') && $this->socid == $object->socid) if (property_exists($this, 'socid') && $this->socid == $object->socid) {
{ if ($this->copy_linked_contact($object, 'external') < 0) {
if ($this->copy_linked_contact($object, 'external') < 0)
$error++; $error++;
}
} }
} }
@@ -381,7 +385,9 @@ class MyObject extends CommonObject
public function fetch($id, $ref = null) public function fetch($id, $ref = null)
{ {
$result = $this->fetchCommon($id, $ref); $result = $this->fetchCommon($id, $ref);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); if ($result > 0 && !empty($this->table_element_line)) {
$this->fetchLines();
}
return $result; return $result;
} }
@@ -421,8 +427,11 @@ class MyObject extends CommonObject
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@@ -455,8 +464,7 @@ class MyObject extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < ($limit ? min($limit, $num) : $num)) while ($i < ($limit ? min($limit, $num) : $num)) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$record = new self($this->db); $record = new self($this->db);
@@ -512,8 +520,7 @@ class MyObject extends CommonObject
*/ */
public function deleteLine(User $user, $idline, $notrigger = false) public function deleteLine(User $user, $idline, $notrigger = false)
{ {
if ($this->status < 0) if ($this->status < 0) {
{
$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
return -2; return -2;
} }
@@ -538,8 +545,7 @@ class MyObject extends CommonObject
$error = 0; $error = 0;
// Protection // Protection
if ($this->status == self::STATUS_VALIDATED) if ($this->status == self::STATUS_VALIDATED) {
{
dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
return 0; return 0;
} }
@@ -557,8 +563,7 @@ class MyObject extends CommonObject
$this->db->begin(); $this->db->begin();
// Define new ref // Define new ref
if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
{
$num = $this->getNextNumRef(); $num = $this->getNextNumRef();
} else { } else {
$num = $this->ref; $num = $this->ref;
@@ -570,57 +575,58 @@ class MyObject extends CommonObject
$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
$sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " SET ref = '".$this->db->escape($num)."',";
$sql .= " status = ".self::STATUS_VALIDATED; $sql .= " status = ".self::STATUS_VALIDATED;
if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'"; if (!empty($this->fields['date_validation'])) {
if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; $sql .= ", date_validation = '".$this->db->idate($now)."'";
}
if (!empty($this->fields['fk_user_valid'])) {
$sql .= ", fk_user_valid = ".$user->id;
}
$sql .= " WHERE rowid = ".$this->id; $sql .= " WHERE rowid = ".$this->id;
dol_syslog(get_class($this)."::validate()", LOG_DEBUG); dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($this->db); dol_print_error($this->db);
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
$error++; $error++;
} }
if (!$error && !$notrigger) if (!$error && !$notrigger) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('MYOBJECT_VALIDATE', $user); $result = $this->call_trigger('MYOBJECT_VALIDATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
} }
if (!$error) if (!$error) {
{
$this->oldref = $this->ref; $this->oldref = $this->ref;
// Rename directory if dir was a temporary ref // Rename directory if dir was a temporary ref
if (preg_match('/^[\(]?PROV/i', $this->ref)) if (preg_match('/^[\(]?PROV/i', $this->ref)) {
{
// Now we rename also files into index // Now we rename also files into index
$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'myobject/".$this->db->escape($this->newref)."'"; $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'myobject/".$this->db->escape($this->newref)."'";
$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'myobject/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->error = $this->db->lasterror(); } if (!$resql) {
$error++; $this->error = $this->db->lasterror();
}
// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
$oldref = dol_sanitizeFileName($this->ref); $oldref = dol_sanitizeFileName($this->ref);
$newref = dol_sanitizeFileName($num); $newref = dol_sanitizeFileName($num);
$dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref; $dirsource = $conf->mymodule->dir_output.'/myobject/'.$oldref;
$dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref; $dirdest = $conf->mymodule->dir_output.'/myobject/'.$newref;
if (!$error && file_exists($dirsource)) if (!$error && file_exists($dirsource)) {
{
dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
if (@rename($dirsource, $dirdest)) if (@rename($dirsource, $dirdest)) {
{
dol_syslog("Rename ok"); dol_syslog("Rename ok");
// Rename docs starting with $oldref with $newref // Rename docs starting with $oldref with $newref
$listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); $listoffiles = dol_dir_list($conf->mymodule->dir_output.'/myobject/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
foreach ($listoffiles as $fileentry) foreach ($listoffiles as $fileentry) {
{
$dirsource = $fileentry['name']; $dirsource = $fileentry['name'];
$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
$dirsource = $fileentry['path'].'/'.$dirsource; $dirsource = $fileentry['path'].'/'.$dirsource;
@@ -633,14 +639,12 @@ class MyObject extends CommonObject
} }
// Set new ref and current status // Set new ref and current status
if (!$error) if (!$error) {
{
$this->ref = $num; $this->ref = $num;
$this->status = self::STATUS_VALIDATED; $this->status = self::STATUS_VALIDATED;
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@@ -660,8 +664,7 @@ class MyObject extends CommonObject
public function setDraft($user, $notrigger = 0) public function setDraft($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status <= self::STATUS_DRAFT) if ($this->status <= self::STATUS_DRAFT) {
{
return 0; return 0;
} }
@@ -685,8 +688,7 @@ class MyObject extends CommonObject
public function cancel($user, $notrigger = 0) public function cancel($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_VALIDATED) if ($this->status != self::STATUS_VALIDATED) {
{
return 0; return 0;
} }
@@ -710,8 +712,7 @@ class MyObject extends CommonObject
public function reopen($user, $notrigger = 0) public function reopen($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_CANCELED) if ($this->status != self::STATUS_CANCELED) {
{
return 0; return 0;
} }
@@ -739,7 +740,9 @@ class MyObject extends CommonObject
{ {
global $conf, $langs, $hookmanager; 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 = ''; $result = '';
@@ -752,25 +755,28 @@ class MyObject extends CommonObject
$url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowMyObject"); $label = $langs->trans("ShowMyObject");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
if ($option == 'nolink') { if ($option == 'nolink') {
$linkstart = '<span'; $linkstart = '<span';
@@ -787,7 +793,9 @@ class MyObject extends CommonObject
$result .= $linkstart; $result .= $linkstart;
if (empty($this->showphoto_on_popup)) { if (empty($this->showphoto_on_popup)) {
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) {
$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);
}
} else { } else {
if ($withpicto) { if ($withpicto) {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@@ -813,7 +821,9 @@ class MyObject extends CommonObject
} }
} }
if ($withpicto != 2) $result .= $this->ref; if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@@ -822,8 +832,11 @@ class MyObject extends CommonObject
$hookmanager->initHooks(array('myobjectdao')); $hookmanager->initHooks(array('myobjectdao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result); $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $result = $hookmanager->resPrint; if ($reshook > 0) {
else $result .= $hookmanager->resPrint; $result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result; return $result;
} }
@@ -850,8 +863,7 @@ class MyObject extends CommonObject
public function LibStatut($status, $mode = 0) public function LibStatut($status, $mode = 0)
{ {
// phpcs:enable // phpcs:enable
if (empty($this->labelStatus) || empty($this->labelStatusShort)) if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
{
global $langs; global $langs;
//$langs->load("mymodule@mymodule"); //$langs->load("mymodule@mymodule");
$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
@@ -864,7 +876,9 @@ class MyObject extends CommonObject
$statusType = 'status'.$status; $statusType = 'status'.$status;
//if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
if ($status == self::STATUS_CANCELED) $statusType = 'status6'; if ($status == self::STATUS_CANCELED) {
$statusType = 'status6';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }
@@ -882,28 +896,23 @@ class MyObject extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;
@@ -943,8 +952,7 @@ class MyObject extends CommonObject
$objectline = new MyObjectLine($this->db); $objectline = new MyObjectLine($this->db);
$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.$this->id)); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_myobject = '.$this->id));
if (is_numeric($result)) if (is_numeric($result)) {
{
$this->error = $this->error; $this->error = $this->error;
$this->errors = $this->errors; $this->errors = $this->errors;
return $result; return $result;
@@ -968,8 +976,7 @@ class MyObject extends CommonObject
$conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard'; $conf->global->MYMODULE_MYOBJECT_ADDON = 'mod_myobject_standard';
} }
if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON)) if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON)) {
{
$mybool = false; $mybool = false;
$file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php"; $file = $conf->global->MYMODULE_MYOBJECT_ADDON.".php";
@@ -977,16 +984,14 @@ class MyObject extends CommonObject
// Include file with class // Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/mymodule/"); $dir = dol_buildpath($reldir."core/modules/mymodule/");
// Load file with numbering class (if found) // Load file with numbering class (if found)
$mybool |= @include_once $dir.$file; $mybool |= @include_once $dir.$file;
} }
if ($mybool === false) if ($mybool === false) {
{
dol_print_error('', "Failed to include file ".$file); dol_print_error('', "Failed to include file ".$file);
return ''; return '';
} }
@@ -995,8 +1000,7 @@ class MyObject extends CommonObject
$obj = new $classname(); $obj = new $classname();
$numref = $obj->getNextValue($this); $numref = $obj->getNextValue($this);
if ($numref != '' && $numref != '-1') if ($numref != '' && $numref != '-1') {
{
return $numref; return $numref;
} else { } else {
$this->error = $obj->error; $this->error = $obj->error;

View File

@@ -48,8 +48,7 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets
global $conf; global $conf;
$this->db = $db; $this->db = $db;
if (is_array($conf->modules)) if (is_array($conf->modules)) {
{
$this->enabled = in_array('mymodule', $conf->modules) ? 1 : 0; $this->enabled = in_array('mymodule', $conf->modules) ? 1 : 0;
} }
} }
@@ -73,8 +72,7 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets
$s .= $langs->trans("Status").': '; $s .= $langs->trans("Status").': ';
$s .= '<select name="filter" class="flat">'; $s .= '<select name="filter" class="flat">';
$s .= '<option value="none">&nbsp;</option>'; $s .= '<option value="none">&nbsp;</option>';
foreach ($arraystatus as $status) foreach ($arraystatus as $status) {
{
$s .= '<option value="'.$status.'">'.$status.'</option>'; $s .= '<option value="'.$status.'">'.$status.'</option>';
} }
$s .= '</select>'; $s .= '</select>';
@@ -112,24 +110,23 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets
$sql = " select rowid as id, email, firstname, lastname, plan, partner"; $sql = " select rowid as id, email, firstname, lastname, plan, partner";
$sql .= " from ".MAIN_DB_PREFIX."myobject"; $sql .= " from ".MAIN_DB_PREFIX."myobject";
$sql .= " where email IS NOT NULL AND email != ''"; $sql .= " where email IS NOT NULL AND email != ''";
if (GETPOSTISSET('filter') && GETPOST('filter', 'alphanohtml') != 'none') $sql .= " AND status = '".$this->db->escape(GETPOST('filter', 'alphanohtml'))."'"; if (GETPOSTISSET('filter') && GETPOST('filter', 'alphanohtml') != 'none') {
$sql .= " AND status = '".$this->db->escape(GETPOST('filter', 'alphanohtml'))."'";
}
$sql .= " ORDER BY email"; $sql .= " ORDER BY email";
// Stocke destinataires dans target // Stocke destinataires dans target
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{
$num = $this->db->num_rows($result); $num = $this->db->num_rows($result);
$i = 0; $i = 0;
dol_syslog("mailinglist_mymodule_myobject.modules.php: mailing ".$num." targets found"); dol_syslog("mailinglist_mymodule_myobject.modules.php: mailing ".$num." targets found");
$old = ''; $old = '';
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
if ($old <> $obj->email) if ($old <> $obj->email) {
{
$target[$j] = array( $target[$j] = array(
'email' => $obj->email, 'email' => $obj->email,
'name' => $obj->lastname, 'name' => $obj->lastname,
@@ -197,7 +194,9 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets
{ {
$a = parent::getNbOfRecipients("select count(distinct(email)) as nb from ".MAIN_DB_PREFIX."myobject as p where email IS NOT NULL AND email != ''"); $a = parent::getNbOfRecipients("select count(distinct(email)) as nb from ".MAIN_DB_PREFIX."myobject as p where email IS NOT NULL AND email != ''");
if ($a < 0) return -1; if ($a < 0) {
return -1;
}
return $a; return $a;
} }
} }

View File

@@ -98,7 +98,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// Recupere emetteur // Recupere emetteur
$this->emetteur = $mysoc; $this->emetteur = $mysoc;
if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined if (!$this->emetteur->country_code) {
$this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
}
} }
@@ -129,8 +131,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$texttitle = $langs->trans("ListOfDirectories"); $texttitle = $langs->trans("ListOfDirectories");
$listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH))); $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH)));
$listoffiles = array(); $listoffiles = array();
foreach ($listofdir as $key=>$tmpdir) foreach ($listofdir as $key => $tmpdir) {
{
$tmpdir = trim($tmpdir); $tmpdir = trim($tmpdir);
$tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
if (!$tmpdir) { if (!$tmpdir) {
@@ -140,7 +141,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0); $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
} else { } else {
$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)'); $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); if (count($tmpfiles)) {
$listoffiles = array_merge($listoffiles, $tmpfiles);
}
} }
} }
$texthelp = $langs->trans("ListOfDirectoriesForModelGenODT"); $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
@@ -159,8 +162,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// Scan directories // Scan directories
$nbofiles = count($listoffiles); $nbofiles = count($listoffiles);
if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH)) if (!empty($conf->global->MYMODULE_MYOBJECT_ADDON_PDF_ODT_PATH)) {
{
$texte .= $langs->trans("NumberOfModelFilesFound").': <b>'; $texte .= $langs->trans("NumberOfModelFilesFound").': <b>';
//$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':''; //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
$texte .= count($listoffiles); $texte .= count($listoffiles);
@@ -168,11 +170,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$texte .= '</b>'; $texte .= '</b>';
} }
if ($nbofiles) if ($nbofiles) {
{
$texte .= '<div id="div_'.get_class($this).'" class="hidden">'; $texte .= '<div id="div_'.get_class($this).'" class="hidden">';
foreach ($listoffiles as $file) foreach ($listoffiles as $file) {
{
$texte .= $file['name'].'<br>'; $texte .= $file['name'].'<br>';
} }
$texte .= '</div>'; $texte .= '</div>';
@@ -208,37 +208,34 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// phpcs:enable // phpcs:enable
global $user, $langs, $conf, $mysoc, $hookmanager; global $user, $langs, $conf, $mysoc, $hookmanager;
if (empty($srctemplatepath)) if (empty($srctemplatepath)) {
{
dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
return -1; return -1;
} }
// Add odtgeneration hook // Add odtgeneration hook
if (!is_object($hookmanager)) if (!is_object($hookmanager)) {
{
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($this->db); $hookmanager = new HookManager($this->db);
} }
$hookmanager->initHooks(array('odtgeneration')); $hookmanager->initHooks(array('odtgeneration'));
global $action; global $action;
if (!is_object($outputlangs)) $outputlangs = $langs; if (!is_object($outputlangs)) {
$outputlangs = $langs;
}
$sav_charset_output = $outputlangs->charset_output; $sav_charset_output = $outputlangs->charset_output;
$outputlangs->charset_output = 'UTF-8'; $outputlangs->charset_output = 'UTF-8';
$outputlangs->loadLangs(array("main", "dict", "companies", "bills")); $outputlangs->loadLangs(array("main", "dict", "companies", "bills"));
if ($conf->commande->dir_output) if ($conf->commande->dir_output) {
{
// If $object is id instead of object // If $object is id instead of object
if (!is_object($object)) if (!is_object($object)) {
{
$id = $object; $id = $object;
$object = new Commande($this->db); $object = new Commande($this->db);
$result = $object->fetch($id); $result = $object->fetch($id);
if ($result < 0) if ($result < 0) {
{
dol_print_error($this->db, $object->error); dol_print_error($this->db, $object->error);
return -1; return -1;
} }
@@ -246,20 +243,19 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$dir = $conf->commande->multidir_output[isset($object->entity) ? $object->entity : 1]; $dir = $conf->commande->multidir_output[isset($object->entity) ? $object->entity : 1];
$objectref = dol_sanitizeFileName($object->ref); $objectref = dol_sanitizeFileName($object->ref);
if (!preg_match('/specimen/i', $objectref)) $dir .= "/".$objectref; if (!preg_match('/specimen/i', $objectref)) {
$dir .= "/".$objectref;
}
$file = $dir."/".$objectref.".odt"; $file = $dir."/".$objectref.".odt";
if (!file_exists($dir)) if (!file_exists($dir)) {
{ if (dol_mkdir($dir) < 0) {
if (dol_mkdir($dir) < 0)
{
$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
return -1; return -1;
} }
} }
if (file_exists($dir)) if (file_exists($dir)) {
{
//print "srctemplatepath=".$srctemplatepath; // Src filename //print "srctemplatepath=".$srctemplatepath; // Src filename
$newfile = basename($srctemplatepath); $newfile = basename($srctemplatepath);
$newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile); $newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile);
@@ -269,10 +265,11 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
//$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
// Get extension (ods or odt) // Get extension (ods or odt)
$newfileformat = substr($newfile, strrpos($newfile, '.') + 1); $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
if (!empty($conf->global->MAIN_DOC_USE_TIMING)) if (!empty($conf->global->MAIN_DOC_USE_TIMING)) {
{
$format = $conf->global->MAIN_DOC_USE_TIMING; $format = $conf->global->MAIN_DOC_USE_TIMING;
if ($format == '1') $format = '%Y%m%d%H%M%S'; if ($format == '1') {
$format = '%Y%m%d%H%M%S';
}
$filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat; $filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat;
} else { } else {
$filename = $newfiletmp.'.'.$newfileformat; $filename = $newfiletmp.'.'.$newfileformat;
@@ -289,16 +286,14 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// If CUSTOMER contact defined on order, we use it // If CUSTOMER contact defined on order, we use it
$usecontact = false; $usecontact = false;
$arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
if (count($arrayidcontact) > 0) if (count($arrayidcontact) > 0) {
{
$usecontact = true; $usecontact = true;
$result = $object->fetch_contact($arrayidcontact[0]); $result = $object->fetch_contact($arrayidcontact[0]);
} }
// Recipient name // Recipient name
$contactobject = null; $contactobject = null;
if (!empty($usecontact)) if (!empty($usecontact)) {
{
if ($usecontact && ($object->contact->fk_soc != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)))) { if ($usecontact && ($object->contact->fk_soc != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)))) {
$socobject = $object->contact; $socobject = $object->contact;
} else { } else {
@@ -326,8 +321,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// Line of free text // Line of free text
$newfreetext = ''; $newfreetext = '';
$paramfreetext = 'ORDER_FREE_TEXT'; $paramfreetext = 'ORDER_FREE_TEXT';
if (!empty($conf->global->$paramfreetext)) if (!empty($conf->global->$paramfreetext)) {
{
$newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray); $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray);
} }
@@ -343,8 +337,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
'DELIMITER_RIGHT' => '}' 'DELIMITER_RIGHT' => '}'
) )
); );
} catch (Exception $e) } catch (Exception $e) {
{
$this->error = $e->getMessage(); $this->error = $e->getMessage();
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
return -1; return -1;
@@ -359,8 +352,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// Make substitutions into odt of freetext // Make substitutions into odt of freetext
try { try {
$odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
@@ -374,7 +366,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$array_other = $this->get_substitutionarray_other($outputlangs); $array_other = $this->get_substitutionarray_other($outputlangs);
// retrieve contact information for use in object as contact_xxx tags // retrieve contact information for use in object as contact_xxx tags
$array_thirdparty_contact = array(); $array_thirdparty_contact = array();
if ($usecontact && is_object($contactobject)) $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); if ($usecontact && is_object($contactobject)) {
$array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
}
$tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact); $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact);
complete_substitutions_array($tmparray, $outputlangs, $object); complete_substitutions_array($tmparray, $outputlangs, $object);
@@ -383,19 +377,20 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
$reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
foreach ($tmparray as $key=>$value) foreach ($tmparray as $key => $value) {
{
try { try {
if (preg_match('/logo$/', $key)) { if (preg_match('/logo$/', $key)) {
// Image // Image
if (file_exists($value)) $odfHandler->setImage($key, $value); if (file_exists($value)) {
else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); $odfHandler->setImage($key, $value);
} else {
$odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
}
} else { } else {
// Text // Text
$odfHandler->setVars($key, $value, true, 'UTF-8'); $odfHandler->setVars($key, $value, true, 'UTF-8');
} }
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
} }
@@ -404,32 +399,26 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$foundtagforlines = 1; $foundtagforlines = 1;
try { try {
$listlines = $odfHandler->setSegment('lines'); $listlines = $odfHandler->setSegment('lines');
} catch (OdfException $e) } catch (OdfException $e) {
{
// We may arrive here if tags for lines not present into template // We may arrive here if tags for lines not present into template
$foundtagforlines = 0; $foundtagforlines = 0;
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
if ($foundtagforlines) if ($foundtagforlines) {
{
$linenumber = 0; $linenumber = 0;
foreach ($object->lines as $line) foreach ($object->lines as $line) {
{
$linenumber++; $linenumber++;
$tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber); $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber);
complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
// Call the ODTSubstitutionLine hook // Call the ODTSubstitutionLine hook
$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line); $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line);
$reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
foreach ($tmparray as $key => $val) foreach ($tmparray as $key => $val) {
{
try { try {
$listlines->setVars($key, $val, true, 'UTF-8'); $listlines->setVars($key, $val, true, 'UTF-8');
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} catch (SegmentException $e) } catch (SegmentException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
} }
@@ -437,8 +426,7 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
} }
$odfHandler->mergeSegment($listlines); $odfHandler->mergeSegment($listlines);
} }
} catch (OdfException $e) } catch (OdfException $e) {
{
$this->error = $e->getMessage(); $this->error = $e->getMessage();
dol_syslog($this->error, LOG_WARNING); dol_syslog($this->error, LOG_WARNING);
return -1; return -1;
@@ -446,12 +434,10 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
// Replace labels translated // Replace labels translated
$tmparray = $outputlangs->get_translations_for_substitutions(); $tmparray = $outputlangs->get_translations_for_substitutions();
foreach ($tmparray as $key=>$value) foreach ($tmparray as $key => $value) {
{
try { try {
$odfHandler->setVars($key, $value, true, 'UTF-8'); $odfHandler->setVars($key, $value, true, 'UTF-8');
} catch (OdfException $e) } catch (OdfException $e) {
{
dol_syslog($e->getMessage(), LOG_INFO); dol_syslog($e->getMessage(), LOG_INFO);
} }
} }
@@ -483,8 +469,9 @@ class doc_generic_myobject_odt extends ModelePDFMyObject
$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
$reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if (!empty($conf->global->MAIN_UMASK)) if (!empty($conf->global->MAIN_UMASK)) {
@chmod($file, octdec($conf->global->MAIN_UMASK)); @chmod($file, octdec($conf->global->MAIN_UMASK));
}
$odfHandler = null; // Destroy object $odfHandler = null; // Destroy object

View File

@@ -163,7 +163,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Get source company // Get source company
$this->emetteur = $mysoc; $this->emetteur = $mysoc;
if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined if (empty($this->emetteur->country_code)) {
$this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
}
// Define position of columns // Define position of columns
$this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff $this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff
@@ -201,9 +203,13 @@ class pdf_standard_myobject extends ModelePDFMyObject
dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
if (!is_object($outputlangs)) $outputlangs = $langs; if (!is_object($outputlangs)) {
$outputlangs = $langs;
}
// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; if (!empty($conf->global->MAIN_USE_FPDF)) {
$outputlangs->charset_output = 'ISO-8859-1';
}
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies"));
@@ -226,67 +232,65 @@ class pdf_standard_myobject extends ModelePDFMyObject
$realpatharray = array(); $realpatharray = array();
$this->atleastonephoto = false; $this->atleastonephoto = false;
/* /*
if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE))
{ {
$objphoto = new Product($this->db); $objphoto = new Product($this->db);
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++)
{ {
if (empty($object->lines[$i]->fk_product)) continue; if (empty($object->lines[$i]->fk_product)) continue;
$objphoto->fetch($object->lines[$i]->fk_product); $objphoto->fetch($object->lines[$i]->fk_product);
//var_dump($objphoto->ref);exit; //var_dump($objphoto->ref);exit;
if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
{ {
$pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/";
$pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/';
} else { } else {
$pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default
$pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative
} }
$arephoto = false; $arephoto = false;
foreach ($pdir as $midir) foreach ($pdir as $midir)
{ {
if (!$arephoto) if (!$arephoto)
{ {
$dir = $conf->product->dir_output.'/'.$midir; $dir = $conf->product->dir_output.'/'.$midir;
foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) foreach ($objphoto->liste_photos($dir, 1) as $key => $obj)
{ {
if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo
{ {
if ($obj['photo_vignette']) if ($obj['photo_vignette'])
{ {
$filename = $obj['photo_vignette']; $filename = $obj['photo_vignette'];
} else { } else {
$filename = $obj['photo']; $filename = $obj['photo'];
} }
} else { } else {
$filename = $obj['photo']; $filename = $obj['photo'];
} }
$realpath = $dir.$filename; $realpath = $dir.$filename;
$arephoto = true; $arephoto = true;
$this->atleastonephoto = true; $this->atleastonephoto = true;
} }
} }
} }
if ($realpath && $arephoto) $realpatharray[$i] = $realpath; if ($realpath && $arephoto) $realpatharray[$i] = $realpath;
} }
} }
*/ */
//if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva;
if ($conf->mymodule->dir_output.'/myobject') if ($conf->mymodule->dir_output.'/myobject') {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
// Definition of $dir and $file // Definition of $dir and $file
if ($object->specimen) if ($object->specimen) {
{
$dir = $conf->mymodule->dir_output.'/myobject'; $dir = $conf->mymodule->dir_output.'/myobject';
$file = $dir."/SPECIMEN.pdf"; $file = $dir."/SPECIMEN.pdf";
} else { } else {
@@ -294,20 +298,16 @@ class pdf_standard_myobject extends ModelePDFMyObject
$dir = $conf->mymodule->dir_output.'/myobject/'.$objectref; $dir = $conf->mymodule->dir_output.'/myobject/'.$objectref;
$file = $dir."/".$objectref.".pdf"; $file = $dir."/".$objectref.".pdf";
} }
if (!file_exists($dir)) if (!file_exists($dir)) {
{ if (dol_mkdir($dir) < 0) {
if (dol_mkdir($dir) < 0)
{
$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
return 0; return 0;
} }
} }
if (file_exists($dir)) if (file_exists($dir)) {
{
// Add pdfgeneration hook // Add pdfgeneration hook
if (!is_object($hookmanager)) if (!is_object($hookmanager)) {
{
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($this->db); $hookmanager = new HookManager($this->db);
} }
@@ -328,16 +328,14 @@ class pdf_standard_myobject extends ModelePDFMyObject
$heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page
$heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin)
if (class_exists('TCPDF')) if (class_exists('TCPDF')) {
{
$pdf->setPrintHeader(false); $pdf->setPrintHeader(false);
$pdf->setPrintFooter(false); $pdf->setPrintFooter(false);
} }
$pdf->SetFont(pdf_getPDFFont($outputlangs)); $pdf->SetFont(pdf_getPDFFont($outputlangs));
// Set path to the background PDF File // Set path to the background PDF File
if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) {
{
$pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
$tplidx = $pdf->importPage(1); $tplidx = $pdf->importPage(1);
} }
@@ -351,7 +349,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pdf->SetCreator("Dolibarr ".DOL_VERSION); $pdf->SetCreator("Dolibarr ".DOL_VERSION);
$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name));
if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
$pdf->SetCompression(false);
}
// Set certificate // Set certificate
$cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT;
@@ -374,7 +374,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
// New page // New page
$pdf->AddPage(); $pdf->AddPage();
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pagenb++; $pagenb++;
$top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis);
@@ -386,7 +388,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10);
$tab_height = 130 - $top_shift; $tab_height = 130 - $top_shift;
$tab_height_newpage = 150; $tab_height_newpage = 150;
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$tab_height_newpage -= $top_shift;
}
$nexY = $tab_top - 1; $nexY = $tab_top - 1;
@@ -394,14 +398,12 @@ class pdf_standard_myobject extends ModelePDFMyObject
$notetoshow = empty($object->note_public) ? '' : $object->note_public; $notetoshow = empty($object->note_public) ? '' : $object->note_public;
// Extrafields in note // Extrafields in note
$extranote = $this->getExtrafieldsInHtml($object, $outputlangs); $extranote = $this->getExtrafieldsInHtml($object, $outputlangs);
if (!empty($extranote)) if (!empty($extranote)) {
{
$notetoshow = dol_concatdesc($notetoshow, $extranote); $notetoshow = dol_concatdesc($notetoshow, $extranote);
} }
$pagenb = $pdf->getPage(); $pagenb = $pdf->getPage();
if ($notetoshow) if ($notetoshow) {
{
$tab_top -= 2; $tab_top -= 2;
$tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite;
@@ -420,16 +422,19 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pageposafternote = $pdf->getPage(); $pageposafternote = $pdf->getPage();
$posyafter = $pdf->GetY(); $posyafter = $pdf->GetY();
if ($pageposafternote > $pageposbeforenote) if ($pageposafternote > $pageposbeforenote) {
{
$pdf->rollbackTransaction(true); $pdf->rollbackTransaction(true);
// prepare pages to receive notes // prepare pages to receive notes
while ($pagenb < $pageposafternote) { while ($pagenb < $pageposafternote) {
$pdf->AddPage(); $pdf->AddPage();
$pagenb++; $pagenb++;
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->useTemplate($tplidx);
}
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
// $this->_pagefoot($pdf,$object,$outputlangs,1); // $this->_pagefoot($pdf,$object,$outputlangs,1);
$pdf->setTopMargin($tab_top_newpage); $pdf->setTopMargin($tab_top_newpage);
// The only function to edit the bottom margin of current page to set it. // The only function to edit the bottom margin of current page to set it.
@@ -445,8 +450,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
$posyafter = $pdf->GetY(); $posyafter = $pdf->GetY();
if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // There is no space left for total+free text
{
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
$pagenb++; $pagenb++;
$pageposafternote++; $pageposafternote++;
@@ -483,8 +487,12 @@ class pdf_standard_myobject extends ModelePDFMyObject
// apply note frame to last page // apply note frame to last page
$pdf->setPage($pageposafternote); $pdf->setPage($pageposafternote);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->useTemplate($tplidx);
}
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
$height_note = $posyafter - $tab_top_newpage; $height_note = $posyafter - $tab_top_newpage;
$pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1);
} else // No pagebreak } else // No pagebreak
@@ -495,15 +503,18 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1);
if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) {
{
// not enough space, need to add page // not enough space, need to add page
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
$pagenb++; $pagenb++;
$pageposafternote++; $pageposafternote++;
$pdf->setPage($pageposafternote); $pdf->setPage($pageposafternote);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->useTemplate($tplidx);
}
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
$posyafter = $tab_top_newpage; $posyafter = $tab_top_newpage;
} }
@@ -528,15 +539,16 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Loop on each lines // Loop on each lines
$pageposbeforeprintlines = $pdf->getPage(); $pageposbeforeprintlines = $pdf->getPage();
$pagenb = $pageposbeforeprintlines; $pagenb = $pageposbeforeprintlines;
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{
$curY = $nexY; $curY = $nexY;
$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
$pdf->SetTextColor(0, 0, 0); $pdf->SetTextColor(0, 0, 0);
// Define size of image if we need it // Define size of image if we need it
$imglinesize = array(); $imglinesize = array();
if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); if (!empty($realpatharray[$i])) {
$imglinesize = pdf_getSizeForImage($realpatharray[$i]);
}
$pdf->setTopMargin($tab_top_newpage); $pdf->setTopMargin($tab_top_newpage);
$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
@@ -545,25 +557,26 @@ class pdf_standard_myobject extends ModelePDFMyObject
$showpricebeforepagebreak = 1; $showpricebeforepagebreak = 1;
$posYAfterImage = 0; $posYAfterImage = 0;
if ($this->getColumnStatus('photo')) if ($this->getColumnStatus('photo')) {
{
// We start with Photo of product line // We start with Photo of product line
if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // If photo too high, we moved completely on new page
{
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pdf->setPage($pageposbefore + 1); $pdf->setPage($pageposbefore + 1);
$curY = $tab_top_newpage; $curY = $tab_top_newpage;
// Allows data in the first page if description is long enough to break in multiples pages // Allows data in the first page if description is long enough to break in multiples pages
if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) {
$showpricebeforepagebreak = 1; $showpricebeforepagebreak = 1;
else $showpricebeforepagebreak = 0; } else {
$showpricebeforepagebreak = 0;
}
} }
if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) {
{
$pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
// $pdf->Image does not increase value return by getY, so we save it manually // $pdf->Image does not increase value return by getY, so we save it manually
$posYAfterImage = $curY + $imglinesize['height']; $posYAfterImage = $curY + $imglinesize['height'];
@@ -571,15 +584,13 @@ class pdf_standard_myobject extends ModelePDFMyObject
} }
// Description of product line // Description of product line
if ($this->getColumnStatus('desc')) if ($this->getColumnStatus('desc')) {
{
$pdf->startTransaction(); $pdf->startTransaction();
$this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc);
$pageposafter = $pdf->getPage(); $pageposafter = $pdf->getPage();
if ($pageposafter > $pageposbefore) // There is a pagebreak if ($pageposafter > $pageposbefore) { // There is a pagebreak
{
$pdf->rollbackTransaction(true); $pdf->rollbackTransaction(true);
$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
@@ -588,20 +599,22 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pageposafter = $pdf->getPage(); $pageposafter = $pdf->getPage();
$posyafter = $pdf->GetY(); $posyafter = $pdf->GetY();
//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text
{ if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page
if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page
{
$pdf->AddPage('', '', true); $pdf->AddPage('', '', true);
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pdf->setPage($pageposafter + 1); $pdf->setPage($pageposafter + 1);
} }
} else { } else {
// We found a page break // We found a page break
// Allows data in the first page if description is long enough to break in multiples pages // Allows data in the first page if description is long enough to break in multiples pages
if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) {
$showpricebeforepagebreak = 1; $showpricebeforepagebreak = 1;
else $showpricebeforepagebreak = 0; } else {
$showpricebeforepagebreak = 0;
}
} }
} else // No pagebreak } else // No pagebreak
{ {
@@ -624,8 +637,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Quantity // Quantity
// Enough for 6 chars // Enough for 6 chars
if ($this->getColumnStatus('qty')) if ($this->getColumnStatus('qty')) {
{
$qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails);
$this->printStdColumnContent($pdf, $curY, 'qty', $qty); $this->printStdColumnContent($pdf, $curY, 'qty', $qty);
$nexY = max($pdf->GetY(), $nexY); $nexY = max($pdf->GetY(), $nexY);
@@ -634,8 +646,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Extrafields // Extrafields
if (!empty($object->lines[$i]->array_options)) { if (!empty($object->lines[$i]->array_options)) {
foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) {
if ($this->getColumnStatus($extrafieldColKey)) if ($this->getColumnStatus($extrafieldColKey)) {
{
$extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey);
$this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue);
$nexY = max($pdf->GetY(), $nexY); $nexY = max($pdf->GetY(), $nexY);
@@ -659,13 +670,18 @@ class pdf_standard_myobject extends ModelePDFMyObject
$sign = 1; $sign = 1;
// Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
$prev_progress = $object->lines[$i]->get_prev_progress($object->id); $prev_progress = $object->lines[$i]->get_prev_progress($object->id);
if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) // Compute progress from previous situation if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) { // Compute progress from previous situation
{ if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) {
if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent;
else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; } else {
$tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent;
}
} else { } else {
if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) {
else $tvaligne = $sign * $object->lines[$i]->total_tva; $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva;
} else {
$tvaligne = $sign * $object->lines[$i]->total_tva;
}
} }
$localtax1ligne = $object->lines[$i]->total_localtax1; $localtax1ligne = $object->lines[$i]->total_localtax1;
@@ -675,16 +691,21 @@ class pdf_standard_myobject extends ModelePDFMyObject
$localtax1_type = $object->lines[$i]->localtax1_type; $localtax1_type = $object->lines[$i]->localtax1_type;
$localtax2_type = $object->lines[$i]->localtax2_type; $localtax2_type = $object->lines[$i]->localtax2_type;
if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; if ($object->remise_percent) {
if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; $tvaligne -= ($tvaligne * $object->remise_percent) / 100;
if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; }
if ($object->remise_percent) {
$localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100;
}
if ($object->remise_percent) {
$localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100;
}
$vatrate = (string) $object->lines[$i]->tva_tx; $vatrate = (string) $object->lines[$i]->tva_tx;
// Retrieve type from database for backward compatibility with old records // Retrieve type from database for backward compatibility with old records
if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined
&& (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax && (!empty($localtax1_rate) || !empty($localtax2_rate))) { // and there is local tax
{
$localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc);
$localtax1_type = isset($localtaxtmp_array[0]) ? $localtaxtmp_array[0] : ''; $localtax1_type = isset($localtaxtmp_array[0]) ? $localtaxtmp_array[0] : '';
$localtax2_type = isset($localtaxtmp_array[2]) ? $localtaxtmp_array[2] : ''; $localtax2_type = isset($localtaxtmp_array[2]) ? $localtaxtmp_array[2] : '';
@@ -698,8 +719,12 @@ class pdf_standard_myobject extends ModelePDFMyObject
$this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne;
} }
if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; if (($object->lines[$i]->info_bits & 0x01) == 0x01) {
if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; $vatrate .= '*';
}
if (!isset($this->tva[$vatrate])) {
$this->tva[$vatrate] = 0;
}
$this->tva[$vatrate] += $tvaligne; $this->tva[$vatrate] += $tvaligne;
$nexY = max($nexY, $posYAfterImage); $nexY = max($nexY, $posYAfterImage);
@@ -725,7 +750,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pagenb++; $pagenb++;
$pdf->setPage($pagenb); $pdf->setPage($pagenb);
$pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it.
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
} }
if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) {
@@ -737,15 +764,18 @@ class pdf_standard_myobject extends ModelePDFMyObject
$this->_pagefoot($pdf, $object, $outputlangs, 1); $this->_pagefoot($pdf, $object, $outputlangs, 1);
// New page // New page
$pdf->AddPage(); $pdf->AddPage();
if (!empty($tplidx)) $pdf->useTemplate($tplidx); if (!empty($tplidx)) {
$pdf->useTemplate($tplidx);
}
$pagenb++; $pagenb++;
if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
$this->_pagehead($pdf, $object, 0, $outputlangs);
}
} }
} }
// Show square // Show square
if ($pagenb == $pageposbeforeprintlines) if ($pagenb == $pageposbeforeprintlines) {
{
$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis);
$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
} else { } else {
@@ -761,15 +791,17 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Display payment area // Display payment area
/* /*
if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS))
{ {
$posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs);
} }
*/ */
// Pagefoot // Pagefoot
$this->_pagefoot($pdf, $object, $outputlangs); $this->_pagefoot($pdf, $object, $outputlangs);
if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); if (method_exists($pdf, 'AliasNbPages')) {
$pdf->AliasNbPages();
}
$pdf->Close(); $pdf->Close();
@@ -780,14 +812,14 @@ class pdf_standard_myobject extends ModelePDFMyObject
$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
global $action; global $action;
$reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) if ($reshook < 0) {
{
$this->error = $hookmanager->error; $this->error = $hookmanager->error;
$this->errors = $hookmanager->errors; $this->errors = $hookmanager->errors;
} }
if (!empty($conf->global->MAIN_UMASK)) if (!empty($conf->global->MAIN_UMASK)) {
@chmod($file, octdec($conf->global->MAIN_UMASK)); @chmod($file, octdec($conf->global->MAIN_UMASK));
}
$this->result = array('fullpath'=>$file); $this->result = array('fullpath'=>$file);
@@ -837,7 +869,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Force to disable hidetop and hidebottom // Force to disable hidetop and hidebottom
$hidebottom = 0; $hidebottom = 0;
if ($hidetop) $hidetop = -1; if ($hidetop) {
$hidetop = -1;
}
$currency = !empty($currency) ? $currency : $conf->currency; $currency = !empty($currency) ? $currency : $conf->currency;
$default_font_size = pdf_getPDFFontSize($outputlangs); $default_font_size = pdf_getPDFFontSize($outputlangs);
@@ -846,8 +880,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pdf->SetTextColor(0, 0, 0); $pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('', '', $default_font_size - 2); $pdf->SetFont('', '', $default_font_size - 2);
if (empty($hidetop)) if (empty($hidetop)) {
{
$titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency));
if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) { if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) {
$titre .= ' - '.$outputlangsbis->transnoentities("AmountInCurrency", $outputlangsbis->transnoentitiesnoconv("Currency".$currency)); $titre .= ' - '.$outputlangsbis->transnoentities("AmountInCurrency", $outputlangsbis->transnoentitiesnoconv("Currency".$currency));
@@ -899,8 +932,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); pdf_pagehead($pdf, $outputlangs, $this->page_hauteur);
// Show Draft Watermark // Show Draft Watermark
if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) {
{
pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK);
} }
@@ -915,20 +947,18 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pdf->SetXY($this->marge_gauche, $posy); $pdf->SetXY($this->marge_gauche, $posy);
// Logo // Logo
if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) {
{ if ($this->emetteur->logo) {
if ($this->emetteur->logo)
{
$logodir = $conf->mycompany->dir_output; $logodir = $conf->mycompany->dir_output;
if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; if (!empty($conf->mycompany->multidir_output[$object->entity])) {
if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) $logodir = $conf->mycompany->multidir_output[$object->entity];
{ }
if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) {
$logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small;
} else { } else {
$logo = $logodir.'/logos/'.$this->emetteur->logo; $logo = $logodir.'/logos/'.$this->emetteur->logo;
} }
if (is_readable($logo)) if (is_readable($logo)) {
{
$height = pdf_getHeightForLogo($logo); $height = pdf_getHeightForLogo($logo);
$pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
} else { } else {
@@ -959,8 +989,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
$textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref); $textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref);
if ($object->statut == $object::STATUS_DRAFT) if ($object->statut == $object::STATUS_DRAFT) {
{
$pdf->SetTextColor(128, 0, 0); $pdf->SetTextColor(128, 0, 0);
$textref .= ' - '.$outputlangs->transnoentities("NotValidated"); $textref .= ' - '.$outputlangs->transnoentities("NotValidated");
} }
@@ -969,19 +998,16 @@ class pdf_standard_myobject extends ModelePDFMyObject
$posy += 1; $posy += 1;
$pdf->SetFont('', '', $default_font_size - 2); $pdf->SetFont('', '', $default_font_size - 2);
if ($object->ref_client) if ($object->ref_client) {
{
$posy += 4; $posy += 4;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
$pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R');
} }
if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) {
{
$object->fetch_projet(); $object->fetch_projet();
if (!empty($object->project->ref)) if (!empty($object->project->ref)) {
{
$posy += 3; $posy += 3;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
@@ -989,11 +1015,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
} }
} }
if (!empty($conf->global->PDF_SHOW_PROJECT)) if (!empty($conf->global->PDF_SHOW_PROJECT)) {
{
$object->fetch_projet(); $object->fetch_projet();
if (!empty($object->project->ref)) if (!empty($object->project->ref)) {
{
$posy += 3; $posy += 3;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
@@ -1011,8 +1035,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
} }
$pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date, "day", false, $outputlangs), '', 'R'); $pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date, "day", false, $outputlangs), '', 'R');
if ($object->thirdparty->code_client) if ($object->thirdparty->code_client) {
{
$posy += 3; $posy += 3;
$pdf->SetXY($posx, $posy); $pdf->SetXY($posx, $posy);
$pdf->SetTextColor(0, 0, 60); $pdf->SetTextColor(0, 0, 60);
@@ -1020,11 +1043,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
} }
// Get contact // Get contact
if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) {
{
$arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL');
if (count($arrayidcontact) > 0) if (count($arrayidcontact) > 0) {
{
$usertmp = new User($this->db); $usertmp = new User($this->db);
$usertmp->fetch($arrayidcontact[0]); $usertmp->fetch($arrayidcontact[0]);
$posy += 4; $posy += 4;
@@ -1040,13 +1061,11 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Show list of linked objects // Show list of linked objects
$current_y = $pdf->getY(); $current_y = $pdf->getY();
$posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size);
if ($current_y < $pdf->getY()) if ($current_y < $pdf->getY()) {
{
$top_shift = $pdf->getY() - $current_y; $top_shift = $pdf->getY() - $current_y;
} }
if ($showaddress) if ($showaddress) {
{
// Sender properties // Sender properties
$carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); $carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object);
@@ -1054,7 +1073,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
$posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
$posy += $top_shift; $posy += $top_shift;
$posx = $this->marge_gauche; $posx = $this->marge_gauche;
if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
$posx = $this->page_largeur - $this->marge_droite - 80;
}
$hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
$widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
@@ -1084,8 +1105,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
// If BILLING contact defined on invoice, we use it // If BILLING contact defined on invoice, we use it
$usecontact = false; $usecontact = false;
$arrayidcontact = $object->getIdContact('external', 'BILLING'); $arrayidcontact = $object->getIdContact('external', 'BILLING');
if (count($arrayidcontact) > 0) if (count($arrayidcontact) > 0) {
{
$usecontact = true; $usecontact = true;
$result = $object->fetch_contact($arrayidcontact[0]); $result = $object->fetch_contact($arrayidcontact[0]);
} }
@@ -1105,11 +1125,15 @@ class pdf_standard_myobject extends ModelePDFMyObject
// Show recipient // Show recipient
$widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format if ($this->page_largeur < 210) {
$widthrecbox = 84; // To work with US executive format
}
$posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
$posy += $top_shift; $posy += $top_shift;
$posx = $this->page_largeur - $this->marge_droite - $widthrecbox; $posx = $this->page_largeur - $this->marge_droite - $widthrecbox;
if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
$posx = $this->marge_gauche;
}
// Show recipient frame // Show recipient frame
$pdf->SetTextColor(0, 0, 0); $pdf->SetTextColor(0, 0, 0);
@@ -1179,22 +1203,22 @@ class pdf_standard_myobject extends ModelePDFMyObject
); );
/* /*
* For exemple * For exemple
$this->cols['theColKey'] = array( $this->cols['theColKey'] = array(
'rank' => $rank, // int : use for ordering columns 'rank' => $rank, // int : use for ordering columns
'width' => 20, // the column width in mm 'width' => 20, // the column width in mm
'title' => array( 'title' => array(
'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label
'label' => ' ', // the final label : used fore final generated text 'label' => ' ', // the final label : used fore final generated text
'align' => 'L', // text alignement : R,C,L 'align' => 'L', // text alignement : R,C,L
'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left
), ),
'content' => array( 'content' => array(
'align' => 'L', // text alignement : R,C,L 'align' => 'L', // text alignement : R,C,L
'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left
), ),
); );
*/ */
$rank = 0; // do not use negative rank $rank = 0; // do not use negative rank
$this->cols['desc'] = array( $this->cols['desc'] = array(
@@ -1230,8 +1254,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
'border-left' => false, // remove left line separator 'border-left' => false, // remove left line separator
); );
if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) {
{
$this->cols['photo']['status'] = true; $this->cols['photo']['status'] = true;
} }
@@ -1247,8 +1270,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
'border-left' => true, // add left line separator 'border-left' => true, // add left line separator
); );
if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) {
{
$this->cols['vat']['status'] = true; $this->cols['vat']['status'] = true;
} }
@@ -1285,8 +1307,7 @@ class pdf_standard_myobject extends ModelePDFMyObject
'border-left' => true, // add left line separator 'border-left' => true, // add left line separator
); );
if ($this->situationinvoice) if ($this->situationinvoice) {
{
$this->cols['progress']['status'] = true; $this->cols['progress']['status'] = true;
} }
@@ -1344,11 +1365,9 @@ class pdf_standard_myobject extends ModelePDFMyObject
); );
$reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook
if ($reshook < 0) if ($reshook < 0) {
{
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
} elseif (empty($reshook)) } elseif (empty($reshook)) {
{
$this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys
} else { } else {
$this->cols = $hookmanager->resArray; $this->cols = $hookmanager->resArray;

View File

@@ -113,8 +113,7 @@ class mod_myobject_advanced extends ModeleNumRefMyObject
/*$mysoc->code_client = $old_code_client; /*$mysoc->code_client = $old_code_client;
$mysoc->typent_code = $old_code_type;*/ $mysoc->typent_code = $old_code_type;*/
if (!$numExample) if (!$numExample) {
{
$numExample = $langs->trans('NotConfigured'); $numExample = $langs->trans('NotConfigured');
} }
return $numExample; return $numExample;
@@ -135,8 +134,7 @@ class mod_myobject_advanced extends ModeleNumRefMyObject
// We get cursor rule // We get cursor rule
$mask = $conf->global->MYMODULE_MYOBJECT_ADVANCED_MASK; $mask = $conf->global->MYMODULE_MYOBJECT_ADVANCED_MASK;
if (!$mask) if (!$mask) {
{
$this->error = 'NotConfigured'; $this->error = 'NotConfigured';
return 0; return 0;
} }

View File

@@ -96,13 +96,13 @@ class mod_myobject_standard extends ModeleNumRefMyObject
} }
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$row = $db->fetch_row($resql); $row = $db->fetch_row($resql);
if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } if ($row) {
$coyymm = substr($row[0], 0, 6); $max = $row[0];
}
} }
if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) {
{
$langs->load("errors"); $langs->load("errors");
$this->error = $langs->trans('ErrorNumRefModel', $max); $this->error = $langs->trans('ErrorNumRefModel', $max);
return false; return false;
@@ -133,11 +133,13 @@ class mod_myobject_standard extends ModeleNumRefMyObject
} }
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) $max = intval($obj->max); if ($obj) {
else $max = 0; $max = intval($obj->max);
} else {
$max = 0;
}
} else { } else {
dol_syslog("mod_myobject_standard::getNextValue", LOG_DEBUG); dol_syslog("mod_myobject_standard::getNextValue", LOG_DEBUG);
return -1; return -1;
@@ -147,8 +149,11 @@ class mod_myobject_standard extends ModeleNumRefMyObject
$date = $object->date_creation; $date = $object->date_creation;
$yymm = strftime("%y%m", $date); $yymm = strftime("%y%m", $date);
if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is if ($max >= (pow(10, 4) - 1)) {
else $num = sprintf("%04s", $max + 1); $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is
} else {
$num = sprintf("%04s", $max + 1);
}
dol_syslog("mod_myobject_standard::getNextValue return ".$this->prefix.$yymm."-".$num); dol_syslog("mod_myobject_standard::getNextValue return ".$this->prefix.$yymm."-".$num);
return $this->prefix.$yymm."-".$num; return $this->prefix.$yymm."-".$num;

View File

@@ -141,10 +141,18 @@ abstract class ModeleNumRefMyObject
global $langs; global $langs;
$langs->load("admin"); $langs->load("admin");
if ($this->version == 'development') return $langs->trans("VersionDevelopment"); if ($this->version == 'development') {
if ($this->version == 'experimental') return $langs->trans("VersionExperimental"); return $langs->trans("VersionDevelopment");
if ($this->version == 'dolibarr') return DOL_VERSION; }
if ($this->version) return $this->version; if ($this->version == 'experimental') {
return $langs->trans("VersionExperimental");
}
if ($this->version == 'dolibarr') {
return DOL_VERSION;
}
if ($this->version) {
return $this->version;
}
return $langs->trans("NotAvailable"); return $langs->trans("NotAvailable");
} }
} }

View File

@@ -16,8 +16,7 @@
*/ */
// Protection to avoid direct call of template // 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"; print "Error, template page can't be called as URL";
exit; exit;
} }
@@ -36,12 +35,13 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock'];
$langs->load("mymodule"); $langs->load("mymodule");
$total = 0; $ilink = 0; $total = 0; $ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink) foreach ($linkedObjectBlock as $key => $objectlink) {
{
$ilink++; $ilink++;
$trclass = 'oddeven'; $trclass = 'oddeven';
if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) {
$trclass .= ' liste_sub_total';
}
?> ?>
<tr class="<?php echo $trclass; ?>"> <tr class="<?php echo $trclass; ?>">
<td><?php echo $langs->trans("MyObject"); ?></td> <td><?php echo $langs->trans("MyObject"); ?></td>

View File

@@ -92,7 +92,9 @@ class InterfaceMyModuleTriggers extends DolibarrTriggers
*/ */
public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
{ {
if (empty($conf->mymodule->enabled)) return 0; // If module is not enabled, we do nothing if (empty($conf->mymodule->enabled)) {
return 0; // If module is not enabled, we do nothing
}
// Put here code you want to execute when a Dolibarr business events occurs. // Put here code you want to execute when a Dolibarr business events occurs.
// Data and type of action are stored into $object and $action // Data and type of action are stored into $object and $action

View File

@@ -23,14 +23,26 @@
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled because need to load personalized language
//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled. Language code is found on url. //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled. Language code is found on url.
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled because need to do translations
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); if (!defined('NOCSRFCHECK')) {
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); define('NOCSRFCHECK', 1);
if (!defined('NOLOGIN')) define('NOLOGIN', 1); // File must be accessed by logon page so without login }
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', 1);
}
if (!defined('NOLOGIN')) {
define('NOLOGIN', 1); // File must be accessed by logon page so without login
}
//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); // We need top menu content
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); if (!defined('NOREQUIREHTML')) {
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); define('NOREQUIREHTML', 1);
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
session_cache_limiter('public'); session_cache_limiter('public');
// false or '' = keep cache instruction added by server // false or '' = keep cache instruction added by server
@@ -40,16 +52,30 @@ session_cache_limiter('public');
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $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(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/../main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/../main.inc.php";
}
// Try main.inc.php using relative path // 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")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; $res = @include "../../main.inc.php";
if (!$res) die("Include of main fails"); }
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';

View File

@@ -17,16 +17,36 @@
* Library javascript to enable Browser notifications * Library javascript to enable Browser notifications
*/ */
if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); if (!defined('NOREQUIREUSER')) {
if (!defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); define('NOREQUIREUSER', '1');
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); }
if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); if (!defined('NOREQUIREDB')) {
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); define('NOREQUIREDB', '1');
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); }
if (!defined('NOLOGIN')) define('NOLOGIN', 1); if (!defined('NOREQUIRESOC')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); define('NOREQUIRESOC', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOREQUIRETRAN')) {
define('NOREQUIRETRAN', '1');
}
if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', 1);
}
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', 1);
}
if (!defined('NOLOGIN')) {
define('NOLOGIN', 1);
}
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', 1);
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', 1);
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
/** /**
@@ -38,16 +58,30 @@ if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1');
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $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(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/../main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/../main.inc.php";
}
// Try main.inc.php using relative path // 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")) {
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; $res = @include "../../main.inc.php";
if (!$res) die("Include of main fails"); }
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
// Define js type // Define js type
header('Content-Type: application/javascript'); header('Content-Type: application/javascript');

View File

@@ -41,14 +41,19 @@ function myobjectPrepareHead($object)
$head[$h][2] = 'card'; $head[$h][2] = 'card';
$h++; $h++;
if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) {
{
$nbNote = 0; $nbNote = 0;
if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_private)) {
if (!empty($object->note_public)) $nbNote++; $nbNote++;
}
if (!empty($object->note_public)) {
$nbNote++;
}
$head[$h][0] = dol_buildpath('/mymodule/myobject_note.php', 1).'?id='.$object->id; $head[$h][0] = dol_buildpath('/mymodule/myobject_note.php', 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Notes'); $head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : ''); if ($nbNote > 0) {
$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : '');
}
$head[$h][2] = 'note'; $head[$h][2] = 'note';
$h++; $h++;
} }
@@ -60,7 +65,9 @@ function myobjectPrepareHead($object)
$nbLinks = Link::count($db, $object->element, $object->id); $nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = dol_buildpath("/mymodule/myobject_document.php", 1).'?id='.$object->id; $head[$h][0] = dol_buildpath("/mymodule/myobject_document.php", 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Documents'); $head[$h][1] = $langs->trans('Documents');
if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; if (($nbFiles + $nbLinks) > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
}
$head[$h][2] = 'document'; $head[$h][2] = 'document';
$h++; $h++;

View File

@@ -27,17 +27,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';

View File

@@ -46,17 +46,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; 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/lib/company.lib.php';

View File

@@ -46,17 +46,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.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.formfile.class.php';
@@ -464,7 +480,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) { if (empty($reshook)) {
// Send // Send

View File

@@ -25,17 +25,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';

View File

@@ -46,17 +46,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';

View File

@@ -46,17 +46,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.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/date.lib.php';
@@ -132,7 +148,9 @@ foreach ($object->fields as $key => $val) {
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) { foreach ($object->fields as $key => $val) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; if ($val['searchall']) {
$fieldstosearchall['t.'.$key] = $val['label'];
}
} }
// Definition of array of fields for columns // Definition of array of fields for columns
@@ -161,7 +179,9 @@ $permissiontoadd = $user->rights->mymodule->myobject->write;
$permissiontodelete = $user->rights->mymodule->myobject->delete; $permissiontodelete = $user->rights->mymodule->myobject->delete;
// Security check // Security check
if (empty($conf->mymodule->enabled)) accessforbidden('Module not enabled'); if (empty($conf->mymodule->enabled)) {
accessforbidden('Module not enabled');
}
$socid = 0; $socid = 0;
if ($user->socid > 0) { // Protection if external user if ($user->socid > 0) { // Protection if external user
//$socid = $user->socid; //$socid = $user->socid;
@@ -260,14 +280,21 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; if ($object->ismultientitymanaged == 1) {
else $sql .= " WHERE 1 = 1"; $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
} else {
$sql .= " WHERE 1 = 1";
}
foreach ($search as $key => $val) { foreach ($search as $key => $val) {
if (in_array($key, $object->fields)) { if (in_array($key, $object->fields)) {
if ($key == 'status' && $search[$key] == -1) continue; if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if (strpos($object->fields[$key]['type'], 'integer:') === 0) { if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
if ($search[$key] == '-1') $search[$key] = ''; if ($search[$key] == '-1') {
$search[$key] = '';
}
$mode_search = 2; $mode_search = 2;
} }
if ($search[$key] != '') { if ($search[$key] != '') {
@@ -330,7 +357,9 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
if ($limit) $sql .= $db->plimit($limit + 1, $offset); if ($limit) {
$sql .= $db->plimit($limit + 1, $offset);
}
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) { if (!$resql) {
@@ -550,7 +579,9 @@ print '</tr>'."\n";
$needToFetchEachLine = 0; $needToFetchEachLine = 0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object if (preg_match('/\$object/', $val)) {
$needToFetchEachLine++; // There is at least one compute field that use $object
}
} }
} }
@@ -618,11 +649,15 @@ while ($i < ($limit ? min($num, $limit) : $num)) {
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected = 0; $selected = 0;
if (in_array($object->id, $arrayofselected)) $selected = 1; if (in_array($object->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";

View File

@@ -46,17 +46,33 @@
// Load Dolibarr environment // Load Dolibarr environment
$res = 0; $res = 0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) // 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 // 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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$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"; $i--; $j--;
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"; }
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 // 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")) {
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../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");
}
dol_include_once('/mymodule/class/myobject.class.php'); dol_include_once('/mymodule/class/myobject.class.php');
dol_include_once('/mymodule/lib/mymodule_myobject.lib.php'); dol_include_once('/mymodule/lib/mymodule_myobject.lib.php');

View File

@@ -46,13 +46,25 @@ define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to
$res = 0; $res = 0;
// Try master.inc.php into web root detected using web root calculated from SCRIPT_FILENAME // Try master.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; $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--; } while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/master.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/master.inc.php"; $i--; $j--;
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php"; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/master.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/master.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php")) {
$res = @include dirname(substr($tmp, 0, ($i + 1)))."/master.inc.php";
}
// Try master.inc.php using relative path // Try master.inc.php using relative path
if (!$res && file_exists("../master.inc.php")) $res = @include "../master.inc.php"; if (!$res && file_exists("../master.inc.php")) {
if (!$res && file_exists("../../master.inc.php")) $res = @include "../../master.inc.php"; $res = @include "../master.inc.php";
if (!$res && file_exists("../../../master.inc.php")) $res = @include "../../../master.inc.php"; }
if (!$res && file_exists("../../master.inc.php")) {
$res = @include "../../master.inc.php";
}
if (!$res && file_exists("../../../master.inc.php")) {
$res = @include "../../../master.inc.php";
}
if (!$res) { if (!$res) {
print "Include of master fails"; print "Include of master fails";
exit(-1); exit(-1);
@@ -65,7 +77,9 @@ $langs->load("main"); // To load language file for default language
// Load user and its permissions // Load user and its permissions
$result = $user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. $result = $user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user.
if (!$result > 0) { dol_print_error('', $user->error); exit; } if (!$result > 0) {
dol_print_error('', $user->error); exit;
}
$user->getrights(); $user->getrights();
@@ -162,8 +176,7 @@ else
// -------------------- END OF YOUR CODE -------------------- // -------------------- END OF YOUR CODE --------------------
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
print '--- end ok'."\n"; print '--- end ok'."\n";
} else { } else {

View File

@@ -22,13 +22,25 @@
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //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('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('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); if (!defined('NOCSRFCHECK')) {
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); define('NOCSRFCHECK', '1');
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); }
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); 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'; require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
@@ -43,12 +55,11 @@ $action = GETPOST('action', 'aZ09');
$object = new BOM($db); $object = new BOM($db);
$result = $object->fetch($idbom); $result = $object->fetch($idbom);
if ($result > 0) if ($result > 0) {
{
// We remove properties we don't need in answer // We remove properties we don't need in answer
unset($object->fields); unset($object->fields);
unset($object->db); unset($object->db);
echo json_encode($object); echo json_encode($object);
} else { } else {
echo 'Failed to load category with id='.$idbom; echo 'Failed to load category with id='.$idbom;
} }

View File

@@ -208,25 +208,24 @@ class Mo extends CommonObject
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) foreach ($val['arrayofkeyval'] as $key2 => $val2) {
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@@ -305,7 +304,9 @@ class Mo extends CommonObject
// Load source object // Load source object
$result = $object->fetchCommon($fromid); $result = $object->fetchCommon($fromid);
if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); if ($result > 0 && !empty($object->table_element_line)) {
$object->fetchLines();
}
// get lines so they will be clone // get lines so they will be clone
//foreach($this->lines as $line) //foreach($this->lines as $line)
@@ -322,14 +323,11 @@ class Mo extends CommonObject
$object->status = self::STATUS_DRAFT; $object->status = self::STATUS_DRAFT;
// ... // ...
// Clear extrafields that are unique // Clear extrafields that are unique
if (is_array($object->array_options) && count($object->array_options) > 0) if (is_array($object->array_options) && count($object->array_options) > 0) {
{
$extrafields->fetch_name_optionals_label($this->table_element); $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); $shortkey = preg_replace('/options_/', '', $key);
if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
{
//var_dump($key); var_dump($clonedObj->array_options[$key]); exit; //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
unset($object->array_options[$key]); unset($object->array_options[$key]);
} }
@@ -345,22 +343,19 @@ class Mo extends CommonObject
$this->errors = $object->errors; $this->errors = $object->errors;
} }
if (!$error) if (!$error) {
{
// copy internal contacts // copy internal contacts
if ($this->copy_linked_contact($object, 'internal') < 0) if ($this->copy_linked_contact($object, 'internal') < 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
// copy external contacts if same company // copy external contacts if same company
if (property_exists($this, 'socid') && $this->socid == $object->socid) if (property_exists($this, 'socid') && $this->socid == $object->socid) {
{ if ($this->copy_linked_contact($object, 'external') < 0) {
if ($this->copy_linked_contact($object, 'external') < 0)
$error++; $error++;
}
} }
} }
@@ -386,7 +381,9 @@ class Mo extends CommonObject
public function fetch($id, $ref = null) public function fetch($id, $ref = null)
{ {
$result = $this->fetchCommon($id, $ref); $result = $this->fetchCommon($id, $ref);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); if ($result > 0 && !empty($this->table_element_line)) {
$this->fetchLines();
}
return $result; return $result;
} }
@@ -426,8 +423,11 @@ class Mo extends CommonObject
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@@ -458,8 +458,7 @@ class Mo extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < min($limit, $num)) while ($i < min($limit, $num)) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$record = new self($this->db); $record = new self($this->db);
@@ -496,8 +495,11 @@ class Mo extends CommonObject
$sql .= $mostatic->getFieldList(); $sql .= $mostatic->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t';
$sql .= " WHERE t.role = '".$this->db->escape($role)."'"; $sql .= " WHERE t.role = '".$this->db->escape($role)."'";
if ($lineid > 0) $sql .= ' AND t.fk_mrp_production = '.$lineid; if ($lineid > 0) {
else $sql .= 'AND t.fk_mo = '.$this->id; $sql .= ' AND t.fk_mrp_production = '.$lineid;
} else {
$sql .= 'AND t.fk_mo = '.$this->id;
}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
@@ -618,8 +620,7 @@ class Mo extends CommonObject
$this->db->begin(); $this->db->begin();
// Insert lines in mrp_production table from BOM data // Insert lines in mrp_production table from BOM data
if (!$error) if (!$error) {
{
// TODO Check that production has not started. If yes, we stop here. // TODO Check that production has not started. If yes, we stop here.
$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.$this->id; $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.$this->id;
@@ -646,12 +647,10 @@ class Mo extends CommonObject
include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php'; include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
$bom = new Bom($this->db); $bom = new Bom($this->db);
$bom->fetch($this->fk_bom); $bom->fetch($this->fk_bom);
if ($bom->id > 0) if ($bom->id > 0) {
{
// Lines to consume // Lines to consume
if (!$error) { if (!$error) {
foreach ($bom->lines as $line) foreach ($bom->lines as $line) {
{
$moline = new MoLine($this->db); $moline = new MoLine($this->db);
$moline->fk_mo = $this->id; $moline->fk_mo = $this->id;
@@ -719,8 +718,7 @@ class Mo extends CommonObject
*/ */
public function deleteLine(User $user, $idline, $notrigger = false) public function deleteLine(User $user, $idline, $notrigger = false)
{ {
if ($this->status < 0) if ($this->status < 0) {
{
$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
return -2; return -2;
} }
@@ -741,8 +739,7 @@ class Mo extends CommonObject
global $langs, $conf; global $langs, $conf;
$langs->load("mrp"); $langs->load("mrp");
if (!empty($conf->global->MRP_MO_ADDON)) if (!empty($conf->global->MRP_MO_ADDON)) {
{
$mybool = false; $mybool = false;
$file = $conf->global->MRP_MO_ADDON.".php"; $file = $conf->global->MRP_MO_ADDON.".php";
@@ -750,16 +747,14 @@ class Mo extends CommonObject
// Include file with class // Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir) foreach ($dirmodels as $reldir) {
{
$dir = dol_buildpath($reldir."core/modules/mrp/"); $dir = dol_buildpath($reldir."core/modules/mrp/");
// Load file with numbering class (if found) // Load file with numbering class (if found)
$mybool |= @include_once $dir.$file; $mybool |= @include_once $dir.$file;
} }
if ($mybool === false) if ($mybool === false) {
{
dol_print_error('', "Failed to include file ".$file); dol_print_error('', "Failed to include file ".$file);
return ''; return '';
} }
@@ -767,8 +762,7 @@ class Mo extends CommonObject
$obj = new $classname(); $obj = new $classname();
$numref = $obj->getNextValue($prod, $this); $numref = $obj->getNextValue($prod, $this);
if ($numref != "") if ($numref != "") {
{
return $numref; return $numref;
} else { } else {
$this->error = $obj->error; $this->error = $obj->error;
@@ -797,8 +791,7 @@ class Mo extends CommonObject
$error = 0; $error = 0;
// Protection // Protection
if ($this->status == self::STATUS_VALIDATED) if ($this->status == self::STATUS_VALIDATED) {
{
dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
return 0; return 0;
} }
@@ -816,8 +809,7 @@ class Mo extends CommonObject
$this->db->begin(); $this->db->begin();
// Define new ref // Define new ref
if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
{
$this->fetch_product(); $this->fetch_product();
$num = $this->getNextNumRef($this->product); $num = $this->getNextNumRef($this->product);
} else { } else {
@@ -835,50 +827,47 @@ class Mo extends CommonObject
dol_syslog(get_class($this)."::validate()", LOG_DEBUG); dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($this->db); dol_print_error($this->db);
$this->error = $this->db->lasterror(); $this->error = $this->db->lasterror();
$error++; $error++;
} }
if (!$error && !$notrigger) if (!$error && !$notrigger) {
{
// Call trigger // Call trigger
$result = $this->call_trigger('MRP_MO_VALIDATE', $user); $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
if (!$error) if (!$error) {
{
$this->oldref = $this->ref; $this->oldref = $this->ref;
// Rename directory if dir was a temporary ref // Rename directory if dir was a temporary ref
if (preg_match('/^[\(]?PROV/i', $this->ref)) if (preg_match('/^[\(]?PROV/i', $this->ref)) {
{
// Now we rename also files into index // Now we rename also files into index
$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'mrp/".$this->db->escape($this->newref)."'"; $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'mrp/".$this->db->escape($this->newref)."'";
$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if (!$resql) { $error++; $this->error = $this->db->lasterror(); } if (!$resql) {
$error++; $this->error = $this->db->lasterror();
}
// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
$oldref = dol_sanitizeFileName($this->ref); $oldref = dol_sanitizeFileName($this->ref);
$newref = dol_sanitizeFileName($num); $newref = dol_sanitizeFileName($num);
$dirsource = $conf->mrp->dir_output.'/'.$oldref; $dirsource = $conf->mrp->dir_output.'/'.$oldref;
$dirdest = $conf->mrp->dir_output.'/'.$newref; $dirdest = $conf->mrp->dir_output.'/'.$newref;
if (!$error && file_exists($dirsource)) if (!$error && file_exists($dirsource)) {
{
dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
if (@rename($dirsource, $dirdest)) if (@rename($dirsource, $dirdest)) {
{
dol_syslog("Rename ok"); dol_syslog("Rename ok");
// Rename docs starting with $oldref with $newref // Rename docs starting with $oldref with $newref
$listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
foreach ($listoffiles as $fileentry) foreach ($listoffiles as $fileentry) {
{
$dirsource = $fileentry['name']; $dirsource = $fileentry['name'];
$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
$dirsource = $fileentry['path'].'/'.$dirsource; $dirsource = $fileentry['path'].'/'.$dirsource;
@@ -891,14 +880,12 @@ class Mo extends CommonObject
} }
// Set new ref and current status // Set new ref and current status
if (!$error) if (!$error) {
{
$this->ref = $num; $this->ref = $num;
$this->status = self::STATUS_VALIDATED; $this->status = self::STATUS_VALIDATED;
} }
if (!$error) if (!$error) {
{
$this->db->commit(); $this->db->commit();
return 1; return 1;
} else { } else {
@@ -917,8 +904,7 @@ class Mo extends CommonObject
public function setDraft($user, $notrigger = 0) public function setDraft($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status <= self::STATUS_DRAFT) if ($this->status <= self::STATUS_DRAFT) {
{
return 0; return 0;
} }
@@ -942,8 +928,7 @@ class Mo extends CommonObject
public function cancel($user, $notrigger = 0) public function cancel($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) {
{
return 0; return 0;
} }
@@ -967,8 +952,7 @@ class Mo extends CommonObject
public function reopen($user, $notrigger = 0) public function reopen($user, $notrigger = 0)
{ {
// Protection // Protection
if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) {
{
return 0; return 0;
} }
@@ -996,7 +980,9 @@ class Mo extends CommonObject
{ {
global $conf, $langs, $hookmanager; 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 = ''; $result = '';
@@ -1008,35 +994,44 @@ class Mo extends CommonObject
$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref; $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
$url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id;
if ($option == 'production') $url = dol_buildpath('/mrp/mo_production.php', 1).'?id='.$this->id; if ($option == 'production') {
$url = dol_buildpath('/mrp/mo_production.php', 1).'?id='.$this->id;
}
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
} }
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowMo"); $label = $langs->trans("ShowMo");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
}
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@@ -1044,8 +1039,11 @@ class Mo extends CommonObject
$hookmanager->initHooks(array('modao')); $hookmanager->initHooks(array('modao'));
$parameters = array('id'=>$this->id, 'getnomurl'=>$result); $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $result = $hookmanager->resPrint; if ($reshook > 0) {
else $result .= $hookmanager->resPrint; $result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result; return $result;
} }
@@ -1072,8 +1070,7 @@ class Mo extends CommonObject
public function LibStatut($status, $mode = 0) public function LibStatut($status, $mode = 0)
{ {
// phpcs:enable // phpcs:enable
if (empty($this->labelStatus)) if (empty($this->labelStatus)) {
{
global $langs; global $langs;
//$langs->load("mrp"); //$langs->load("mrp");
$this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
@@ -1090,10 +1087,18 @@ class Mo extends CommonObject
} }
$statusType = 'status'.$status; $statusType = 'status'.$status;
if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; if ($status == self::STATUS_VALIDATED) {
if ($status == self::STATUS_INPROGRESS) $statusType = 'status4'; $statusType = 'status1';
if ($status == self::STATUS_PRODUCED) $statusType = 'status6'; }
if ($status == self::STATUS_CANCELED) $statusType = 'status9'; if ($status == self::STATUS_INPROGRESS) {
$statusType = 'status4';
}
if ($status == self::STATUS_PRODUCED) {
$statusType = 'status6';
}
if ($status == self::STATUS_CANCELED) {
$statusType = 'status9';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }
@@ -1111,28 +1116,23 @@ class Mo extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql .= ' WHERE t.rowid = '.$id; $sql .= ' WHERE t.rowid = '.$id;
$result = $this->db->query($sql); $result = $this->db->query($sql);
if ($result) if ($result) {
{ if ($this->db->num_rows($result)) {
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$this->id = $obj->rowid; $this->id = $obj->rowid;
if ($obj->fk_user_author) if ($obj->fk_user_author) {
{
$cuser = new User($this->db); $cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author); $cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser; $this->user_creation = $cuser;
} }
if ($obj->fk_user_valid) if ($obj->fk_user_valid) {
{
$vuser = new User($this->db); $vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid); $vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser; $this->user_validation = $vuser;
} }
if ($obj->fk_user_cloture) if ($obj->fk_user_cloture) {
{
$cluser = new User($this->db); $cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture); $cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser; $this->user_cloture = $cluser;
@@ -1172,8 +1172,7 @@ class Mo extends CommonObject
$objectline = new MoLine($this->db); $objectline = new MoLine($this->db);
$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_mo = '.$this->id)); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_mo = '.$this->id));
if (is_numeric($result)) if (is_numeric($result)) {
{
$this->error = $this->error; $this->error = $this->error;
$this->errors = $this->errors; $this->errors = $this->errors;
return $result; return $result;
@@ -1213,7 +1212,9 @@ class Mo extends CommonObject
$modelpath = "core/modules/mrp/doc/"; $modelpath = "core/modules/mrp/doc/";
if (empty($modele)) return 1; // Remove this once a pdf_standard.php exists. if (empty($modele)) {
return 1; // Remove this once a pdf_standard.php exists.
}
return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
} }
@@ -1273,10 +1274,8 @@ class Mo extends CommonObject
print '</tr>'; print '</tr>';
$i = 0; $i = 0;
if (!empty($this->lines)) if (!empty($this->lines)) {
{ foreach ($this->lines as $line) {
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)) if (empty($line->fk_parent_line))
@@ -1317,8 +1316,7 @@ class Mo extends CommonObject
$this->tpl['id'] = $line->id; $this->tpl['id'] = $line->id;
$this->tpl['label'] = ''; $this->tpl['label'] = '';
if (!empty($line->fk_product)) if (!empty($line->fk_product)) {
{
$productstatic = new Product($this->db); $productstatic = new Product($this->db);
$productstatic->fetch($line->fk_product); $productstatic->fetch($line->fk_product);
$this->tpl['label'] .= $productstatic->getNomUrl(1); $this->tpl['label'] .= $productstatic->getNomUrl(1);
@@ -1432,27 +1430,25 @@ class MoLine extends CommonObjectLine
$this->db = $db; $this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; $this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Unset fields that are disabled // Unset fields that are disabled
foreach ($this->fields as $key => $val) foreach ($this->fields as $key => $val) {
{ if (isset($val['enabled']) && empty($val['enabled'])) {
if (isset($val['enabled']) && empty($val['enabled']))
{
unset($this->fields[$key]); unset($this->fields[$key]);
} }
} }
// Translate some data of arrayofkeyval // Translate some data of arrayofkeyval
if (is_object($langs)) if (is_object($langs)) {
{ foreach ($this->fields as $key => $val) {
foreach ($this->fields as $key => $val) if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
{ foreach ($val['arrayofkeyval'] as $key2 => $val2) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
{
foreach ($val['arrayofkeyval'] as $key2 => $val2)
{
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
} }
} }
@@ -1487,7 +1483,9 @@ class MoLine extends CommonObjectLine
public function fetch($id, $ref = null) public function fetch($id, $ref = null)
{ {
$result = $this->fetchCommon($id, $ref); $result = $this->fetchCommon($id, $ref);
if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); if ($result > 0 && !empty($this->table_element_line)) {
$this->fetchLines();
}
return $result; return $result;
} }
@@ -1513,8 +1511,11 @@ class MoLine extends CommonObjectLine
$sql = 'SELECT '; $sql = 'SELECT ';
$sql .= $this->getFieldList(); $sql .= $this->getFieldList();
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
else $sql .= ' WHERE 1 = 1'; $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
} else {
$sql .= ' WHERE 1 = 1';
}
// Manage filter // Manage filter
$sqlwhere = array(); $sqlwhere = array();
if (count($filter) > 0) { if (count($filter) > 0) {
@@ -1545,8 +1546,7 @@ class MoLine extends CommonObjectLine
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < min($limit, $num)) while ($i < min($limit, $num)) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$record = new self($this->db); $record = new self($this->db);

View File

@@ -61,16 +61,14 @@ print '<div class="fichecenter"><div class="fichethirdleft">';
* Statistics * Statistics
*/ */
if ($conf->use_javascript_ajax) if ($conf->use_javascript_ajax) {
{
$sql = "SELECT COUNT(t.rowid) as nb, status"; $sql = "SELECT COUNT(t.rowid) as nb, status";
$sql .= " FROM ".MAIN_DB_PREFIX."mrp_mo as t"; $sql .= " FROM ".MAIN_DB_PREFIX."mrp_mo as t";
$sql .= " GROUP BY t.status"; $sql .= " GROUP BY t.status";
$sql .= " ORDER BY t.status ASC"; $sql .= " ORDER BY t.status ASC";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
@@ -81,14 +79,12 @@ if ($conf->use_javascript_ajax)
include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php';
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) if ($obj) {
{
$vals[$obj->status] = $obj->nb; $vals[$obj->status] = $obj->nb;
$totalnb += $obj->nb; $totalnb += $obj->nb;
} }
$i++; $i++;
} }
@@ -98,25 +94,32 @@ if ($conf->use_javascript_ajax)
print '<table class="noborder nohover centpercent">'; print '<table class="noborder nohover centpercent">';
print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("ManufacturingOrder").'</th></tr>'."\n"; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("ManufacturingOrder").'</th></tr>'."\n";
$listofstatus = array(0, 1, 2, 3, 9); $listofstatus = array(0, 1, 2, 3, 9);
foreach ($listofstatus as $status) foreach ($listofstatus as $status) {
{
$dataseries[] = array($staticmo->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); $dataseries[] = array($staticmo->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0));
if ($status == Mo::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; if ($status == Mo::STATUS_DRAFT) {
if ($status == Mo::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; $colorseries[$status] = '-'.$badgeStatus0;
if ($status == Mo::STATUS_INPROGRESS) $colorseries[$status] = $badgeStatus4; }
if ($status == Mo::STATUS_PRODUCED) $colorseries[$status] = $badgeStatus6; if ($status == Mo::STATUS_VALIDATED) {
if ($status == Mo::STATUS_CANCELED) $colorseries[$status] = $badgeStatus9; $colorseries[$status] = $badgeStatus1;
}
if ($status == Mo::STATUS_INPROGRESS) {
$colorseries[$status] = $badgeStatus4;
}
if ($status == Mo::STATUS_PRODUCED) {
$colorseries[$status] = $badgeStatus6;
}
if ($status == Mo::STATUS_CANCELED) {
$colorseries[$status] = $badgeStatus9;
}
if (empty($conf->use_javascript_ajax)) if (empty($conf->use_javascript_ajax)) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$staticmo->LibStatut($status, 0).'</td>'; print '<td>'.$staticmo->LibStatut($status, 0).'</td>';
print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>';
print "</tr>\n"; print "</tr>\n";
} }
} }
if ($conf->use_javascript_ajax) if ($conf->use_javascript_ajax) {
{
print '<tr><td class="center" colspan="2">'; print '<tr><td class="center" colspan="2">';
include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
@@ -159,19 +162,16 @@ $sql .= $db->order("a.tms", "DESC");
$sql .= $db->plimit($max, 0); $sql .= $db->plimit($max, 0);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<th colspan="4">'.$langs->trans("LatestBOMModified", $max).'</th></tr>'; print '<th colspan="4">'.$langs->trans("LatestBOMModified", $max).'</th></tr>';
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num) if ($num) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$staticbom->id = $obj->rowid; $staticbom->id = $obj->rowid;
@@ -210,19 +210,16 @@ $sql .= $db->order("a.tms", "DESC");
$sql .= $db->plimit($max, 0); $sql .= $db->plimit($max, 0);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<th colspan="4">'.$langs->trans("LatestMOModified", $max).'</th></tr>'; print '<th colspan="4">'.$langs->trans("LatestMOModified", $max).'</th></tr>';
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num) if ($num) {
{
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$staticmo->id = $obj->rowid; $staticmo->id = $obj->rowid;

View File

@@ -21,13 +21,27 @@
* \brief File that include javascript functions used for dispatching qty/stock/lot * \brief File that include javascript functions used for dispatching qty/stock/lot
*/ */
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); if (!defined('NOREQUIRESOC')) {
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); define('NOREQUIRESOC', '1');
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); }
if (!defined('NOLOGIN')) define('NOLOGIN', 1); if (!defined('NOCSRFCHECK')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); define('NOCSRFCHECK', 1);
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', 1);
}
if (!defined('NOLOGIN')) {
define('NOLOGIN', 1);
}
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', 1);
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', 1);
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
session_cache_limiter('public'); session_cache_limiter('public');
@@ -36,8 +50,11 @@ require_once '../../main.inc.php';
// Define javascript type // Define javascript type
top_httphead('text/javascript; charset=UTF-8'); top_httphead('text/javascript; charset=UTF-8');
// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); if (empty($dolibarr_nocache)) {
else header('Cache-Control: no-cache'); header('Cache-Control: max-age=10800, public, must-revalidate');
} else {
header('Cache-Control: no-cache');
}
?> ?>
/** /**

View File

@@ -59,14 +59,19 @@ function moPrepareHead($object)
$head[$h][2] = 'stockmovement'; $head[$h][2] = 'stockmovement';
$h++; $h++;
if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) {
{
$nbNote = 0; $nbNote = 0;
if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_private)) {
if (!empty($object->note_public)) $nbNote++; $nbNote++;
}
if (!empty($object->note_public)) {
$nbNote++;
}
$head[$h][0] = dol_buildpath('/mrp/mo_note.php', 1).'?id='.$object->id; $head[$h][0] = dol_buildpath('/mrp/mo_note.php', 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Notes'); $head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; if ($nbNote > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>';
}
$head[$h][2] = 'note'; $head[$h][2] = 'note';
$h++; $h++;
} }
@@ -78,7 +83,9 @@ function moPrepareHead($object)
$nbLinks = Link::count($db, $object->element, $object->id); $nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = dol_buildpath("/mrp/mo_document.php", 1).'?id='.$object->id; $head[$h][0] = dol_buildpath("/mrp/mo_document.php", 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Documents'); $head[$h][1] = $langs->trans('Documents');
if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; if (($nbFiles + $nbLinks) > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
}
$head[$h][2] = 'document'; $head[$h][2] = 'document';
$h++; $h++;

View File

@@ -44,10 +44,11 @@ $action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
if (GETPOST('actioncode', 'array')) if (GETPOST('actioncode', 'array')) {
{
$actioncode = GETPOST('actioncode', 'array', 3); $actioncode = GETPOST('actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0'; if (!count($actioncode)) {
$actioncode = '0';
}
} else { } else {
$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
} }
@@ -57,12 +58,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = 'a.datep,a.id'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'DESC'; $sortfield = 'a.datep,a.id';
}
if (!$sortorder) {
$sortorder = 'DESC';
}
// Initialize technical objects // Initialize technical objects
$object = new Mo($db); $object = new Mo($db);
@@ -75,7 +82,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id;
}
// Security check - Protection if external user // Security check - Protection if external user
//if ($user->socid > 0) accessforbidden(); //if ($user->socid > 0) accessforbidden();
@@ -90,20 +99,19 @@ $result = restrictedArea($user, 'mrp', $object->id, 'mrp_mo', '', 'fk_soc', 'row
$parameters = array('id'=>$socid); $parameters = array('id'=>$socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Cancel // Cancel
if (GETPOST('cancel', 'alpha') && !empty($backtopage)) if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
{
header("Location: ".$backtopage); header("Location: ".$backtopage);
exit; exit;
} }
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$actioncode = ''; $actioncode = '';
$search_agenda_label = ''; $search_agenda_label = '';
} }
@@ -120,14 +128,15 @@ $contactstatic = new Contact($db);
$form = new Form($db); $form = new Form($db);
$formproject = new FormProjets($db); $formproject = new FormProjets($db);
if ($object->id > 0) if ($object->id > 0) {
{
$title = $langs->trans("Agenda"); $title = $langs->trans("Agenda");
//if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
$help_url = ''; $help_url = '';
llxHeader('', $title, $help_url); llxHeader('', $title, $help_url);
if (!empty($conf->notification->enabled)) $langs->load("mails"); if (!empty($conf->notification->enabled)) {
$langs->load("mails");
}
$head = moPrepareHead($object); $head = moPrepareHead($object);
@@ -144,14 +153,13 @@ if ($object->id > 0)
// Thirdparty // 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 // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($action != 'classify') {
if ($action != 'classify')
$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
}
if ($action == 'classify') { 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.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@@ -196,10 +204,11 @@ if ($object->id > 0)
$out = '&origin='.$object->element.'&originid='.$object->id; $out = '&origin='.$object->element.'&originid='.$object->id;
$permok = $user->rights->agenda->myactions->create; $permok = $user->rights->agenda->myactions->create;
if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) {
{
//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'; //$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id; if (get_class($objthirdparty) == 'Societe') {
$out .= '&amp;socid='.$objthirdparty->id;
}
$out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1'; $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1';
//$out.=$langs->trans("AddAnAction").' '; //$out.=$langs->trans("AddAnAction").' ';
//$out.=img_picto($langs->trans("AddAnAction"),'filenew'); //$out.=img_picto($langs->trans("AddAnAction"),'filenew');
@@ -209,10 +218,8 @@ if ($object->id > 0)
print '<div class="tabsAction">'; print '<div class="tabsAction">';
if (!empty($conf->agenda->enabled)) if (!empty($conf->agenda->enabled)) {
{ if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) {
if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create))
{
print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>'; print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>';
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>';
@@ -221,11 +228,14 @@ if ($object->id > 0)
print '</div>'; print '</div>';
if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
{
$param = '&id='.$object->id.'&socid='.$socid; $param = '&id='.$object->id.'&socid='.$socid;
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
//print load_fiche_titre($langs->trans("ActionsOnMo"), '', ''); //print load_fiche_titre($langs->trans("ActionsOnMo"), '', '');

View File

@@ -61,18 +61,20 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
if (empty($action) && empty($id) && empty($ref)) $action = 'view'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
if (GETPOST('fk_bom', 'int')) if (GETPOST('fk_bom', 'int')) {
{
$objectbom->fetch(GETPOST('fk_bom', 'int')); $objectbom->fetch(GETPOST('fk_bom', 'int'));
if ($action != 'add') { if ($action != 'add') {
@@ -103,18 +105,22 @@ $upload_dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->enti
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
$error = 0; $error = 0;
$backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && empty($id))) {
if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); $backtopage = $backurlforlist;
} else {
$backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__');
}
} }
} }
if ($cancel && !empty($backtopageforcancel)) { if ($cancel && !empty($backtopageforcancel)) {
@@ -141,28 +147,27 @@ if (empty($reshook))
// Action to move up and down lines of object // Action to move up and down lines of object
//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 == 'set_thirdparty' && $permissiontoadd) if ($action == 'set_thirdparty' && $permissiontoadd) {
{
$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY');
} }
if ($action == 'classin' && $permissiontoadd) if ($action == 'classin' && $permissiontoadd) {
{
$object->setProject(GETPOST('projectid', 'int')); $object->setProject(GETPOST('projectid', 'int'));
} }
// Action close produced // Action close produced
if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) {
{
$result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
if ($result >= 0) if ($result >= 0) {
{
// Define output language // Define output language
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
{
$outputlangs = $langs; $outputlangs = $langs;
$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) && GETPOST('lang_id', 'aZ09')) {
if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; $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 = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang); $outputlangs->setDefaultLang($newlang);
@@ -208,15 +213,18 @@ jQuery(document).ready(function() {
// Part to create // Part to create
if ($action == 'create') if ($action == 'create') {
{
print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Mo")), '', 'mrp'); print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Mo")), '', 'mrp');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="add">'; print '<input type="hidden" name="action" value="add">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
}
print dol_get_fiche_head(array(), ''); print dol_get_fiche_head(array(), '');
@@ -234,7 +242,7 @@ if ($action == 'create')
?> ?>
<script> <script>
$(document).ready(function () { $(document).ready(function () {
jQuery('#fk_bom').change(function() { jQuery('#fk_bom').change(function() {
console.log('We change value of BOM with BOM of id '+jQuery('#fk_bom').val()); console.log('We change value of BOM with BOM of id '+jQuery('#fk_bom').val());
if (jQuery('#fk_bom').val() > 0) if (jQuery('#fk_bom').val() > 0)
@@ -280,7 +288,7 @@ if ($action == 'create')
$('#fk_warehouse').trigger('change'); // Notify any JS components that the value changed $('#fk_warehouse').trigger('change'); // Notify any JS components that the value changed
*/ */
} }
}); });
//jQuery('#fk_bom').trigger('change'); //jQuery('#fk_bom').trigger('change');
}) })
@@ -312,16 +320,19 @@ if ($action == 'create')
} }
// Part to edit record // Part to edit record
if (($id || $ref) && $action == 'edit') if (($id || $ref) && $action == 'edit') {
{
print load_fiche_titre($langs->trans("ManufacturingOrder"), '', 'mrp'); print load_fiche_titre($langs->trans("ManufacturingOrder"), '', 'mrp');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">'; print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id" value="'.$object->id.'">'; print '<input type="hidden" name="id" value="'.$object->id.'">';
if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; if ($backtopage) {
if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
}
print dol_get_fiche_head(); print dol_get_fiche_head();
@@ -347,8 +358,7 @@ if (($id || $ref) && $action == 'edit')
} }
// Part to show record // Part to show record
if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
{
$res = $object->fetch_thirdparty(); $res = $object->fetch_thirdparty();
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
@@ -359,19 +369,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$formconfirm = ''; $formconfirm = '';
// Confirmation to delete // Confirmation to delete
if ($action == 'delete') if ($action == 'delete') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('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 // Confirmation to delete line
if ($action == 'deleteline') if ($action == 'deleteline') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
} }
// Confirmation of validation // Confirmation of validation
if ($action == 'validate') if ($action == 'validate') {
{
// We check that object has a temporary ref // We check that object has a temporary ref
$ref = substr($object->ref, 1, 4); $ref = substr($object->ref, 1, 4);
if ($ref == 'PROV') { if ($ref == 'PROV') {
@@ -391,13 +398,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->mrp->enabled)) if (!empty($conf->mrp->enabled)) {
{
$langs->load("mrp"); $langs->load("mrp");
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
$forcecombo = 0; $forcecombo = 0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy if ($conf->browser->name == 'ie') {
$forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
}
$formquestion = array( $formquestion = array(
// 'text' => $langs->trans("ConfirmClone"), // 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
@@ -418,8 +426,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Call Hook formConfirm // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@@ -438,14 +449,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$morehtmlref .= $langs->trans('ThirdParty').' '; $morehtmlref .= $langs->trans('ThirdParty').' ';
$morehtmlref .= ': '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); $morehtmlref .= ': '.(is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
// Project // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($action != 'classify') {
if ($action != 'classify')
$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
}
if ($action == 'classify') { 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.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@@ -500,8 +510,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
* Lines * Lines
*/ */
if (!empty($object->table_element_line)) if (!empty($object->table_element_line)) {
{
// Show object lines // Show object lines
//$result = $object->getLinesArray(); //$result = $object->getLinesArray();
$object->fetchLines(); $object->fetchLines();
@@ -514,11 +523,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
'; ';
/*if (!empty($conf->use_javascript_ajax) && $object->status == 0) { /*if (!empty($conf->use_javascript_ajax) && $object->status == 0) {
include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
}*/ }*/
if (!empty($object->lines)) if (!empty($object->lines)) {
{
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
print '<table id="tablelines" class="noborder noshadow" width="100%">'; print '<table id="tablelines" class="noborder noshadow" width="100%">';
@@ -530,12 +538,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("ProductsToConsume").'</td>'; print '<td>'.$langs->trans("ProductsToConsume").'</td>';
print '<td>'; print '<td>';
if (!empty($object->lines)) if (!empty($object->lines)) {
{
$i = 0; $i = 0;
foreach ($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toconsume') { if ($line->role == 'toconsume') {
if ($i) print ', '; if ($i) {
print ', ';
}
$tmpproduct = new Product($db); $tmpproduct = new Product($db);
$tmpproduct->fetch($line->fk_product); $tmpproduct->fetch($line->fk_product);
print $tmpproduct->getNomUrl(1); print $tmpproduct->getNomUrl(1);
@@ -549,12 +558,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$langs->trans("ProductsToProduce").'</td>'; print '<td>'.$langs->trans("ProductsToProduce").'</td>';
print '<td>'; print '<td>';
if (!empty($object->lines)) if (!empty($object->lines)) {
{
$i = 0; $i = 0;
foreach ($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toproduce') { if ($line->role == 'toproduce') {
if ($i) print ', '; if ($i) {
print ', ';
}
$tmpproduct = new Product($db); $tmpproduct = new Product($db);
$tmpproduct->fetch($line->fk_product); $tmpproduct->fetch($line->fk_product);
print $tmpproduct->getNomUrl(1); print $tmpproduct->getNomUrl(1);
@@ -579,20 +589,19 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<div class="tabsAction">'."\n"; print '<div class="tabsAction">'."\n";
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Send // Send
//if (empty($user->socid)) { //if (empty($user->socid)) {
// print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n"; // print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n";
//} //}
// Back to draft // Back to draft
if ($object->status == $object::STATUS_VALIDATED) if ($object->status == $object::STATUS_VALIDATED) {
{ if ($permissiontoadd) {
if ($permissiontoadd)
{
// TODO Add test that production has not started // TODO Add test that production has not started
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>';
} }
@@ -600,8 +609,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Modify // Modify
if ($object->status == $object::STATUS_DRAFT) { if ($object->status == $object::STATUS_DRAFT) {
if ($permissiontoadd) if ($permissiontoadd) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
@@ -609,12 +617,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Validate // Validate
if ($object->status == $object::STATUS_DRAFT) if ($object->status == $object::STATUS_DRAFT) {
{ if ($permissiontoadd) {
if ($permissiontoadd) if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) {
{
if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0))
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>';
} else { } else {
$langs->load("errors"); $langs->load("errors");
@@ -624,16 +629,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Clone // Clone
if ($permissiontoadd) if ($permissiontoadd) {
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->fk_soc.'&action=clone&object=mo">'.$langs->trans("ToClone").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->fk_soc.'&action=clone&object=mo">'.$langs->trans("ToClone").'</a>';
} }
// Cancel - Reopen // Cancel - Reopen
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) {
if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
{
$arrayproduced = $object->fetchLinesLinked('produced', 0); $arrayproduced = $object->fetchLinesLinked('produced', 0);
$nbProduced = 0; $nbProduced = 0;
foreach ($arrayproduced as $lineproduced) { foreach ($arrayproduced as $lineproduced) {
@@ -648,15 +650,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n"; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n";
} }
if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("ReOpen").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("ReOpen").'</a>'."\n";
} }
} }
// Delete (need delete permission, or if draft, just need create/modify permission) // Delete (need delete permission, or if draft, just need create/modify permission)
if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) {
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
} else { } else {
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
@@ -671,8 +671,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$action = 'presend'; $action = 'presend';
} }
if ($action != 'presend') if ($action != 'presend') {
{
print '<div class="fichecenter"><div class="fichehalfleft">'; print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre print '<a name="builddoc"></a>'; // ancre
@@ -707,7 +706,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
//Select mail models is same action as presend //Select mail models is same action as presend
if (GETPOST('modelselected')) $action = 'presend'; if (GETPOST('modelselected')) {
$action = 'presend';
}
// Presend form // Presend form
$modelmail = 'mo'; $modelmail = 'mo';

View File

@@ -47,12 +47,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortorder) $sortorder = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "name";
}
//if (! $sortfield) $sortfield="position_name"; //if (! $sortfield) $sortfield="position_name";
// Initialize technical objects // Initialize technical objects
@@ -67,7 +73,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object->entity ? $object->entity : $conf->entity]."/mo/".get_exdir(0, 0, 0, 1, $object); if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->mrp->multidir_output[$object->entity ? $object->entity : $conf->entity]."/mo/".get_exdir(0, 0, 0, 1, $object);
}
// Security check - Protection if external user // Security check - Protection if external user
//if ($user->socid > 0) accessforbidden(); //if ($user->socid > 0) accessforbidden();
@@ -95,8 +103,7 @@ $help_url = '';
//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url); llxHeader('', $title, $help_url);
if ($object->id) if ($object->id) {
{
/* /*
* Show tabs * Show tabs
*/ */
@@ -107,8 +114,7 @@ if ($object->id)
// Build file list // Build file list
$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
$totalsize = 0; $totalsize = 0;
foreach ($filearray as $key => $file) foreach ($filearray as $key => $file) {
{
$totalsize += $file['size']; $totalsize += $file['size'];
} }
@@ -123,14 +129,13 @@ if ($object->id)
// Thirdparty // 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 // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($action != 'classify') {
if ($action != 'classify')
$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
}
if ($action == 'classify') { 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.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';

View File

@@ -54,7 +54,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@@ -73,15 +75,20 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Security check // Security check
if (empty($conf->mrp->enabled)) accessforbidden('Module not enabled'); if (empty($conf->mrp->enabled)) {
accessforbidden('Module not enabled');
}
$socid = 0; $socid = 0;
if ($user->socid > 0) // Protection if external user if ($user->socid > 0) { // Protection if external user
{ //$socid = $user->socid;
//$socid = $user->socid;
accessforbidden(); accessforbidden();
} }
//$result = restrictedArea($user, 'mrp', $id, ''); //$result = restrictedArea($user, 'mrp', $id, '');
@@ -90,30 +97,31 @@ if ($user->socid > 0) // Protection if external user
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha') !== '') {
if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array(); $fieldstosearchall = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if ($val['searchall']) {
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; $fieldstosearchall['t.'.$key] = $val['label'];
}
} }
// Definition of fields for list // Definition of fields for list
$arrayfields = array(); $arrayfields = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); if (!empty($val['visible'])) {
$arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']);
}
} }
// Extra fields // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
$arrayfields["ef.".$key] = array( $arrayfields["ef.".$key] = array(
'label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@@ -136,31 +144,33 @@ $permissiontodelete = $user->rights->mrp->delete;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{ foreach ($object->fields as $key => $val) {
foreach ($object->fields as $key => $val)
{
$search[$key] = ''; $search[$key] = '';
} }
$toselect = ''; $toselect = '';
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@@ -189,13 +199,14 @@ $title = $langs->trans('ListOfManufacturingOrders');
// Build and execute select // Build and execute select
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$sql = 'SELECT '; $sql = 'SELECT ';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$sql .= 't.'.$key.', '; $sql .= 't.'.$key.', ';
} }
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) { if (!empty($extrafields->attributes[$object->table_element]['label'])) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@@ -203,20 +214,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
$sql = preg_replace('/,\s*$/', '', $sql); $sql = preg_replace('/,\s*$/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
else $sql .= " WHERE 1 = 1"; }
foreach ($search as $key => $val) if ($object->ismultientitymanaged == 1) {
{ $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
if ($key == 'status' && $search[$key] == -1) continue; } else {
$sql .= " WHERE 1 = 1";
}
foreach ($search as $key => $val) {
if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if (strpos($object->fields[$key]['type'], 'integer:') === 0) { if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
if ($search[$key] == '-1') $search[$key] = ''; if ($search[$key] == '-1') {
$search[$key] = '';
}
$mode_search = 2; $mode_search = 2;
} }
if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); if ($search[$key] != '') {
$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
}
}
if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
} }
if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
// Add where from extra fields // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@@ -246,26 +269,24 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
if ($limit) $sql .= $db->plimit($limit + 1, $offset); if ($limit) {
$sql .= $db->plimit($limit + 1, $offset);
}
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@@ -274,8 +295,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".dol_buildpath('/mrp/mo_card.php', 1).'?id='.$id); header("Location: ".dol_buildpath('/mrp/mo_card.php', 1).'?id='.$id);
@@ -306,14 +326,24 @@ jQuery(document).ready(function() {
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
foreach ($search as $key => $val) }
{ if ($limit > 0 && $limit != $conf->liste_limit) {
if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); $param .= '&limit='.urlencode($limit);
else $param .= '&search_'.$key.'='.urlencode($search[$key]); }
foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) {
$param .= '&search_'.$key.'[]='.urlencode($skey);
}
} else {
$param .= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
} }
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -324,12 +354,18 @@ $arrayofmassactions = array(
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@@ -348,9 +384,10 @@ $objecttmp = new Mo($db);
$trackid = 'mo'.$object->id; $trackid = 'mo'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($search_all) if ($search_all) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
} }
@@ -361,11 +398,13 @@ $moreforfilter.= '</div>';*/
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@@ -382,20 +421,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit
// Fields title search // Fields title search
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">'; print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
elseif (strpos($val['type'], 'integer:') === 0) { print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
} elseif (strpos($val['type'], 'integer:') === 0) {
print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1); print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1);
} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">'; } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
}
print '</td>'; print '</td>';
} }
} }
@@ -417,15 +462,18 @@ print '</tr>'."\n";
// Fields title label // Fields title label
// -------------------------------------------------------------------- // --------------------------------------------------------------------
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; if ($key == 'status') {
elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
if (!empty($arrayfields['t.'.$key]['checked'])) } elseif (in_array($val['type'], array('timestamp'))) {
{ $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
} }
} }
@@ -442,11 +490,11 @@ print '</tr>'."\n";
// Detect if we need a fetch on each output line // Detect if we need a fetch on each output line
$needToFetchEachLine = 0; $needToFetchEachLine = 0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) if (preg_match('/\$object/', $val)) {
{ $needToFetchEachLine++; // There is at least one compute field that use $object
if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object }
} }
} }
@@ -455,38 +503,53 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < ($limit ? min($num, $limit) : $num)) while ($i < ($limit ? min($num, $limit) : $num)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (empty($obj)) break; // Should not happen if (empty($obj)) {
break; // Should not happen
}
// Store properties in $object // Store properties in $object
$object->setVarsFromFetchObj($obj); $object->setVarsFromFetchObj($obj);
// Show here line of result // Show here line of result
print '<tr class="oddeven">'; print '<tr class="oddeven">';
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{
$cssforfield = (empty($val['css']) ? '' : $val['css']); $cssforfield = (empty($val['css']) ? '' : $val['css']);
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; $cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
}
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; if (in_array($val['type'], array('timestamp'))) {
elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif ($key == 'ref') {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') {
if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; $cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) {
$cssforfield = 'tdoverflowmax100';
}
if (!empty($arrayfields['t.'.$key]['checked'])) if (!empty($arrayfields['t.'.$key]['checked'])) {
{
print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>'; print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
if ($key == 'status') print $object->getLibStatut(5); if ($key == 'status') {
else print $object->showOutputField($val, $key, $object->$key, ''); print $object->getLibStatut(5);
} else {
print $object->showOutputField($val, $key, $object->$key, '');
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!empty($val['isameasure'])) $totalarray['nbfield']++;
{ }
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; if (!empty($val['isameasure'])) {
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
}
$totalarray['val']['t.'.$key] += $object->$key; $totalarray['val']['t.'.$key] += $object->$key;
} }
} }
@@ -499,14 +562,17 @@ while ($i < ($limit ? min($num, $limit) : $num))
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($object->id, $arrayofselected)) $selected = 1; if (in_array($object->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
@@ -518,10 +584,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) if ($num == 0) {
{
$colspan = 1; $colspan = 1;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
@@ -537,10 +606,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

View File

@@ -66,10 +66,16 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
$sortfield = GETPOST("sortfield", 'alpha'); $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
if (!$sortfield) $sortfield = "m.datem"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "m.datem";
}
if (!$sortorder) {
$sortorder = "DESC";
}
// Initialize technical objects // Initialize technical objects
$object = new Mo($db); $object = new Mo($db);
@@ -85,12 +91,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = trim(GETPOST("search_all", 'alpha')); $search_all = trim(GETPOST("search_all", 'alpha'));
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
if (empty($action) && empty($id) && empty($ref)) $action = 'view'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
@@ -145,18 +154,23 @@ $permissiontoproduce = $permissiontoadd;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Do we click on purge search criteria ? // 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 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 = ''; $year = '';
$month = ''; $month = '';
$search_ref = ''; $search_ref = '';
@@ -174,16 +188,18 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
$search_array_options = array(); $search_array_options = array();
} }
if (empty($reshook)) if (empty($reshook)) {
{
$error = 0; $error = 0;
$backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && empty($id))) {
//var_dump($backurlforlist);exit; //var_dump($backurlforlist);exit;
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
else $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__'); $backtopage = $backurlforlist;
} else {
$backtopage = DOL_URL_ROOT.'/mrp/mo_production.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
@@ -205,12 +221,10 @@ if (empty($reshook))
// Action to move up and down lines of object // Action to move up and down lines of object
//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 == 'set_thirdparty' && $permissiontoadd) if ($action == 'set_thirdparty' && $permissiontoadd) {
{
$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY');
} }
if ($action == 'classin' && $permissiontoadd) if ($action == 'classin' && $permissiontoadd) {
{
$object->setProject(GETPOST('projectid', 'int')); $object->setProject(GETPOST('projectid', 'int'));
} }
@@ -236,8 +250,7 @@ $userstatic = new User($db);
llxHeader('', $langs->trans('Mo'), ''); llxHeader('', $langs->trans('Mo'), '');
// Part to show record // Part to show record
if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
{
$res = $object->fetch_thirdparty(); $res = $object->fetch_thirdparty();
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
@@ -248,13 +261,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$formconfirm = ''; $formconfirm = '';
// Confirmation to delete // Confirmation to delete
if ($action == 'delete') if ($action == 'delete') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('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 // Confirmation to delete line
if ($action == 'deleteline') if ($action == 'deleteline') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
} }
// Clone confirmation // Clone confirmation
@@ -265,27 +276,29 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of action xxxx // Confirmation of action xxxx
if ($action == 'xxx') if ($action == 'xxx') {
{
$formquestion = array(); $formquestion = array();
/* /*
$forcecombo=0; $forcecombo=0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
$formquestion = array( $formquestion = array(
// 'text' => $langs->trans("ConfirmClone"), // 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), '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')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) // 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 // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@@ -303,14 +316,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Thirdparty // 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 // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($action != 'classify') {
if ($action != 'classify')
$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
}
if ($action == 'classify') { 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.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@@ -403,7 +415,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$sql .= " u.login, u.photo, u.lastname, u.firstname"; $sql .= " u.login, u.photo, u.lastname, u.firstname";
// Add fields from extrafields // Add fields from extrafields
if (!empty($extrafields->attributes[$objectlist->table_element]['label'])) { if (!empty($extrafields->attributes[$objectlist->table_element]['label'])) {
foreach ($extrafields->attributes[$objectlist->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$objectlist->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); foreach ($extrafields->attributes[$objectlist->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$objectlist->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
}
} }
// Add fields from hooks // Add fields from hooks
$parameters = array(); $parameters = array();
@@ -412,26 +426,52 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,"; $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e,";
$sql .= " ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."product as p,";
$sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql .= " ".MAIN_DB_PREFIX."stock_mouvement as m";
if (is_array($extrafields->attributes[$objectlist->table_element]['label']) && count($extrafields->attributes[$objectlist->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$objectlist->table_element."_extrafields as ef on (m.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$objectlist->table_element]['label']) && count($extrafields->attributes[$objectlist->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$objectlist->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."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 .= " 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"; $sql .= " WHERE m.fk_product = p.rowid";
$sql .= " AND m.origintype = 'mo' AND m.fk_origin = ".(int) $object->id; $sql .= " AND m.origintype = 'mo' AND m.fk_origin = ".(int) $object->id;
if ($msid > 0) $sql .= " AND m.rowid = ".$msid; if ($msid > 0) {
$sql .= " AND m.rowid = ".$msid;
}
$sql .= " AND m.fk_entrepot = e.rowid"; $sql .= " AND m.fk_entrepot = e.rowid";
$sql .= " AND e.entity IN (".getEntity('stock').")"; $sql .= " AND e.entity IN (".getEntity('stock').")";
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql .= " AND p.fk_product_type = 0"; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
$sql .= " AND p.fk_product_type = 0";
}
$sql .= dolSqlDateFilter('m.datem', 0, $month, $year); $sql .= dolSqlDateFilter('m.datem', 0, $month, $year);
if (!empty($search_ref)) $sql .= natural_search('m.rowid', $search_ref, 1); if (!empty($search_ref)) {
if (!empty($search_movement)) $sql .= natural_search('m.label', $search_movement); $sql .= natural_search('m.rowid', $search_ref, 1);
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_movement)) {
if (!empty($search_product)) $sql .= natural_search('p.label', $search_product); $sql .= natural_search('m.label', $search_movement);
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_inventorycode)) {
if (!empty($search_batch)) $sql .= natural_search('m.batch', $search_batch); $sql .= natural_search('m.inventorycode', $search_inventorycode);
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); 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 // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@@ -441,12 +481,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@@ -454,17 +492,39 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($id > 0) $param .= '&id='.urlencode($id); }
if ($search_movement) $param .= '&search_movement='.urlencode($search_movement); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_inventorycode) $param .= '&search_inventorycode='.urlencode($search_inventorycode); $param .= '&limit='.urlencode($limit);
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 ($id > 0) {
if ($search_product) $param .= '&search_product='.urlencode($search_product); $param .= '&id='.urlencode($id);
if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); }
if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); if ($search_movement) {
if ($search_user) $param .= '&search_user='.urlencode($search_user); $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 ($search_user) {
$param .= '&search_user='.urlencode($search_user);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -475,11 +535,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// 'builddoc'=>$langs->trans("PDFMerge"), // 'builddoc'=>$langs->trans("PDFMerge"),
); );
//if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); if (in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@@ -487,20 +551,27 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
if ($id > 0) print '<input type="hidden" name="id" value="'.$id.'">'; if ($id > 0) {
print '<input type="hidden" name="id" value="'.$id.'">';
}
if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); if ($id > 0) {
else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit);
} else {
print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit);
}
$moreforfilter = ''; $moreforfilter = '';
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@@ -514,84 +585,74 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Fields title search // Fields title search
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
if (!empty($arrayfields['m.rowid']['checked'])) if (!empty($arrayfields['m.rowid']['checked'])) {
{
// Ref // Ref
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">'; print '<input class="flat maxwidth25" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.datem']['checked'])) if (!empty($arrayfields['m.datem']['checked'])) {
{
print '<td class="liste_titre nowraponall">'; print '<td class="liste_titre nowraponall">';
print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">'; print '<input class="flat" type="text" size="2" maxlength="2" placeholder="'.dol_escape_htmltag($langs->trans("Month")).'" name="month" value="'.$month.'">';
if (empty($conf->productbatch->enabled)) print '&nbsp;'; if (empty($conf->productbatch->enabled)) {
print '&nbsp;';
}
//else print '<br>'; //else print '<br>';
$syear = $year ? $year : -1; $syear = $year ? $year : -1;
print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">'; print '<input class="flat maxwidth50" type="text" maxlength="4" placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" name="year" value="'.($syear > 0 ? $syear : '').'">';
//print $formother->selectyear($syear,'year',1, 20, 5); //print $formother->selectyear($syear,'year',1, 20, 5);
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['p.ref']['checked'])) if (!empty($arrayfields['p.ref']['checked'])) {
{
// Product Ref // Product Ref
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">'; print '<input class="flat maxwidth75" type="text" name="search_product_ref" value="'.dol_escape_htmltag($idproduct ? $product->ref : $search_product_ref).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['p.label']['checked'])) if (!empty($arrayfields['p.label']['checked'])) {
{
// Product label // Product label
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">'; print '<input class="flat maxwidth100" type="text" name="search_product" value="'.dol_escape_htmltag($idproduct ? $product->label : $search_product).'">';
print '</td>'; print '</td>';
} }
// Batch // Batch
if (!empty($arrayfields['m.batch']['checked'])) if (!empty($arrayfields['m.batch']['checked'])) {
{
print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>'; print '<td class="liste_titre center"><input class="flat maxwidth75" type="text" name="search_batch" value="'.dol_escape_htmltag($search_batch).'"></td>';
} }
if (!empty($arrayfields['pl.eatby']['checked'])) if (!empty($arrayfields['pl.eatby']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['pl.sellby']['checked'])) if (!empty($arrayfields['pl.sellby']['checked'])) {
{
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '</td>'; print '</td>';
} }
// Warehouse // Warehouse
if (!empty($arrayfields['e.ref']['checked'])) if (!empty($arrayfields['e.ref']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone left">'; print '<td class="liste_titre maxwidthonsmartphone left">';
//print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">'; //print '<input class="flat" type="text" size="8" name="search_warehouse" value="'.($search_warehouse).'">';
print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.fk_user_author']['checked'])) if (!empty($arrayfields['m.fk_user_author']['checked'])) {
{
// Author // Author
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">'; print '<input class="flat" type="text" size="6" name="search_user" value="'.dol_escape_htmltag($search_user).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.inventorycode']['checked'])) if (!empty($arrayfields['m.inventorycode']['checked'])) {
{
// Inventory code // Inventory code
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">'; print '<input class="flat" type="text" size="4" name="search_inventorycode" value="'.dol_escape_htmltag($search_inventorycode).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.label']['checked'])) if (!empty($arrayfields['m.label']['checked'])) {
{
// Label of movement // Label of movement
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">'; print '<input class="flat" type="text" size="8" name="search_movement" value="'.dol_escape_htmltag($search_movement).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.type_mouvement']['checked'])) if (!empty($arrayfields['m.type_mouvement']['checked'])) {
{
// Type of movement // Type of movement
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
//print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">'; //print '<input class="flat" type="text" size="3" name="search_type_mouvement" value="'.dol_escape_htmltag($search_type_mouvement).'">';
@@ -607,22 +668,19 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); // print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'maxwidth200');
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['origin']['checked'])) if (!empty($arrayfields['origin']['checked'])) {
{
// Origin of movement // Origin of movement
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '&nbsp; '; print '&nbsp; ';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.value']['checked'])) if (!empty($arrayfields['m.value']['checked'])) {
{
// Qty // Qty
print '<td class="liste_titre right">'; print '<td class="liste_titre right">';
print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">'; print '<input class="flat" type="text" size="4" name="search_qty" value="'.dol_escape_htmltag($search_qty).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.price']['checked'])) if (!empty($arrayfields['m.price']['checked'])) {
{
// Price // Price
print '<td class="liste_titre left">'; print '<td class="liste_titre left">';
print '&nbsp; '; print '&nbsp; ';
@@ -638,14 +696,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Date creation // Date creation
if (!empty($arrayfields['m.datec']['checked'])) if (!empty($arrayfields['m.datec']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Date modification // Date modification
if (!empty($arrayfields['m.tms']['checked'])) if (!empty($arrayfields['m.tms']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
@@ -657,38 +713,52 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
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); 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); 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); 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); 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 '); 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 '); 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 '); 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 // 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); 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); 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); 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); 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 '); 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); 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 '); 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 '); print_liste_field_titre($arrayfields['m.price']['label'], $_SERVER["PHP_SELF"], "m.price", "", $param, '', $sortfield, $sortorder, 'right ');
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@@ -775,9 +845,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
if (!empty($arrayfields['m.batch']['checked'])) { if (!empty($arrayfields['m.batch']['checked'])) {
print '<td class="center nowraponall">'; print '<td class="center nowraponall">';
if ($productlot->id > 0) if ($productlot->id > 0) {
print $productlot->getNomUrl(1); 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 '</td>'; print '</td>';
} }
if (!empty($arrayfields['pl.eatby']['checked'])) { if (!empty($arrayfields['pl.eatby']['checked'])) {
@@ -834,30 +906,33 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
if (!empty($arrayfields['m.value']['checked'])) { if (!empty($arrayfields['m.value']['checked'])) {
// Qty // Qty
print '<td class="right">'; print '<td class="right">';
if ($objp->qt > 0) if ($objp->qt > 0) {
print '+'; print '+';
}
print $objp->qty; print $objp->qty;
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['m.price']['checked'])) { if (!empty($arrayfields['m.price']['checked'])) {
// Price // Price
print '<td class="right">'; print '<td class="right">';
if ($objp->price != 0) if ($objp->price != 0) {
print price($objp->price); print price($objp->price);
}
print '</td>'; print '</td>';
} }
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1; $selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) if (!$i) {
$totalarray['nbfield']++; $totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;

View File

@@ -50,7 +50,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || !empty($ref)) $upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->mrp->multidir_output[$object->entity]."/".$object->id;
}
// Security check - Protection if external user // Security check - Protection if external user
//if ($user->socid > 0) accessforbidden(); //if ($user->socid > 0) accessforbidden();
@@ -81,8 +83,7 @@ $formproject = new FormProjets($db);
$help_url = ''; $help_url = '';
llxHeader('', $langs->trans('Mo'), $help_url); llxHeader('', $langs->trans('Mo'), $help_url);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$head = moPrepareHead($object); $head = moPrepareHead($object);
@@ -100,14 +101,13 @@ if ($id > 0 || !empty($ref))
// Thirdparty // 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 // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($action != 'classify') {
if ($action != 'classify')
$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
}
if ($action == 'classify') { 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.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';

View File

@@ -65,12 +65,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // Initialize array of search criterias
$search_all = GETPOST("search_all", 'alpha'); $search_all = GETPOST("search_all", 'alpha');
$search = array(); $search = array();
foreach ($object->fields as $key => $val) foreach ($object->fields as $key => $val) {
{ if (GETPOST('search_'.$key, 'alpha')) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); $search[$key] = GETPOST('search_'.$key, 'alpha');
}
} }
if (empty($action) && empty($id) && empty($ref)) $action = 'view'; if (empty($action) && empty($id) && empty($ref)) {
$action = 'view';
}
// Load object // Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
@@ -96,18 +99,22 @@ $permissiontoproduce = $permissiontoadd;
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
$error = 0; $error = 0;
$backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
if (empty($backtopage) || ($cancel && empty($id))) { if (empty($backtopage) || ($cancel && empty($id))) {
//var_dump($backurlforlist);exit; //var_dump($backurlforlist);exit;
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
else $backtopage = DOL_URL_ROOT.'/mrp/mo_production.php?id='.($id > 0 ? $id : '__ID__'); $backtopage = $backurlforlist;
} else {
$backtopage = DOL_URL_ROOT.'/mrp/mo_production.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
@@ -129,12 +136,10 @@ if (empty($reshook))
// Action to move up and down lines of object // Action to move up and down lines of object
//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 == 'set_thirdparty' && $permissiontoadd) if ($action == 'set_thirdparty' && $permissiontoadd) {
{
$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY');
} }
if ($action == 'classin' && $permissiontoadd) if ($action == 'classin' && $permissiontoadd) {
{
$object->setProject(GETPOST('projectid', 'int')); $object->setProject(GETPOST('projectid', 'int'));
} }
@@ -364,18 +369,19 @@ if (empty($reshook))
} }
// Action close produced // Action close produced
if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) {
{
$result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
if ($result >= 0) if ($result >= 0) {
{
// Define output language // Define output language
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
{
$outputlangs = $langs; $outputlangs = $langs;
$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) && GETPOST('lang_id', 'aZ09')) {
if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; $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 = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang); $outputlangs->setDefaultLang($newlang);
@@ -407,8 +413,7 @@ $help_url = 'EN:Module_Manufacturing_Orders|FR:Module_Ordres_de_Fabrication';
llxHeader('', $langs->trans('Mo'), $help_url, '', 0, 0, array('/mrp/js/lib_dispatch.js.php')); llxHeader('', $langs->trans('Mo'), $help_url, '', 0, 0, array('/mrp/js/lib_dispatch.js.php'));
// Part to show record // Part to show record
if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
{
$res = $object->fetch_thirdparty(); $res = $object->fetch_thirdparty();
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
@@ -419,13 +424,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$formconfirm = ''; $formconfirm = '';
// Confirmation to delete // Confirmation to delete
if ($action == 'delete') if ($action == 'delete') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('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 // Confirmation to delete line
if ($action == 'deleteline') if ($action == 'deleteline') {
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
} }
// Clone confirmation // Clone confirmation
@@ -436,8 +439,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of validation // Confirmation of validation
if ($action == 'validate') if ($action == 'validate') {
{
// We check that object has a temporary ref // We check that object has a temporary ref
$ref = substr($object->ref, 1, 4); $ref = substr($object->ref, 1, 4);
if ($ref == 'PROV') { if ($ref == 'PROV') {
@@ -457,13 +459,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->mrp->enabled)) if (!empty($conf->mrp->enabled)) {
{
$langs->load("mrp"); $langs->load("mrp");
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$formproduct = new FormProduct($db); $formproduct = new FormProduct($db);
$forcecombo = 0; $forcecombo = 0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy if ($conf->browser->name == 'ie') {
$forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
}
$formquestion = array( $formquestion = array(
// 'text' => $langs->trans("ConfirmClone"), // 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
@@ -477,8 +480,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Call Hook formConfirm // Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; if (empty($reshook)) {
elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; $formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm // Print form confirm
print $formconfirm; print $formconfirm;
@@ -496,14 +502,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Thirdparty // 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 // Project
if (!empty($conf->projet->enabled)) if (!empty($conf->projet->enabled)) {
{
$langs->load("projects"); $langs->load("projects");
$morehtmlref .= '<br>'.$langs->trans('Project').' '; $morehtmlref .= '<br>'.$langs->trans('Project').' ';
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($action != 'classify') {
if ($action != 'classify')
$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
}
if ($action == 'classify') { 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.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@@ -554,8 +559,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print dol_get_fiche_end(); print dol_get_fiche_end();
if (!in_array($action, array('consumeorproduce', 'consumeandproduceall'))) if (!in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
$parameters = array(); $parameters = array();
@@ -563,12 +567,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
if (empty($reshook)) { if (empty($reshook)) {
// Validate // Validate
if ($object->status == $object::STATUS_DRAFT) if ($object->status == $object::STATUS_DRAFT) {
{ if ($permissiontoadd) {
if ($permissiontoadd) if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) {
{
if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0))
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>';
} else { } else {
$langs->load("errors"); $langs->load("errors");
@@ -600,10 +601,8 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Cancel - Reopen // Cancel - Reopen
if ($permissiontoadd) if ($permissiontoadd) {
{ if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) {
if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
{
$arrayproduced = $object->fetchLinesLinked('produced', 0); $arrayproduced = $object->fetchLinesLinked('produced', 0);
$nbProduced = 0; $nbProduced = 0;
foreach ($arrayproduced as $lineproduced) { foreach ($arrayproduced as $lineproduced) {
@@ -618,8 +617,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n"; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n";
} }
if ($object->status == $object::STATUS_CANCELED) if ($object->status == $object::STATUS_CANCELED) {
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("Re-Open").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("Re-Open").'</a>'."\n";
} }
@@ -636,8 +634,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '</div>'; print '</div>';
} }
if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) {
{
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="confirm_'.$action.'">'; print '<input type="hidden" name="action" value="confirm_'.$action.'">';
@@ -672,8 +669,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
*/ */
$collapse = 1; $collapse = 1;
if (!empty($object->table_element_line)) if (!empty($object->table_element_line)) {
{
// Show object lines // Show object lines
$object->fetchLines(); $object->fetchLines();
@@ -695,11 +691,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<td class="right">'.$langs->trans("Qty").'</td>'; print '<td class="right">'.$langs->trans("Qty").'</td>';
print '<td class="right">'.$langs->trans("QtyAlreadyConsumed").'</td>'; print '<td class="right">'.$langs->trans("QtyAlreadyConsumed").'</td>';
print '<td>'; print '<td>';
if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse"); if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
print $langs->trans("Warehouse");
}
print '</td>'; print '</td>';
if ($conf->productbatch->enabled) { if ($conf->productbatch->enabled) {
print '<td>'; print '<td>';
if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Batch"); if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
print $langs->trans("Batch");
}
print '</td>'; print '</td>';
} }
print '</tr>'; print '</tr>';
@@ -723,8 +723,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Lines to consume // Lines to consume
if (!empty($object->lines)) if (!empty($object->lines)) {
{
$nblinetoconsume = 0; $nblinetoconsume = 0;
foreach ($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toconsume') { if ($line->role == 'toconsume') {
@@ -752,8 +751,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '</td>'; print '</td>';
print '<td class="right nowraponall">'; print '<td class="right nowraponall">';
$help = ''; $help = '';
if ($line->qty_frozen) $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("QuantityFrozen").'</strong>: '.yn(1).' ('.$langs->trans("QuantityConsumedInvariable").')'; if ($line->qty_frozen) {
if ($line->disable_stock_change) $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("DisableStockChange").'</strong>: '.yn(1).' ('.(($tmpproduct->type == Product::TYPE_SERVICE && empty($conf->global->STOCK_SUPPORTS_SERVICES)) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")).')'; $help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("QuantityFrozen").'</strong>: '.yn(1).' ('.$langs->trans("QuantityConsumedInvariable").')';
}
if ($line->disable_stock_change) {
$help .= ($help ? '<br>' : '').'<strong>'.$langs->trans("DisableStockChange").'</strong>: '.yn(1).' ('.(($tmpproduct->type == Product::TYPE_SERVICE && empty($conf->global->STOCK_SUPPORTS_SERVICES)) ? $langs->trans("NoStockChangeOnServices") : $langs->trans("DisableStockChangeHelp")).')';
}
if ($help) { if ($help) {
print $form->textwithpicto($line->qty, $help, -1); print $form->textwithpicto($line->qty, $help, -1);
} else { } else {
@@ -774,9 +777,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}); });
});'; });';
print '</script>'; print '</script>';
if (empty($conf->use_javascript_ajax)) print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">'; if (empty($conf->use_javascript_ajax)) {
print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">';
}
print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"'); print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"');
if (empty($conf->use_javascript_ajax)) print '</a>'; if (empty($conf->use_javascript_ajax)) {
print '</a>';
}
} else { } else {
if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line if ($nblinetoconsume == $nblinetoconsumecursor) { // If it is the last line
print '<script>jQuery("#tablelines").removeClass("nobottom");</script>'; print '<script>jQuery("#tablelines").removeClass("nobottom");</script>';
@@ -802,7 +809,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<td class="tdoverflowmax150">'; print '<td class="tdoverflowmax150">';
if ($line2['fk_warehouse'] > 0) { if ($line2['fk_warehouse'] > 0) {
$result = $tmpwarehouse->fetch($line2['fk_warehouse']); $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
if ($result > 0) print $tmpwarehouse->getNomUrl(1); if ($result > 0) {
print $tmpwarehouse->getNomUrl(1);
}
} }
print '</td>'; print '</td>';
// Lot Batch // Lot Batch
@@ -821,7 +830,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<tr>'; print '<tr>';
print '<td><span class="opacitymedium">'.$langs->trans("ToConsume").'</span></td>'; print '<td><span class="opacitymedium">'.$langs->trans("ToConsume").'</span></td>';
$preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed)); $preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed));
if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) $preselected = 0; if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) {
$preselected = 0;
}
print '<td class="right"><input type="text" class="width50 right" name="qty-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; print '<td class="right"><input type="text" class="width50 right" name="qty-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
print '<td></td>'; print '<td></td>';
print '<td>'; print '<td>';
@@ -851,7 +862,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
} }
print '</table>'; print '</table>';
print '</div>'; print '</div>';
// Lines to produce // Lines to produce
@@ -870,18 +881,21 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<td class="right">'.$langs->trans("Qty").'</td>'; print '<td class="right">'.$langs->trans("Qty").'</td>';
print '<td class="right">'.$langs->trans("QtyAlreadyProduced").'</td>'; print '<td class="right">'.$langs->trans("QtyAlreadyProduced").'</td>';
print '<td>'; print '<td>';
if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Warehouse"); if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
print $langs->trans("Warehouse");
}
print '</td>'; print '</td>';
if ($conf->productbatch->enabled) { if ($conf->productbatch->enabled) {
print '<td>'; print '<td>';
if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) print $langs->trans("Batch"); if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
print $langs->trans("Batch");
}
print '</td>'; print '</td>';
print '<td></td>'; print '<td></td>';
} }
print '</tr>'; print '</tr>';
if (!empty($object->lines)) if (!empty($object->lines)) {
{
$nblinetoproduce = 0; $nblinetoproduce = 0;
foreach ($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toproduce') { if ($line->role == 'toproduce') {
@@ -930,9 +944,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}); });
});'; });';
print '</script>'; print '</script>';
if (empty($conf->use_javascript_ajax)) print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">'; if (empty($conf->use_javascript_ajax)) {
print '<a href="'.$_SERVER["PHP_SELF"].'?collapse='.$collapse.','.$line->id.'">';
}
print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"'); print img_picto($langs->trans("ShowDetails"), "chevron-down", 'id="expandtoproduce'.$line->id.'"');
if (empty($conf->use_javascript_ajax)) print '</a>'; if (empty($conf->use_javascript_ajax)) {
print '</a>';
}
} }
print ' '.$alreadyproduced; print ' '.$alreadyproduced;
print '</td>'; print '</td>';
@@ -955,7 +973,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<td class="tdoverflowmax150">'; print '<td class="tdoverflowmax150">';
if ($line2['fk_warehouse'] > 0) { if ($line2['fk_warehouse'] > 0) {
$result = $tmpwarehouse->fetch($line2['fk_warehouse']); $result = $tmpwarehouse->fetch($line2['fk_warehouse']);
if ($result > 0) print $tmpwarehouse->getNomUrl(1); if ($result > 0) {
print $tmpwarehouse->getNomUrl(1);
}
} }
print '</td>'; print '</td>';
if ($conf->productbatch->enabled) { if ($conf->productbatch->enabled) {
@@ -975,7 +995,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<tr name="batch_'.$line->id.'_'.$i.'">'; print '<tr name="batch_'.$line->id.'_'.$i.'">';
print '<td><span class="opacitymedium">'.$langs->trans("ToProduce").'</span></td>'; print '<td><span class="opacitymedium">'.$langs->trans("ToProduce").'</span></td>';
$preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced)); $preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced));
if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) $preselected = 0; if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) {
$preselected = 0;
}
print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>'; print '<td class="right"><input type="text" class="width50 right" id="qtytoproduce-'.$line->id.'-'.$i.'" name="qtytoproduce-'.$line->id.'-'.$i.'" value="'.$preselected.'"></td>';
print '<td></td>'; print '<td></td>';
print '<td>'; print '<td>';
@@ -1013,8 +1035,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '</div>'; print '</div>';
} }
if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) if (in_array($action, array('consumeorproduce', 'consumeandproduceall', 'addconsumeline'))) {
{
print "</form>\n"; print "</form>\n";
} }
} }

View File

@@ -17,13 +17,14 @@
*/ */
// Protection to avoid direct call of template // 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"; print "Error, template page can't be called as URL";
exit; exit;
} }
if (!is_object($form)) $form = new Form($db); if (!is_object($form)) {
$form = new Form($db);
}
$qtytoconsumeforline = $this->tpl['qty'] / $this->tpl['efficiency']; $qtytoconsumeforline = $this->tpl['qty'] / $this->tpl['efficiency'];
/*if ((empty($this->tpl['qty_frozen']) && $this->tpl['qty_bom'] > 1)) { /*if ((empty($this->tpl['qty_frozen']) && $this->tpl['qty_bom'] > 1)) {
@@ -43,7 +44,9 @@ print '<td class="center">'.($this->tpl['disable_stock_change'] ? yn($this->tpl[
//print '<td class="right">'.$this->tpl['efficiency'].'</td>'; //print '<td class="right">'.$this->tpl['efficiency'].'</td>';
$selected = 1; $selected = 1;
if (!empty($selectedLines) && !in_array($this->tpl['id'], $selectedLines)) $selected = 0; if (!empty($selectedLines) && !in_array($this->tpl['id'], $selectedLines)) {
$selected = 0;
}
print '<td class="center">'; print '<td class="center">';
//print '<input id="cb'.$this->tpl['id'].'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$this->tpl['id'].'"'.($selected?' checked="checked"':'').'>'; //print '<input id="cb'.$this->tpl['id'].'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$this->tpl['id'].'"'.($selected?' checked="checked"':'').'>';
print '</td>'; print '</td>';

View File

@@ -121,14 +121,15 @@ class MultiCurrency extends CommonObject
$error = 0; $error = 0;
if (self::checkCodeAlreadyExists($this->code)) if (self::checkCodeAlreadyExists($this->code)) {
{
$error++; $error++;
$this->errors[] = $langs->trans('multicurrency_code_already_added'); $this->errors[] = $langs->trans('multicurrency_code_already_added');
return -1; return -1;
} }
if (empty($this->entity) || $this->entity <= 0) $this->entity = $conf->entity; if (empty($this->entity) || $this->entity <= 0) {
$this->entity = $conf->entity;
}
$now = date('Y-m-d H:i:s'); $now = date('Y-m-d H:i:s');
// Insert request // Insert request
@@ -163,7 +164,9 @@ class MultiCurrency extends CommonObject
if ($trigger) { if ($trigger) {
$result = $this->call_trigger('CURRENCY_CREATE', $user); $result = $this->call_trigger('CURRENCY_CREATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
} }
} }
@@ -194,8 +197,11 @@ class MultiCurrency extends CommonObject
$sql = 'SELECT'; $sql = 'SELECT';
$sql .= ' c.rowid, c.name, c.code, c.entity, c.date_create, c.fk_user'; $sql .= ' c.rowid, c.name, c.code, c.entity, c.date_create, c.fk_user';
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' AS c'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' AS c';
if (!empty($code)) $sql .= ' WHERE c.code = \''.$this->db->escape($code).'\' AND c.entity = '.$conf->entity; if (!empty($code)) {
else $sql .= ' WHERE c.rowid = '.$id; $sql .= ' WHERE c.code = \''.$this->db->escape($code).'\' AND c.entity = '.$conf->entity;
} else {
$sql .= ' WHERE c.rowid = '.$id;
}
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@@ -308,7 +314,9 @@ class MultiCurrency extends CommonObject
if (!$error && $trigger) { if (!$error && $trigger) {
$result = $this->call_trigger('CURRENCY_MODIFY', $user); $result = $this->call_trigger('CURRENCY_MODIFY', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
} }
// Commit or rollback // Commit or rollback
@@ -341,7 +349,9 @@ class MultiCurrency extends CommonObject
if ($trigger) { if ($trigger) {
$result = $this->call_trigger('CURRENCY_DELETE', $user); $result = $this->call_trigger('CURRENCY_DELETE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
} }
if (!$error) { if (!$error) {
@@ -383,10 +393,8 @@ class MultiCurrency extends CommonObject
*/ */
public function deleteRates() public function deleteRates()
{ {
foreach ($this->rates as &$rate) foreach ($this->rates as &$rate) {
{ if ($rate->delete() <= 0) {
if ($rate->delete() <= 0)
{
return false; return false;
} }
} }
@@ -402,11 +410,10 @@ class MultiCurrency extends CommonObject
*/ */
public function addRate($rate) public function addRate($rate)
{ {
$currencyRate = new CurrencyRate($this->db); $currencyRate = new CurrencyRate($this->db);
$currencyRate->rate = price2num($rate); $currencyRate->rate = price2num($rate);
if ($currencyRate->create($this->id) > 0) if ($currencyRate->create($this->id) > 0) {
{
$this->rate = $currencyRate; $this->rate = $currencyRate;
return 1; return 1;
} else { } else {
@@ -433,19 +440,20 @@ class MultiCurrency extends CommonObject
$sql = 'SELECT label FROM '.MAIN_DB_PREFIX."c_currencies WHERE code_iso = '".$this->db->escape($code)."'"; $sql = 'SELECT label FROM '.MAIN_DB_PREFIX."c_currencies WHERE code_iso = '".$this->db->escape($code)."'";
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql && ($line = $db->fetch_object($resql))) if ($resql && ($line = $db->fetch_object($resql))) {
{
$currency->name = $line->label; $currency->name = $line->label;
} }
if ($currency->create($user) > 0) if ($currency->create($user) > 0) {
{
$currency->addRate($rate); $currency->addRate($rate);
if (!empty($line)) return 2; if (!empty($line)) {
else return 1; return 2;
} else {
return 1;
}
} }
return -1; return -1;
@@ -469,7 +477,7 @@ class MultiCurrency extends CommonObject
*/ */
public function getRate() public function getRate()
{ {
$sql = 'SELECT cr.rowid'; $sql = 'SELECT cr.rowid';
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as cr'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as cr';
$sql .= ' WHERE cr.fk_multicurrency = '.$this->id; $sql .= ' WHERE cr.fk_multicurrency = '.$this->id;
$sql .= ' AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM '.MAIN_DB_PREFIX.$this->table_element_line.' AS cr2 WHERE cr2.fk_multicurrency = '.$this->id.')'; $sql .= ' AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM '.MAIN_DB_PREFIX.$this->table_element_line.' AS cr2 WHERE cr2.fk_multicurrency = '.$this->id.')';
@@ -492,14 +500,17 @@ class MultiCurrency extends CommonObject
*/ */
public static function getIdFromCode($db, $code) public static function getIdFromCode($db, $code)
{ {
global $conf; global $conf;
$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."multicurrency WHERE code = '".$db->escape($code)."' AND entity = ".$conf->entity; $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."multicurrency WHERE code = '".$db->escape($code)."' AND entity = ".$conf->entity;
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql && $obj = $db->fetch_object($resql)) return $obj->rowid; if ($resql && $obj = $db->fetch_object($resql)) {
else return 0; return $obj->rowid;
} else {
return 0;
}
} }
/** /**
@@ -516,7 +527,7 @@ class MultiCurrency extends CommonObject
{ {
global $conf; global $conf;
$sql1 = 'SELECT m.rowid, mc.rate FROM '.MAIN_DB_PREFIX.'multicurrency m'; $sql1 = 'SELECT m.rowid, mc.rate FROM '.MAIN_DB_PREFIX.'multicurrency m';
$sql1 .= ' LEFT JOIN '.MAIN_DB_PREFIX.'multicurrency_rate mc ON (m.rowid = mc.fk_multicurrency)'; $sql1 .= ' LEFT JOIN '.MAIN_DB_PREFIX.'multicurrency_rate mc ON (m.rowid = mc.fk_multicurrency)';
$sql1 .= " WHERE m.code = '".$db->escape($code)."'"; $sql1 .= " WHERE m.code = '".$db->escape($code)."'";
@@ -531,12 +542,14 @@ class MultiCurrency extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $db->query($sql1.$sql2.$sql3); $resql = $db->query($sql1.$sql2.$sql3);
if ($resql && $obj = $db->fetch_object($resql)) return array($obj->rowid, $obj->rate); if ($resql && $obj = $db->fetch_object($resql)) {
else { return array($obj->rowid, $obj->rate);
if (!empty($conf->global->MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE)) } else {
{ if (!empty($conf->global->MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE)) {
$resql = $db->query($sql1.$sql3); $resql = $db->query($sql1.$sql3);
if ($resql && $obj = $db->fetch_object($resql)) return array($obj->rowid, $obj->rate); if ($resql && $obj = $db->fetch_object($resql)) {
return array($obj->rowid, $obj->rate);
}
} }
return array(0, 1); return array(0, 1);
@@ -556,11 +569,15 @@ class MultiCurrency extends CommonObject
{ {
$multicurrency_tx = self::getInvoiceRate($fk_facture, $table); $multicurrency_tx = self::getInvoiceRate($fk_facture, $table);
if ($multicurrency_tx) if ($multicurrency_tx) {
{ if ($way == 'dolibarr') {
if ($way == 'dolibarr') return price2num($amount * $multicurrency_tx, 'MU'); return price2num($amount * $multicurrency_tx, 'MU');
else return price2num($amount / $multicurrency_tx, 'MU'); } else {
} else return $amount; return price2num($amount / $multicurrency_tx, 'MU');
}
} else {
return $amount;
}
} }
/** /**
@@ -578,8 +595,7 @@ class MultiCurrency extends CommonObject
dol_syslog(__METHOD__, LOG_DEBUG); dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql && ($line = $db->fetch_object($resql))) if ($resql && ($line = $db->fetch_object($resql))) {
{
return $line->multicurrency_tx; return $line->multicurrency_tx;
} }
@@ -597,14 +613,11 @@ class MultiCurrency extends CommonObject
{ {
global $conf; global $conf;
if ($conf->currency != $conf->global->MULTICURRENCY_APP_SOURCE) if ($conf->currency != $conf->global->MULTICURRENCY_APP_SOURCE) {
{
$alternate_source = 'USD'.$conf->currency; $alternate_source = 'USD'.$conf->currency;
if (!empty($TRate->{$alternate_source})) if (!empty($TRate->{$alternate_source})) {
{
$coef = $TRate->USDUSD / $TRate->{$alternate_source}; $coef = $TRate->USDUSD / $TRate->{$alternate_source};
foreach ($TRate as $attr => &$rate) foreach ($TRate as $attr => &$rate) {
{
$rate *= $coef; $rate *= $coef;
} }
@@ -642,22 +655,17 @@ class MultiCurrency extends CommonObject
$response = $resget['content']; $response = $resget['content'];
$response = json_decode($response); $response = json_decode($response);
if ($response->success) if ($response->success) {
{
$TRate = $response->quotes; $TRate = $response->quotes;
$timestamp = $response->timestamp; $timestamp = $response->timestamp;
if (self::recalculRates($TRate) >= 0) if (self::recalculRates($TRate) >= 0) {
{ foreach ($TRate as $currency_code => $rate) {
foreach ($TRate as $currency_code => $rate)
{
$code = substr($currency_code, 3, 3); $code = substr($currency_code, 3, 3);
$obj = new MultiCurrency($db); $obj = new MultiCurrency($db);
if ($obj->fetch(null, $code) > 0) if ($obj->fetch(null, $code) > 0) {
{
$obj->updateRate($rate); $obj->updateRate($rate);
} elseif ($addifnotfound) } elseif ($addifnotfound) {
{
self::addRateFromDolibarr($code, $rate); self::addRateFromDolibarr($code, $rate);
} }
} }
@@ -681,11 +689,14 @@ class MultiCurrency extends CommonObject
*/ */
public static function checkCodeAlreadyExists($code) public static function checkCodeAlreadyExists($code)
{ {
global $db; global $db;
$currency = new MultiCurrency($db); $currency = new MultiCurrency($db);
if ($currency->fetch('', $code) > 0) return true; if ($currency->fetch('', $code) > 0) {
else return false; return true;
} else {
return false;
}
} }
} }
@@ -758,7 +769,9 @@ class CurrencyRate extends CommonObjectLine
$error = 0; $error = 0;
$this->rate = price2num($this->rate); $this->rate = price2num($this->rate);
if (empty($this->entity) || $this->entity <= 0) $this->entity = $conf->entity; if (empty($this->entity) || $this->entity <= 0) {
$this->entity = $conf->entity;
}
$now = empty($this->date_sync) ? dol_now() : $this->date_sync; $now = empty($this->date_sync) ? dol_now() : $this->date_sync;
// Insert request // Insert request
@@ -791,7 +804,9 @@ class CurrencyRate extends CommonObjectLine
if ($trigger) { if ($trigger) {
$result = $this->call_trigger('CURRENCYRATE_CREATE', $user); $result = $this->call_trigger('CURRENCYRATE_CREATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
} }
} }
@@ -867,8 +882,12 @@ class CurrencyRate extends CommonObjectLine
// Update request // Update request
$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
$sql .= ' rate='.$this->rate; $sql .= ' rate='.$this->rate;
if (!empty($this->date_sync)) $sql .= ", date_sync='".$this->db->idate($this->date_sync)."'"; if (!empty($this->date_sync)) {
if (!empty($this->fk_multicurrency)) $sql .= ', fk_multicurrency='.$this->fk_multicurrency; $sql .= ", date_sync='".$this->db->idate($this->date_sync)."'";
}
if (!empty($this->fk_multicurrency)) {
$sql .= ', fk_multicurrency='.$this->fk_multicurrency;
}
$sql .= ' WHERE rowid='.$this->id; $sql .= ' WHERE rowid='.$this->id;
$this->db->begin(); $this->db->begin();
@@ -883,7 +902,9 @@ class CurrencyRate extends CommonObjectLine
if (!$error && $trigger) { if (!$error && $trigger) {
$result = $this->call_trigger('CURRENCYRATE_MODIFY', $user); $result = $this->call_trigger('CURRENCYRATE_MODIFY', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
} }
// Commit or rollback // Commit or rollback
@@ -916,7 +937,9 @@ class CurrencyRate extends CommonObjectLine
if ($trigger) { if ($trigger) {
$result = $this->call_trigger('CURRENCYRATE_DELETE', $user); $result = $this->call_trigger('CURRENCYRATE_DELETE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
} }
if (!$error) { if (!$error) {

View File

@@ -58,12 +58,18 @@ $sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", '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 if (empty($page) || $page == -1) {
$page = 0;
} // If $page is not defined, or '' or -1
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
if (!$sortfield) $sortfield = "cr.date_sync"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "cr.date_sync";
}
if (!$sortorder) {
$sortorder = "DESC";
}
// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
@@ -74,7 +80,9 @@ $form = new Form($db);
$hookmanager->initHooks(array('EditorRatelist', 'globallist')); $hookmanager->initHooks(array('EditorRatelist', 'globallist'));
if (empty($action)) $action = 'list'; if (empty($action)) {
$action = 'list';
}
// List of fields to search into when doing a "search in all" // List of fields to search into when doing a "search in all"
$fieldstosearchall = array( $fieldstosearchall = array(
@@ -184,20 +192,24 @@ if ($action == "confirm_delete") {
} }
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
if (empty($reshook)) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
{ }
if (empty($reshook)) {
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$sall = ""; $sall = "";
$search_date_sync = ""; $search_date_sync = "";
$search_rate = ""; $search_rate = "";
@@ -324,10 +336,18 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql .= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr '; $sql .= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr ';
$sql .= " INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid";
if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); if ($sall) {
if ($search_date_sync) $sql .= natural_search('cr.date_sync', $search_date_sync); $sql .= natural_search(array_keys($fieldstosearchall), $sall);
if ($search_rate) $sql .= natural_search('cr.rate', $search_rate); }
if ($search_code) $sql .= natural_search('m.code', $search_code); if ($search_date_sync) {
$sql .= natural_search('cr.date_sync', $search_date_sync);
}
if ($search_rate) {
$sql .= natural_search('cr.rate', $search_rate);
}
if ($search_code) {
$sql .= natural_search('m.code', $search_code);
}
$sql .= " WHERE m.code <> '".$db->escape($conf->currency)."'"; $sql .= " WHERE m.code <> '".$db->escape($conf->currency)."'";
// Add where from hooks // Add where from hooks
@@ -345,14 +365,12 @@ $sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$result = $db->query($sql); $result = $db->query($sql);
if ($result) { if ($result) {
$nbtotalofrecords = $db->num_rows($result); $nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
@@ -364,29 +382,46 @@ 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) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
if ($sall) $param .= "&sall=".urlencode($sall); }
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
if ($sall) {
$param .= "&sall=".urlencode($sall);
}
if ($search_date_sync) $param = "&search_date_sync=".urlencode($search_date_sync); if ($search_date_sync) {
if ($search_rate) $param = "&search_rate=".urlencode($search_rate); $param = "&search_date_sync=".urlencode($search_date_sync);
if ($search_code != '') $param .= "&search_code=".urlencode($search_code); }
if ($search_rate) {
$param = "&search_rate=".urlencode($search_rate);
}
if ($search_code != '') {
$param .= "&search_code=".urlencode($search_code);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
if ($user->admin) $arrayofmassactions['predelete'] = $langs->trans("Delete"); if ($user->admin) {
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = $langs->trans("Delete");
}
if (in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">'; print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@@ -399,9 +434,10 @@ if ($resql)
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) if ($sall) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@@ -411,11 +447,13 @@ if ($resql)
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if ($moreforfilter) if ($moreforfilter) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@@ -423,7 +461,9 @@ if ($resql)
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); if ($massactionbutton) {
$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
}
print '<div class="div-table-responsive">'; print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
@@ -432,22 +472,19 @@ if ($resql)
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
// date // date
if (!empty($arrayfields['cr.date_sync']['checked'])) if (!empty($arrayfields['cr.date_sync']['checked'])) {
{
print '<td class="liste_titre" align="left">'; print '<td class="liste_titre" align="left">';
print '<input class="flat" type="text" name="search_date_sync" size="8" value="'.dol_escape_htmltag($search_date_sync).'">'; print '<input class="flat" type="text" name="search_date_sync" size="8" value="'.dol_escape_htmltag($search_date_sync).'">';
print '</td>'; print '</td>';
} }
// code // code
if (!empty($arrayfields['m.code']['checked'])) if (!empty($arrayfields['m.code']['checked'])) {
{
print '<td class="liste_titre" align="left">'; print '<td class="liste_titre" align="left">';
print '<input class="flat" type="text" name="search_code" size="12" value="'.dol_escape_htmltag($search_code).'">'; print '<input class="flat" type="text" name="search_code" size="12" value="'.dol_escape_htmltag($search_code).'">';
print '</td>'; print '</td>';
} }
// rate // rate
if (!empty($arrayfields['cr.rate']['checked'])) if (!empty($arrayfields['cr.rate']['checked'])) {
{
print '<td class="liste_titre" align="left">'; print '<td class="liste_titre" align="left">';
print '<input class="flat" type="text" name="search_rate" size="8" value="'.dol_escape_htmltag($search_rate).'">'; print '<input class="flat" type="text" name="search_rate" size="8" value="'.dol_escape_htmltag($search_rate).'">';
print '</td>'; print '</td>';
@@ -466,9 +503,15 @@ if ($resql)
print '</tr>'; print '</tr>';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['cr.date_sync']['checked'])) print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['cr.date_sync']['checked'])) {
if (!empty($arrayfields['m.code']['checked'])) print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['cr.rate']['checked'])) print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder); }
if (!empty($arrayfields['m.code']['checked'])) {
print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder);
}
if (!empty($arrayfields['cr.rate']['checked'])) {
print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder);
}
// Hook fields // Hook fields
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
@@ -480,38 +523,40 @@ if ($resql)
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// date_sync // date_sync
if (!empty($arrayfields['cr.date_sync']['checked'])) if (!empty($arrayfields['cr.date_sync']['checked'])) {
{
print '<td class="tdoverflowmax200">'; print '<td class="tdoverflowmax200">';
print $obj->date_sync; print $obj->date_sync;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// code // code
if (!empty($arrayfields['m.code']['checked'])) if (!empty($arrayfields['m.code']['checked'])) {
{
print '<td class="tdoverflowmax200">'; print '<td class="tdoverflowmax200">';
print $obj->code." ".$obj->name; print $obj->code." ".$obj->name;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// rate // rate
if (!empty($arrayfields['cr.rate']['checked'])) if (!empty($arrayfields['cr.rate']['checked'])) {
{
print '<td class="tdoverflowmax200">'; print '<td class="tdoverflowmax200">';
print $obj->rate; print $obj->rate;
print "</td>\n"; print "</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Fields from hook // Fields from hook
@@ -521,16 +566,19 @@ if ($resql)
// Action // Action
print '<td class="nowrap" align="center">'; print '<td class="nowrap" align="center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=updateRate&amp;id_rate='.$obj->rowid.'">'.img_picto('edit', 'edit').'</a>'; print '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=updateRate&amp;id_rate='.$obj->rowid.'">'.img_picto('edit', 'edit').'</a>';
print '<a class="marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=deleteRate&amp;id_rate='.$obj->rowid.'">'.img_picto('delete', 'delete').'</a>'; print '<a class="marginleftonly marginrightonly" href="'.$_SERVER["PHP_SELF"].'?action=deleteRate&amp;id_rate='.$obj->rowid.'">'.img_picto('delete', 'delete').'</a>';
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect marginleftonly" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect marginleftonly" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print "</tr>\n"; print "</tr>\n";
$i++; $i++;
@@ -542,8 +590,7 @@ if ($resql)
print "</div>"; print "</div>";
print '</form>'; print '</form>';
} } else {
else {
dol_print_error($db); dol_print_error($db);
} }

View File

@@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
// Initialisation des variables // Initialisation des variables
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
@@ -62,17 +64,21 @@ $expiredate = dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'),
$parameters = array('id' => $numsondage); $parameters = array('id' => $numsondage);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{ if ($cancel) {
if ($cancel) $action = ''; $action = '';
}
// Delete // Delete
if ($action == 'delete_confirm') if ($action == 'delete_confirm') {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$result = $object->delete($user, '', $numsondage); $result = $object->delete($user, '', $numsondage);
@@ -81,36 +87,33 @@ if (empty($reshook))
} }
// Close // Close
if ($action == 'close') if ($action == 'close') {
{
$object->status = Opensurveysondage::STATUS_CLOSED; $object->status = Opensurveysondage::STATUS_CLOSED;
$object->update($user); $object->update($user);
} }
// Reopend // Reopend
if ($action == 'reopen') if ($action == 'reopen') {
{
$object->status = Opensurveysondage::STATUS_VALIDATED; $object->status = Opensurveysondage::STATUS_VALIDATED;
$object->update($user); $object->update($user);
} }
// Update // Update
if ($action == 'update') if ($action == 'update') {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); 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'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors');
$error++; $error++;
$action = 'edit'; $action = 'edit';
} }
if (!$error) if (!$error) {
{
$object->title = (string) GETPOST('nouveautitre', 'alphanohtml'); $object->title = (string) GETPOST('nouveautitre', 'alphanohtml');
$object->description = (string) GETPOST('nouveauxcommentaires', 'restricthtml'); $object->description = (string) GETPOST('nouveauxcommentaires', 'restricthtml');
$object->mail_admin = (string) GETPOST('nouvelleadresse', 'alpha'); $object->mail_admin = (string) GETPOST('nouvelleadresse', 'alpha');
@@ -128,8 +131,7 @@ if (empty($reshook))
} }
// Add comment // Add comment
if (GETPOST('ajoutcomment')) if (GETPOST('ajoutcomment')) {
{
$error = 0; $error = 0;
if (!GETPOST('comment')) { if (!GETPOST('comment')) {
@@ -147,8 +149,7 @@ if (empty($reshook))
$resql = $object->addComment($comment, $comment_user); $resql = $object->addComment($comment, $comment_user);
if (!$resql) if (!$resql) {
{
setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors'); setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors');
} }
} }
@@ -156,17 +157,20 @@ if (empty($reshook))
// Delete comment // Delete comment
$idcomment = GETPOST('deletecomment', 'int'); $idcomment = GETPOST('deletecomment', 'int');
if ($idcomment) if ($idcomment) {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$resql = $object->deleteComment($idcomment); $resql = $object->deleteComment($idcomment);
} }
if ($action == 'edit') { if ($action == 'edit') {
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
} }
} }
@@ -177,8 +181,7 @@ if (empty($reshook))
$form = new Form($db); $form = new Form($db);
if ($object->fk_user_creat) if ($object->fk_user_creat) {
{
$userstatic = new User($db); $userstatic = new User($db);
$userstatic->fetch($object->fk_user_creat); $userstatic->fetch($object->fk_user_creat);
} }
@@ -193,8 +196,7 @@ llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss);
// Define format of choices // Define format of choices
$toutsujet = explode(",", $object->sujet); $toutsujet = explode(",", $object->sujet);
$listofanswers = array(); $listofanswers = array();
foreach ($toutsujet as $value) foreach ($toutsujet as $value) {
{
$tmp = explode('@', $value); $tmp = explode('@', $value);
$listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox'));
} }
@@ -232,16 +234,16 @@ print ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate").'</td><
print '<tr><td>'; print '<tr><td>';
$adresseadmin = $object->mail_admin; $adresseadmin = $object->mail_admin;
print $langs->trans("Title").'</td><td colspan="2">'; print $langs->trans("Title").'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="text" name="nouveautitre" style="width: 95%" value="'.dol_escape_htmltag(dol_htmlentities($object->title)).'">'; print '<input type="text" name="nouveautitre" style="width: 95%" value="'.dol_escape_htmltag(dol_htmlentities($object->title)).'">';
} else print dol_htmlentities($object->title); } else {
print dol_htmlentities($object->title);
}
print '</td></tr>'; print '</td></tr>';
// Description // Description
print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td colspan="2">'; print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
$doleditor = new DolEditor('nouveauxcommentaires', $object->description, '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%'); $doleditor = new DolEditor('nouveauxcommentaires', $object->description, '', 120, 'dolibarr_notes', 'In', 1, 1, 1, ROWS_7, '90%');
$doleditor->Create(0, ''); $doleditor->Create(0, '');
} else { } else {
@@ -253,17 +255,17 @@ print '</td></tr>';
//If linked user, then emails are going to be sent to users' email //If linked user, then emails are going to be sent to users' email
if (!$object->fk_user_creat) { if (!$object->fk_user_creat) {
print '<tr><td>'.$langs->trans("EMail").'</td><td colspan="2">'; print '<tr><td>'.$langs->trans("EMail").'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="text" name="nouvelleadresse" class="minwith200" value="'.$object->mail_admin.'">'; print '<input type="text" name="nouvelleadresse" class="minwith200" value="'.$object->mail_admin.'">';
} else print dol_print_email($object->mail_admin, 0, 0, 1); } else {
print dol_print_email($object->mail_admin, 0, 0, 1);
}
print '</td></tr>'; print '</td></tr>';
} }
// Receive an email with each vote // Receive an email with each vote
print '<tr><td>'.$langs->trans('ToReceiveEMailForEachVote').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('ToReceiveEMailForEachVote').'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="checkbox" name="mailsonde" '.($object->mailsonde ? 'checked="checked"' : '').'">'; print '<input type="checkbox" name="mailsonde" '.($object->mailsonde ? 'checked="checked"' : '').'">';
} else { } else {
print yn($object->mailsonde); print yn($object->mailsonde);
@@ -279,26 +281,31 @@ print '</td></tr>';
// Users can comment // Users can comment
print '<tr><td>'.$langs->trans('CanComment').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('CanComment').'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="checkbox" name="cancomment" '.($object->allow_comments ? 'checked="checked"' : '').'">'; print '<input type="checkbox" name="cancomment" '.($object->allow_comments ? 'checked="checked"' : '').'">';
} else print yn($object->allow_comments); } else {
print yn($object->allow_comments);
}
print '</td></tr>'; print '</td></tr>';
// Users can see others vote // Users can see others vote
print '<tr><td>'.$langs->trans('CanSeeOthersVote').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('CanSeeOthersVote').'</td><td colspan="2">';
if ($action == 'edit') if ($action == 'edit') {
{
print '<input type="checkbox" name="canseeothersvote" '.($object->allow_spy ? 'checked="checked"' : '').'">'; print '<input type="checkbox" name="canseeothersvote" '.($object->allow_spy ? 'checked="checked"' : '').'">';
} else print yn($object->allow_spy); } else {
print yn($object->allow_spy);
}
print '</td></tr>'; print '</td></tr>';
// Expire date // Expire date
print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">';
if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); if ($action == 'edit') {
else { print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0);
} else {
print dol_print_date($object->date_fin, 'day'); print dol_print_date($object->date_fin, 'day');
if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) {
print img_warning($langs->trans("Expired"));
}
} }
print '</td></tr>'; print '</td></tr>';
@@ -322,7 +329,9 @@ $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domai
$url = $urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage; $url = $urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage;
print '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">'; print '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">';
if ($action != 'edit') print ajax_autoselect("opensurveyurl", $url); if ($action != 'edit') {
print ajax_autoselect("opensurveyurl", $url);
}
print '</td></tr>'; print '</td></tr>';
@@ -332,8 +341,7 @@ print '</div>';
print dol_get_fiche_end(); print dol_get_fiche_end();
if ($action == 'edit') if ($action == 'edit') {
{
print '<div class="center">'; print '<div class="center">';
print '<input type="submit" class="button button-save" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; print '<input type="submit" class="button button-save" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
print ' &nbsp; '; print ' &nbsp; ';
@@ -354,13 +362,11 @@ if ($action != 'edit' && $user->rights->opensurvey->write) {
//Modify button //Modify button
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$numsondage.'">'.$langs->trans("Modify").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$numsondage.'">'.$langs->trans("Modify").'</a>';
if ($object->status == Opensurveysondage::STATUS_VALIDATED) if ($object->status == Opensurveysondage::STATUS_VALIDATED) {
{
//Close button //Close button
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=close&id='.$numsondage.'">'.$langs->trans("Close").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=close&id='.$numsondage.'">'.$langs->trans("Close").'</a>';
} }
if ($object->status == Opensurveysondage::STATUS_CLOSED) if ($object->status == Opensurveysondage::STATUS_CLOSED) {
{
//Opened button //Opened button
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=reopen&id='.$numsondage.'">'.$langs->trans("ReOpen").'</a>'; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=reopen&id='.$numsondage.'">'.$langs->trans("ReOpen").'</a>';
} }
@@ -371,8 +377,7 @@ if ($action != 'edit' && $user->rights->opensurvey->write) {
print '</div>'; print '</div>';
if ($action == 'delete') if ($action == 'delete') {
{
print $form->formconfirm($_SERVER["PHP_SELF"].'?&id='.$numsondage, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll", $id), 'delete_confirm', '', '', 1); print $form->formconfirm($_SERVER["PHP_SELF"].'?&id='.$numsondage, $langs->trans("RemovePoll"), $langs->trans("ConfirmRemovalOfPoll", $id), 'delete_confirm', '', '', 1);
} }

View File

@@ -175,7 +175,7 @@ class Opensurveysondage extends CommonObject
$sql .= "allow_comments,"; $sql .= "allow_comments,";
$sql .= "allow_spy,"; $sql .= "allow_spy,";
$sql .= "sujet,"; $sql .= "sujet,";
$sql .= "entity"; $sql .= "entity";
$sql .= ") VALUES ("; $sql .= ") VALUES (";
$sql .= "'".$this->db->escape($this->id_sondage)."',"; $sql .= "'".$this->db->escape($this->id_sondage)."',";
$sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").","; $sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").",";
@@ -188,21 +188,25 @@ class Opensurveysondage extends CommonObject
$sql .= " ".((int) $this->allow_comments).","; $sql .= " ".((int) $this->allow_comments).",";
$sql .= " ".((int) $this->allow_spy).","; $sql .= " ".((int) $this->allow_spy).",";
$sql .= " '".$this->db->escape($this->sujet)."',"; $sql .= " '".$this->db->escape($this->sujet)."',";
$sql .= " ".((int) $conf->entity); $sql .= " ".((int) $conf->entity);
$sql .= ")"; $sql .= ")";
$this->db->begin(); $this->db->begin();
dol_syslog(get_class($this)."::create", LOG_DEBUG); dol_syslog(get_class($this)."::create", LOG_DEBUG);
$resql = $this->db->query($sql); $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 && !$notrigger) { if (!$error && !$notrigger) {
global $langs, $conf; global $langs, $conf;
// Call trigger // Call trigger
$result = $this->call_trigger('OPENSURVEY_CREATE', $user); $result = $this->call_trigger('OPENSURVEY_CREATE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
@@ -250,10 +254,8 @@ class Opensurveysondage extends CommonObject
dol_syslog(get_class($this)."::fetch", LOG_DEBUG); dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ if ($this->db->num_rows($resql)) {
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$this->id_sondage = $obj->id_sondage; $this->id_sondage = $obj->id_sondage;
@@ -336,15 +338,15 @@ class Opensurveysondage extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('OPENSURVEY_MODIFY', $user); $result = $this->call_trigger('OPENSURVEY_MODIFY', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
// Commit or rollback // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@@ -369,8 +371,7 @@ class Opensurveysondage extends CommonObject
global $conf, $langs; global $conf, $langs;
$error = 0; $error = 0;
if (empty($numsondage)) if (empty($numsondage)) {
{
$numsondage = $this->id_sondage; $numsondage = $this->id_sondage;
} }
@@ -379,12 +380,13 @@ class Opensurveysondage extends CommonObject
if (!$error && !$notrigger) { if (!$error && !$notrigger) {
// Call trigger // Call trigger
$result = $this->call_trigger('OPENSURVEY_DELETE', $user); $result = $this->call_trigger('OPENSURVEY_DELETE', $user);
if ($result < 0) $error++; if ($result < 0) {
$error++;
}
// End call triggers // End call triggers
} }
if (!$error) if (!$error) {
{
$sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'"; $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'";
dol_syslog(get_class($this)."::delete", LOG_DEBUG); dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@@ -397,14 +399,14 @@ class Opensurveysondage extends CommonObject
dol_syslog(get_class($this)."::delete", LOG_DEBUG); dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$resql = $this->db->query($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 // Commit or rollback
if ($error) if ($error) {
{ foreach ($this->errors as $errmsg) {
foreach ($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error .= ($this->error ? ', '.$errmsg : $errmsg); $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
} }
@@ -431,7 +433,9 @@ class Opensurveysondage extends CommonObject
global $dolibarr_main_authentication, $dolibarr_main_demo; global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager; 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 = ''; $result = '';
@@ -444,14 +448,16 @@ class Opensurveysondage extends CommonObject
// Add param to save lastsearch_values or not // Add param to save lastsearch_values or not
$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; $add_save_lastsearch_values = 1;
}
if ($add_save_lastsearch_values) {
$url .= '&save_lastsearch_values=1';
}
$linkclose = ''; $linkclose = '';
if (empty($notooltip)) if (empty($notooltip)) {
{ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label = $langs->trans("ShowMyObject"); $label = $langs->trans("ShowMyObject");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@@ -466,8 +472,12 @@ class Opensurveysondage extends CommonObject
$linkend = '</a>'; $linkend = '</a>';
$result .= $linkstart; $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) {
if ($withpicto != 2) $result .= $this->ref; $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; $result .= $linkend;
return $result; return $result;
@@ -488,19 +498,19 @@ class Opensurveysondage extends CommonObject
$sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'"; $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses); $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses);
$ret[] = $tmp; $ret[] = $tmp;
$i++; $i++;
} }
} else dol_print_error($this->db); } else {
dol_print_error($this->db);
}
$this->lines = $ret; $this->lines = $ret;
@@ -543,14 +553,11 @@ class Opensurveysondage extends CommonObject
$sql .= " ORDER BY id_comment"; $sql .= " ORDER BY id_comment";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{
$num_rows = $this->db->num_rows($resql); $num_rows = $this->db->num_rows($resql);
if ($num_rows > 0) if ($num_rows > 0) {
{ while ($obj = $this->db->fetch_object($resql)) {
while ($obj = $this->db->fetch_object($resql))
{
$comments[] = $obj; $comments[] = $obj;
} }
} }
@@ -642,8 +649,7 @@ class Opensurveysondage extends CommonObject
// phpcs:enable // phpcs:enable
global $langs, $conf; global $langs, $conf;
if (empty($this->labelStatus) || empty($this->labelStatusShort)) if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
{
global $langs; global $langs;
//$langs->load("mymodule"); //$langs->load("mymodule");
$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
@@ -656,10 +662,15 @@ class Opensurveysondage extends CommonObject
$statusType = 'status'.$status; $statusType = 'status'.$status;
if ($status == self::STATUS_VALIDATED) { if ($status == self::STATUS_VALIDATED) {
if (0) $statusType = 'status1'; if (0) {
else $statusType = 'status4'; $statusType = 'status1';
} else {
$statusType = 'status4';
}
}
if ($status == self::STATUS_CLOSED) {
$statusType = 'status6';
} }
if ($status == self::STATUS_CLOSED) $statusType = 'status6';
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }

View File

@@ -30,14 +30,15 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/class/opensurveysondage.class.php";
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$numsondage = ''; $numsondage = '';
if (GETPOST('id')) if (GETPOST('id')) {
{
$numsondage = GETPOST("id", 'alpha'); $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('', 'Failed to get survey id '.$numsondage); if ($result <= 0) {
dol_print_error('', 'Failed to get survey id '.$numsondage);
}
/* /*
@@ -57,10 +58,8 @@ $toutsujet = explode(",", $object->sujet);
// affichage des sujets du sondage // affichage des sujets du sondage
$input .= $langs->trans("Name").";"; $input .= $langs->trans("Name").";";
for ($i = 0; $toutsujet[$i]; $i++) for ($i = 0; $toutsujet[$i]; $i++) {
{ if ($object->format == "D") {
if ($object->format == "D")
{
$input .= ''.dol_print_date($toutsujet[$i], 'dayhour').';'; $input .= ''.dol_print_date($toutsujet[$i], 'dayhour').';';
} else { } else {
$input .= ''.$toutsujet[$i].';'; $input .= ''.$toutsujet[$i].';';
@@ -69,11 +68,9 @@ for ($i = 0; $toutsujet[$i]; $i++)
$input .= "\r\n"; $input .= "\r\n";
if (strpos($object->sujet, '@') !== false) if (strpos($object->sujet, '@') !== false) {
{
$input .= ";"; $input .= ";";
for ($i = 0; $toutsujet[$i]; $i++) for ($i = 0; $toutsujet[$i]; $i++) {
{
$heures = explode("@", $toutsujet[$i]); $heures = explode("@", $toutsujet[$i]);
$input .= ''.$heures[1].';'; $input .= ''.$heures[1].';';
} }
@@ -87,12 +84,10 @@ $sql .= ' FROM '.MAIN_DB_PREFIX."opensurvey_user_studs";
$sql .= " WHERE id_sondage='".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage='".$db->escape($numsondage)."'";
$sql .= " ORDER BY id_users"; $sql .= " ORDER BY id_users";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
// Le name de l'utilisateur // Le name de l'utilisateur
@@ -101,15 +96,12 @@ if ($resql)
//affichage des resultats //affichage des resultats
$ensemblereponses = $obj->reponses; $ensemblereponses = $obj->reponses;
for ($k = 0; $k < $nbcolonnes; $k++) for ($k = 0; $k < $nbcolonnes; $k++) {
{
$car = substr($ensemblereponses, $k, 1); $car = substr($ensemblereponses, $k, 1);
if ($car == "1") if ($car == "1") {
{
$input .= 'OK;'; $input .= 'OK;';
$somme[$k]++; $somme[$k]++;
} elseif ($car == "2") } elseif ($car == "2") {
{
$input .= 'KO;'; $input .= 'KO;';
$somme[$k]++; $somme[$k]++;
} else { } else {
@@ -120,7 +112,9 @@ if ($resql)
$input .= "\r\n"; $input .= "\r\n";
$i++; $i++;
} }
} else dol_print_error($db); } else {
dol_print_error($db);
}
$filesize = strlen($input); $filesize = strlen($input);

View File

@@ -96,19 +96,16 @@ function llxHeaderSurvey($title, $head = "", $disablejs = 0, $disablehead = 0, $
// Define urllogo // Define urllogo
$urllogo = ''; $urllogo = '';
$urllogofull = ''; $urllogofull = '';
if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
{
$urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall); $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
$urllogofull = $dolibarr_main_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);
} 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&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo); $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
$urllogofull = $dolibarr_main_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);
} }
// Output html code for logo // Output html code for logo
if ($urllogo) if ($urllogo) {
{
print '<div class="backgreypublicpayment">'; print '<div class="backgreypublicpayment">';
print '<div class="logopublicpayment">'; print '<div class="logopublicpayment">';
print '<img id="dolpaymentlogo" src="'.$urllogo.'"'; print '<img id="dolpaymentlogo" src="'.$urllogo.'"';

View File

@@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
$langs->load("opensurvey"); $langs->load("opensurvey");
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
$hookmanager = new HookManager($db); $hookmanager = new HookManager($db);
@@ -48,11 +50,12 @@ $sql = 'SELECT COUNT(*) as nb';
$sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_sondage'; $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_sondage';
$sql .= ' WHERE entity IN ('.getEntity('survey').')'; $sql .= ' WHERE entity IN ('.getEntity('survey').')';
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$nbsondages = $obj->nb; $nbsondages = $obj->nb;
} else dol_print_error($db, ''); } else {
dol_print_error($db, '');
}
$title = $langs->trans("OpenSurveyArea"); $title = $langs->trans("OpenSurveyArea");

View File

@@ -50,7 +50,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma'); $sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
$page = 0;
} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$offset = $limit * $page; $offset = $limit * $page;
$pageprev = $page - 1; $pageprev = $page - 1;
$pagenext = $page + 1; $pagenext = $page + 1;
@@ -67,24 +69,29 @@ $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST) // Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) $sortfield = "p.date_fin"; if (!$sortfield) {
if (!$sortorder) $sortorder = "DESC"; $sortfield = "p.date_fin";
}
if (!$sortorder) {
$sortorder = "DESC";
}
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
// Definition of fields for list // Definition of fields for list
$arrayfields = array(); $arrayfields = array();
foreach ($arrayfields as $key => $val) foreach ($arrayfields as $key => $val) {
{
// If $val['visible']==0, then we never show the field // If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>$val['enabled'], '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 // Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
{ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
$arrayfields["ef.".$key] = array( $arrayfields["ef.".$key] = array(
'label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@@ -107,21 +114,25 @@ $permissiontodelete = $user->rights->opensurvey->delete;
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) if (empty($reshook)) {
{
// Selection of new fields // Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria // Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
{
$search_status = ''; $search_status = '';
$search_title = ''; $search_title = '';
$search_ref = ''; $search_ref = '';
@@ -129,8 +140,7 @@ if (empty($reshook))
$search_array_options = array(); $search_array_options = array();
} }
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
{
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
} }
@@ -160,11 +170,21 @@ $sql .= " u.login, u.firstname, u.lastname";
$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as p"; $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 .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON u.rowid = p.fk_user_creat";
$sql .= " WHERE p.entity IN (".getEntity('survey').")"; $sql .= " WHERE p.entity IN (".getEntity('survey').")";
if ($search_status != '-1' && $search_status != '') $sql .= natural_search("p.status", $search_status, 2); if ($search_status != '-1' && $search_status != '') {
if ($search_expired == 'expired') $sql .= " AND p.date_fin < '".$db->idate($now)."'"; $sql .= natural_search("p.status", $search_status, 2);
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_expired == 'expired') {
if ($search_title) $sql .= natural_search("p.titre", $search_title); $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 // Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks // Add where from hooks
@@ -176,26 +196,22 @@ $sql .= $db->order($sortfield, $sortorder);
// Count total nb of records // Count total nb of records
$nbtotalofrecords = ''; $nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
{
$resql = $db->query($sql); $resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql); $nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0; $page = 0;
$offset = 0; $offset = 0;
} }
} }
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
{
$num = $nbtotalofrecords; $num = $nbtotalofrecords;
} else { } else {
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@@ -204,8 +220,7 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
} }
// Direct jump if only one record found // Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".dol_buildpath('/opensurvey/card.php', 1).'?id='.$id); header("Location: ".dol_buildpath('/opensurvey/card.php', 1).'?id='.$id);
@@ -221,11 +236,17 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
$param = ''; $param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); $param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
$fieldtosortuser = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 'firstname' : 'lastname'; $fieldtosortuser = empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 'firstname' : 'lastname';
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -234,15 +255,21 @@ $arrayofmassactions = array(
//'presend'=>$langs->trans("SendByMail"), //'presend'=>$langs->trans("SendByMail"),
//'builddoc'=>$langs->trans("PDFMerge"), //'builddoc'=>$langs->trans("PDFMerge"),
); );
if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($permissiontodelete) {
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
// List of surveys into database // List of surveys into database
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="action" value="list">';
@@ -261,9 +288,10 @@ $objecttmp = new Opensurveysondage($db);
$trackid = 'surv'.$object->id; $trackid = 'surv'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) if ($sall) {
{ foreach ($fieldstosearchall as $key => $val) {
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); $fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
} }
@@ -274,11 +302,13 @@ $moreforfilter.= '</div>';*/
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; if (empty($reshook)) {
else $moreforfilter = $hookmanager->resPrint; $moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) if (!empty($moreforfilter)) {
{
print '<div class="liste_titre liste_titre_bydiv centpercent">'; print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter; print $moreforfilter;
print '</div>'; print '</div>';
@@ -346,18 +376,20 @@ print '</tr>'."\n";
// -------------------------------------------------------------------- // --------------------------------------------------------------------
$i = 0; $i = 0;
$totalarray = array(); $totalarray = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $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->rowid)."'"; $sql2 = 'select COUNT(*) as nb from '.MAIN_DB_PREFIX."opensurvey_user_studs where id_sondage='".$db->escape($obj->rowid)."'";
$resql2 = $db->query($sql2); $resql2 = $db->query($sql2);
if ($resql2) if ($resql2) {
{
$obj2 = $db->fetch_object($resql2); $obj2 = $db->fetch_object($resql2);
$nbuser = $obj2->nb; $nbuser = $obj2->nb;
} else dol_print_error($db); } else {
dol_print_error($db);
}
$opensurvey_static->id = $obj->rowid; $opensurvey_static->id = $obj->rowid;
$opensurvey_static->ref = $obj->rowid; $opensurvey_static->ref = $obj->rowid;
@@ -372,11 +404,15 @@ while ($i < min($num, $limit))
print '<td>'; print '<td>';
print $opensurvey_static->getNomUrl(1); print $opensurvey_static->getNomUrl(1);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Title // Title
print '<td>'.dol_htmlentities($obj->title).'</td>'; print '<td>'.dol_htmlentities($obj->title).'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Type // Type
print '<td>'; print '<td>';
@@ -384,7 +420,9 @@ while ($i < min($num, $limit))
print img_picto('', dol_buildpath('/opensurvey/img/'.($type == 'classic' ? 'chart-32.png' : 'calendar-32.png'), 1), 'width="16"', 1); 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 ' '.$langs->trans($type == 'classic' ? "TypeClassic" : "TypeDate");
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td>'; print '<td>';
// Author // Author
@@ -400,23 +438,35 @@ while ($i < min($num, $limit))
print dol_htmlentities($obj->nom_admin); print dol_htmlentities($obj->nom_admin);
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Nb of voters // Nb of voters
print'<td class="right">'.$nbuser.'</td>'."\n"; print'<td class="right">'.$nbuser.'</td>'."\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center">'.dol_print_date($db->jdate($obj->date_fin), 'day'); print '<td class="center">'.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")); } if ($db->jdate($obj->date_fin) < $now && $obj->status == Opensurveysondage::STATUS_VALIDATED) {
print img_warning($langs->trans("Expired"));
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center">'.dol_print_date($db->jdate($obj->tms), 'dayhour'); print '<td class="center">'.dol_print_date($db->jdate($obj->tms), 'dayhour');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center">'.$opensurvey_static->getLibStatut(5).'</td>'."\n"; print '<td class="center">'.$opensurvey_static->getLibStatut(5).'</td>'."\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
// Extra fields // Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
@@ -426,14 +476,17 @@ while ($i < min($num, $limit))
print $hookmanager->resPrint; print $hookmanager->resPrint;
// Action column // Action column
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected = 0; $selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1; if (in_array($obj->rowid, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>'."\n"; print '</tr>'."\n";
$i++; $i++;
@@ -444,10 +497,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found // If no record found
if ($num == 0) if ($num == 0) {
{
$colspan = 8; $colspan = 8;
foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>'; print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
} }
@@ -463,10 +519,11 @@ print '</div>'."\n";
print '</form>'."\n"; print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
{
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db); $formfile = new FormFile($db);

View File

@@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->read) accessforbidden(); if (!$user->rights->opensurvey->read) {
accessforbidden();
}
// Init vars // Init vars
@@ -40,7 +42,9 @@ $numsondage = GETPOST("id");
$object = new Opensurveysondage($db); $object = new Opensurveysondage($db);
$result = $object->fetch(0, $numsondage); $result = $object->fetch(0, $numsondage);
if ($result <= 0) dol_print_error('', 'Failed to get survey id '.$numsondage); if ($result <= 0) {
dol_print_error('', 'Failed to get survey id '.$numsondage);
}
$nblines = $object->fetch_lines(); $nblines = $object->fetch_lines();
@@ -58,20 +62,15 @@ if (GETPOST('retoursondage')) {
$nbcolonnes = substr_count($object->sujet, ',') + 1; $nbcolonnes = substr_count($object->sujet, ',') + 1;
// Add vote // Add vote
if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // boutonp for chrome, boutonp.x for firefox if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) { // boutonp for chrome, boutonp.x for firefox
{ if (GETPOST('nom')) {
if (GETPOST('nom'))
{
$erreur_prenom = false; $erreur_prenom = false;
$nouveauchoix = ''; $nouveauchoix = '';
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{ if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') {
if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1')
{
$nouveauchoix .= "1"; $nouveauchoix .= "1";
} elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') {
{
$nouveauchoix .= "2"; $nouveauchoix .= "2";
} else { // sinon c'est 0 } else { // sinon c'est 0
$nouveauchoix .= "0"; $nouveauchoix .= "0";
@@ -87,15 +86,16 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout
$sql .= ' ORDER BY id_users'; $sql .= ' ORDER BY id_users';
$resql = $db->query($sql); $resql = $db->query($sql);
$num_rows = $db->num_rows($resql); $num_rows = $db->num_rows($resql);
if ($num_rows > 0) if ($num_rows > 0) {
{
setEventMessages($langs->trans("VoteNameAlreadyExists"), null, 'errors'); setEventMessages($langs->trans("VoteNameAlreadyExists"), null, 'errors');
$error++; $error++;
} else { } else {
$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)'; $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'opensurvey_user_studs (nom, id_sondage, reponses)';
$sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')"; $sql .= " VALUES ('".$db->escape($nom)."', '".$db->escape($numsondage)."','".$db->escape($nouveauchoix)."')";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
} }
} }
} }
@@ -104,35 +104,30 @@ if (GETPOST("boutonp") || GETPOST("boutonp.x") || GETPOST("boutonp_x")) // bout
$testmodifier = false; $testmodifier = false;
$testligneamodifier = false; $testligneamodifier = false;
$ligneamodifier = -1; $ligneamodifier = -1;
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{ if (isset($_POST['modifierligne'.$i])) {
if (isset($_POST['modifierligne'.$i]))
{
$ligneamodifier = $i; $ligneamodifier = $i;
$testligneamodifier = true; $testligneamodifier = true;
} }
//test pour voir si une ligne est a modifier //test pour voir si une ligne est a modifier
if (isset($_POST['validermodifier'.$i])) if (isset($_POST['validermodifier'.$i])) {
{
$modifier = $i; $modifier = $i;
$testmodifier = true; $testmodifier = true;
} }
} }
if ($testmodifier) if ($testmodifier) {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$nouveauchoix = ''; $nouveauchoix = '';
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
//var_dump($_POST["choix$i"]); //var_dump($_POST["choix$i"]);
if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') if (isset($_POST["choix$i"]) && $_POST["choix$i"] == '1') {
{
$nouveauchoix .= "1"; $nouveauchoix .= "1";
} elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') } elseif (isset($_POST["choix$i"]) && $_POST["choix$i"] == '2') {
{
$nouveauchoix .= "2"; $nouveauchoix .= "2";
} else { // sinon c'est 0 } else { // sinon c'est 0
$nouveauchoix .= "0"; $nouveauchoix .= "0";
@@ -145,14 +140,17 @@ if ($testmodifier)
$sql .= " WHERE id_users = '".$db->escape($idtomodify)."'"; $sql .= " WHERE id_users = '".$db->escape($idtomodify)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
} }
// Add column (not for date) // Add column (not for date)
if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format == "A") if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format == "A") {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$nouveauxsujets = $object->sujet; $nouveauxsujets = $object->sujet;
@@ -165,17 +163,19 @@ if (GETPOST("ajoutercolonne") && GETPOST('nouvellecolonne') && $object->format =
$sql .= " SET sujet = '".$db->escape($nouveauxsujets)."'"; $sql .= " SET sujet = '".$db->escape($nouveauxsujets)."'";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
else { dol_print_error($db);
} else {
header('Location: results.php?id='.$object->id_sondage); header('Location: results.php?id='.$object->id_sondage);
} }
} }
// Add column (with format date) // Add column (with format date)
if (isset($_POST["ajoutercolonne"]) && $object->format == "D") if (isset($_POST["ajoutercolonne"]) && $object->format == "D") {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$nouveauxsujets = $object->sujet; $nouveauxsujets = $object->sujet;
@@ -223,8 +223,7 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D")
$cleinsertion = count($datesbase); $cleinsertion = count($datesbase);
} else { } else {
$nbdatesbase = count($datesbase); $nbdatesbase = count($datesbase);
for ($i = 0; $i < $nbdatesbase; $i++) for ($i = 0; $i < $nbdatesbase; $i++) {
{
$j = $i + 1; $j = $i + 1;
if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) { if ($nouvelledate > $datesbase[$i] && $nouvelledate < $datesbase[$j]) {
$cleinsertion = $j; $cleinsertion = $j;
@@ -244,14 +243,14 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D")
$dateinsertion = substr("$dateinsertion", 1); $dateinsertion = substr("$dateinsertion", 1);
// update with new topics into database // update with new topics into database
if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) if (isset($erreur_ajout_date) && empty($erreur_ajout_date)) {
{
$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; $sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage";
$sql .= " SET sujet = '".$db->escape($dateinsertion)."'"; $sql .= " SET sujet = '".$db->escape($dateinsertion)."'";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
else { dol_print_error($db);
} else {
header('Location: results.php?id='.$object->id_sondage); header('Location: results.php?id='.$object->id_sondage);
} }
} }
@@ -263,12 +262,12 @@ if (isset($_POST["ajoutercolonne"]) && $object->format == "D")
} }
// Delete line // Delete line
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{ if (GETPOST("effaceligne".$i) || GETPOST("effaceligne".$i."_x") || GETPOST("effaceligne".$i.".x")) { // effacelignei for chrome, effacelignei_x for firefox
if (GETPOST("effaceligne".$i) || GETPOST("effaceligne".$i."_x") || GETPOST("effaceligne".$i.".x")) // effacelignei for chrome, effacelignei_x for firefox // Security check
{ if (!$user->rights->opensurvey->write) {
// Security check accessforbidden();
if (!$user->rights->opensurvey->write) accessforbidden(); }
$compteur = 0; $compteur = 0;
@@ -278,14 +277,14 @@ for ($i = 0; $i < $nblines; $i++)
$sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs"; $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($compteur < $num) 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 = '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); $resql2 = $db->query($sql2);
@@ -297,13 +296,13 @@ for ($i = 0; $i < $nblines; $i++)
} }
// Delete column // Delete column
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
if ((GETPOST("effacecolonne".$i) || GETPOST("effacecolonne".$i."_x") || GETPOST("effacecolonne".$i.".x")) if ((GETPOST("effacecolonne".$i) || GETPOST("effacecolonne".$i."_x") || GETPOST("effacecolonne".$i.".x"))
&& $nbcolonnes > 1) // effacecolonnei for chrome, effacecolonnei_x for firefox && $nbcolonnes > 1) { // effacecolonnei for chrome, effacecolonnei_x for firefox
{ // Security check
// Security check if (!$user->rights->opensurvey->write) {
if (!$user->rights->opensurvey->write) accessforbidden(); accessforbidden();
}
$db->begin(); $db->begin();
@@ -312,12 +311,12 @@ for ($i = 0; $i < $nbcolonnes; $i++)
$nouveauxsujets = ''; $nouveauxsujets = '';
//parcours de tous les sujets actuels //parcours de tous les sujets actuels
while (isset($toutsujet[$j])) while (isset($toutsujet[$j])) {
{
//si le sujet n'est pas celui qui a été effacé alors on concatene //si le sujet n'est pas celui qui a été effacé alors on concatene
if ($i != $j) if ($i != $j) {
{ if (!empty($nouveauxsujets)) {
if (!empty($nouveauxsujets)) $nouveauxsujets .= ','; $nouveauxsujets .= ',';
}
$nouveauxsujets .= $toutsujet[$j]; $nouveauxsujets .= $toutsujet[$j];
} }
@@ -328,7 +327,9 @@ for ($i = 0; $i < $nbcolonnes; $i++)
$sql = 'UPDATE '.MAIN_DB_PREFIX."opensurvey_sondage"; $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); $resql = $db->query($sql);
if (!$resql) dol_print_error($db); if (!$resql) {
dol_print_error($db);
}
// Clean current answer to remove deleted columns // Clean current answer to remove deleted columns
$compteur = 0; $compteur = 0;
@@ -337,22 +338,19 @@ for ($i = 0; $i < $nbcolonnes; $i++)
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
dol_syslog('sql='.$sql); dol_syslog('sql='.$sql);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($compteur < $num) while ($compteur < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$newcar = ''; $newcar = '';
$ensemblereponses = $obj->reponses; $ensemblereponses = $obj->reponses;
// parcours de toutes les réponses actuelles // parcours de toutes les réponses actuelles
for ($j = 0; $j < $nbcolonnes; $j++) 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 //si les reponses ne concerne pas la colonne effacée, on concatene
if ($i != $j) { if ($i != $j) {
@@ -389,8 +387,7 @@ if ($object->fk_user_creat) {
} }
$result = $object->fetch(0, $numsondage); $result = $object->fetch(0, $numsondage);
if ($result <= 0) if ($result <= 0) {
{
dol_print_error($db, $object->error); dol_print_error($db, $object->error);
exit; exit;
} }
@@ -405,8 +402,7 @@ llxHeader('', $title, $helpurl, 0, 0, 0, $arrayofjs, $arrayofcss);
// Define format of choices // Define format of choices
$toutsujet = explode(",", $object->sujet); $toutsujet = explode(",", $object->sujet);
$listofanswers = array(); $listofanswers = array();
foreach ($toutsujet as $value) foreach ($toutsujet as $value) {
{
$tmp = explode('@', $value); $tmp = explode('@', $value);
$listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox')); $listofanswers[] = array('label'=>$tmp[0], 'format'=>($tmp[1] ? $tmp[1] : 'checkbox'));
} }
@@ -452,10 +448,13 @@ print '</td></tr>';
// Expire date // Expire date
print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">'; print '<tr><td>'.$langs->trans('ExpireDate').'</td><td colspan="2">';
if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0); if ($action == 'edit') {
else { print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0);
} else {
print dol_print_date($object->date_fin, 'day'); print dol_print_date($object->date_fin, 'day');
if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired")); if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) {
print img_warning($langs->trans("Expired"));
}
} }
print '</td></tr>'; print '</td></tr>';
@@ -480,8 +479,7 @@ $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domai
$url = $urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage; $url = $urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php', 1).'?sondage='.$object->id_sondage;
$urllink = '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">'; $urllink = '<input type="text" style="width: 60%" '.($action == 'edit' ? 'disabled' : '').' id="opensurveyurl" name="opensurveyurl" value="'.$url.'">';
print $urllink; print $urllink;
if ($action != 'edit') if ($action != 'edit') {
{
print '<script type="text/javascript"> print '<script type="text/javascript">
jQuery(document).ready(function () { jQuery(document).ready(function () {
jQuery("#opensurveyurl").click(function() { jQuery(this).select(); } ); jQuery("#opensurveyurl").click(function() { jQuery(this).select(); } );
@@ -511,10 +509,11 @@ print '</div>';
// Show form to add a new field/column // Show form to add a new field/column
if (GETPOST('ajoutsujet')) if (GETPOST('ajoutsujet')) {
{
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
print '<form name="formulaire" action="" method="POST">'."\n"; print '<form name="formulaire" action="" method="POST">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@@ -524,8 +523,7 @@ if (GETPOST('ajoutsujet'))
print "<br><br>\n"; print "<br><br>\n";
// Add new column // Add new column
if ($object->format == "A") if ($object->format == "A") {
{
print $langs->trans("AddNewColumn").':<br><br>'; print $langs->trans("AddNewColumn").':<br><br>';
print $langs->trans("Title").' <input type="text" name="nouvellecolonne" size="40"><br>'; print $langs->trans("Title").' <input type="text" name="nouvellecolonne" size="40"><br>';
$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"));
@@ -628,8 +626,7 @@ print '</tr>'."\n";
// Show choice titles // Show choice titles
if ($object->format == "D") if ($object->format == "D") {
{
//affichage des sujets du sondage //affichage des sujets du sondage
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
@@ -638,8 +635,7 @@ if ($object->format == "D")
//affichage des années //affichage des années
$colspan = 1; $colspan = 1;
$nbofsujet = count($toutsujet); $nbofsujet = count($toutsujet);
for ($i = 0; $i < $nbofsujet; $i++) for ($i = 0; $i < $nbofsujet; $i++) {
{
$current = $toutsujet[$i]; $current = $toutsujet[$i];
if (strpos($toutsujet[$i], '@') !== false) { if (strpos($toutsujet[$i], '@') !== false) {
@@ -653,15 +649,20 @@ if ($object->format == "D")
} }
$currenty = 0; $currenty = 0;
if ($current) $currenty = strftime("%Y", $current); if ($current) {
$currenty = strftime("%Y", $current);
}
$next = 0; $next = 0;
if ($next) $nexty = strftime("%Y", $next); if ($next) {
if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) $nexty = strftime("%Y", $next);
{ }
if (isset($toutsujet[$i + 1]) && ($currenty == $nexty)) {
$colspan++; $colspan++;
} else { } else {
print '<td colspan='.$colspan.' class="annee">'; print '<td colspan='.$colspan.' class="annee">';
if ($current) print strftime("%Y", $current); if ($current) {
print strftime("%Y", $current);
}
print '</td>'."\n"; print '</td>'."\n";
$colspan = 1; $colspan = 1;
} }
@@ -756,8 +757,7 @@ if ($object->format == "D")
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
for ($i = 0; isset($toutsujet[$i]); $i++) for ($i = 0; isset($toutsujet[$i]); $i++) {
{
$tmp = explode('@', $toutsujet[$i]); $tmp = explode('@', $toutsujet[$i]);
print '<td class="sujet">'.dol_htmlentities($tmp[0]).'</td>'."\n"; print '<td class="sujet">'.dol_htmlentities($tmp[0]).'</td>'."\n";
} }
@@ -776,14 +776,12 @@ $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
$sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'"; $sql .= " WHERE id_sondage = '".$db->escape($numsondage)."'";
dol_syslog('sql='.$sql); dol_syslog('sql='.$sql);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
while ($compteur < $num) while ($compteur < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$ensemblereponses = $obj->reponses; $ensemblereponses = $obj->reponses;
@@ -798,121 +796,167 @@ while ($compteur < $num)
print '</td><td class="nom">'.dol_htmlentities($obj->name).'</td>'."\n"; print '</td><td class="nom">'.dol_htmlentities($obj->name).'</td>'."\n";
// si la ligne n'est pas a changer, on affiche les données // si la ligne n'est pas a changer, on affiche les données
if (!$testligneamodifier) if (!$testligneamodifier) {
{ for ($i = 0; $i < $nbcolonnes; $i++) {
for ($i = 0; $i < $nbcolonnes; $i++)
{
$car = substr($ensemblereponses, $i, 1); $car = substr($ensemblereponses, $i, 1);
//print 'xx'.$i."-".$car.'-'.$listofanswers[$i]['format'].'zz'; //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") {
if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; print '<td class="ok">OK</td>'."\n";
else print '<td class="non">KO</td>'."\n"; } else {
print '<td class="non">KO</td>'."\n";
}
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (((string) $car) == "1") $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") {
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n"; print '<td class="ok">'.$langs->trans("Yes").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("No").'</td>'."\n"; } elseif (((string) $car) == "0") {
else print '<td class="vide">&nbsp;</td>'."\n"; print '<td class="non">'.$langs->trans("No").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
}
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; 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") {
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; } elseif (((string) $car) == "0") {
else print '<td class="vide">&nbsp;</td>'."\n"; print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
}
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; if (!isset($sumagainst[$i])) {
$sumagainst[$i] = 0;
}
if (((string) $car) == "1") {
$sumfor[$i]++;
}
if (((string) $car) == "0") {
$sumagainst[$i]++;
}
} }
} }
} else { } else {
//sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs //sinon on remplace les choix de l'utilisateur par une ligne de checkbox pour recuperer de nouvelles valeurs
if ($compteur == $ligneamodifier) if ($compteur == $ligneamodifier) {
{ for ($i = 0; $i < $nbcolonnes; $i++) {
for ($i = 0; $i < $nbcolonnes; $i++)
{
$car = substr($ensemblereponses, $i, 1); $car = substr($ensemblereponses, $i, 1);
print '<td class="vide">'; print '<td class="vide">';
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 '<input type="checkbox" name="choix'.$i.'" value="1" '; print '<input type="checkbox" name="choix'.$i.'" value="1" ';
if ($car == '1') print 'checked'; if ($car == '1') {
print 'checked';
}
print '>'; print '>';
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
{
$arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes"));
print $form->selectarray("choix".$i, $arraychoice, $car); 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'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For"));
print $form->selectarray("choix".$i, $arraychoice, $car); print $form->selectarray("choix".$i, $arraychoice, $car);
} }
print '</td>'."\n"; print '</td>'."\n";
} }
} else { } else {
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
$car = substr($ensemblereponses, $i, 1); $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") {
if (((string) $car) == "1") print '<td class="ok">OK</td>'."\n"; print '<td class="ok">OK</td>'."\n";
else print '<td class="non">KO</td>'."\n"; } else {
print '<td class="non">KO</td>'."\n";
}
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (((string) $car) == "1") $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") {
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; } elseif (((string) $car) == "0") {
else print '<td class="vide">&nbsp;</td>'."\n"; print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
}
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; 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") {
if (((string) $car) == "1") print '<td class="ok">'.$langs->trans("For").'</td>'."\n"; print '<td class="ok">'.$langs->trans("For").'</td>'."\n";
elseif (((string) $car) == "0") print '<td class="non">'.$langs->trans("Against").'</td>'."\n"; } elseif (((string) $car) == "0") {
else print '<td class="vide">&nbsp;</td>'."\n"; print '<td class="non">'.$langs->trans("Against").'</td>'."\n";
} else {
print '<td class="vide">&nbsp;</td>'."\n";
}
// Total // Total
if (!isset($sumfor[$i])) $sumfor[$i] = 0; if (!isset($sumfor[$i])) {
if (!isset($sumagainst[$i])) $sumagainst[$i] = 0; $sumfor[$i] = 0;
if (((string) $car) == "1") $sumfor[$i]++; }
if (((string) $car) == "0") $sumagainst[$i]++; if (!isset($sumagainst[$i])) {
$sumagainst[$i] = 0;
}
if (((string) $car) == "1") {
$sumfor[$i]++;
}
if (((string) $car) == "0") {
$sumagainst[$i]++;
}
} }
} }
} }
} }
// Button edit at end of line // Button edit at end of line
if ($compteur != $ligneamodifier && ($user->rights->opensurvey->write)) if ($compteur != $ligneamodifier && ($user->rights->opensurvey->write)) {
{
print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n"; print '<td class="casevide"><input type="submit" class="button" name="modifierligne'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Edit")).'"></td>'."\n";
} }
//demande de confirmation pour modification de ligne //demande de confirmation pour modification de ligne
for ($i = 0; $i < $nblines; $i++) for ($i = 0; $i < $nblines; $i++) {
{ if (GETPOSTISSET("modifierligne".$i)) {
if (GETPOSTISSET("modifierligne".$i)) if ($compteur == $i) {
{
if ($compteur == $i)
{
print '<td class="casevide">'; print '<td class="casevide">';
print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">'; print '<input type="hidden" name="idtomodify'.$compteur.'" value="'.$obj->id_users.'">';
print '<input type="submit" class="button button-save" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">'; print '<input type="submit" class="button button-save" name="validermodifier'.$compteur.'" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
@@ -926,33 +970,27 @@ while ($compteur < $num)
} }
// Add line to add new record // Add line to add new record
if (empty($testligneamodifier)) if (empty($testligneamodifier)) {
{
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td class="nom">'."\n"; print '<td class="nom">'."\n";
print '<input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" name="nom" maxlength="64" size="24">'."\n"; print '<input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Name")).'" name="nom" maxlength="64" size="24">'."\n";
print '</td>'."\n"; print '</td>'."\n";
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
print '<td class="vide">'; print '<td class="vide">';
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 '<input type="checkbox" name="choix'.$i.'" value="1"'; print '<input type="checkbox" name="choix'.$i.'" value="1"';
if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') if (GETPOSTISSET('choix'.$i) && GETPOST('choix'.$i) == '1') {
{
print ' checked'; print ' checked';
} }
print '>'; print '>';
} }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
{
$arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes"));
print $form->selectarray("choix".$i, $arraychoice); 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'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For")); $arraychoice = array('2'=>'&nbsp;', '0'=>$langs->trans("Against"), '1'=>$langs->trans("For"));
print $form->selectarray("choix".$i, $arraychoice); print $form->selectarray("choix".$i, $arraychoice);
} }
@@ -966,18 +1004,15 @@ if (empty($testligneamodifier))
// Select value of best choice (for checkbox columns only) // Select value of best choice (for checkbox columns only)
$nbofcheckbox = 0; $nbofcheckbox = 0;
for ($i = 0; $i < $nbcolonnes + 1; $i++) 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++;
$nbofcheckbox++; }
if (isset($sumfor[$i])) if (isset($sumfor[$i])) {
{ if ($i == 0) {
if ($i == 0)
{
$meilleurecolonne = $sumfor[$i]; $meilleurecolonne = $sumfor[$i];
} }
if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne) if (isset($sumfor[$i]) && $sumfor[$i] > $meilleurecolonne) {
{
$meilleurecolonne = $sumfor[$i]; $meilleurecolonne = $sumfor[$i];
} }
} }
@@ -988,29 +1023,36 @@ for ($i = 0; $i < $nbcolonnes + 1; $i++)
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td class="center">'.$langs->trans("Total").'</td>'."\n"; print '<td class="center">'.$langs->trans("Total").'</td>'."\n";
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{
$showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : ''; $showsumfor = isset($sumfor[$i]) ? $sumfor[$i] : '';
$showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : ''; $showsumagainst = isset($sumagainst[$i]) ? $sumagainst[$i] : '';
if (empty($showsumfor)) $showsumfor = 0; if (empty($showsumfor)) {
if (empty($showsumagainst)) $showsumagainst = 0; $showsumfor = 0;
}
if (empty($showsumagainst)) {
$showsumagainst = 0;
}
print '<td>'; print '<td>';
if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) print $showsumfor; if (empty($listofanswers[$i]['format']) || !in_array($listofanswers[$i]['format'], array('yesno', 'foragainst'))) {
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst; print $showsumfor;
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst; }
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'yesno') {
print $langs->trans("Yes").': '.$showsumfor.'<br>'.$langs->trans("No").': '.$showsumagainst;
}
if (!empty($listofanswers[$i]['format']) && $listofanswers[$i]['format'] == 'foragainst') {
print $langs->trans("For").': '.$showsumfor.'<br>'.$langs->trans("Against").': '.$showsumagainst;
}
print '</td>'."\n"; print '</td>'."\n";
} }
print '</tr>'; print '</tr>';
// Show picto winner // Show picto winner
if ($nbofcheckbox >= 2) if ($nbofcheckbox >= 2) {
{
print '<tr>'."\n"; print '<tr>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
print '<td></td>'."\n"; print '<td></td>'."\n";
for ($i = 0; $i < $nbcolonnes; $i++) { 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 '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png', 1).'"></td>'."\n"; print '<td class="somme"><img src="'.dol_buildpath('/opensurvey/img/medaille.png', 1).'"></td>'."\n";
} else { } else {
print '<td class="somme"></td>'."\n"; print '<td class="somme"></td>'."\n";
@@ -1041,10 +1083,8 @@ $toutsujet = explode(",", $object->sujet); // With old versions, this field was
$compteursujet = 0; $compteursujet = 0;
$meilleursujet = ''; $meilleursujet = '';
for ($i = 0; $i < $nbcolonnes; $i++) for ($i = 0; $i < $nbcolonnes; $i++) {
{ if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne) {
if (isset($sumfor[$i]) === true && isset($meilleurecolonne) === true && $sumfor[$i] == $meilleurecolonne)
{
$meilleursujet .= ", "; $meilleursujet .= ", ";
if ($object->format == "D") { if ($object->format == "D") {
@@ -1068,8 +1108,7 @@ $meilleursujet = substr($meilleursujet, 1);
$meilleursujet = str_replace("°", "'", $meilleursujet); $meilleursujet = str_replace("°", "'", $meilleursujet);
// Show best choice // Show best choice
if ($nbofcheckbox >= 2) if ($nbofcheckbox >= 2) {
{
$vote_str = $langs->trans('votes'); $vote_str = $langs->trans('votes');
print '<p class="affichageresultats">'."\n"; print '<p class="affichageresultats">'."\n";

View File

@@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
@@ -53,20 +55,16 @@ if (isset($_SESSION["nbrecases"])) {
$_SESSION["nbrecases"] = 5; $_SESSION["nbrecases"] = 5;
} }
if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) if (GETPOST("ajoutcases") || GETPOST("ajoutcases_x")) {
{
$_SESSION["nbrecases"] = $_SESSION["nbrecases"] + 5; $_SESSION["nbrecases"] = $_SESSION["nbrecases"] + 5;
} }
// Create survey into database // Create survey into database
if (GETPOSTISSET("confirmecreation")) if (GETPOSTISSET("confirmecreation")) {
{
//recuperation des données de champs textes //recuperation des données de champs textes
$toutchoix = ''; $toutchoix = '';
for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) for ($i = 0; $i < $_SESSION["nbrecases"] + 1; $i++) {
{ if (!empty($arrayofchoices[$i])) {
if (!empty($arrayofchoices[$i]))
{
$toutchoix .= ','; $toutchoix .= ',';
$toutchoix .= str_replace(array(",", "@"), " ", $arrayofchoices[$i]).(empty($arrayoftypecolumn[$i]) ? '' : '@'.$arrayoftypecolumn[$i]); $toutchoix .= str_replace(array(",", "@"), " ", $arrayofchoices[$i]).(empty($arrayoftypecolumn[$i]) ? '' : '@'.$arrayoftypecolumn[$i]);
} }
@@ -77,10 +75,8 @@ if (GETPOSTISSET("confirmecreation"))
//test de remplissage des cases //test de remplissage des cases
$testremplissage = ''; $testremplissage = '';
for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) for ($i = 0; $i < $_SESSION["nbrecases"]; $i++) {
{ if (isset($arrayofchoices[$i])) {
if (isset($arrayofchoices[$i]))
{
$testremplissage = "ok"; $testremplissage = "ok";
} }
} }
@@ -107,8 +103,7 @@ $arrayofjs = array();
$arrayofcss = array('/opensurvey/css/style.css'); $arrayofcss = array('/opensurvey/css/style.css');
llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss);
if (empty($_SESSION['title'])) if (empty($_SESSION['title'])) {
{
dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection')); dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection'));
llxFooter(); llxFooter();
exit; exit;

View File

@@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
// Survey type is DATE // Survey type is DATE
$_SESSION["formatsondage"] = "D"; $_SESSION["formatsondage"] = "D";
@@ -40,19 +42,15 @@ $erreur = false;
*/ */
// Insert survey // Insert survey
if (GETPOST('confirmation')) if (GETPOST('confirmation')) {
{
// We save hours entered // We save hours entered
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('nbrecaseshoraires', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
$errheure = array(); $errheure = array();
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
// Show hours choices // Show hours choices
for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
{
$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j]; $_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
$tmphorairesi = GETPOST('horaires'.$i, 'array'); $tmphorairesi = GETPOST('horaires'.$i, 'array');
@@ -170,8 +168,7 @@ if (GETPOST('confirmation'))
} }
// Add survey into database // Add survey into database
if (!$erreur) if (!$erreur) {
{
$_SESSION["toutchoix"] = substr("$choixdate", 1); $_SESSION["toutchoix"] = substr("$choixdate", 1);
ajouter_sondage(); ajouter_sondage();
@@ -179,11 +176,9 @@ if (GETPOST('confirmation'))
} }
// Reset days // Reset days
if (GETPOST('reset')) if (GETPOST('reset')) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
unset($_SESSION["horaires$i"][$j]); unset($_SESSION["horaires$i"][$j]);
} }
@@ -199,8 +194,7 @@ if (GETPOST('reset'))
* View * View
*/ */
if (!isset($_SESSION['description']) && !isset($_SESSION['mail'])) if (!isset($_SESSION['description']) && !isset($_SESSION['mail'])) {
{
dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection')); dol_print_error('', $langs->trans('ErrorOpenSurveyFillFirstSection'));
exit; exit;
} }
@@ -210,11 +204,9 @@ $arrayofcss = array('/opensurvey/css/style.css');
llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss); llxHeader('', $langs->trans("OpenSurvey"), "", '', 0, 0, $arrayofjs, $arrayofcss);
//nombre de cases par défaut //nombre de cases par défaut
if (!isset($_SESSION["nbrecaseshoraires"])) if (!isset($_SESSION["nbrecaseshoraires"])) {
{
$_SESSION["nbrecaseshoraires"] = 5; $_SESSION["nbrecaseshoraires"] = 5;
} elseif (GETPOST('ajoutcases') && $_SESSION["nbrecaseshoraires"] == 5) } elseif (GETPOST('ajoutcases') && $_SESSION["nbrecaseshoraires"] == 5) {
{
$_SESSION["nbrecaseshoraires"] = 10; $_SESSION["nbrecaseshoraires"] = 10;
} }
@@ -224,9 +216,15 @@ $moisAJ = date("n");
$anneeAJ = date("Y"); $anneeAJ = date("Y");
// Initialisation des jour, mois et année // Initialisation des jour, mois et année
if (!isset($_SESSION['jour'])) $_SESSION['jour'] = date('j'); if (!isset($_SESSION['jour'])) {
if (!isset($_SESSION['mois'])) $_SESSION['mois'] = date('n'); $_SESSION['jour'] = date('j');
if (!isset($_SESSION['annee'])) $_SESSION['annee'] = date('Y'); }
if (!isset($_SESSION['mois'])) {
$_SESSION['mois'] = date('n');
}
if (!isset($_SESSION['annee'])) {
$_SESSION['annee'] = date('Y');
}
//mise a jour des valeurs de session si bouton retour a aujourd'hui //mise a jour des valeurs de session si bouton retour a aujourd'hui
if (!issetAndNoEmpty('choixjourajout') && !issetAndNoEmpty('choixjourretrait') && (issetAndNoEmpty('retourmois') || issetAndNoEmpty('retourmois_x'))) { if (!issetAndNoEmpty('choixjourajout') && !issetAndNoEmpty('choixjourretrait') && (issetAndNoEmpty('retourmois') || issetAndNoEmpty('retourmois_x'))) {
@@ -245,8 +243,7 @@ if (issetAndNoEmpty('moisavant_x') || issetAndNoEmpty('moisavant')) {
} }
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
//affichage des 5 cases horaires //affichage des 5 cases horaires
@@ -267,11 +264,9 @@ if (issetAndNoEmpty('moisapres_x') || issetAndNoEmpty('moisapres')) {
} }
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
//affichage des 5 cases horaires //affichage des 5 cases horaires
for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) { for ($j = 0; $j < $_SESSION["nbrecaseshoraires"]; $j++) {
$_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j]; $_SESSION["horaires$i"][$j] = $_POST["horaires$i"][$j];
@@ -285,8 +280,7 @@ if (issetAndNoEmpty('anneeavant_x') || issetAndNoEmpty('anneeavant')) {
$_SESSION["annee"] -= 1; $_SESSION["annee"] -= 1;
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
//affichage des 5 cases horaires //affichage des 5 cases horaires
@@ -302,8 +296,7 @@ if (issetAndNoEmpty('anneeapres_x') || issetAndNoEmpty('anneeapres')) {
$_SESSION["annee"] += 1; $_SESSION["annee"] += 1;
//On sauvegarde les heures deja entrées //On sauvegarde les heures deja entrées
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
//affichage des 5 cases horaires //affichage des 5 cases horaires
@@ -319,8 +312,7 @@ $nbrejourmois = date("t", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee
$premierjourmois = date("N", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"])) - 1; $premierjourmois = date("N", mktime(0, 0, 0, $_SESSION["mois"], 1, $_SESSION["annee"])) - 1;
//traduction de la valeur du mois //traduction de la valeur du mois
if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13) if (is_integer($_SESSION["mois"]) && $_SESSION["mois"] > 0 && $_SESSION["mois"] < 13) {
{
$motmois = dol_print_date(mktime(0, 0, 0, $_SESSION["mois"], 10), '%B'); $motmois = dol_print_date(mktime(0, 0, 0, $_SESSION["mois"], 10), '%B');
} else { } else {
$motmois = dol_print_date(dol_now(), '%B'); $motmois = dol_print_date(dol_now(), '%B');
@@ -356,8 +348,7 @@ print '<table align="center">'."\n"; // The div class=center has no effect on ta
print '<tr>'."\n"; print '<tr>'."\n";
//affichage des jours de la semaine en haut du tableau //affichage des jours de la semaine en haut du tableau
for ($i = 0; $i < 7; $i++) for ($i = 0; $i < 7; $i++) {
{
print '<td align="center" class="joursemaine">'.dol_print_date(mktime(0, 0, 0, 0, $i, 10), '%A').'</td>'; print '<td align="center" class="joursemaine">'.dol_print_date(mktime(0, 0, 0, 0, $i, 10), '%A').'</td>';
} }
@@ -371,8 +362,7 @@ if (issetAndNoEmpty('choixjourajout')) {
// Test pour éviter les doublons dans la variable qui contient toutes les dates // Test pour éviter les doublons dans la variable qui contient toutes les dates
$journeuf = true; $journeuf = true;
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true && issetAndNoEmpty('choixjourajout') === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) { for ($i = 0; $i < $nbofchoice; $i++) {
if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"])) { if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourajout"][0], $_SESSION["annee"])) {
@@ -421,10 +411,8 @@ if (issetAndNoEmpty('choixjourretrait')) {
} }
} }
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{ if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"])) {
if ($_SESSION["totalchoixjour"][$i] == mktime(0, 0, 0, $_SESSION["mois"], $_POST["choixjourretrait"][0], $_SESSION["annee"]))
{
for ($j = $i; $j < $nbofchoice; $j++) { for ($j = $i; $j < $nbofchoice; $j++) {
$k = $j + 1; $k = $j + 1;
$_SESSION["horaires$j"] = $_SESSION["horaires$k"]; $_SESSION["horaires$j"] = $_SESSION["horaires$k"];
@@ -468,8 +456,7 @@ for ($i = 0; $i < $nbrejourmois + $premierjourmois; $i++) {
if ($i < $premierjourmois) { if ($i < $premierjourmois) {
print '<td class="avant"></td>'."\n"; print '<td class="avant"></td>'."\n";
} else { } else {
if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) if (issetAndNoEmpty('totalchoixjour', $_SESSION) === true) {
{
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($j = 0; $j < $nbofchoice; $j++) { for ($j = 0; $j < $nbofchoice; $j++) {
// show red buttons // show red buttons
@@ -501,8 +488,7 @@ print '</div></div>'."\n";
print '<div class="bodydate"><div class="center">'."\n"; print '<div class="bodydate"><div class="center">'."\n";
// affichage de tous les jours choisis // affichage de tous les jours choisis
if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur) {
{
//affichage des jours //affichage des jours
print '<br>'."\n"; print '<br>'."\n";
print '<div align="left">'; print '<div align="left">';
@@ -528,8 +514,7 @@ if (issetAndNoEmpty('totalchoixjour', $_SESSION) || $erreur)
//affichage de la liste des jours choisis //affichage de la liste des jours choisis
$nbofchoice = count($_SESSION["totalchoixjour"]); $nbofchoice = count($_SESSION["totalchoixjour"]);
for ($i = 0; $i < $nbofchoice; $i++) for ($i = 0; $i < $nbofchoice; $i++) {
{
print '<tr>'."\n"; print '<tr>'."\n";
print '<td>'.dol_print_date($_SESSION["totalchoixjour"][$i], 'daytext').' ('.dol_print_date($_SESSION["totalchoixjour"][$i], '%A').')</td>'; print '<td>'.dol_print_date($_SESSION["totalchoixjour"][$i], 'daytext').' ('.dol_print_date($_SESSION["totalchoixjour"][$i], '%A').')</td>';

View File

@@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php";
require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php"; require_once DOL_DOCUMENT_ROOT."/opensurvey/fonctions.php";
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$langs->load("opensurvey"); $langs->load("opensurvey");
@@ -43,9 +45,10 @@ $creation_sondage_autre = GETPOST('creation_sondage_autre');
// We init some session variable to avoir warning // We init some session variable to avoir warning
$session_var = array('title', 'description', 'mailsonde'); $session_var = array('title', 'description', 'mailsonde');
foreach ($session_var as $var) foreach ($session_var as $var) {
{ if (isset($_SESSION[$var])) {
if (isset($_SESSION[$var])) $_SESSION[$var] = null; $_SESSION[$var] = null;
}
} }
// On initialise également les autres variables // On initialise également les autres variables
@@ -53,8 +56,7 @@ $cocheplus = '';
$cochemail = ''; $cochemail = '';
// Jump to correct page // Jump to correct page
if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) if (!empty($creation_sondage_date) || !empty($creation_sondage_autre)) {
{
$_SESSION["title"] = $title; $_SESSION["title"] = $title;
$_SESSION["description"] = $description; $_SESSION["description"] = $description;
@@ -79,11 +81,9 @@ if (!empty($creation_sondage_date) || !empty($creation_sondage_autre))
$testdate = false; $testdate = false;
$champdatefin = dol_mktime(0, 0, 0, GETPOST('champdatefinmonth'), GETPOST('champdatefinday'), GETPOST('champdatefinyear')); $champdatefin = dol_mktime(0, 0, 0, GETPOST('champdatefinmonth'), GETPOST('champdatefinday'), GETPOST('champdatefinyear'));
if ($champdatefin && ($champdatefin > 0)) // A date was provided if ($champdatefin && ($champdatefin > 0)) { // A date was provided
{ // Expire date is not before today
// Expire date is not before today if ($champdatefin >= dol_now()) {
if ($champdatefin >= dol_now())
{
$testdate = true; $testdate = true;
$_SESSION['champdatefin'] = dol_print_date($champdatefin, 'dayrfc'); $_SESSION['champdatefin'] = dol_print_date($champdatefin, 'dayrfc');
} else { } else {
@@ -99,16 +99,13 @@ if (!empty($creation_sondage_date) || !empty($creation_sondage_autre))
setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("ExpireDate")), null, 'errors'); setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("ExpireDate")), null, 'errors');
} }
if ($title && $testdate) if ($title && $testdate) {
{ if (!empty($creation_sondage_date)) {
if (!empty($creation_sondage_date))
{
header("Location: choix_date.php"); header("Location: choix_date.php");
exit(); exit();
} }
if (!empty($creation_sondage_autre)) if (!empty($creation_sondage_autre)) {
{
header("Location: choix_autre.php"); header("Location: choix_autre.php");
exit(); exit();
} }
@@ -140,8 +137,7 @@ print dol_get_fiche_head();
print '<table class="border centpercent">'."\n"; print '<table class="border centpercent">'."\n";
print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("PollTitle").'</td><td><input type="text" name="title" class="minwidth300" maxlength="80" value="'.$_SESSION["title"].'"></td>'."\n"; print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("PollTitle").'</td><td><input type="text" name="title" class="minwidth300" maxlength="80" value="'.$_SESSION["title"].'"></td>'."\n";
if (!$_SESSION["title"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) if (!$_SESSION["title"] && (GETPOST('creation_sondage_date') || GETPOST('creation_sondage_autre'))) {
{
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PollTitle")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PollTitle")), null, 'errors');
} }
@@ -170,22 +166,34 @@ print '<br>'."\n";
// Check or not // Check or not
if ($_SESSION["mailsonde"]) $cochemail = "checked"; if ($_SESSION["mailsonde"]) {
$cochemail = "checked";
}
print '<input type="checkbox" name="mailsonde" '.$cochemail.'> '.$langs->trans("ToReceiveEMailForEachVote").'<br>'."\n"; print '<input type="checkbox" name="mailsonde" '.$cochemail.'> '.$langs->trans("ToReceiveEMailForEachVote").'<br>'."\n";
if ($_SESSION['allow_comments']) $allow_comments = 'checked'; if ($_SESSION['allow_comments']) {
if (GETPOSTISSET('allow_comments')) $allow_comments = GETPOST('allow_comments') ? 'checked' : ''; $allow_comments = 'checked';
}
if (GETPOSTISSET('allow_comments')) {
$allow_comments = GETPOST('allow_comments') ? 'checked' : '';
}
print '<input type="checkbox" name="allow_comments" '.$allow_comments.'"> '.$langs->trans('CanComment').'<br>'."\n"; print '<input type="checkbox" name="allow_comments" '.$allow_comments.'"> '.$langs->trans('CanComment').'<br>'."\n";
if ($_SESSION['allow_spy']) $allow_spy = 'checked'; if ($_SESSION['allow_spy']) {
if (GETPOSTISSET('allow_spy')) $allow_spy = GETPOST('allow_spy') ? 'checked' : ''; $allow_spy = 'checked';
}
if (GETPOSTISSET('allow_spy')) {
$allow_spy = GETPOST('allow_spy') ? 'checked' : '';
}
print '<input type="checkbox" name="allow_spy" '.$allow_spy.'> '.$langs->trans('CanSeeOthersVote').'<br>'."\n"; print '<input type="checkbox" name="allow_spy" '.$allow_spy.'> '.$langs->trans('CanSeeOthersVote').'<br>'."\n";
if (GETPOST('choix_sondage')) if (GETPOST('choix_sondage')) {
{ if (GETPOST('choix_sondage') == 'date') {
if (GETPOST('choix_sondage') == 'date') print '<input type="hidden" name="creation_sondage_date" value="date">'; print '<input type="hidden" name="creation_sondage_date" value="date">';
else print '<input type="hidden" name="creation_sondage_autre" value="autre">'; } else {
print '<input type="hidden" name="creation_sondage_autre" value="autre">';
}
print '<input type="hidden" name="choix_sondage" value="'.GETPOST('choix_sondage').'">'; print '<input type="hidden" name="choix_sondage" value="'.GETPOST('choix_sondage').'">';
print '<br><input type="submit" class="button" name="submit" value="'.$langs->trans("CreatePoll").' ('.(GETPOST('choix_sondage') == 'date' ? $langs->trans("TypeDate") : $langs->trans("TypeClassic")).')">'; print '<br><input type="submit" class="button" name="submit" value="'.$langs->trans("CreatePoll").' ('.(GETPOST('choix_sondage') == 'date' ? $langs->trans("TypeDate") : $langs->trans("TypeClassic")).')">';
} else { } else {

View File

@@ -19,7 +19,9 @@
*/ */
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
@@ -27,7 +29,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/opensurvey/fonctions.php'; require_once DOL_DOCUMENT_ROOT.'/opensurvey/fonctions.php';
// Security check // Security check
if (!$user->rights->opensurvey->write) accessforbidden(); if (!$user->rights->opensurvey->write) {
accessforbidden();
}
$langs->load("opensurvey"); $langs->load("opensurvey");