Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop

This commit is contained in:
Laurent Destailleur 2021-02-26 13:22:28 +01:00
commit 77356afd03
106 changed files with 5832 additions and 5364 deletions

View File

@ -41,8 +41,7 @@ $langs->load("admin");
*/ */
// Enable and test if module Api is enabled // Enable and test if module Api is enabled
if (empty($conf->global->MAIN_MODULE_API)) if (empty($conf->global->MAIN_MODULE_API)) {
{
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
print $langs->trans("ToActivateModule"); print $langs->trans("ToActivateModule");
@ -59,20 +58,16 @@ $api->r->addAuthenticationClass('DolibarrApiAccess', '');
$listofapis = array(); $listofapis = array();
$modulesdir = dolGetModulesDirs(); $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
/* /*
* Search available module * Search available module
*/ */
//dol_syslog("Scan directory ".$dir." for API modules"); //dol_syslog("Scan directory ".$dir." for API modules");
$handle = @opendir(dol_osencode($dir)); $handle = @opendir(dol_osencode($dir));
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false) if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
{
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
{
$modulename = $reg[1]; $modulename = $reg[1];
// Defined if module is enabled // Defined if module is enabled
@ -96,60 +91,58 @@ foreach ($modulesdir as $dir)
$module = 'fichinter'; $module = 'fichinter';
} }
if (empty($conf->$module->enabled)) $enabled = false; if (empty($conf->$module->enabled)) {
$enabled = false;
}
if ($enabled) { if ($enabled) {
/* /*
* If exists, load the API class for enable module * If exists, load the API class for enable module
* *
* Search files named api_<object>.class.php into /htdocs/<module>/class directory * Search files named api_<object>.class.php into /htdocs/<module>/class directory
* *
* @todo : take care of externals module! * @todo : take care of externals module!
* @todo : use getElementProperties() function ? * @todo : use getElementProperties() function ?
*/ */
$dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/';
$handle_part = @opendir(dol_osencode($dir_part)); $handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part)) if (is_resource($handle_part)) {
{ while (($file_searched = readdir($handle_part)) !== false) {
while (($file_searched = readdir($handle_part)) !== false) if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) {
{
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg))
{
$classname = ucwords($reg[1]); $classname = ucwords($reg[1]);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname)) if (class_exists($classname)) {
{
dol_syslog("Found API classname=".$classname." into ".$dir); dol_syslog("Found API classname=".$classname." into ".$dir);
$listofapis[] = $classname; $listofapis[] = $classname;
} }
} }
/* /*
if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg))
{ {
$classname=$reg[1]; $classname=$reg[1];
$classname = str_replace('Api_','',ucwords($reg[1])).'Api'; $classname = str_replace('Api_','',ucwords($reg[1])).'Api';
//$classname = str_replace('Api_','',ucwords($reg[1])); //$classname = str_replace('Api_','',ucwords($reg[1]));
$classname = ucfirst($classname); $classname = ucfirst($classname);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
// if (class_exists($classname)) // if (class_exists($classname))
// { // {
// dol_syslog("Found API classname=".$classname); // dol_syslog("Found API classname=".$classname);
// $api->r->addAPIClass($classname,''); // $api->r->addAPIClass($classname,'');
// require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php'; // require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php';
// $tmpclass = new ReflectionClass($classname); // $tmpclass = new ReflectionClass($classname);
// try { // try {
// $classMetadata = CommentParser::parse($tmpclass->getDocComment()); // $classMetadata = CommentParser::parse($tmpclass->getDocComment());
// } catch (Exception $e) { // } catch (Exception $e) {
// throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage()); // throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage());
// } // }
// //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched); // //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched);
// } // }
}*/ }*/
} }
} }
} }
@ -186,21 +179,23 @@ print '<br>';
$oldclass = ''; $oldclass = '';
print $langs->trans("ListOfAvailableAPIs").':<br>'; print $langs->trans("ListOfAvailableAPIs").':<br>';
foreach ($listofapis['v1'] as $key => $val) foreach ($listofapis['v1'] as $key => $val) {
{ if ($key == 'login') {
if ($key == 'login') continue; continue;
if ($key == 'index') continue; }
if ($key == 'index') {
continue;
}
if ($key) if ($key) {
{ foreach ($val as $method => $val2) {
foreach ($val as $method => $val2)
{
$newclass = $val2['className']; $newclass = $val2['className'];
if (preg_match('/restler/i', $newclass)) continue; if (preg_match('/restler/i', $newclass)) {
continue;
}
if ($oldclass != $newclass) if ($oldclass != $newclass) {
{
print "\n<br>\n".$langs->trans("Class").': '.$newclass.'<br>'."\n"; print "\n<br>\n".$langs->trans("Class").': '.$newclass.'<br>'."\n";
$oldclass = $newclass; $oldclass = $newclass;
} }

View File

@ -51,7 +51,9 @@ class DolibarrApi
{ {
global $conf, $dolibarr_main_url_root; global $conf, $dolibarr_main_url_root;
if (empty($cachedir)) $cachedir = $conf->api->dir_temp; if (empty($cachedir)) {
$cachedir = $conf->api->dir_temp;
}
Defaults::$cacheDirectory = $cachedir; Defaults::$cacheDirectory = $cachedir;
$this->db = $db; $this->db = $db;
@ -140,7 +142,7 @@ class DolibarrApi
unset($object->labelStatusShort); unset($object->labelStatusShort);
unset($object->stats_propale); unset($object->stats_propale);
unset($object->stats_commande); unset($object->stats_commande);
unset($object->stats_contrat); unset($object->stats_contrat);
unset($object->stats_facture); unset($object->stats_facture);
unset($object->stats_commande_fournisseur); unset($object->stats_commande_fournisseur);
@ -191,8 +193,7 @@ class 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]->contact); unset($object->lines[$i]->contact);
@ -284,12 +285,14 @@ class DolibarrApi
$ok = 0; $ok = 0;
$i = 0; $nb = strlen($tmp); $i = 0; $nb = strlen($tmp);
$counter = 0; $counter = 0;
while ($i < $nb) while ($i < $nb) {
{ if ($tmp[$i] == '(') {
if ($tmp[$i] == '(') $counter++; $counter++;
if ($tmp[$i] == ')') $counter--; }
if ($counter < 0) if ($tmp[$i] == ')') {
{ $counter--;
}
if ($counter < 0) {
$error = "Bad sqlfilters=".$sqlfilters; $error = "Bad sqlfilters=".$sqlfilters;
dol_syslog($error, LOG_WARNING); dol_syslog($error, LOG_WARNING);
return false; return false;
@ -313,14 +316,17 @@ class DolibarrApi
global $db; global $db;
//dol_syslog("Convert matches ".$matches[1]); //dol_syslog("Convert matches ".$matches[1]);
if (empty($matches[1])) return ''; if (empty($matches[1])) {
return '';
}
$tmp = explode(':', $matches[1]); $tmp = explode(':', $matches[1]);
if (count($tmp) < 3) return ''; if (count($tmp) < 3) {
return '';
}
$tmpescaped = $tmp[2]; $tmpescaped = $tmp[2];
$regbis = array(); $regbis = array();
if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
{
$tmpescaped = "'".$db->escape($regbis[1])."'"; $tmpescaped = "'".$db->escape($regbis[1])."'";
} else { } else {
$tmpescaped = $db->escape($tmpescaped); $tmpescaped = $db->escape($tmpescaped);

View File

@ -35,7 +35,6 @@ use \Luracast\Restler\Resources;
use \Luracast\Restler\Defaults; use \Luracast\Restler\Defaults;
use \Luracast\Restler\RestException; use \Luracast\Restler\RestException;
/** /**
* Dolibarr API access class * Dolibarr API access class
* *
@ -90,28 +89,24 @@ class DolibarrApiAccess implements iAuthenticate
/*foreach ($_SERVER as $key => $val) /*foreach ($_SERVER as $key => $val)
{ {
dol_syslog($key.' - '.$val); dol_syslog($key.' - '.$val);
}*/ }*/
// api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
$api_key = ''; $api_key = '';
if (isset($_GET['api_key'])) // For backward compatibility if (isset($_GET['api_key'])) { // For backward compatibility
{
// TODO Add option to disable use of api key on url. Return errors if used. // TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['api_key']; $api_key = $_GET['api_key'];
} }
if (isset($_GET['DOLAPIKEY'])) if (isset($_GET['DOLAPIKEY'])) {
{
// TODO Add option to disable use of api key on url. Return errors if used. // TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['DOLAPIKEY']; // With GET method $api_key = $_GET['DOLAPIKEY']; // With GET method
} }
if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
{
$api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded) $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
} }
if ($api_key) if ($api_key) {
{
$userentity = 0; $userentity = 0;
$sql = "SELECT u.login, u.datec, u.api_key, "; $sql = "SELECT u.login, u.datec, u.api_key, ";
@ -121,17 +116,14 @@ class DolibarrApiAccess implements iAuthenticate
// TODO Check if 2 users has same API key. // TODO Check if 2 users has same API key.
$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);
$login = $obj->login; $login = $obj->login;
$stored_key = $obj->api_key; $stored_key = $obj->api_key;
$userentity = $obj->entity; $userentity = $obj->entity;
if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) { // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user
{
$conf->entity = ($obj->entity ? $obj->entity : 1); $conf->entity = ($obj->entity ? $obj->entity : 1);
// We must also reload global conf to get params from the entity // We must also reload global conf to get params from the entity
dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING); dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING);
@ -147,8 +139,7 @@ class DolibarrApiAccess implements iAuthenticate
return false; return false;
} }
if (!$login) if (!$login) {
{
throw new RestException(503, 'Error when searching login user from api key'); throw new RestException(503, 'Error when searching login user from api key');
} }
$fuser = new User($this->db); $fuser = new User($this->db);
@ -173,7 +164,9 @@ class DolibarrApiAccess implements iAuthenticate
$userClass::setCacheIdentifier(static::$role); $userClass::setCacheIdentifier(static::$role);
Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
$requirefortest = static::$requires; $requirefortest = static::$requires;
if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest); if (!is_array($requirefortest)) {
$requirefortest = explode(',', $requirefortest);
}
return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
} }

View File

@ -20,7 +20,6 @@
use Luracast\Restler\RestException; use Luracast\Restler\RestException;
use Luracast\Restler\Format\UploadFormat; use Luracast\Restler\Format\UploadFormat;
require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@ -36,7 +35,7 @@ class Documents extends DolibarrApi
/** /**
* @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object
*/ */
static $DOCUMENT_FIELDS = array( public static $DOCUMENT_FIELDS = array(
'modulepart' 'modulepart'
); );
@ -106,8 +105,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -148,8 +146,7 @@ class Documents extends DolibarrApi
} }
$outputlangs = $langs; $outputlangs = $langs;
if ($langcode && $langs->defaultlang != $langcode) if ($langcode && $langs->defaultlang != $langcode) {
{
$outputlangs = new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang($langcode); $outputlangs->setDefaultLang($langcode);
} }
@ -187,8 +184,7 @@ class Documents extends DolibarrApi
$templateused = ''; $templateused = '';
if ($modulepart == 'facture' || $modulepart == 'invoice') if ($modulepart == 'facture' || $modulepart == 'invoice') {
{
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$this->invoice = new Facture($this->db); $this->invoice = new Facture($this->db);
$result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -201,9 +197,7 @@ class Documents extends DolibarrApi
if ($result <= 0) { if ($result <= 0) {
throw new RestException(500, 'Error generating document'); throw new RestException(500, 'Error generating document');
} }
} } elseif ($modulepart == 'commande' || $modulepart == 'order') {
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
$this->order = new Commande($this->db); $this->order = new Commande($this->db);
$result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -215,9 +209,7 @@ class Documents extends DolibarrApi
if ($result <= 0) { if ($result <= 0) {
throw new RestException(500, 'Error generating document'); throw new RestException(500, 'Error generating document');
} }
} } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$this->propal = new Propal($this->db); $this->propal = new Propal($this->db);
$result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
@ -236,8 +228,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -278,8 +269,7 @@ class Documents extends DolibarrApi
$recursive = 0; $recursive = 0;
$type = 'files'; $type = 'files';
if ($modulepart == 'societe' || $modulepart == 'thirdparty') if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
{
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
if (!DolibarrApiAccess::$user->rights->societe->lire) { if (!DolibarrApiAccess::$user->rights->societe->lire) {
@ -293,9 +283,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
} } elseif ($modulepart == 'user') {
elseif ($modulepart == 'user')
{
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
// Can get doc if has permission to read all user or if it is user itself // Can get doc if has permission to read all user or if it is user itself
@ -310,9 +298,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id; $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id;
} } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
if (!DolibarrApiAccess::$user->rights->adherent->lire) { if (!DolibarrApiAccess::$user->rights->adherent->lire) {
@ -326,9 +312,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member'); $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member');
} } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
elseif ($modulepart == 'propal' || $modulepart == 'proposal')
{
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
if (!DolibarrApiAccess::$user->rights->propal->lire) { if (!DolibarrApiAccess::$user->rights->propal->lire) {
@ -342,9 +326,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal'); $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
} } elseif ($modulepart == 'commande' || $modulepart == 'order') {
elseif ($modulepart == 'commande' || $modulepart == 'order')
{
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
if (!DolibarrApiAccess::$user->rights->commande->lire) { if (!DolibarrApiAccess::$user->rights->commande->lire) {
@ -358,9 +340,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande'); $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
} } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
elseif ($modulepart == 'shipment' || $modulepart == 'expedition')
{
require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
if (!DolibarrApiAccess::$user->rights->expedition->lire) { if (!DolibarrApiAccess::$user->rights->expedition->lire) {
@ -374,9 +354,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment'); $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
} } elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
elseif ($modulepart == 'facture' || $modulepart == 'invoice')
{
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
if (!DolibarrApiAccess::$user->rights->facture->lire) { if (!DolibarrApiAccess::$user->rights->facture->lire) {
@ -390,9 +368,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice'); $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
} } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
$modulepart = 'supplier_invoice'; $modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
@ -408,9 +384,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref); $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'produit' || $modulepart == 'product') {
elseif ($modulepart == 'produit' || $modulepart == 'product')
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
if (!DolibarrApiAccess::$user->rights->produit->lire) { if (!DolibarrApiAccess::$user->rights->produit->lire) {
@ -426,9 +400,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
} } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event')
{
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) { if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) {
@ -442,9 +414,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'expensereport') {
elseif ($modulepart == 'expensereport')
{
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) { if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) {
@ -458,9 +428,7 @@ class Documents extends DolibarrApi
} }
$upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
} } elseif ($modulepart == 'categorie' || $modulepart == 'category') {
elseif ($modulepart == 'categorie' || $modulepart == 'category')
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
if (!DolibarrApiAccess::$user->rights->categorie->lire) { if (!DolibarrApiAccess::$user->rights->categorie->lire) {
@ -523,9 +491,9 @@ class Documents extends DolibarrApi
* @throws RestException * @throws RestException
*/ */
/* /*
public function get($id) { public function get($id) {
return array('note'=>'xxx'); return array('note'=>'xxx');
}*/ }*/
/** /**
@ -557,12 +525,11 @@ class Documents extends DolibarrApi
global $db, $conf; global $db, $conf;
/*var_dump($modulepart); /*var_dump($modulepart);
var_dump($filename); var_dump($filename);
var_dump($filecontent); var_dump($filecontent);
exit;*/ exit;*/
if (empty($modulepart)) if (empty($modulepart)) {
{
throw new RestException(400, 'Modulepart not provided.'); throw new RestException(400, 'Modulepart not provided.');
} }
@ -571,41 +538,39 @@ class Documents extends DolibarrApi
} }
$newfilecontent = ''; $newfilecontent = '';
if (empty($fileencoding)) $newfilecontent = $filecontent; if (empty($fileencoding)) {
if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); $newfilecontent = $filecontent;
}
if ($fileencoding == 'base64') {
$newfilecontent = base64_decode($filecontent);
}
$original_file = dol_sanitizeFileName($filename); $original_file = dol_sanitizeFileName($filename);
// Define $uploadir // Define $uploadir
$object = null; $object = null;
$entity = DolibarrApiAccess::$user->entity; $entity = DolibarrApiAccess::$user->entity;
if (empty($entity)) $entity = 1; if (empty($entity)) {
$entity = 1;
}
if ($ref) if ($ref) {
{
$tmpreldir = ''; $tmpreldir = '';
if ($modulepart == 'facture' || $modulepart == 'invoice') if ($modulepart == 'facture' || $modulepart == 'invoice') {
{
$modulepart = 'facture'; $modulepart = 'facture';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$object = new Facture($this->db); $object = new Facture($this->db);
} } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
{
$modulepart = 'supplier_invoice'; $modulepart = 'supplier_invoice';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
$object = new FactureFournisseur($this->db); $object = new FactureFournisseur($this->db);
} } elseif ($modulepart == 'project') {
elseif ($modulepart == 'project')
{
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$object = new Project($this->db); $object = new Project($this->db);
} } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
elseif ($modulepart == 'task' || $modulepart == 'project_task')
{
$modulepart = 'project_task'; $modulepart = 'project_task';
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
@ -614,36 +579,26 @@ class Documents extends DolibarrApi
$task_result = $object->fetch('', $ref); $task_result = $object->fetch('', $ref);
// Fetching the tasks project is required because its out_dir might be a sub-directory of the project // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
if ($task_result > 0) if ($task_result > 0) {
{
$project_result = $object->fetch_projet(); $project_result = $object->fetch_projet();
if ($project_result >= 0) if ($project_result >= 0) {
{
$tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
} }
} else { } else {
throw new RestException(500, 'Error while fetching Task '.$ref); throw new RestException(500, 'Error while fetching Task '.$ref);
} }
} } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
{
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
$object = new Product($this->db); $object = new Product($this->db);
} } elseif ($modulepart == 'expensereport') {
elseif ($modulepart == 'expensereport')
{
require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
$object = new ExpenseReport($this->db); $object = new ExpenseReport($this->db);
} } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
elseif ($modulepart == 'adherent' || $modulepart == 'member')
{
$modulepart = 'adherent'; $modulepart = 'adherent';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
$object = new Adherent($this->db); $object = new Adherent($this->db);
} } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale')
{
$modulepart = 'propale'; $modulepart = 'propale';
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
$object = new Propal($this->db); $object = new Propal($this->db);
@ -652,22 +607,18 @@ class Documents extends DolibarrApi
throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
} }
if (is_object($object)) if (is_object($object)) {
{
$result = $object->fetch('', $ref); $result = $object->fetch('', $ref);
if ($result == 0) if ($result == 0) {
{
throw new RestException(404, "Object with ref '".$ref."' was not found."); throw new RestException(404, "Object with ref '".$ref."' was not found.");
} } elseif ($result < 0) {
elseif ($result < 0)
{
throw new RestException(500, 'Error while fetching object: '.$object->error); throw new RestException(500, 'Error while fetching object: '.$object->error);
} }
} }
if (!($object->id > 0)) { if (!($object->id > 0)) {
throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found."); throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
} }
// Special cases that need to use get_exdir to get real dir of object // Special cases that need to use get_exdir to get real dir of object
@ -681,13 +632,16 @@ class Documents extends DolibarrApi
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write'); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
$upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir
if (empty($upload_dir) || $upload_dir == '/') if (empty($upload_dir) || $upload_dir == '/') {
{
throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.');
} }
} else { } else {
if ($modulepart == 'invoice') $modulepart = 'facture'; if ($modulepart == 'invoice') {
if ($modulepart == 'member') $modulepart = 'adherent'; $modulepart = 'facture';
}
if ($modulepart == 'member') {
$modulepart = 'adherent';
}
$relativefile = $subdir; $relativefile = $subdir;
$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write'); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
@ -771,12 +725,12 @@ class Documents extends DolibarrApi
// Special cases that need to use get_exdir to get real dir of object // Special cases that need to use get_exdir to get real dir of object
// If future, all object should use this to define path of documents. // If future, all object should use this to define path of documents.
/* /*
$tmpreldir = ''; $tmpreldir = '';
if ($modulepart == 'supplier_invoice') { if ($modulepart == 'supplier_invoice') {
$tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
} }
$relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
$relativefile = $original_file; $relativefile = $original_file;
$check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read'); $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
@ -794,8 +748,7 @@ class Documents extends DolibarrApi
$filename = basename($original_file); $filename = basename($original_file);
$original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
if (!file_exists($original_file_osencoded)) if (!file_exists($original_file_osencoded)) {
{
dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
throw new RestException(404, 'File not found'); throw new RestException(404, 'File not found');
} }
@ -825,8 +778,9 @@ class Documents extends DolibarrApi
// phpcs:enable // phpcs:enable
$result = array(); $result = array();
foreach (Documents::$DOCUMENT_FIELDS as $field) { foreach (Documents::$DOCUMENT_FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$result[$field] = $data[$field]; $result[$field] = $data[$field];
} }
return $result; return $result;

View File

@ -61,14 +61,16 @@ class Login
// TODO Remove the API login. The token must be generated from backoffice only. // TODO Remove the API login. The token must be generated from backoffice only.
// Authentication mode // Authentication mode
if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr'; if (empty($dolibarr_main_authentication)) {
$dolibarr_main_authentication = 'dolibarr';
}
// Authentication mode: forceuser // Authentication mode: forceuser
if ($dolibarr_main_authentication == 'forceuser') if ($dolibarr_main_authentication == 'forceuser') {
{ if (empty($dolibarr_auto_user)) {
if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; $dolibarr_auto_user = 'auto';
if ($dolibarr_auto_user != $login) }
{ if ($dolibarr_auto_user != $login) {
dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
} }
@ -77,16 +79,16 @@ class Login
// Set authmode // Set authmode
$authmode = explode(',', $dolibarr_main_authentication); $authmode = explode(',', $dolibarr_main_authentication);
if ($entity != '' && !is_numeric($entity)) if ($entity != '' && !is_numeric($entity)) {
{
throw new RestException(403, "Bad value for entity, must be the numeric ID of company."); throw new RestException(403, "Bad value for entity, must be the numeric ID of company.");
} }
if ($entity == '') $entity = 1; if ($entity == '') {
$entity = 1;
}
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api');
if (empty($login)) if (empty($login)) {
{
throw new RestException(403, 'Access denied'); throw new RestException(403, 'Access denied');
} }
@ -94,17 +96,14 @@ class Login
$tmpuser = new User($this->db); $tmpuser = new User($this->db);
$tmpuser->fetch(0, $login, 0, 0, $entity); $tmpuser->fetch(0, $login, 0, 0, $entity);
if (empty($tmpuser->id)) if (empty($tmpuser->id)) {
{
throw new RestException(500, 'Failed to load user'); throw new RestException(500, 'Failed to load user');
} }
// Renew the hash // Renew the hash
if (empty($tmpuser->api_key) || $reset) if (empty($tmpuser->api_key) || $reset) {
{
$tmpuser->getrights(); $tmpuser->getrights();
if (empty($tmpuser->rights->user->self->creer)) if (empty($tmpuser->rights->user->self->creer)) {
{
throw new RestException(403, 'User need write permission on itself to reset its API token'); throw new RestException(403, 'User need write permission on itself to reset its API token');
} }
@ -118,8 +117,7 @@ class Login
dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
$result = $this->db->query($sql); $result = $this->db->query($sql);
if (!$result) if (!$result) {
{
throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror()); throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
} }
} else { } else {

View File

@ -310,7 +310,7 @@ class Setup extends DolibarrApi
* Get state by ID. * Get state by ID.
* *
* @param int $id ID of state * @param int $id ID of state
* @return array Array of cleaned object properties * @return array Array of cleaned object properties
* *
* @url GET dictionary/states/{id} * @url GET dictionary/states/{id}
* *

View File

@ -26,22 +26,42 @@
use Luracast\Restler\Format\UploadFormat; use Luracast\Restler\Format\UploadFormat;
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test if (!defined('NOCSRFCHECK')) {
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu }
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test
if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) }
if (!defined("NOSESSION")) define("NOSESSION", '1'); if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
}
if (!defined("NOLOGIN")) {
define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
}
if (!defined("NOSESSION")) {
define("NOSESSION", '1');
}
// Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used. // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used.
if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) {
define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
}
$res = 0; $res = 0;
if (!$res && file_exists("../main.inc.php")) $res = include '../main.inc.php'; if (!$res && file_exists("../main.inc.php")) {
if (!$res) die("Include of main fails"); $res = include '../main.inc.php';
}
if (!$res) {
die("Include of main fails");
}
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php'; require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
@ -61,14 +81,12 @@ if (preg_match('/api\/index\.php$/', $url)) { // sometimes $_SERVER['PHP_SELF']
$url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO']; $url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO'];
} }
// Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases) // Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases)
if (!empty($conf->global->MAIN_NGINX_FIX)) if (!empty($conf->global->MAIN_NGINX_FIX)) {
{
$url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF']; $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF'];
} }
// Enable and test if module Api is enabled // Enable and test if module Api is enabled
if (empty($conf->global->MAIN_MODULE_API)) if (empty($conf->global->MAIN_MODULE_API)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
@ -78,8 +96,7 @@ if (empty($conf->global->MAIN_MODULE_API))
} }
// Test if explorer is not disabled // Test if explorer is not disabled
if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr API interfaces with module REST disabled"); dol_syslog("Call Dolibarr API interfaces with module REST disabled");
print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>'; print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>';
@ -112,8 +129,7 @@ preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg);
// using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned. // using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned.
// So we force refresh to each call. // So we force refresh to each call.
$refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false); $refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false);
if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
{
$refreshcache = true; $refreshcache = true;
} }
@ -132,12 +148,10 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain',
// Restrict API to some IPs // Restrict API to some IPs
if (!empty($conf->global->API_RESTRICT_ON_IP)) if (!empty($conf->global->API_RESTRICT_ON_IP)) {
{
$allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP);
$ipremote = getUserRemoteIP(); $ipremote = getUserRemoteIP();
if (!in_array($ipremote, $allowedip)) if (!in_array($ipremote, $allowedip)) {
{
dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP); dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP);
print 'APIs are not allowed from the IP '.$ipremote; print 'APIs are not allowed from the IP '.$ipremote;
header('HTTP/1.1 503 API not allowed from your IP '.$ipremote); header('HTTP/1.1 503 API not allowed from your IP '.$ipremote);
@ -148,65 +162,64 @@ if (!empty($conf->global->API_RESTRICT_ON_IP))
// Call Explorer file for all APIs definitions (this part is slow) // Call Explorer file for all APIs definitions (this part is slow)
if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
{
// Scan all API files to load them // Scan all API files to load them
$listofapis = array(); $listofapis = array();
$modulesdir = dolGetModulesDirs(); $modulesdir = dolGetModulesDirs();
foreach ($modulesdir as $dir) foreach ($modulesdir as $dir) {
{
// Search available module // Search available module
dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files"); dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
$handle = @opendir(dol_osencode($dir)); $handle = @opendir(dol_osencode($dir));
if (is_resource($handle)) if (is_resource($handle)) {
{ while (($file = readdir($handle)) !== false) {
while (($file = readdir($handle)) !== false)
{
$regmod = array(); $regmod = array();
if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) {
{
$module = strtolower($regmod[1]); $module = strtolower($regmod[1]);
$moduledirforclass = getModuleDirForApiClass($module); $moduledirforclass = getModuleDirForApiClass($module);
$modulenameforenabled = $module; $modulenameforenabled = $module;
if ($module == 'propale') { $modulenameforenabled = 'propal'; } if ($module == 'propale') {
if ($module == 'supplierproposal') { $modulenameforenabled = 'supplier_proposal'; } $modulenameforenabled = 'propal';
if ($module == 'ficheinter') { $modulenameforenabled = 'ficheinter'; } }
if ($module == 'supplierproposal') {
$modulenameforenabled = 'supplier_proposal';
}
if ($module == 'ficheinter') {
$modulenameforenabled = 'ficheinter';
}
dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass); dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
// Defined if module is enabled // Defined if module is enabled
$enabled = true; $enabled = true;
if (empty($conf->$modulenameforenabled->enabled)) $enabled = false; if (empty($conf->$modulenameforenabled->enabled)) {
$enabled = false;
}
if ($enabled) if ($enabled) {
{
// If exists, load the API class for enable module // If exists, load the API class for enable module
// Search files named api_<object>.class.php into /htdocs/<module>/class directory // Search files named api_<object>.class.php into /htdocs/<module>/class directory
// @todo : use getElementProperties() function ? // @todo : use getElementProperties() function ?
$dir_part = dol_buildpath('/'.$moduledirforclass.'/class/'); $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
$handle_part = @opendir(dol_osencode($dir_part)); $handle_part = @opendir(dol_osencode($dir_part));
if (is_resource($handle_part)) if (is_resource($handle_part)) {
{ while (($file_searched = readdir($handle_part)) !== false) {
while (($file_searched = readdir($handle_part)) !== false) if ($file_searched == 'api_access.class.php') {
{ continue;
if ($file_searched == 'api_access.class.php') continue; }
$regapi = array(); $regapi = array();
if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
{
$classname = ucwords($regapi[1]); $classname = ucwords($regapi[1]);
$classname = str_replace('_', '', $classname); $classname = str_replace('_', '', $classname);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname.'Api')) if (class_exists($classname.'Api')) {
{
//dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched); //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
$listofapis[strtolower($classname.'Api')] = $classname.'Api'; $listofapis[strtolower($classname.'Api')] = $classname.'Api';
} elseif (class_exists($classname)) } elseif (class_exists($classname)) {
{
//dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
$listofapis[strtolower($classname)] = $classname; $listofapis[strtolower($classname)] = $classname;
} else { } else {
@ -224,8 +237,7 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// Sort the classes before adding them to Restler. // Sort the classes before adding them to Restler.
// The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
asort($listofapis); asort($listofapis);
foreach ($listofapis as $apiname => $classname) foreach ($listofapis as $apiname => $classname) {
{
$api->r->addAPIClass($classname, $apiname); $api->r->addAPIClass($classname, $apiname);
} }
//var_dump($api->r); //var_dump($api->r);
@ -233,11 +245,9 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $
// Call one APIs or one definition of an API // Call one APIs or one definition of an API
$regbis = array(); $regbis = array();
if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) {
{
$moduleobject = $reg[1]; $moduleobject = $reg[1];
if ($moduleobject == 'explorer') // If we call page to explore details of a service if ($moduleobject == 'explorer') { // If we call page to explore details of a service
{
$moduleobject = $regbis[2]; $moduleobject = $regbis[2];
} }
@ -248,21 +258,27 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass); dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
$tmpmodule = $moduleobject; $tmpmodule = $moduleobject;
if ($tmpmodule != 'api') if ($tmpmodule != 'api') {
$tmpmodule = preg_replace('/api$/i', '', $tmpmodule); $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
}
$classfile = str_replace('_', '', $tmpmodule); $classfile = str_replace('_', '', $tmpmodule);
// Special cases that does not match name rules conventions // Special cases that does not match name rules conventions
if ($moduleobject == 'supplierproposals') if ($moduleobject == 'supplierproposals') {
$classfile = 'supplier_proposals'; $classfile = 'supplier_proposals';
if ($moduleobject == 'supplierorders') }
if ($moduleobject == 'supplierorders') {
$classfile = 'supplier_orders'; $classfile = 'supplier_orders';
if ($moduleobject == 'supplierinvoices') }
if ($moduleobject == 'supplierinvoices') {
$classfile = 'supplier_invoices'; $classfile = 'supplier_invoices';
if ($moduleobject == 'ficheinter') }
if ($moduleobject == 'ficheinter') {
$classfile = 'interventions'; $classfile = 'interventions';
if ($moduleobject == 'interventions') }
if ($moduleobject == 'interventions') {
$classfile = 'interventions'; $classfile = 'interventions';
}
$dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2); $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
@ -271,8 +287,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname); dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname);
$res = false; $res = false;
if ($dir_part_file) if ($dir_part_file) {
$res = include_once $dir_part_file; $res = include_once $dir_part_file;
}
if (!$res) { if (!$res) {
dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING); dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
print 'API not found (failed to include API file)'; print 'API not found (failed to include API file)';
@ -281,8 +298,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' &&
exit(0); exit(0);
} }
if (class_exists($classname)) if (class_exists($classname)) {
$api->r->addAPIClass($classname); $api->r->addAPIClass($classname);
}
} }

View File

@ -41,10 +41,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));
} }
@ -59,12 +60,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 BOM($db); $object = new BOM($db);
@ -76,7 +83,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->bom->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id;
}
@ -86,20 +95,19 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->
$parameters = array('id'=>$socid); $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 = '';
} }
@ -115,14 +123,15 @@ $contactstatic = new Contact($db);
$form = new Form($db); $form = new Form($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 = bomPrepareHead($object); $head = bomPrepareHead($object);
@ -147,31 +156,31 @@ if ($object->id > 0)
if ($user->rights->bom->creer) if ($user->rights->bom->creer)
{ {
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> : ';
$morehtmlref.=' : '; $morehtmlref.=' : ';
if ($action == 'classify') { if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">'; $morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>'; $morehtmlref.='</form>';
} else { } else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
} }
} else { } else {
if (! empty($object->fk_project)) { if (! empty($object->fk_project)) {
$proj = new Project($db); $proj = new Project($db);
$proj->fetch($object->fk_project); $proj->fetch($object->fk_project);
$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
$morehtmlref.=$proj->ref; $morehtmlref.=$proj->ref;
$morehtmlref.='</a>'; $morehtmlref.='</a>';
} else { } else {
$morehtmlref.=''; $morehtmlref.='';
} }
} }
}*/ }*/
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
@ -196,10 +205,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 +219,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 +229,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("ActionsOnBom"), '', ''); //print load_fiche_titre($langs->trans("ActionsOnBom"), '', '');

View File

@ -37,10 +37,10 @@ $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha'); $confirm = GETPOST('confirm', 'alpha');
$cancel = GETPOST('cancel', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09');
$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomcard'; // To manage different context of search $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomcard'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
$lineid = GETPOST('lineid', 'int'); $lineid = GETPOST('lineid', 'int');
// PDF // PDF
$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
@ -59,12 +59,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Initialize array of search criterias // 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.
@ -88,18 +91,22 @@ $upload_dir = $conf->bom->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_URL_ROOT.'/bom/bom_list.php'; $backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php';
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_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); $backtopage = $backurlforlist;
} else {
$backtopage = dol_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
}
} }
} }
@ -127,8 +134,7 @@ if (empty($reshook))
include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
// Add line // Add line
if ($action == 'addline' && $user->rights->bom->write) if ($action == 'addline' && $user->rights->bom->write) {
{
$langs->load('errors'); $langs->load('errors');
$error = 0; $error = 0;
@ -153,8 +159,7 @@ if (empty($reshook))
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$bomline = new BOMLine($db); $bomline = new BOMLine($db);
$bomline->fk_bom = $id; $bomline->fk_bom = $id;
$bomline->fk_product = $idprod; $bomline->fk_product = $idprod;
@ -164,10 +169,10 @@ if (empty($reshook))
$bomline->efficiency = $efficiency; $bomline->efficiency = $efficiency;
// Rang to use // Rang to use
$rangmax = $object->line_max(0); $rangmax = $object->line_max(0);
$ranktouse = $rangmax + 1; $ranktouse = $rangmax + 1;
$bomline->position = ($ranktouse + 1); $bomline->position = ($ranktouse + 1);
$result = $bomline->create($user); $result = $bomline->create($user);
if ($result <= 0) { if ($result <= 0) {
@ -179,16 +184,15 @@ if (empty($reshook))
unset($_POST['qty_frozen']); unset($_POST['qty_frozen']);
unset($_POST['disable_stock_change']); unset($_POST['disable_stock_change']);
$object->fetchLines(); $object->fetchLines();
$object->calculateCosts(); $object->calculateCosts();
} }
} }
} }
// Add line // Add line
if ($action == 'updateline' && $user->rights->bom->write) if ($action == 'updateline' && $user->rights->bom->write) {
{
$langs->load('errors'); $langs->load('errors');
$error = 0; $error = 0;
@ -211,8 +215,7 @@ if (empty($reshook))
$bomline->efficiency = $efficiency; $bomline->efficiency = $efficiency;
$result = $bomline->update($user); $result = $bomline->update($user);
if ($result <= 0) if ($result <= 0) {
{
setEventMessages($bomline->error, $bomline->errors, 'errors'); setEventMessages($bomline->error, $bomline->errors, 'errors');
$action = ''; $action = '';
} else { } else {
@ -221,9 +224,9 @@ if (empty($reshook))
unset($_POST['qty_frozen']); unset($_POST['qty_frozen']);
unset($_POST['disable_stock_change']); unset($_POST['disable_stock_change']);
$object->fetchLines(); $object->fetchLines();
$object->calculateCosts(); $object->calculateCosts();
} }
} }
} }
@ -255,8 +258,7 @@ jQuery(document).ready(function() {
// Part to create // Part to create
if ($action == 'create') if ($action == 'create') {
{
print load_fiche_titre($langs->trans("NewBOM"), '', 'bom'); print load_fiche_titre($langs->trans("NewBOM"), '', 'bom');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@ -288,8 +290,7 @@ 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("BillOfMaterials"), '', 'cubes'); print load_fiche_titre($langs->trans("BillOfMaterials"), '', 'cubes');
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@ -322,8 +323,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_optionals(); $res = $object->fetch_optionals();
$head = bomPrepareHead($object); $head = bomPrepareHead($object);
@ -332,19 +332,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('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1);
} }
// Confirmation to delete line // 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') {
@ -364,13 +361,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->bom->enabled)) if (!empty($conf->bom->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),
@ -382,8 +380,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of closing // Confirmation of closing
if ($action == 'close') if ($action == 'close') {
{
$text = $langs->trans('ConfirmCloseBom', $object->ref); $text = $langs->trans('ConfirmCloseBom', $object->ref);
/*if (! empty($conf->notification->enabled)) /*if (! empty($conf->notification->enabled))
{ {
@ -394,13 +391,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->bom->enabled)) if (!empty($conf->bom->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),
@ -412,8 +410,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of reopen // Confirmation of reopen
if ($action == 'reopen') if ($action == 'reopen') {
{
$text = $langs->trans('ConfirmReopenBom', $object->ref); $text = $langs->trans('ConfirmReopenBom', $object->ref);
/*if (! empty($conf->notification->enabled)) /*if (! empty($conf->notification->enabled))
{ {
@ -424,13 +421,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}*/ }*/
$formquestion = array(); $formquestion = array();
if (!empty($conf->bom->enabled)) if (!empty($conf->bom->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),
@ -449,8 +447,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Confirmation of action xxxx // Confirmation of action xxxx
if ($action == 'setdraft') if ($action == 'setdraft') {
{
$text = $langs->trans('ConfirmSetToDraft', $object->ref); $text = $langs->trans('ConfirmSetToDraft', $object->ref);
$formquestion = array(); $formquestion = array();
@ -460,8 +457,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;
@ -481,32 +481,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// 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->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">'; $morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>'; $morehtmlref.='</form>';
} else { } else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
} }
} else { } else {
if (! empty($object->fk_project)) { if (! empty($object->fk_project)) {
$proj = new Project($db); $proj = new Project($db);
$proj->fetch($object->fk_project); $proj->fetch($object->fk_project);
$morehtmlref.=$proj->getNomUrl(); $morehtmlref.=$proj->getNomUrl();
} else { } else {
$morehtmlref.=''; $morehtmlref.='';
} }
} }
} }
*/ */
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
@ -544,8 +544,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)) {
{
print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '').'" method="POST"> print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '').'" method="POST">
<input type="hidden" name="token" value="' . newToken().'"> <input type="hidden" name="token" value="' . newToken().'">
<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'"> <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
@ -558,21 +557,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
print '<div class="div-table-responsive-no-min">'; print '<div class="div-table-responsive-no-min">';
if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
{
print '<table id="tablelines" class="noborder noshadow" width="100%">'; print '<table id="tablelines" class="noborder noshadow" width="100%">';
} }
if (!empty($object->lines)) if (!empty($object->lines)) {
{
$object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/bom/tpl'); $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/bom/tpl');
} }
// Form to add new line // Form to add new line
if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') {
{ if ($action != 'editline') {
if ($action != 'editline')
{
// Add products/services form // Add products/services form
$object->formAddObjectLine(1, $mysoc, null, '/bom/tpl'); $object->formAddObjectLine(1, $mysoc, null, '/bom/tpl');
@ -581,8 +576,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
} }
if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
{
print '</table>'; print '</table>';
} }
print '</div>'; print '</div>';
@ -597,29 +591,26 @@ 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)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=setdraft&token='.newToken().'">'.$langs->trans("SetToDraft").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=setdraft&token='.newToken().'">'.$langs->trans("SetToDraft").'</a>';
} }
} }
// 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&amp;token='.newToken().'">'.$langs->trans("Modify").'</a>'."\n"; print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit&amp;token='.newToken().'">'.$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";
@ -627,12 +618,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 (is_array($object->lines) && count($object->lines) > 0) {
{
if (is_array($object->lines) && count($object->lines) > 0)
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate&amp;token='.newToken().'">'.$langs->trans("Validate").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate&amp;token='.newToken().'">'.$langs->trans("Validate").'</a>';
} else { } else {
$langs->load("errors"); $langs->load("errors");
@ -642,48 +630,42 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
} }
// Re-open // Re-open
if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) {
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen">'.$langs->trans("ReOpen").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen">'.$langs->trans("ReOpen").'</a>';
} }
// Create MO // Create MO
if ($conf->mrp->enabled) if ($conf->mrp->enabled) {
{ if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) {
if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write))
{
print '<a class="butAction" href="'.DOL_URL_ROOT.'/mrp/mo_card.php?action=create&fk_bom='.$object->id.'&backtopageforcancel='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id).'">'.$langs->trans("CreateMO").'</a>'; print '<a class="butAction" href="'.DOL_URL_ROOT.'/mrp/mo_card.php?action=create&fk_bom='.$object->id.'&backtopageforcancel='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id).'">'.$langs->trans("CreateMO").'</a>';
} }
} }
// Clone // Clone
if ($permissiontoadd) if ($permissiontoadd) {
{
print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=clone&object=bom">'.$langs->trans("ToClone").'</a>'; print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=clone&object=bom">'.$langs->trans("ToClone").'</a>';
} }
// Close / Cancel // Close / Cancel
if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) {
{
print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close">'.$langs->trans("Disable").'</a>'; print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close">'.$langs->trans("Disable").'</a>';
} }
/* /*
if ($user->rights->bom->write) if ($user->rights->bom->write)
{
if ($object->status == 1)
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a>'."\n";
}
else
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a>'."\n";
}
}
*/
if ($permissiontodelete)
{ {
if ($object->status == 1)
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a>'."\n";
}
else
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a>'."\n";
}
}
*/
if ($permissiontodelete) {
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n"; print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;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";
@ -698,8 +680,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
@ -734,7 +715,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 = 'bom'; $modelmail = 'bom';

View File

@ -50,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 = "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
@ -69,7 +75,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->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object); if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object);
}
/* /*
@ -90,8 +98,7 @@ $help_url = '';
//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; //$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
*/ */
@ -103,8 +110,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'];
} }

View File

@ -48,7 +48,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,14 +69,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->bom->enabled)) accessforbidden('Module not enabled'); if (empty($conf->bom->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();
} }
@ -83,30 +91,31 @@ if ($user->socid > 0) // Protection if external user
// 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');
}
} }
// 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],
@ -129,31 +138,33 @@ $permissiontodelete = $user->rights->bom->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
} }
@ -167,22 +178,17 @@ if (empty($reshook))
// Validate records // Validate records
if (!$error && $massaction == 'disable' && $permissiontoadd) if (!$error && $massaction == 'disable' && $permissiontoadd) {
{
$objecttmp = new $objectclass($db); $objecttmp = new $objectclass($db);
if (!$error) if (!$error) {
{
$db->begin(); $db->begin();
$nbok = 0; $nbok = 0;
foreach ($toselect as $toselectid) foreach ($toselect as $toselectid) {
{
$result = $objecttmp->fetch($toselectid); $result = $objecttmp->fetch($toselectid);
if ($result > 0) if ($result > 0) {
{ if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) {
if ($objecttmp->status != $objecttmp::STATUS_VALIDATED)
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors'); setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors');
$error++; $error++;
@ -191,12 +197,13 @@ if (empty($reshook))
// Can be 'cancel()' or 'close()' // Can be 'cancel()' or 'close()'
$result = $objecttmp->cancel($user); $result = $objecttmp->cancel($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
break; break;
} else $nbok++; } else {
$nbok++;
}
} else { } else {
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
@ -204,10 +211,12 @@ if (empty($reshook))
} }
} }
if (!$error) if (!$error) {
{ if ($nbok > 1) {
if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); } else {
setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
}
$db->commit(); $db->commit();
} else { } else {
$db->rollback(); $db->rollback();
@ -217,22 +226,17 @@ if (empty($reshook))
} }
// Validate records // Validate records
if (!$error && $massaction == 'enable' && $permissiontoadd) if (!$error && $massaction == 'enable' && $permissiontoadd) {
{
$objecttmp = new $objectclass($db); $objecttmp = new $objectclass($db);
if (!$error) if (!$error) {
{
$db->begin(); $db->begin();
$nbok = 0; $nbok = 0;
foreach ($toselect as $toselectid) foreach ($toselect as $toselectid) {
{
$result = $objecttmp->fetch($toselectid); $result = $objecttmp->fetch($toselectid);
if ($result > 0) if ($result > 0) {
{ if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) {
if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED)
{
$langs->load("errors"); $langs->load("errors");
setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors'); setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors');
$error++; $error++;
@ -241,12 +245,13 @@ if (empty($reshook))
// Can be 'cancel()' or 'close()' // Can be 'cancel()' or 'close()'
$result = $objecttmp->validate($user); $result = $objecttmp->validate($user);
if ($result < 0) if ($result < 0) {
{
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
break; break;
} else $nbok++; } else {
$nbok++;
}
} else { } else {
setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
$error++; $error++;
@ -254,10 +259,12 @@ if (empty($reshook))
} }
} }
if (!$error) if (!$error) {
{ if ($nbok > 1) {
if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); } else {
setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
}
$db->commit(); $db->commit();
} else { } else {
$db->rollback(); $db->rollback();
@ -284,13 +291,14 @@ $title = $langs->trans('ListOfBOMs');
// 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();
@ -298,21 +306,33 @@ $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);
}
// 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
@ -341,26 +361,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;
} }
@ -369,8 +387,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_URL_ROOT.'/bom/bom_card.php?id='.$id); header("Location: ".DOL_URL_ROOT.'/bom/bom_card.php?id='.$id);
@ -386,14 +403,24 @@ llxHeader('', $title, $help_url);
$arrayofselected = is_array($toselect) ? $toselect : array(); $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';
@ -403,12 +430,18 @@ $arrayofmassactions = array(
'enable'=>$langs->trans("Enable"), 'enable'=>$langs->trans("Enable"),
'disable'=>$langs->trans("Disable"), 'disable'=>$langs->trans("Disable"),
); );
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">';
@ -427,9 +460,10 @@ $objecttmp = new BOM($db);
$trackid = 'bom'.$object->id; $trackid = 'bom'.$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>';
} }
@ -440,11 +474,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>';
@ -461,20 +497,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_', 'maxwidth150', 1); print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 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>';
} }
} }
@ -496,15 +538,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";
} }
} }
@ -521,11 +566,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 }
} }
} }
@ -534,38 +579,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;
} }
} }
@ -578,14 +638,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";
@ -597,10 +660,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>';
} }
@ -617,10 +683,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

@ -34,7 +34,7 @@ $langs->loadLangs(array("mrp", "companies"));
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha');
// Initialize technical objects // Initialize technical objects
@ -53,7 +53,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->bom->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id;
}
$permissionnote = 1; $permissionnote = 1;
//$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php //$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php
@ -77,8 +79,7 @@ $form = new Form($db);
$help_url = ''; $help_url = '';
llxHeader('', $langs->trans('BillOfMaterials'), $help_url); llxHeader('', $langs->trans('BillOfMaterials'), $help_url);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$head = bomPrepareHead($object); $head = bomPrepareHead($object);
@ -99,35 +100,35 @@ if ($id > 0 || !empty($ref))
// 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 ($user->rights->bom->creer) if ($user->rights->bom->creer)
{ {
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> : ';
$morehtmlref.=' : '; $morehtmlref.=' : ';
if ($action == 'classify') { if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">'; $morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>'; $morehtmlref.='</form>';
} else { } else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
} }
} else { } else {
if (! empty($object->fk_project)) { if (! empty($object->fk_project)) {
$proj = new Project($db); $proj = new Project($db);
$proj->fetch($object->fk_project); $proj->fetch($object->fk_project);
$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
$morehtmlref.=$proj->ref; $morehtmlref.=$proj->ref;
$morehtmlref.='</a>'; $morehtmlref.='</a>';
} else { } else {
$morehtmlref.=''; $morehtmlref.='';
} }
} }
}*/ }*/
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';

View File

@ -108,30 +108,42 @@ class Boms 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);
} }
@ -141,8 +153,7 @@ class Boms extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -151,12 +162,10 @@ class Boms extends DolibarrApi
} }
$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;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$bom_static = new BOM($this->db); $bom_static = new BOM($this->db);
if ($bom_static->fetch($obj->rowid)) { if ($bom_static->fetch($obj->rowid)) {
@ -220,7 +229,9 @@ class Boms extends DolibarrApi
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->bom->$field = $value; $this->bom->$field = $value;
} }
@ -251,8 +262,7 @@ class Boms extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
if (!$this->bom->delete(DolibarrApiAccess::$user)) if (!$this->bom->delete(DolibarrApiAccess::$user)) {
{
throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error); throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error);
} }
@ -316,8 +326,7 @@ class Boms extends DolibarrApi
// If object has lines, remove $db property // If 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);
@ -340,9 +349,12 @@ class Boms extends DolibarrApi
{ {
$myobject = array(); $myobject = array();
foreach ($this->bom->fields as $field => $propfield) { foreach ($this->bom->fields as $field => $propfield) {
if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field if (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

@ -230,25 +230,24 @@ class BOM 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);
} }
} }
@ -264,7 +263,9 @@ class BOM extends CommonObject
*/ */
public function create(User $user, $notrigger = false) public function create(User $user, $notrigger = false)
{ {
if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency <= 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->createCommon($user, $notrigger); return $this->createCommon($user, $notrigger);
} }
@ -289,7 +290,9 @@ class BOM 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 ($object->lines as $line) //foreach ($object->lines as $line)
@ -306,14 +309,11 @@ class BOM 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($object->table_element); $extrafields->fetch_name_optionals_label($object->table_element);
foreach ($object->array_options as $key => $option) foreach ($object->array_options as $key => $option) {
{
$shortkey = preg_replace('/options_/', '', $key); $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]);
} }
@ -329,22 +329,19 @@ class BOM 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++;
}
} }
} }
@ -375,7 +372,9 @@ class BOM extends CommonObject
{ {
$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();
}
$this->calculateCosts(); $this->calculateCosts();
return $result; return $result;
@ -416,8 +415,11 @@ class BOM 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 ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if ($this->ismultientitymanaged) {
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) {
@ -448,8 +450,7 @@ class BOM extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql)) {
{
$record = new self($this->db); $record = new self($this->db);
$record->setVarsFromFetchObj($obj); $record->setVarsFromFetchObj($obj);
@ -475,7 +476,9 @@ class BOM extends CommonObject
*/ */
public function update(User $user, $notrigger = false) public function update(User $user, $notrigger = false)
{ {
if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency <= 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->updateCommon($user, $notrigger); return $this->updateCommon($user, $notrigger);
} }
@ -503,8 +506,7 @@ class BOM 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;
} }
@ -524,8 +526,7 @@ class BOM extends CommonObject
global $langs, $conf; global $langs, $conf;
$langs->load("mrp"); $langs->load("mrp");
if (!empty($conf->global->BOM_ADDON)) if (!empty($conf->global->BOM_ADDON)) {
{
$mybool = false; $mybool = false;
$file = $conf->global->BOM_ADDON.".php"; $file = $conf->global->BOM_ADDON.".php";
@ -533,16 +534,14 @@ class BOM 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/bom/"); $dir = dol_buildpath($reldir."core/modules/bom/");
// 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 '';
} }
@ -550,8 +549,7 @@ class BOM 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;
@ -580,27 +578,25 @@ class BOM 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;
} }
/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->create)) /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->create))
|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate)))) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
{ {
$this->error='NotEnoughPermissions'; $this->error='NotEnoughPermissions';
dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
return -1; return -1;
}*/ }*/
$now = dol_now(); $now = dol_now();
$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 {
@ -618,50 +614,47 @@ class BOM 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('BOM_VALIDATE', $user); $result = $this->call_trigger('BOM_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 = 'bom/".$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 = 'bom/".$this->db->escape($this->newref)."'";
$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
$resql = $this->db->query($sql); $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->bom->dir_output.'/'.$oldref; $dirsource = $conf->bom->dir_output.'/'.$oldref;
$dirdest = $conf->bom->dir_output.'/'.$newref; $dirdest = $conf->bom->dir_output.'/'.$newref;
if (!$error && file_exists($dirsource)) if (!$error && file_exists($dirsource)) {
{
dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); 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->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
foreach ($listoffiles as $fileentry) foreach ($listoffiles as $fileentry) {
{
$dirsource = $fileentry['name']; $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;
@ -674,14 +667,12 @@ class BOM 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 {
@ -700,8 +691,7 @@ class BOM 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;
} }
@ -725,8 +715,7 @@ class BOM 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;
} }
@ -750,8 +739,7 @@ class BOM 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;
} }
@ -780,7 +768,9 @@ class BOM extends CommonObject
{ {
global $db, $conf, $langs, $hookmanager; global $db, $conf, $langs, $hookmanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -793,19 +783,20 @@ class BOM extends CommonObject
$url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add 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("ShowBillOfMaterials"); $label = $langs->trans("ShowBillOfMaterials");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@ -813,20 +804,26 @@ class BOM extends CommonObject
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
/* /*
$hookmanager->initHooks(array('bomdao')); $hookmanager->initHooks(array('bomdao'));
$parameters=array('id'=>$this->id); $parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint; if ($reshook > 0) $linkclose = $hookmanager->resPrint;
*/ */
} 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)) : '');
@ -834,8 +831,11 @@ class BOM extends CommonObject
$hookmanager->initHooks(array('bomdao')); $hookmanager->initHooks(array('bomdao'));
$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;
} }
@ -862,8 +862,7 @@ class BOM 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');
@ -872,8 +871,12 @@ class BOM extends CommonObject
} }
$statusType = 'status'.$status; $statusType = 'status'.$status;
if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) {
if ($status == self::STATUS_CANCELED) $statusType = 'status6'; $statusType = 'status4';
}
if ($status == self::STATUS_CANCELED) {
$statusType = 'status6';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode);
} }
@ -891,28 +894,23 @@ class BOM extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' 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;
@ -941,8 +939,7 @@ class BOM extends CommonObject
$objectline = new BOMLine($this->db); $objectline = new BOMLine($this->db);
$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id)); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id));
if (is_numeric($result)) if (is_numeric($result)) {
{
$this->error = $this->error; $this->error = $this->error;
$this->errors = $this->errors; $this->errors = $this->errors;
return $result; return $result;
@ -1051,8 +1048,7 @@ class BOM extends CommonObject
} }
$line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp); $line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
if (empty($line->unit_cost)) { if (empty($line->unit_cost)) {
if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) {
{
$line->unit_cost = $productFournisseur->fourn_unitprice; $line->unit_cost = $productFournisseur->fourn_unitprice;
} }
} }
@ -1197,25 +1193,24 @@ class BOMLine 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
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);
} }
} }
@ -1231,7 +1226,9 @@ class BOMLine extends CommonObjectLine
*/ */
public function create(User $user, $notrigger = false) public function create(User $user, $notrigger = false)
{ {
if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency < 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->createCommon($user, $notrigger); return $this->createCommon($user, $notrigger);
} }
@ -1272,8 +1269,11 @@ class BOMLine 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 ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; if ($this->ismultientitymanaged) {
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) {
@ -1304,8 +1304,7 @@ class BOMLine extends CommonObjectLine
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql)) {
{
$record = new self($this->db); $record = new self($this->db);
$record->setVarsFromFetchObj($obj); $record->setVarsFromFetchObj($obj);
@ -1331,7 +1330,9 @@ class BOMLine extends CommonObjectLine
*/ */
public function update(User $user, $notrigger = false) public function update(User $user, $notrigger = false)
{ {
if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; if ($this->efficiency < 0 || $this->efficiency > 1) {
$this->efficiency = 1;
}
return $this->updateCommon($user, $notrigger); return $this->updateCommon($user, $notrigger);
} }
@ -1363,7 +1364,9 @@ class BOMLine extends CommonObjectLine
{ {
global $db, $conf, $langs, $hookmanager; global $db, $conf, $langs, $hookmanager;
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips if (!empty($conf->dol_no_mouse_hover)) {
$notooltip = 1; // Force disable tooltips
}
$result = ''; $result = '';
@ -1373,19 +1376,20 @@ class BOMLine extends CommonObjectLine
$url = dol_buildpath('/bom/bomline_card.php', 1).'?id='.$this->id; $url = dol_buildpath('/bom/bomline_card.php', 1).'?id='.$this->id;
if ($option != 'nolink') if ($option != 'nolink') {
{
// Add param to save lastsearch_values or not // Add 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("ShowBillOfMaterialsLine"); $label = $langs->trans("ShowBillOfMaterialsLine");
$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
} }
@ -1393,20 +1397,26 @@ class BOMLine extends CommonObjectLine
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
/* /*
$hookmanager->initHooks(array('bomlinedao')); $hookmanager->initHooks(array('bomlinedao'));
$parameters=array('id'=>$this->id); $parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint; if ($reshook > 0) $linkclose = $hookmanager->resPrint;
*/ */
} 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)) : '');
@ -1414,8 +1424,11 @@ class BOMLine extends CommonObjectLine
$hookmanager->initHooks(array('bomlinedao')); $hookmanager->initHooks(array('bomlinedao'));
$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;
} }
@ -1458,28 +1471,23 @@ class BOMLine extends CommonObjectLine
$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;

View File

@ -50,7 +50,7 @@ function bomAdminPrepareHead()
$head[$h][1] = $langs->trans("About"); $head[$h][1] = $langs->trans("About");
$head[$h][2] = 'about'; $head[$h][2] = 'about';
$h++; $h++;
*/ */
// Show more tabs from modules // Show more tabs from modules
// Entries must be declared in modules descriptor with line // Entries must be declared in modules descriptor with line
@ -88,14 +88,19 @@ function bomPrepareHead($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_URL_ROOT.'/bom/bom_note.php?id='.$object->id; $head[$h][0] = DOL_URL_ROOT.'/bom/bom_note.php?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++;
} }
@ -107,7 +112,9 @@ function bomPrepareHead($object)
$nbLinks = Link::count($db, $object->element, $object->id); $nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/bom/bom_document.php?id='.$object->id; $head[$h][0] = DOL_URL_ROOT.'/bom/bom_document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents'); $head[$h][1] = $langs->trans('Documents');
if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>' : ''); if (($nbFiles + $nbLinks) > 0) {
$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>' : '');
}
$head[$h][2] = 'document'; $head[$h][2] = 'document';
$h++; $h++;

View File

@ -39,12 +39,13 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1)
$total = 0; $total = 0;
$ilink = 0; $ilink = 0;
foreach ($linkedObjectBlock as $key => $objectlink) foreach ($linkedObjectBlock as $key => $objectlink) {
{
$ilink++; $ilink++;
$product_static = new Product($db); $product_static = new Product($db);
$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';
}
echo '<tr class="'.$trclass.'" >'; echo '<tr class="'.$trclass.'" >';
echo '<td class="linkedcol-element" >'.$langs->trans("Bom"); echo '<td class="linkedcol-element" >'.$langs->trans("Bom");
if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) {

View File

@ -38,7 +38,9 @@ if (empty($object) || !is_object($object)) {
global $forceall, $forcetoshowtitlelines; global $forceall, $forcetoshowtitlelines;
if (empty($forceall)) $forceall = 0; if (empty($forceall)) {
$forceall = 0;
}
// Define colspan for the button 'Add' // Define colspan for the button 'Add'
@ -60,8 +62,7 @@ if ($nolinesbefore) {
print '<div id="add"></div><span class="hideonsmartphone">'.$langs->trans('AddNewLine').'</span>'; print '<div id="add"></div><span class="hideonsmartphone">'.$langs->trans('AddNewLine').'</span>';
print '</td>'; print '</td>';
print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>'; print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
print '<td class="linecoluseunit left">'; print '<td class="linecoluseunit left">';
print '<span id="title_units">'; print '<span id="title_units">';
print $langs->trans('Unit'); print $langs->trans('Unit');
@ -86,16 +87,18 @@ $coldisplay++;
print '<td class="bordertop nobottom linecoldescription minwidth500imp">'; print '<td class="bordertop nobottom linecoldescription minwidth500imp">';
// Predefined product/service // Predefined product/service
if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) {
{ if ($forceall >= 0 && $freelines) {
if ($forceall >= 0 && $freelines) echo '<br>'; echo '<br>';
}
echo '<span class="prod_entry_mode_predef">'; echo '<span class="prod_entry_mode_predef">';
$filtertype = ''; $filtertype = '';
if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $filtertype = '1'; if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) {
$filtertype = '1';
}
$statustoshow = -1; $statustoshow = -1;
if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
{
// hide products in closed warehouse, but show products for internal transfer // hide products in closed warehouse, but show products for internal transfer
$form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array')); $form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array'));
} else { } else {
@ -109,8 +112,7 @@ $coldisplay++;
print '<td class="bordertop nobottom linecolqty right"><input type="text" size="2" name="qty" id="qty" class="flat right" value="'.(GETPOSTISSET("qty") ? GETPOST("qty", 'alpha', 2) : 1).'">'; print '<td class="bordertop nobottom linecolqty right"><input type="text" size="2" name="qty" id="qty" class="flat right" value="'.(GETPOSTISSET("qty") ? GETPOST("qty", 'alpha', 2) : 1).'">';
print '</td>'; print '</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
$coldisplay++; $coldisplay++;
print '<td class="nobottom linecoluseunit left">'; print '<td class="nobottom linecoluseunit left">';
print '</td>'; print '</td>';
@ -154,18 +156,18 @@ jQuery(document).ready(function() {
{ {
console.log("#idprod change triggered"); console.log("#idprod change triggered");
/* To set focus */ /* To set focus */
if (jQuery('#idprod').val() > 0) if (jQuery('#idprod').val() > 0)
{ {
/* focus work on a standard textarea but not if field was replaced with CKEDITOR */ /* focus work on a standard textarea but not if field was replaced with CKEDITOR */
jQuery('#dp_desc').focus(); jQuery('#dp_desc').focus();
/* focus if CKEDITOR */ /* focus if CKEDITOR */
if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined") if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined")
{ {
var editor = CKEDITOR.instances['dp_desc']; var editor = CKEDITOR.instances['dp_desc'];
if (editor) { editor.focus(); } if (editor) { editor.focus(); }
}
} }
}
}); });
}); });

View File

@ -32,8 +32,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($object) || !is_object($object)) if (empty($object) || !is_object($object)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -41,7 +40,9 @@ if (empty($object) || !is_object($object))
global $forceall; global $forceall;
if (empty($forceall)) $forceall = 0; if (empty($forceall)) {
$forceall = 0;
}
// Define colspan for the button 'Add' // Define colspan for the button 'Add'
@ -79,8 +80,7 @@ if ($line->fk_product > 0) {
print $tmpproduct->getNomUrl(1); print $tmpproduct->getNomUrl(1);
} }
if (is_object($hookmanager)) if (is_object($hookmanager)) {
{
$fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line); $fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line);
$parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer); $parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer);
$reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action); $reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action);
@ -90,7 +90,7 @@ print '</td>';
/*if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines /*if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines
{ {
$coldisplay++; $coldisplay++;
?> ?>
<td class="right"><input id="fourn_ref" name="fourn_ref" class="flat minwidth75" value="<?php echo ($line->ref_supplier ? $line->ref_supplier : $line->ref_fourn); ?>"></td> <td class="right"><input id="fourn_ref" name="fourn_ref" class="flat minwidth75" value="<?php echo ($line->ref_supplier ? $line->ref_supplier : $line->ref_fourn); ?>"></td>
<?php <?php
@ -108,8 +108,7 @@ if (($line->info_bits & 2) != 2) {
} }
print '</td>'; print '</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
$coldisplay++; $coldisplay++;
print '<td class="nobottom linecoluseunit left">'; print '<td class="nobottom linecoluseunit left">';
print '</td>'; print '</td>';

View File

@ -34,8 +34,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($object) || !is_object($object)) if (empty($object) || !is_object($object)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -46,7 +45,9 @@ print "<thead>\n";
print '<tr class="liste_titre nodrag nodrop">'; print '<tr class="liste_titre nodrag nodrop">';
// Adds a line numbering column // Adds a line numbering column
if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum center">&nbsp;</td>'; if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
print '<td class="linecolnum center">&nbsp;</td>';
}
// Description // Description
print '<td class="linecoldescription">'.$langs->trans('Description').'</td>'; print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
@ -54,8 +55,7 @@ print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
// Qty // Qty
print '<td class="linecolqty right">'.$form->textwithpicto($langs->trans('Qty'), $langs->trans("QtyRequiredIfNoLoss")).'</td>'; print '<td class="linecolqty right">'.$form->textwithpicto($langs->trans('Qty'), $langs->trans("QtyRequiredIfNoLoss")).'</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>'; print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
} }
@ -77,8 +77,7 @@ print '<td class="linecoldelete" style="width: 10px"></td>';
print '<td class="linecolmove" style="width: 10px"></td>'; print '<td class="linecolmove" style="width: 10px"></td>';
if ($action == 'selectlines') if ($action == 'selectlines') {
{
print '<td class="linecolcheckall center">'; print '<td class="linecolcheckall center">';
print '<input type="checkbox" class="linecheckboxtoggle" />'; print '<input type="checkbox" class="linecheckboxtoggle" />';
print '<script>$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>'; print '<script>$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';

View File

@ -35,8 +35,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($object) || !is_object($object)) if (empty($object) || !is_object($object)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -44,11 +43,21 @@ if (empty($object) || !is_object($object))
global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax; global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax;
if (empty($dateSelector)) $dateSelector = 0; if (empty($dateSelector)) {
if (empty($forceall)) $forceall = 0; $dateSelector = 0;
if (empty($senderissupplier)) $senderissupplier = 0; }
if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0; if (empty($forceall)) {
if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0; $forceall = 0;
}
if (empty($senderissupplier)) {
$senderissupplier = 0;
}
if (empty($inputalsopricewithtax)) {
$inputalsopricewithtax = 0;
}
if (empty($outputalsopricetotalwithtax)) {
$outputalsopricetotalwithtax = 0;
}
// add html5 elements // add html5 elements
$domData = ' data-element="'.$line->element.'"'; $domData = ' data-element="'.$line->element.'"';
@ -79,8 +88,7 @@ $coldisplay++;
echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price
print '</td>'; print '</td>';
if (!empty($conf->global->PRODUCT_USE_UNITS)) if (!empty($conf->global->PRODUCT_USE_UNITS)) {
{
print '<td class="linecoluseunit nowrap left">'; print '<td class="linecoluseunit nowrap left">';
$label = $tmpproduct->getLabelOfUnit('long'); $label = $tmpproduct->getLabelOfUnit('long');
if ($label !== '') { if ($label !== '') {
@ -159,8 +167,7 @@ if ($action == 'selectlines') {
print '</tr>'; print '</tr>';
//Line extrafield //Line extrafield
if (!empty($extrafields)) if (!empty($extrafields)) {
{
print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1, 'line'); print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1, 'line');
} }

View File

@ -27,16 +27,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
// If socid provided by ajax company selector // If socid provided by ajax company selector
if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) {
{
$_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha');
$_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha');
$_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha');
} }
// Security check // Security check
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("admin", "cashdesk")); $langs->loadLangs(array("admin", "cashdesk"));
@ -45,11 +45,12 @@ $langs->loadLangs(array("admin", "cashdesk"));
/* /*
* Actions * Actions
*/ */
if (GETPOST('action', 'alpha') == 'set') if (GETPOST('action', 'alpha') == 'set') {
{
$db->begin(); $db->begin();
if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; if (GETPOST('socid', 'int') < 0) {
$_POST["socid"] = '';
}
$res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY", (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY", (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity);
$res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_CASH", (GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') : ''), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_CASH", (GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') : ''), 'chaine', 0, '', $conf->entity);
@ -62,10 +63,11 @@ if (GETPOST('action', 'alpha') == 'set')
dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha'));
if (!($res > 0)) $error++; if (!($res > 0)) {
$error++;
}
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} else { } else {
@ -93,8 +95,7 @@ print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="set">'; print '<input type="hidden" name="action" value="set">';
if (!empty($conf->service->enabled)) if (!empty($conf->service->enabled)) {
{
print '<table class="noborder centpercent">'; print '<table class="noborder centpercent">';
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
print '<td>'.$langs->trans("Parameters").'</td><td>'.$langs->trans("Value").'</td>'; print '<td>'.$langs->trans("Parameters").'</td><td>'.$langs->trans("Value").'</td>';
@ -121,8 +122,7 @@ print '<tr class="oddeven"><td width=\"50%\">'.$langs->trans("CashDeskThirdParty
print '<td colspan="2">'; print '<td colspan="2">';
print $form->select_company($conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client in (1,3) AND s.status = 1)', 1, 0, 0, array(), 0); print $form->select_company($conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client in (1,3) AND s.status = 1)', 1, 0, 0, array(), 0);
print '</td></tr>'; print '</td></tr>';
if (!empty($conf->banque->enabled)) if (!empty($conf->banque->enabled)) {
{
print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForSell").'</td>'; print '<tr class="oddeven"><td>'.$langs->trans("CashDeskBankAccountForSell").'</td>';
print '<td colspan="2">'; print '<td colspan="2">';
$form->select_comptes($conf->global->CASHDESK_ID_BANKACCOUNT_CASH, 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", 1); $form->select_comptes($conf->global->CASHDESK_ID_BANKACCOUNT_CASH, 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", 1);
@ -141,8 +141,7 @@ if (!empty($conf->banque->enabled))
print '</td></tr>'; print '</td></tr>';
} }
if (!empty($conf->stock->enabled)) if (!empty($conf->stock->enabled)) {
{
print '<tr class="oddeven"><td>'.$langs->trans("CashDeskDoNotDecreaseStock").'</td>'; // Force warehouse (this is not a default value) print '<tr class="oddeven"><td>'.$langs->trans("CashDeskDoNotDecreaseStock").'</td>'; // Force warehouse (this is not a default value)
print '<td colspan="2">'; print '<td colspan="2">';
if (empty($conf->productbatch->enabled)) { if (empty($conf->productbatch->enabled)) {
@ -161,8 +160,7 @@ if (!empty($conf->stock->enabled))
print '<tr class="oddeven"><td>'.$langs->trans("CashDeskIdWareHouse").'</td>'; // Force warehouse (this is not a default value) print '<tr class="oddeven"><td>'.$langs->trans("CashDeskIdWareHouse").'</td>'; // Force warehouse (this is not a default value)
print '<td colspan="2">'; print '<td colspan="2">';
if (!$disabled) if (!$disabled) {
{
print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled); print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled);
print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">('.$langs->trans("Create").')</a>'; print ' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">('.$langs->trans("Create").')</a>';
} else { } else {
@ -172,8 +170,7 @@ if (!empty($conf->stock->enabled))
} }
// Use Dolibarr Receipt Printer // Use Dolibarr Receipt Printer
if (!empty($conf->receiptprinter->enabled)) if (!empty($conf->receiptprinter->enabled)) {
{
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')'; print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')';
print '<td colspan="2">'; print '<td colspan="2">';

View File

@ -25,15 +25,13 @@
require_once 'class/Facturation.class.php'; require_once 'class/Facturation.class.php';
// Si nouvelle vente, reinitialisation des donnees (destruction de l'objet et vidage de la table contenant la liste des articles) // Si nouvelle vente, reinitialisation des donnees (destruction de l'objet et vidage de la table contenant la liste des articles)
if ($_GET['id'] == 'NOUV') if ($_GET['id'] == 'NOUV') {
{
unset($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']);
unset($_SESSION['poscart']); unset($_SESSION['poscart']);
} }
// Recuperation, s'il existe, de l'objet contenant les infos de la vente en cours ... // Recuperation, s'il existe, de l'objet contenant les infos de la vente en cours ...
if (isset($_SESSION['serObjFacturation'])) if (isset($_SESSION['serObjFacturation'])) {
{
$obj_facturation = unserialize($_SESSION['serObjFacturation']); $obj_facturation = unserialize($_SESSION['serObjFacturation']);
unset($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']);
} else { } else {
@ -58,17 +56,18 @@ print '<div class="inline-block" style="vertical-align: top">';
print '<div class="principal">'; print '<div class="principal">';
$page = GETPOST('menutpl', 'alpha'); $page = GETPOST('menutpl', 'alpha');
if (empty($page)) $page = 'facturation'; if (empty($page)) {
$page = 'facturation';
}
if (in_array( if (in_array(
$page, $page,
array( array(
'deconnexion', 'deconnexion',
'index', 'index_verif', 'facturation', 'facturation_verif', 'facturation_dhtml', 'index', 'index_verif', 'facturation', 'facturation_verif', 'facturation_dhtml',
'validation', 'validation_ok', 'validation_ticket', 'validation_verif', 'validation', 'validation_ok', 'validation_ticket', 'validation_verif',
) )
)) )) {
{
include $page.'.php'; include $page.'.php';
} else { } else {
dol_print_error('', 'menu param '.$page.' is not inside allowed list'); dol_print_error('', 'menu param '.$page.' is not inside allowed list');

View File

@ -30,8 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/cashdesk/include/keypad.php';
$error = GETPOST('error'); $error = GETPOST('error');
// Test if already logged // Test if already logged
if ($_SESSION['uid'] <= 0) if ($_SESSION['uid'] <= 0) {
{
header('Location: index.php'); header('Location: index.php');
exit; exit;
} }
@ -53,8 +52,7 @@ top_htmlhead($head, $langs->trans("CashDesk"), 0, 0, $arrayofjs, $arrayofcss);
print '<body>'."\n"; print '<body>'."\n";
if (!empty($error)) if (!empty($error)) {
{
dol_htmloutput_events(); dol_htmloutput_events();
} }

View File

@ -27,8 +27,7 @@
<?php <?php
// Wrapper to show tooltips // Wrapper to show tooltips
if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) {
{
print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n"; print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n";
print '<script type="text/javascript"> print '<script type="text/javascript">
jQuery(document).ready(function () { jQuery(document).ready(function () {

View File

@ -95,15 +95,18 @@ class Auth
$test = true; $test = true;
// Authentication mode // Authentication mode
if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr'; if (empty($dolibarr_main_authentication)) {
$dolibarr_main_authentication = 'http,dolibarr';
}
// Authentication mode: forceuser // Authentication mode: forceuser
if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) {
$dolibarr_auto_user = 'auto';
}
// Set authmode // Set authmode
$authmode = explode(',', $dolibarr_main_authentication); $authmode = explode(',', $dolibarr_main_authentication);
// No authentication mode // No authentication mode
if (!count($authmode)) if (!count($authmode)) {
{
$langs->load('main'); $langs->load('main');
dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication')); dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication'));
exit; exit;
@ -117,15 +120,17 @@ class Auth
// If ok, the variable will be initialized login // If ok, the variable will be initialized login
// If error, we will put error message in session under the name dol_loginmesg // If error, we will put error message in session under the name dol_loginmesg
$goontestloop = false; $goontestloop = false;
if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true; if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) {
if (isset($aLogin) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true; $goontestloop = true;
}
if (isset($aLogin) || GETPOST('openid_mode', 'alpha', 1)) {
$goontestloop = true;
}
if ($test && $goontestloop) if ($test && $goontestloop) {
{
include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode); $login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
if ($login) if ($login) {
{
$this->login($aLogin); $this->login($aLogin);
$this->passwd($aPasswd); $this->passwd($aPasswd);
$ret = 0; $ret = 0;

View File

@ -116,8 +116,7 @@ class Facturation
// Clean vat code // Clean vat code
$reg = array(); $reg = array();
$vat_src_code = ''; $vat_src_code = '';
if (preg_match('/\((.*)\)/', $txtva, $reg)) if (preg_match('/\((.*)\)/', $txtva, $reg)) {
{
$vat_src_code = $reg[1]; $vat_src_code = $reg[1];
$txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
} }
@ -133,8 +132,7 @@ class Facturation
$total_localtax2 = $resultarray[10]; $total_localtax2 = $resultarray[10];
// Calculation of the discount amount // Calculation of the discount amount
if ($this->remisePercent()) if ($this->remisePercent()) {
{
$remise_percent = $this->remisePercent(); $remise_percent = $this->remisePercent();
} else { } else {
$remise_percent = 0; $remise_percent = 0;
@ -155,10 +153,8 @@ class Facturation
$newcartarray[$i]['price'] = $product->price; $newcartarray[$i]['price'] = $product->price;
$newcartarray[$i]['price_ttc'] = $product->price_ttc; $newcartarray[$i]['price_ttc'] = $product->price_ttc;
if (!empty($conf->global->PRODUIT_MULTIPRICES)) if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
{ if (isset($product->multiprices[$societe->price_level])) {
if (isset($product->multiprices[$societe->price_level]))
{
$newcartarray[$i]['price'] = $product->multiprices[$societe->price_level]; $newcartarray[$i]['price'] = $product->multiprices[$societe->price_level];
$newcartarray[$i]['price_ttc'] = $product->multiprices_ttc[$societe->price_level]; $newcartarray[$i]['price_ttc'] = $product->multiprices_ttc[$societe->price_level];
} }
@ -191,10 +187,8 @@ class Facturation
$j = 0; $j = 0;
$newposcart = array(); $newposcart = array();
foreach ($poscart as $key => $val) foreach ($poscart as $key => $val) {
{ if ($poscart[$key]['id'] != $aArticle) {
if ($poscart[$key]['id'] != $aArticle)
{
$newposcart[$j] = $poscart[$key]; $newposcart[$j] = $poscart[$key];
$newposcart[$j]['id'] = $j; $newposcart[$j]['id'] = $j;
$j++; $j++;
@ -223,8 +217,7 @@ class Facturation
$tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array());
$tab_size = count($tab); $tab_size = count($tab);
for ($i = 0; $i < $tab_size; $i++) for ($i = 0; $i < $tab_size; $i++) {
{
// Total HT // Total HT
$remise = $tab[$i]['remise']; $remise = $tab[$i]['remise'];
$total_ht += ($tab[$i]['total_ht']); $total_ht += ($tab[$i]['total_ht']);
@ -291,11 +284,9 @@ class Facturation
public function id($aId = null) public function id($aId = null)
{ {
if (!$aId) if (!$aId) {
{
return $this->id; return $this->id;
} elseif ($aId == 'RESET') } elseif ($aId == 'RESET') {
{
$this->id = null; $this->id = null;
} else { } else {
$this->id = $aId; $this->id = $aId;
@ -311,11 +302,9 @@ class Facturation
public function ref($aRef = null) public function ref($aRef = null)
{ {
if (is_null($aRef)) if (is_null($aRef)) {
{
return $this->ref; return $this->ref;
} elseif ($aRef == 'RESET') } elseif ($aRef == 'RESET') {
{
$this->ref = null; $this->ref = null;
} else { } else {
$this->ref = $aRef; $this->ref = $aRef;
@ -330,11 +319,9 @@ class Facturation
*/ */
public function qte($aQte = null) public function qte($aQte = null)
{ {
if (is_null($aQte)) if (is_null($aQte)) {
{
return $this->qte; return $this->qte;
} elseif ($aQte == 'RESET') } elseif ($aQte == 'RESET') {
{
$this->qte = null; $this->qte = null;
} else { } else {
$this->qte = $aQte; $this->qte = $aQte;
@ -350,11 +337,9 @@ class Facturation
public function stock($aStock = null) public function stock($aStock = null)
{ {
if (is_null($aStock)) if (is_null($aStock)) {
{
return $this->stock; return $this->stock;
} elseif ($aStock == 'RESET') } elseif ($aStock == 'RESET') {
{
$this->stock = null; $this->stock = null;
} else { } else {
$this->stock = $aStock; $this->stock = $aStock;
@ -370,11 +355,9 @@ class Facturation
public function remisePercent($aRemisePercent = null) public function remisePercent($aRemisePercent = null)
{ {
if (is_null($aRemisePercent)) if (is_null($aRemisePercent)) {
{
return $this->remise_percent; return $this->remise_percent;
} elseif ($aRemisePercent == 'RESET') } elseif ($aRemisePercent == 'RESET') {
{
$this->remise_percent = null; $this->remise_percent = null;
} else { } else {
$this->remise_percent = $aRemisePercent; $this->remise_percent = $aRemisePercent;
@ -564,11 +547,9 @@ class Facturation
*/ */
public function amountWithTax($aTotalTtc = null) public function amountWithTax($aTotalTtc = null)
{ {
if (is_null($aTotalTtc)) if (is_null($aTotalTtc)) {
{
return $this->prix_total_ttc; return $this->prix_total_ttc;
} elseif ($aTotalTtc == 'RESET') } elseif ($aTotalTtc == 'RESET') {
{
$this->prix_total_ttc = null; $this->prix_total_ttc = null;
} else { } else {
$this->prix_total_ttc = $aTotalTtc; $this->prix_total_ttc = $aTotalTtc;

View File

@ -22,10 +22,18 @@
*/ */
//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Uncomment creates pb to relogon after a disconnect //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Uncomment creates pb to relogon after a disconnect
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); if (!defined('NOREQUIREMENU')) {
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); }
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
require_once '../main.inc.php'; require_once '../main.inc.php';

View File

@ -40,16 +40,21 @@ if (GETPOST('filtre', 'alpha')) {
$ret = array(); $i = 0; $ret = array(); $i = 0;
$sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx, p.fk_product_type"; $sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx, p.fk_product_type";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
$sql .= " AND p.tosell = 1"; $sql .= " AND p.tosell = 1";
if (!$conf->global->CASHDESK_SERVICES) $sql .= " AND p.fk_product_type = 0"; if (!$conf->global->CASHDESK_SERVICES) {
$sql .= " AND p.fk_product_type = 0";
}
$sql .= " AND ("; $sql .= " AND (";
$sql .= "p.ref LIKE '%".$db->escape(GETPOST('filtre'))."%' OR p.label LIKE '%".$db->escape(GETPOST('filtre'))."%'"; $sql .= "p.ref LIKE '%".$db->escape(GETPOST('filtre'))."%' OR p.label LIKE '%".$db->escape(GETPOST('filtre'))."%'";
if (!empty($conf->barcode->enabled)) if (!empty($conf->barcode->enabled)) {
{
$filtre = GETPOST('filtre', 'alpha'); $filtre = GETPOST('filtre', 'alpha');
//If the barcode looks like an EAN13 format and the last digit is included in it, //If the barcode looks like an EAN13 format and the last digit is included in it,
@ -67,14 +72,11 @@ if (GETPOST('filtre', 'alpha')) {
dol_syslog("facturation.php", LOG_DEBUG); dol_syslog("facturation.php", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$nbr_enreg = $db->num_rows($resql); $nbr_enreg = $db->num_rows($resql);
while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) {
{ foreach ($tab as $cle => $valeur) {
foreach ($tab as $cle => $valeur)
{
$ret[$i][$cle] = $valeur; $ret[$i][$cle] = $valeur;
} }
$i++; $i++;
@ -90,24 +92,27 @@ if (GETPOST('filtre', 'alpha')) {
$i = 0; $i = 0;
$sql = "SELECT p.rowid, ref, label, tva_tx, p.fk_product_type"; $sql = "SELECT p.rowid, ref, label, tva_tx, p.fk_product_type";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
$sql .= " AND p.tosell = 1"; $sql .= " AND p.tosell = 1";
if (!$conf->global->CASHDESK_SERVICES) $sql .= " AND p.fk_product_type = 0"; if (!$conf->global->CASHDESK_SERVICES) {
$sql .= " AND p.fk_product_type = 0";
}
$sql .= " ORDER BY p.label"; $sql .= " ORDER BY p.label";
dol_syslog($sql); dol_syslog($sql);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$nbr_enreg = $db->num_rows($resql); $nbr_enreg = $db->num_rows($resql);
while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) while ($i < $conf_taille_listes && $tab = $db->fetch_array($resql)) {
{ foreach ($tab as $cle => $valeur) {
foreach ($tab as $cle => $valeur)
{
$ret[$i][$cle] = $valeur; $ret[$i][$cle] = $valeur;
} }
$i++; $i++;
@ -121,16 +126,13 @@ if (GETPOST('filtre', 'alpha')) {
//$nbr_enreg = count($tab_designations); //$nbr_enreg = count($tab_designations);
if ($nbr_enreg > 1) if ($nbr_enreg > 1) {
{ if ($nbr_enreg > $conf_taille_listes) {
if ($nbr_enreg > $conf_taille_listes)
{
$top_liste_produits = '----- '.$conf_taille_listes.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----'; $top_liste_produits = '----- '.$conf_taille_listes.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----';
} else { } else {
$top_liste_produits = '----- '.$nbr_enreg.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----'; $top_liste_produits = '----- '.$nbr_enreg.' '.$langs->transnoentitiesnoconv("CashDeskProducts").' '.$langs->trans("CashDeskOn").' '.$nbr_enreg.' -----';
} }
} elseif ($nbr_enreg == 1) } elseif ($nbr_enreg == 1) {
{
$top_liste_produits = '----- 1 '.$langs->transnoentitiesnoconv("ProductFound").' -----'; $top_liste_produits = '----- 1 '.$langs->transnoentitiesnoconv("ProductFound").' -----';
} else { } else {
$top_liste_produits = '----- '.$langs->transnoentitiesnoconv("NoProductFound").' -----'; $top_liste_produits = '----- '.$langs->transnoentitiesnoconv("NoProductFound").' -----';

View File

@ -24,12 +24,24 @@
*/ */
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('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); if (!defined('NOCSRFCHECK')) {
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); define('NOCSRFCHECK', '1');
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); }
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1');
}
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
// Change this following line to use the correct relative path (../, ../../, etc) // Change this following line to use the correct relative path (../, ../../, etc)
require '../main.inc.php'; require '../main.inc.php';
@ -40,24 +52,30 @@ top_httphead('text/html');
$search = GETPOST("code", "alpha"); $search = GETPOST("code", "alpha");
// Search from criteria // Search from criteria
if (dol_strlen($search) >= 0) // If search criteria is on char length at least if (dol_strlen($search) >= 0) { // If search criteria is on char length at least
{
$sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx"; $sql = "SELECT p.rowid, p.ref, p.label, p.tva_tx";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = '".$db->escape($conf_fkentrepot)."'";
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
$sql .= " AND p.tosell = 1"; $sql .= " AND p.tosell = 1";
$sql .= " AND p.fk_product_type = 0"; $sql .= " AND p.fk_product_type = 0";
// Add criteria on ref/label // Add criteria on ref/label
if (!empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)) if (!empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)) {
{
$sql .= " AND (p.ref LIKE '".$db->escape($search)."%' OR p.label LIKE '".$db->escape($search)."%'"; $sql .= " AND (p.ref LIKE '".$db->escape($search)."%' OR p.label LIKE '".$db->escape($search)."%'";
if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$db->escape($search)."%'"; if (!empty($conf->barcode->enabled)) {
$sql .= " OR p.barcode LIKE '".$db->escape($search)."%'";
}
$sql .= ")"; $sql .= ")";
} else { } else {
$sql .= " AND (p.ref LIKE '%".$db->escape($search)."%' OR p.label LIKE '%".$db->escape($search)."%'"; $sql .= " AND (p.ref LIKE '%".$db->escape($search)."%' OR p.label LIKE '%".$db->escape($search)."%'";
if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '%".$db->escape($search)."%'"; if (!empty($conf->barcode->enabled)) {
$sql .= " OR p.barcode LIKE '%".$db->escape($search)."%'";
}
$sql .= ")"; $sql .= ")";
} }
$sql .= " ORDER BY label"; $sql .= " ORDER BY label";
@ -65,17 +83,13 @@ if (dol_strlen($search) >= 0) // If search criteria is on char length at least
dol_syslog("facturation_dhtml.php", LOG_DEBUG); dol_syslog("facturation_dhtml.php", LOG_DEBUG);
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{ if ($nbr = $db->num_rows($result)) {
if ($nbr = $db->num_rows($result))
{
$resultat = '<ul class="dhtml_bloc">'; $resultat = '<ul class="dhtml_bloc">';
$ret = array(); $i = 0; $ret = array(); $i = 0;
while ($tab = $db->fetch_array($result)) while ($tab = $db->fetch_array($result)) {
{ foreach ($tab as $cle => $valeur) {
foreach ($tab as $cle => $valeur)
{
$ret[$i][$cle] = $valeur; $ret[$i][$cle] = $valeur;
} }
$i++; $i++;
@ -83,8 +97,7 @@ if (dol_strlen($search) >= 0) // If search criteria is on char length at least
$tab = $ret; $tab = $ret;
$tab_size = count($tab); $tab_size = count($tab);
for ($i = 0; $i < $tab_size; $i++) for ($i = 0; $i < $tab_size; $i++) {
{
$resultat .= ' $resultat .= '
<li class="dhtml_defaut" title="'.$tab[$i]['ref'].'" <li class="dhtml_defaut" title="'.$tab[$i]['ref'].'"
onMouseOver="javascript: this.className = \'dhtml_selection\';" onMouseOver="javascript: this.className = \'dhtml_selection\';"

View File

@ -35,36 +35,33 @@ $obj_facturation = unserialize($_SESSION['serObjFacturation']);
unset($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']);
switch ($action) switch ($action) {
{
default: default:
if ($_POST['hdnSource'] != 'NULL') if ($_POST['hdnSource'] != 'NULL') {
{
$sql = "SELECT p.rowid, p.ref, p.price, p.tva_tx, p.default_vat_code, p.recuperableonly"; $sql = "SELECT p.rowid, p.ref, p.price, p.tva_tx, p.default_vat_code, p.recuperableonly";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= ", ps.reel"; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= ", ps.reel";
}
$sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = ".$conf_fkentrepot; if (!empty($conf->stock->enabled) && !empty($conf_fkentrepot)) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot = ".$conf_fkentrepot;
}
$sql .= " WHERE p.entity IN (".getEntity('product').")"; $sql .= " WHERE p.entity IN (".getEntity('product').")";
// Recuperation des donnees en fonction de la source (liste deroulante ou champ texte) ... // Recuperation des donnees en fonction de la source (liste deroulante ou champ texte) ...
if ($_POST['hdnSource'] == 'LISTE') if ($_POST['hdnSource'] == 'LISTE') {
{
$sql .= " AND p.rowid = ".((int) GETPOST('selProduit', 'int')); $sql .= " AND p.rowid = ".((int) GETPOST('selProduit', 'int'));
} elseif ($_POST['hdnSource'] == 'REF') } elseif ($_POST['hdnSource'] == 'REF') {
{
$sql .= " AND p.ref = '".$db->escape(GETPOST('txtRef', 'alpha'))."'"; $sql .= " AND p.ref = '".$db->escape(GETPOST('txtRef', 'alpha'))."'";
} }
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
// ... et enregistrement dans l'objet // ... et enregistrement dans l'objet
if ($db->num_rows($result)) if ($db->num_rows($result)) {
{
$ret = array(); $ret = array();
$tab = $db->fetch_array($result); $tab = $db->fetch_array($result);
foreach ($tab as $key => $value) foreach ($tab as $key => $value) {
{
$ret[$key] = $value; $ret[$key] = $value;
} }
// Here $ret['tva_tx'] is vat rate of product but we want to not use the one into table but found by function // Here $ret['tva_tx'] is vat rate of product but we want to not use the one into table but found by function
@ -81,7 +78,9 @@ switch ($action)
// Update if prices fields are defined // Update if prices fields are defined
$tva_tx = get_default_tva($mysoc, $societe, $product->id); $tva_tx = get_default_tva($mysoc, $societe, $product->id);
$tva_npr = get_default_npr($mysoc, $societe, $product->id); $tva_npr = get_default_npr($mysoc, $societe, $product->id);
if (empty($tva_tx)) $tva_npr = 0; if (empty($tva_tx)) {
$tva_npr = 0;
}
$pu_ht = $prod->price; $pu_ht = $prod->price;
$pu_ttc = $prod->price_ttc; $pu_ttc = $prod->price_ttc;
@ -89,19 +88,20 @@ switch ($action)
$price_base_type = $prod->price_base_type; $price_base_type = $prod->price_base_type;
// multiprix // multiprix
if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($societe->price_level)) if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($societe->price_level)) {
{
$pu_ht = $prod->multiprices[$societe->price_level]; $pu_ht = $prod->multiprices[$societe->price_level];
$pu_ttc = $prod->multiprices_ttc[$societe->price_level]; $pu_ttc = $prod->multiprices_ttc[$societe->price_level];
$price_min = $prod->multiprices_min[$societe->price_level]; $price_min = $prod->multiprices_min[$societe->price_level];
$price_base_type = $prod->multiprices_base_type[$societe->price_level]; $price_base_type = $prod->multiprices_base_type[$societe->price_level];
if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
{ if (isset($prod->multiprices_tva_tx[$societe->price_level])) {
if (isset($prod->multiprices_tva_tx[$societe->price_level])) $tva_tx = $prod->multiprices_tva_tx[$societe->price_level]; $tva_tx = $prod->multiprices_tva_tx[$societe->price_level];
if (isset($prod->multiprices_recuperableonly[$societe->price_level])) $tva_npr = $prod->multiprices_recuperableonly[$societe->price_level]; }
if (isset($prod->multiprices_recuperableonly[$societe->price_level])) {
$tva_npr = $prod->multiprices_recuperableonly[$societe->price_level];
}
} }
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
{
require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
$prodcustprice = new Productcustomerprice($db); $prodcustprice = new Productcustomerprice($db);
@ -109,17 +109,19 @@ switch ($action)
$filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $societe->id); $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $societe->id);
$result = $prodcustprice->fetch_all('', '', 0, 0, $filter); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
if ($result >= 0) if ($result >= 0) {
{ if (count($prodcustprice->lines) > 0) {
if (count($prodcustprice->lines) > 0)
{
$pu_ht = price($prodcustprice->lines[0]->price); $pu_ht = price($prodcustprice->lines[0]->price);
$pu_ttc = price($prodcustprice->lines[0]->price_ttc); $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
$price_base_type = $prodcustprice->lines[0]->price_base_type; $price_base_type = $prodcustprice->lines[0]->price_base_type;
$tva_tx = $prodcustprice->lines[0]->tva_tx; $tva_tx = $prodcustprice->lines[0]->tva_tx;
if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
$tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
}
$tva_npr = $prodcustprice->lines[0]->recuperableonly; $tva_npr = $prodcustprice->lines[0]->recuperableonly;
if (empty($tva_tx)) $tva_npr = 0; if (empty($tva_tx)) {
$tva_npr = 0;
}
} }
} else { } else {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
@ -133,10 +135,9 @@ switch ($action)
if (!empty($price_ht)) { if (!empty($price_ht)) {
$pu_ht = price2num($price_ht, 'MU'); $pu_ht = price2num($price_ht, 'MU');
$pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
} } elseif ($tmpvat != $tmpprodvat) {
// On reevalue prix selon taux tva car taux tva transaction peut etre different // On reevalue prix selon taux tva car taux tva transaction peut etre different
// de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
elseif ($tmpvat != $tmpprodvat) {
if ($price_base_type != 'HT') { if ($price_base_type != 'HT') {
$pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
} else { } else {
@ -155,11 +156,9 @@ switch ($action)
$obj_facturation->vatrate = $vatrate; // Save vat rate (full text vat with code) $obj_facturation->vatrate = $vatrate; // Save vat rate (full text vat with code)
// Definition du filtre pour n'afficher que le produit concerne // Definition du filtre pour n'afficher que le produit concerne
if ($_POST['hdnSource'] == 'LISTE') if ($_POST['hdnSource'] == 'LISTE') {
{
$filtre = $ret['ref']; $filtre = $ret['ref'];
} elseif ($_POST['hdnSource'] == 'REF') } elseif ($_POST['hdnSource'] == 'REF') {
{
$filtre = $_POST['txtRef']; $filtre = $_POST['txtRef'];
} }
@ -167,8 +166,7 @@ switch ($action)
} else { } else {
$obj_facturation->raz(); $obj_facturation->raz();
if ($_POST['hdnSource'] == 'REF') if ($_POST['hdnSource'] == 'REF') {
{
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation&filtre='.$_POST['txtRef']; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation&filtre='.$_POST['txtRef'];
} else { } else {
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation'; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation';
@ -185,18 +183,15 @@ switch ($action)
case 'change_thirdparty': // We have clicked on button "Modify" a thirdparty case 'change_thirdparty': // We have clicked on button "Modify" a thirdparty
$newthirdpartyid = GETPOST('CASHDESK_ID_THIRDPARTY', 'int'); $newthirdpartyid = GETPOST('CASHDESK_ID_THIRDPARTY', 'int');
if ($newthirdpartyid > 0) if ($newthirdpartyid > 0) {
{
$_SESSION["CASHDESK_ID_THIRDPARTY"] = $newthirdpartyid; $_SESSION["CASHDESK_ID_THIRDPARTY"] = $newthirdpartyid;
} }
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation'; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=facturation';
break; break;
case 'ajout_article': // We have clicked on button "Add product" case 'ajout_article':
if (!empty($obj_facturation->id)) { // A product was previously selected and stored in session, so we can add it
if (!empty($obj_facturation->id)) // A product was previously selected and stored in session, so we can add it
{
dol_syslog("facturation_verif save vat ".$_POST['selTva']); dol_syslog("facturation_verif save vat ".$_POST['selTva']);
$obj_facturation->qte($_POST['txtQte']); $obj_facturation->qte($_POST['txtQte']);
$obj_facturation->tva($_POST['selTva']); // id of vat. Saved so we can use it for next product $obj_facturation->tva($_POST['selTva']); // id of vat. Saved so we can use it for next product

View File

@ -32,7 +32,9 @@ $conf_db_base = $dolibarr_main_db_name;
$conf_fksoc = (!empty($_SESSION["CASHDESK_ID_THIRDPARTY"])) ? $_SESSION["CASHDESK_ID_THIRDPARTY"] : ($conf->global->CASHDESK_ID_THIRDPARTY > 0 ? $conf->global->CASHDESK_ID_THIRDPARTY : 0); $conf_fksoc = (!empty($_SESSION["CASHDESK_ID_THIRDPARTY"])) ? $_SESSION["CASHDESK_ID_THIRDPARTY"] : ($conf->global->CASHDESK_ID_THIRDPARTY > 0 ? $conf->global->CASHDESK_ID_THIRDPARTY : 0);
// Identifiant unique correspondant a l'entrepot a utiliser // Identifiant unique correspondant a l'entrepot a utiliser
$conf_fkentrepot = (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"])) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : ($conf->global->CASHDESK_ID_WAREHOUSE > 0 ? $conf->global->CASHDESK_ID_WAREHOUSE : 0); $conf_fkentrepot = (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"])) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : ($conf->global->CASHDESK_ID_WAREHOUSE > 0 ? $conf->global->CASHDESK_ID_WAREHOUSE : 0);
if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $conf_fkentrepot = 0; // If option to disable the stock decrease is on, we set warehouse id to 0. if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
$conf_fkentrepot = 0; // If option to disable the stock decrease is on, we set warehouse id to 0.
}
// Identifiant unique correspondant au compte caisse / liquide // Identifiant unique correspondant au compte caisse / liquide
$conf_fkaccount_cash = (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) ? $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"] : ($conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0 ? $conf->global->CASHDESK_ID_BANKACCOUNT_CASH : 0); $conf_fkaccount_cash = (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) ? $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"] : ($conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0 ? $conf->global->CASHDESK_ID_BANKACCOUNT_CASH : 0);

View File

@ -26,7 +26,9 @@ function genkeypad($keypadname, $formname)
{ {
global $conf; global $conf;
if (empty($conf->global->CASHDESK_SHOW_KEYPAD)) return ''; if (empty($conf->global->CASHDESK_SHOW_KEYPAD)) {
return '';
}
// défine the font size of button // défine the font size of button
$btnsize = 32; $btnsize = 32;

View File

@ -32,8 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
$langs->loadLangs(array("admin", "cashdesk")); $langs->loadLangs(array("admin", "cashdesk"));
// Test if user logged // Test if user logged
if ($_SESSION['uid'] > 0) if ($_SESSION['uid'] > 0) {
{
header('Location: '.DOL_URL_ROOT.'/cashdesk/affIndex.php'); header('Location: '.DOL_URL_ROOT.'/cashdesk/affIndex.php');
exit; exit;
} }
@ -72,8 +71,7 @@ if (is_array($hookmanager->resArray) && !empty($hookmanager->resArray)) {
<div class="menu_principal hideonsmartphone"> <div class="menu_principal hideonsmartphone">
<div class="logo"> <div class="logo">
<?php <?php
if (!empty($mysoc->logo_small)) if (!empty($mysoc->logo_small)) {
{
print '<img class="logopos" alt="Logo company" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small).'">'; print '<img class="logopos" alt="Logo company" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small).'">';
} else { } else {
print '<div class="logopos">'.$mysoc->name.'</div>'; print '<div class="logopos">'.$mysoc->name.'</div>';
@ -85,7 +83,9 @@ if (!empty($mysoc->logo_small))
<div class="contenu"> <div class="contenu">
<div class="inline-block" style="vertical-align: top"> <div class="inline-block" style="vertical-align: top">
<div class="principal_login"> <div class="principal_login">
<?php if ($err) print dol_escape_htmltag($err)."<br><br>\n"; ?> <?php if ($err) {
print dol_escape_htmltag($err)."<br><br>\n";
} ?>
<fieldset class="cadre_facturation"><legend class="titre1"><?php echo $langs->trans("Identification"); ?></legend> <fieldset class="cadre_facturation"><legend class="titre1"><?php echo $langs->trans("Identification"); ?></legend>
<form id="frmLogin" method="POST" action="index_verif.php"> <form id="frmLogin" method="POST" action="index_verif.php">
<input type="hidden" name="token" value="<?php echo newToken(); ?>" /> <input type="hidden" name="token" value="<?php echo newToken(); ?>" />
@ -104,8 +104,7 @@ if (!empty($mysoc->logo_small))
<?php <?php
if (!empty($morelogincontent)) { if (!empty($morelogincontent)) {
if (is_array($morelogincontent)) { if (is_array($morelogincontent)) {
foreach ($morelogincontent as $format => $option) foreach ($morelogincontent as $format => $option) {
{
if ($format == 'table') { if ($format == 'table') {
echo '<!-- Option by hook -->'; echo '<!-- Option by hook -->';
echo $option; echo $option;
@ -130,20 +129,23 @@ print '<td class="label1">'.$langs->trans("CashDeskThirdPartyForSell").'</td>';
print '<td>'; print '<td>';
$disabled = 0; $disabled = 0;
$langs->load("companies"); $langs->load("companies");
if (!empty($conf->global->CASHDESK_ID_THIRDPARTY)) $disabled = 1; // If a particular third party is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_THIRDPARTY)) {
$disabled = 1; // If a particular third party is defined, we disable choice
}
print $form->select_company(GETPOST('socid', 'int') ?GETPOST('socid', 'int') : $conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client IN (1,3) AND s.status = 1)', !$disabled, $disabled, 0, array(), 0, 'maxwidth300'); print $form->select_company(GETPOST('socid', 'int') ?GETPOST('socid', 'int') : $conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client IN (1,3) AND s.status = 1)', !$disabled, $disabled, 0, array(), 0, 'maxwidth300');
//print '<input name="warehouse_id" class="texte_login" type="warehouse_id" value="" />'; //print '<input name="warehouse_id" class="texte_login" type="warehouse_id" value="" />';
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
{
$langs->load("stocks"); $langs->load("stocks");
print "<tr>"; print "<tr>";
print '<td class="label1">'.$langs->trans("Warehouse").'</td>'; print '<td class="label1">'.$langs->trans("Warehouse").'</td>';
print '<td>'; print '<td>';
$disabled = 0; $disabled = 0;
if ($conf->global->CASHDESK_ID_WAREHOUSE > 0) $disabled = 1; // If a particular stock is defined, we disable choice if ($conf->global->CASHDESK_ID_WAREHOUSE > 0) {
$disabled = 1; // If a particular stock is defined, we disable choice
}
print $formproduct->selectWarehouses((GETPOST('warehouseid') ?GETPOST('warehouseid', 'int') : (empty($conf->global->CASHDESK_ID_WAREHOUSE) ? 'ifone' : $conf->global->CASHDESK_ID_WAREHOUSE)), 'warehouseid', '', !$disabled, $disabled); print $formproduct->selectWarehouses((GETPOST('warehouseid') ?GETPOST('warehouseid', 'int') : (empty($conf->global->CASHDESK_ID_WAREHOUSE) ? 'ifone' : $conf->global->CASHDESK_ID_WAREHOUSE)), 'warehouseid', '', !$disabled, $disabled);
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -153,7 +155,9 @@ print "<tr>";
print '<td class="label1">'.$langs->trans("CashDeskBankAccountForSell").'</td>'; print '<td class="label1">'.$langs->trans("CashDeskBankAccountForSell").'</td>';
print '<td>'; print '<td>';
$defaultknown = 0; $defaultknown = 0;
if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && $conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0) $defaultknown = 1; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && $conf->global->CASHDESK_ID_BANKACCOUNT_CASH > 0) {
$defaultknown = 1; // If a particular stock is defined, we disable choice
}
$form->select_comptes(((GETPOST('bankid_cash') > 0) ?GETPOST('bankid_cash') : $conf->global->CASHDESK_ID_BANKACCOUNT_CASH), 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", ($defaultknown ? 0 : 2)); $form->select_comptes(((GETPOST('bankid_cash') > 0) ?GETPOST('bankid_cash') : $conf->global->CASHDESK_ID_BANKACCOUNT_CASH), 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", ($defaultknown ? 0 : 2));
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -162,7 +166,9 @@ print "<tr>";
print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCheque").'</td>'; print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCheque").'</td>';
print '<td>'; print '<td>';
$defaultknown = 0; $defaultknown = 0;
if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE) && $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE > 0) $defaultknown = 1; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE) && $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE > 0) {
$defaultknown = 1; // If a particular stock is defined, we disable choice
}
$form->select_comptes(((GETPOST('bankid_cheque') > 0) ?GETPOST('bankid_cheque') : $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE), 'CASHDESK_ID_BANKACCOUNT_CHEQUE', 0, "courant=1", ($defaultknown ? 0 : 2)); $form->select_comptes(((GETPOST('bankid_cheque') > 0) ?GETPOST('bankid_cheque') : $conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE), 'CASHDESK_ID_BANKACCOUNT_CHEQUE', 0, "courant=1", ($defaultknown ? 0 : 2));
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -171,7 +177,9 @@ print "<tr>";
print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCB").'</td>'; print '<td class="label1">'.$langs->trans("CashDeskBankAccountForCB").'</td>';
print '<td>'; print '<td>';
$defaultknown = 0; $defaultknown = 0;
if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CB) && $conf->global->CASHDESK_ID_BANKACCOUNT_CB > 0) $defaultknown = 1; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_ID_BANKACCOUNT_CB) && $conf->global->CASHDESK_ID_BANKACCOUNT_CB > 0) {
$defaultknown = 1; // If a particular stock is defined, we disable choice
}
$form->select_comptes(((GETPOST('bankid_cb') > 0) ?GETPOST('bankid_cb') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB), 'CASHDESK_ID_BANKACCOUNT_CB', 0, "courant=1", ($defaultknown ? 0 : 2)); $form->select_comptes(((GETPOST('bankid_cb') > 0) ?GETPOST('bankid_cb') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB), 'CASHDESK_ID_BANKACCOUNT_CB', 0, "courant=1", ($defaultknown ? 0 : 2));
print '</td>'; print '</td>';
print "</tr>\n"; print "</tr>\n";
@ -195,8 +203,7 @@ print "</tr>\n";
<?php <?php
if ($_GET['err'] < 0) if ($_GET['err'] < 0) {
{
echo ('<script type="text/javascript">'); echo ('<script type="text/javascript">');
echo (' document.getElementById(\'frmLogin\').pwdPassword.focus();'); echo (' document.getElementById(\'frmLogin\').pwdPassword.focus();');
echo ('</script>'); echo ('</script>');

View File

@ -42,36 +42,31 @@ $bankid_cheque = (GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE") > 0) ?GETPOST("CASHD
$bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0) ?GETPOST("CASHDESK_ID_BANKACCOUNT_CB", 'int') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB; $bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0) ?GETPOST("CASHDESK_ID_BANKACCOUNT_CB", 'int') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB;
// Check username // Check username
if (empty($username)) if (empty($username)) {
{
$retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Login")); $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Login"));
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
} }
// Check third party id // Check third party id
if (!($thirdpartyid > 0)) if (!($thirdpartyid > 0)) {
{
$retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("CashDeskThirdPartyForSell")); $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("CashDeskThirdPartyForSell"));
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
} }
// If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished. // If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished.
if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) {
{
$retour = $langs->trans("CashDeskYouDidNotDisableStockDecease"); $retour = $langs->trans("CashDeskYouDidNotDisableStockDecease");
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
} }
// If stock decrease on bill validation, check user has stock edit permissions // If stock decrease on bill validation, check user has stock edit permissions
if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) {
{
$testuser = new User($db); $testuser = new User($db);
$testuser->fetch(0, $username); $testuser->fetch(0, $username);
$testuser->getrights('stock'); $testuser->getrights('stock');
if (empty($testuser->rights->stock->creer)) if (empty($testuser->rights->stock->creer)) {
{
$retour = $langs->trans("UserNeedPermissionToEditStockToUsePos"); $retour = $langs->trans("UserNeedPermissionToEditStockToUsePos");
header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb);
exit; exit;
@ -83,8 +78,7 @@ if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_S
$auth = new Auth($db); $auth = new Auth($db);
$retour = $auth->verif($username, $password); $retour = $auth->verif($username, $password);
if ($retour >= 0) if ($retour >= 0) {
{
$return = array(); $return = array();
$sql = "SELECT rowid, lastname, firstname"; $sql = "SELECT rowid, lastname, firstname";
@ -93,12 +87,10 @@ if ($retour >= 0)
$sql .= " AND entity IN (0,".$conf->entity.")"; $sql .= " AND entity IN (0,".$conf->entity.")";
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$tab = $db->fetch_array($res); $tab = $db->fetch_array($res);
foreach ($tab as $key => $value) foreach ($tab as $key => $value) {
{
$return[$key] = $value; $return[$key] = $value;
} }

View File

@ -21,8 +21,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -64,10 +63,11 @@ $id = $obj_facturation->id();
// Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ... // Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ...
$nbtoshow = $nbr_enreg; $nbtoshow = $nbr_enreg;
if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) $nbtoshow = $conf_taille_listes; if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) {
$nbtoshow = $conf_taille_listes;
}
for ($i = 0; $i < $nbtoshow; $i++) for ($i = 0; $i < $nbtoshow; $i++) {
{
if ($id == $tab_designations[$i]['rowid']) { if ($id == $tab_designations[$i]['rowid']) {
$selected = 'selected'; $selected = 'selected';
} else { } else {
@ -96,9 +96,9 @@ for ($i = 0; $i < $nbtoshow; $i++)
<th><?php echo $langs->trans("Qty"); ?></th> <th><?php echo $langs->trans("Qty"); ?></th>
<th><?php echo $langs->trans("PriceUHT"); ?></th> <th><?php echo $langs->trans("PriceUHT"); ?></th>
<th><?php echo $langs->trans("Discount"); ?> (%)</th> <th><?php echo $langs->trans("Discount"); ?> (%)</th>
<th><?php echo $langs->trans("VATRate"); ?></th> <th><?php echo $langs->trans("VATRate"); ?></th>
<th></th> <th></th>
</tr> </tr>
<tr> <tr>
<td><input class="texte1 maxwidth50onsmartphone" type="text" id="txtQte" name="txtQte" value="1" onkeyup="javascript: modif();" onfocus="javascript: this.select();" /> <td><input class="texte1 maxwidth50onsmartphone" type="text" id="txtQte" name="txtQte" value="1" onkeyup="javascript: modif();" onfocus="javascript: this.select();" />
<?php print genkeypad("txtQte", "frmQte"); ?> <?php print genkeypad("txtQte", "frmQte"); ?>
@ -106,20 +106,22 @@ for ($i = 0; $i < $nbtoshow; $i++)
<!-- Show unit price --> <!-- Show unit price -->
<?php // TODO Remove the disabled and use this value when adding product into cart ?> <?php // TODO Remove the disabled and use this value when adding product into cart ?>
<td><input class="texte1_off maxwidth50onsmartphone" type="text" name="txtPrixUnit" value="<?php echo price2num($obj_facturation->prix(), 'MU'); ?>" onchange="javascript: modif();" disabled /></td> <td><input class="texte1_off maxwidth50onsmartphone" type="text" name="txtPrixUnit" value="<?php echo price2num($obj_facturation->prix(), 'MU'); ?>" onchange="javascript: modif();" disabled /></td>
<!-- Choix de la remise --> <!-- Choix de la remise -->
<td><input class="texte1 maxwidth50onsmartphone" type="text" id="txtRemise" name="txtRemise" value="0" onkeyup="javascript: modif();" onfocus="javascript: this.select();"/> <td><input class="texte1 maxwidth50onsmartphone" type="text" id="txtRemise" name="txtRemise" value="0" onkeyup="javascript: modif();" onfocus="javascript: this.select();"/>
<?php print genkeypad("txtRemise", "frmQte"); ?> <?php print genkeypad("txtRemise", "frmQte"); ?>
</td> </td>
<!-- Choix du taux de TVA --> <!-- Choix du taux de TVA -->
<td class="select_tva center"> <td class="select_tva center">
<?php <?php
$vatrate = $obj_facturation->vatrate; // To get vat rate we just have selected $vatrate = $obj_facturation->vatrate; // To get vat rate we just have selected
$buyer = new Societe($db); $buyer = new Societe($db);
if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) {
$buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]);
}
echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1); echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1);
?> ?>
</td> </td>
<td></td> <td></td>
</tr> </tr>
<tr> <tr>
@ -130,8 +132,8 @@ for ($i = 0; $i < $nbtoshow; $i++)
<input class="texte1_off maxwidth50onsmartphone" type="text" name="txtStock" value="<?php echo $obj_facturation->stock() ?>" disabled /> <input class="texte1_off maxwidth50onsmartphone" type="text" name="txtStock" value="<?php echo $obj_facturation->stock() ?>" disabled />
</td> </td>
<td><?php echo $langs->trans("TotalHT"); ?></td> <td><?php echo $langs->trans("TotalHT"); ?></td>
<!-- Affichage du total HT --> <!-- Affichage du total HT -->
<td colspan="2"><input class="texte1_off maxwidth50onsmartphone" type="text" name="txtTotal" value="" disabled /></td><td></td> <td colspan="2"><input class="texte1_off maxwidth50onsmartphone" type="text" name="txtTotal" value="" disabled /></td><td></td>
</tr> </tr>
</table> </table>
@ -165,25 +167,28 @@ for ($i = 0; $i < $nbtoshow; $i++)
<div class="inline-block"> <div class="inline-block">
<?php <?php
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';
if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) {
{
$langs->load("errors"); $langs->load("errors");
print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("Cash").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />'; print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("Cash").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />';
} else print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("Cash").'" onclick="javascript: verifClic(\'ESP\');" />'; } else {
print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("Cash").'" onclick="javascript: verifClic(\'ESP\');" />';
}
print '</div>'; print '</div>';
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';
if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) {
{
$langs->load("errors"); $langs->load("errors");
print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />'; print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("CashDesk"))).'" />';
} else print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" onclick="javascript: verifClic(\'CB\');" />'; } else {
print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CreditCard").'" onclick="javascript: verifClic(\'CB\');" />';
}
print '</div>'; print '</div>';
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';
if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) {
{
$langs->load("errors"); $langs->load("errors");
print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete"), $langs->transnoentitiesnoconv("CashDesk")).'" />'; print '<input class="bouton_mode_reglement_disabled" type="button" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" title="'.dol_escape_htmltag($langs->trans("ErrorModuleSetupNotComplete"), $langs->transnoentitiesnoconv("CashDesk")).'" />';
} else print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" onclick="javascript: verifClic(\'CHQ\');" />'; } else {
print '<input class="button bouton_mode_reglement" type="submit" name="btnModeReglement" value="'.$langs->trans("CheckBank").'" onclick="javascript: verifClic(\'CHQ\');" />';
}
print '</div>'; print '</div>';
print '<div class="clearboth">'; print '<div class="clearboth">';
print '<div class="inline-block" style="margin: 6px;">'; print '<div class="inline-block" style="margin: 6px;">';

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -48,10 +47,10 @@ $societe->fetch($thirdpartyid);
$tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array());
$tab_size = count($tab); $tab_size = count($tab);
if ($tab_size <= 0) print '<div class="center">'.$langs->trans("NoArticle").'</div><br>'; if ($tab_size <= 0) {
else { print '<div class="center">'.$langs->trans("NoArticle").'</div><br>';
for ($i = 0; $i < $tab_size; $i++) } else {
{ for ($i = 0; $i < $tab_size; $i++) {
echo ('<div class="cadre_article">'."\n"); echo ('<div class="cadre_article">'."\n");
echo ('<p><a href="facturation_verif.php?action=suppr_article&suppr_id='.$tab[$i]['id'].'" title="'.$langs->trans("DeleteArticle").'">'.$tab[$i]['ref'].' - '.$tab[$i]['label'].'</a></p>'."\n"); echo ('<p><a href="facturation_verif.php?action=suppr_article&suppr_id='.$tab[$i]['id'].'" title="'.$langs->trans("DeleteArticle").'">'.$tab[$i]['ref'].' - '.$tab[$i]['label'].'</a></p>'."\n");

View File

@ -20,8 +20,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -37,27 +36,23 @@ include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$company->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); $company->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]);
$companyLink = $company->getNomUrl(1); $companyLink = $company->getNomUrl(1);
}*/ }*/
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) {
{
$bankcash = new Account($db); $bankcash = new Account($db);
$bankcash->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]); $bankcash->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]);
$bankcash->label = $bankcash->ref; $bankcash->label = $bankcash->ref;
$bankcashLink = $bankcash->getNomUrl(1); $bankcashLink = $bankcash->getNomUrl(1);
} }
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) {
{
$bankcb = new Account($db); $bankcb = new Account($db);
$bankcb->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]); $bankcb->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]);
$bankcbLink = $bankcb->getNomUrl(1); $bankcbLink = $bankcb->getNomUrl(1);
} }
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) {
{
$bankcheque = new Account($db); $bankcheque = new Account($db);
$bankcheque->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]); $bankcheque->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]);
$bankchequeLink = $bankcheque->getNomUrl(1); $bankchequeLink = $bankcheque->getNomUrl(1);
} }
if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) {
{
$warehouse = new Entrepot($db); $warehouse = new Entrepot($db);
$warehouse->fetch($_SESSION["CASHDESK_ID_WAREHOUSE"]); $warehouse->fetch($_SESSION["CASHDESK_ID_WAREHOUSE"]);
$warehouseLink = $warehouse->getNomUrl(1); $warehouseLink = $warehouse->getNomUrl(1);
@ -87,8 +82,7 @@ print '</form>';
print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'<br>'; print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'<br>';
print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'<br>';*/ print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'<br>';*/
print '<div class="clearboth">'; print '<div class="clearboth">';
if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
{
print $langs->trans("CashDeskWarehouse").': '.$warehouseLink; print $langs->trans("CashDeskWarehouse").': '.$warehouseLink;
} }
print '</div></li></ul>'; print '</div></li></ul>';

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -38,82 +37,81 @@ $object->fetch($facid);
?> ?>
<html> <html>
<head> <head>
<title><?php echo $langs->trans('PrintTicket') ?></title> <title><?php echo $langs->trans('PrintTicket') ?></title>
<link rel="stylesheet" type="text/css" href="<?php echo DOL_URL_ROOT; ?>/cashdesk/css/ticket.css"> <link rel="stylesheet" type="text/css" href="<?php echo DOL_URL_ROOT; ?>/cashdesk/css/ticket.css">
</head> </head>
<body> <body>
<div class="entete"> <div class="entete">
<div class="logo"> <div class="logo">
<?php print '<img src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small).'">'; ?> <?php print '<img src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small).'">'; ?>
</div> </div>
<div class="infos"> <div class="infos">
<p class="address"><?php echo $mysoc->name; ?><br> <p class="address"><?php echo $mysoc->name; ?><br>
<?php print dol_nl2br(dol_format_address($mysoc)); ?><br> <?php print dol_nl2br(dol_format_address($mysoc)); ?><br>
</p> </p>
<p class="date_heure"><?php <p class="date_heure"><?php
// Recuperation et affichage de la date et de l'heure // Recuperation et affichage de la date et de l'heure
$now = dol_now(); $now = dol_now();
print dol_print_date($now, 'dayhourtext').'<br>'; print dol_print_date($now, 'dayhourtext').'<br>';
print $object->ref; print $object->ref;
?></p> ?></p>
</div> </div>
</div> </div>
<br> <br>
<table class="liste_articles"> <table class="liste_articles">
<thead> <thead>
<tr class="titres"> <tr class="titres">
<th><?php print $langs->trans("Code"); ?></th> <th><?php print $langs->trans("Code"); ?></th>
<th><?php print $langs->trans("Label"); ?></th> <th><?php print $langs->trans("Label"); ?></th>
<th><?php print $langs->trans("Qty"); ?></th> <th><?php print $langs->trans("Qty"); ?></th>
<th><?php print $langs->trans("Discount").' (%)'; ?></th> <th><?php print $langs->trans("Discount").' (%)'; ?></th>
<th><?php print $langs->trans("TotalHT"); ?></th> <th><?php print $langs->trans("TotalHT"); ?></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php <?php
$tab = array(); $tab = array();
$tab = $_SESSION['poscart']; $tab = $_SESSION['poscart'];
$tab_size = count($tab); $tab_size = count($tab);
for ($i = 0; $i < $tab_size; $i++) for ($i = 0; $i < $tab_size; $i++) {
{
$remise = $tab[$i]['remise']; $remise = $tab[$i]['remise'];
?> ?>
<tr> <tr>
<td><?php echo $tab[$i]['ref']; ?></td> <td><?php echo $tab[$i]['ref']; ?></td>
<td><?php echo $tab[$i]['label']; ?></td> <td><?php echo $tab[$i]['label']; ?></td>
<td><?php echo $tab[$i]['qte']; ?></td> <td><?php echo $tab[$i]['qte']; ?></td>
<td><?php echo $tab[$i]['remise_percent']; ?></td> <td><?php echo $tab[$i]['remise_percent']; ?></td>
<td class="total"><?php echo price(price2num($tab[$i]['total_ht'], 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?></td> <td class="total"><?php echo price(price2num($tab[$i]['total_ht'], 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?></td>
</tr> </tr>
<?php <?php
} }
?> ?>
</tbody> </tbody>
</table> </table>
<table class="totaux"> <table class="totaux">
<tr> <tr>
<th class="nowrap"><?php echo $langs->trans("TotalHT"); ?></th> <th class="nowrap"><?php echo $langs->trans("TotalHT"); ?></th>
<td class="nowrap"><?php echo price(price2num($obj_facturation->amountWithoutTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?></td> <td class="nowrap"><?php echo price(price2num($obj_facturation->amountWithoutTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?></td>
</tr> </tr>
<tr> <tr>
<th class="nowrap"><?php echo $langs->trans("TotalVAT").'</th><td class="nowrap">'.price(price2num($obj_facturation->amountVat(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?></td> <th class="nowrap"><?php echo $langs->trans("TotalVAT").'</th><td class="nowrap">'.price(price2num($obj_facturation->amountVat(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?></td>
</tr> </tr>
<tr> <tr>
<th class="nowrap"><?php echo ''.$langs->trans("TotalTTC").'</th><td class="nowrap">'.price(price2num($obj_facturation->amountWithTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?></td> <th class="nowrap"><?php echo ''.$langs->trans("TotalTTC").'</th><td class="nowrap">'.price(price2num($obj_facturation->amountWithTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?></td>
</tr> </tr>
</table> </table>
<script type="text/javascript"> <script type="text/javascript">
window.print(); window.print();
</script> </script>
<a class="lien" href="#" onclick="javascript: window.close(); return(false);"><?php echo $langs->trans("Close"); ?></a> <a class="lien" href="#" onclick="javascript: window.close(); return(false);"><?php echo $langs->trans("Close"); ?></a>

View File

@ -17,8 +17,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }
@ -47,25 +46,27 @@ if ($obj_facturation->amountVat()) {
<tr><td class="resume_label"><?php echo $langs->trans("TotalTTC"); ?> </td><td><?php echo price(price2num($obj_facturation->amountWithTax(), 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?></td></tr> <tr><td class="resume_label"><?php echo $langs->trans("TotalTTC"); ?> </td><td><?php echo price(price2num($obj_facturation->amountWithTax(), 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?></td></tr>
<tr><td class="resume_label"><?php echo $langs->trans("PaymentMode"); ?> </td><td> <tr><td class="resume_label"><?php echo $langs->trans("PaymentMode"); ?> </td><td>
<?php <?php
switch ($obj_facturation->getSetPaymentMode()) switch ($obj_facturation->getSetPaymentMode()) {
{
case 'ESP': case 'ESP':
echo $langs->trans("Cash"); echo $langs->trans("Cash");
$filtre = 'courant=2'; $filtre = 'courant=2';
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) {
$selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]; $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"];
}
break; break;
case 'CB': case 'CB':
echo $langs->trans("CreditCard"); echo $langs->trans("CreditCard");
$filtre = 'courant=1'; $filtre = 'courant=1';
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) {
$selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]; $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"];
}
break; break;
case 'CHQ': case 'CHQ':
echo $langs->trans("Cheque"); echo $langs->trans("Cheque");
$filtre = 'courant=1'; $filtre = 'courant=1';
if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) {
$selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]; $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"];
}
break; break;
case 'DIF': case 'DIF':
echo $langs->trans("Reported"); echo $langs->trans("Reported");

View File

@ -18,8 +18,7 @@
*/ */
// Protection to avoid direct call of template // Protection to avoid direct call of template
if (empty($langs) || !is_object($langs)) if (empty($langs) || !is_object($langs)) {
{
print "Error, template page can't be called as URL"; print "Error, template page can't be called as URL";
exit; exit;
} }

View File

@ -33,8 +33,7 @@ $hookmanager->initHooks(array('cashdeskTplTicket'));
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $obj_facturation); $reshook = $hookmanager->executeHooks('doActions', $parameters, $obj_facturation);
if (empty($reshook)) if (empty($reshook)) {
{
require 'tpl/ticket.tpl.php'; require 'tpl/ticket.tpl.php';
} }

View File

@ -36,8 +36,7 @@ $obj_facturation = unserialize($_SESSION['serObjFacturation']);
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$bankaccountid = GETPOST('cashdeskbank'); $bankaccountid = GETPOST('cashdeskbank');
switch ($action) switch ($action) {
{
default: default:
$redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=validation'; $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=validation';
break; break;
@ -55,15 +54,18 @@ switch ($action)
// To use a specific numbering module for POS, reset $conf->global->FACTURE_ADDON and other vars here // To use a specific numbering module for POS, reset $conf->global->FACTURE_ADDON and other vars here
// and restore values just after // and restore values just after
$sav_FACTURE_ADDON = ''; $sav_FACTURE_ADDON = '';
if (!empty($conf->global->POS_ADDON)) if (!empty($conf->global->POS_ADDON)) {
{
$sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON; $sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON;
$conf->global->FACTURE_ADDON = $conf->global->POS_ADDON; $conf->global->FACTURE_ADDON = $conf->global->POS_ADDON;
// To force prefix only for POS with terre module // To force prefix only for POS with terre module
if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX; if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) {
$conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX;
}
// To force prefix only for POS with mars module // To force prefix only for POS with mars module
if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX; if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) {
$conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX;
}
// To force rule only for POS with mercure // To force rule only for POS with mercure
//... //...
} }
@ -71,8 +73,7 @@ switch ($action)
$num = $invoice->getNextNumRef($company); $num = $invoice->getNextNumRef($company);
// Restore save values // Restore save values
if (!empty($sav_FACTURE_ADDON)) if (!empty($sav_FACTURE_ADDON)) {
{
$conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON; $conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON;
} }
@ -120,14 +121,12 @@ switch ($action)
$heure = dol_print_date($now, 'hour'); $heure = dol_print_date($now, 'hour');
$note = ''; $note = '';
if (!is_object($obj_facturation)) if (!is_object($obj_facturation)) {
{
dol_print_error('', 'Empty context'); dol_print_error('', 'Empty context');
exit; exit;
} }
switch ($obj_facturation->getSetPaymentMode()) switch ($obj_facturation->getSetPaymentMode()) {
{
case 'DIF': case 'DIF':
$mode_reglement_id = 0; $mode_reglement_id = 0;
//$cond_reglement_id = dol_getIdFromCode($db,'RECEP','cond_reglement','code','rowid') //$cond_reglement_id = dol_getIdFromCode($db,'RECEP','cond_reglement','code','rowid')
@ -151,8 +150,12 @@ switch ($action)
$cond_reglement_id = 0; $cond_reglement_id = 0;
break; break;
} }
if (empty($mode_reglement_id)) $mode_reglement_id = 0; // If mode_reglement_id not found if (empty($mode_reglement_id)) {
if (empty($cond_reglement_id)) $cond_reglement_id = 0; // If cond_reglement_id not found $mode_reglement_id = 0; // If mode_reglement_id not found
}
if (empty($cond_reglement_id)) {
$cond_reglement_id = 0; // If cond_reglement_id not found
}
$note .= $_POST['txtaNotes']; $note .= $_POST['txtaNotes'];
dol_syslog("obj_facturation->getSetPaymentMode()=".$obj_facturation->getSetPaymentMode()." mode_reglement_id=".$mode_reglement_id." cond_reglement_id=".$cond_reglement_id); dol_syslog("obj_facturation->getSetPaymentMode()=".$obj_facturation->getSetPaymentMode()." mode_reglement_id=".$mode_reglement_id." cond_reglement_id=".$cond_reglement_id);
@ -175,8 +178,7 @@ switch ($action)
// Loop on each line into cart // Loop on each line into cart
$tab_liste_size = count($tab_liste); $tab_liste_size = count($tab_liste);
for ($i = 0; $i < $tab_liste_size; $i++) for ($i = 0; $i < $tab_liste_size; $i++) {
{
$tmp = getTaxesFromId($tab_liste[$i]['fk_tva']); $tmp = getTaxesFromId($tab_liste[$i]['fk_tva']);
$vat_rate = $tmp['rate']; $vat_rate = $tmp['rate'];
$vat_npr = $tmp['npr']; $vat_npr = $tmp['npr'];
@ -218,32 +220,32 @@ switch ($action)
//print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit; //print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit;
// Si paiement differe ... // Si paiement differe ...
if ($obj_facturation->getSetPaymentMode() == 'DIF') if ($obj_facturation->getSetPaymentMode() == 'DIF') {
{
$resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe())); $resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe()));
if ($resultcreate > 0) if ($resultcreate > 0) {
{
$warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0);
if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
$warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice
}
$resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0);
if ($warehouseidtodecrease > 0) if ($warehouseidtodecrease > 0) {
{
// Decrease // Decrease
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
$langs->load("agenda"); $langs->load("agenda");
// Loop on each line // Loop on each line
$cpt = count($invoice->lines); $cpt = count($invoice->lines);
for ($i = 0; $i < $cpt; $i++) for ($i = 0; $i < $cpt; $i++) {
{ if ($invoice->lines[$i]->fk_product > 0) {
if ($invoice->lines[$i]->fk_product > 0)
{
$mouvP = new MouvementStock($db); $mouvP = new MouvementStock($db);
$mouvP->origin = &$invoice; $mouvP->origin = &$invoice;
// We decrease stock for product // We decrease stock for product
if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) {
else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
} else {
$result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
}
if ($result < 0) { if ($result < 0) {
$error++; $error++;
} }
@ -258,29 +260,30 @@ switch ($action)
$id = $invoice->id; $id = $invoice->id;
} else { } else {
$resultcreate = $invoice->create($user, 0, 0); $resultcreate = $invoice->create($user, 0, 0);
if ($resultcreate > 0) if ($resultcreate > 0) {
{
$warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0);
if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) {
$warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice
}
$resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0);
if ($warehouseidtodecrease > 0) if ($warehouseidtodecrease > 0) {
{
// Decrease // Decrease
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
$langs->load("agenda"); $langs->load("agenda");
// Loop on each line // Loop on each line
$cpt = count($invoice->lines); $cpt = count($invoice->lines);
for ($i = 0; $i < $cpt; $i++) for ($i = 0; $i < $cpt; $i++) {
{ if ($invoice->lines[$i]->fk_product > 0) {
if ($invoice->lines[$i]->fk_product > 0)
{
$mouvP = new MouvementStock($db); $mouvP = new MouvementStock($db);
$mouvP->origin = &$invoice; $mouvP->origin = &$invoice;
// We decrease stock for product // We decrease stock for product
if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) {
else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
} else {
$result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref));
}
if ($result < 0) { if ($result < 0) {
setEventMessages($mouvP->error, $mouvP->errors, 'errors'); setEventMessages($mouvP->error, $mouvP->errors, 'errors');
$error++; $error++;
@ -301,26 +304,21 @@ switch ($action)
$payment->num_payment = ''; $payment->num_payment = '';
$paiement_id = $payment->create($user); $paiement_id = $payment->create($user);
if ($paiement_id > 0) if ($paiement_id > 0) {
{ if (!$error) {
if (!$error)
{
$result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', ''); $result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', '');
if (!$result > 0) if (!$result > 0) {
{
$errmsg = $paiement->error; $errmsg = $paiement->error;
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
if ($invoice->total_ttc == $obj_facturation->amountWithTax() if ($invoice->total_ttc == $obj_facturation->amountWithTax()
&& $obj_facturation->getSetPaymentMode() != 'DIFF') && $obj_facturation->getSetPaymentMode() != 'DIFF') {
{
// We set status to paid // We set status to paid
$result = $invoice->setPaid($user); $result = $invoice->setPaid($user);
//print 'set paid';exit; //print 'set paid';exit;
} }
} }
} else { } else {
@ -334,8 +332,7 @@ switch ($action)
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$redirection = 'affIndex.php?menutpl=validation_ok&facid='.$id; // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr $redirection = 'affIndex.php?menutpl=validation_ok&facid='.$id; // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr
} else { } else {

View File

@ -40,13 +40,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'contrat'; //Must be the $element of the class that manage extrafield $elementtype = 'contrat'; //Must be the $element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -78,8 +82,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div name="topofform" id="newattrib"></div>'; print '<br><div name="topofform" id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -105,8 +107,7 @@ if ($action == 'create')
/* Edition of an optional field */ /* Edition of an optional field */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print '<div name="topofform"></div><br>'; print '<div name="topofform"></div><br>';
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -40,13 +40,17 @@ $form = new Form($db);
// List of supported format // List of supported format
$tmptype2label = ExtraFields::$type2label; $tmptype2label = ExtraFields::$type2label;
$type2label = array(''); $type2label = array('');
foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); foreach ($tmptype2label as $key => $val) {
$type2label[$key] = $langs->transnoentitiesnoconv($val);
}
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$attrname = GETPOST('attrname', 'alpha'); $attrname = GETPOST('attrname', 'alpha');
$elementtype = 'contratdet'; //Must be the $element of the class that manage extrafield $elementtype = 'contratdet'; //Must be the $element of the class that manage extrafield
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
/* /*
@ -78,8 +82,7 @@ print dol_get_fiche_end();
// Buttons // Buttons
if ($action != 'create' && $action != 'edit') if ($action != 'create' && $action != 'edit') {
{
print '<div class="tabsAction">'; print '<div class="tabsAction">';
print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
print "</div>"; print "</div>";
@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit')
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'create') if ($action == 'create') {
{
print '<br><div id="newattrib"></div>'; print '<br><div id="newattrib"></div>';
print load_fiche_titre($langs->trans('NewAttribute')); print load_fiche_titre($langs->trans('NewAttribute'));
@ -105,8 +107,7 @@ if ($action == 'create')
/* Edition d'un champ optionnel */ /* Edition d'un champ optionnel */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
if ($action == 'edit' && !empty($attrname)) if ($action == 'edit' && !empty($attrname)) {
{
print "<br>"; print "<br>";
print load_fiche_titre($langs->trans("FieldEdition", $attrname)); print load_fiche_titre($langs->trans("FieldEdition", $attrname));

View File

@ -35,10 +35,11 @@ if (!empty($conf->projet->enabled)) {
// Load translation files required by the page // Load translation files required by the page
$langs->loadLangs(array("companies", "contracts")); $langs->loadLangs(array("companies", "contracts"));
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));
} }
@ -50,19 +51,27 @@ $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'contrat', $id, ''); $result = restrictedArea($user, 'contrat', $id, '');
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha'); $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,DESC'; $sortfield = 'a.datep,a.id';
}
if (!$sortorder) {
$sortorder = 'DESC,DESC';
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('agendacontract', 'globalcard')); $hookmanager->initHooks(array('agendacontract', 'globalcard'));
@ -74,20 +83,19 @@ $hookmanager->initHooks(array('agendacontract', 'globalcard'));
$parameters = array('id'=>$id); $parameters = array('id'=>$id);
$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 = '';
} }
@ -102,19 +110,18 @@ if (empty($reshook))
$form = new Form($db); $form = new Form($db);
$formfile = new FormFile($db); $formfile = new FormFile($db);
if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); if (!empty($conf->projet->enabled)) {
$formproject = new FormProjets($db);
}
if ($id > 0) if ($id > 0) {
{
// Load object modContract // Load object modContract
$module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
{
$module = substr($module, 0, dol_strlen($module) - 4); $module = substr($module, 0, dol_strlen($module) - 4);
} }
$result = dol_include_once('/core/modules/contract/'.$module.'.php'); $result = dol_include_once('/core/modules/contract/'.$module.'.php');
if ($result > 0) if ($result > 0) {
{
$modCodeContract = new $module(); $modCodeContract = new $module();
} }
@ -126,10 +133,14 @@ if ($id > 0)
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$title = $langs->trans("Agenda"); $title = $langs->trans("Agenda");
if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contractrefonly/', $conf->global->MAIN_HTML_TITLE) && $object->ref) $title = $object->ref." - ".$title; if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contractrefonly/', $conf->global->MAIN_HTML_TITLE) && $object->ref) {
$title = $object->ref." - ".$title;
}
llxHeader('', $title); llxHeader('', $title);
if (!empty($conf->notification->enabled)) $langs->load("mails"); if (!empty($conf->notification->enabled)) {
$langs->load("mails");
}
$head = contract_prepare_head($object); $head = contract_prepare_head($object);
print dol_get_fiche_head($head, 'agenda', $langs->trans("Contract"), -1, 'contract'); print dol_get_fiche_head($head, 'agenda', $langs->trans("Contract"), -1, 'contract');
@ -156,14 +167,14 @@ if ($id > 0)
$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $permtoedit, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $permtoedit, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)'; if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
$morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
}
// 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 ($user->rights->contrat->creer) if ($user->rights->contrat->creer) {
{
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>';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';
@ -231,21 +242,22 @@ if ($id > 0)
$newcardbutton = ''; $newcardbutton = '';
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))
{
$newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out); $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
} }
} }
if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
{
print '<br>'; print '<br>';
$param = '&id='.$id; $param = '&id='.$id;
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 ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.$limit;
}
print load_fiche_titre($langs->trans("ActionsOnContract"), $newcardbutton, ''); print load_fiche_titre($langs->trans("ActionsOnContract"), $newcardbutton, '');
//print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $newcardbutton, '', 0, 1, 1); //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $newcardbutton, '', 0, 1, 1);

File diff suppressed because it is too large Load Diff

View File

@ -113,28 +113,37 @@ class Contracts 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 (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid"; $sql = "SELECT t.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
$sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
}
$sql .= " FROM ".MAIN_DB_PREFIX."contrat as t"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as t";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
}
$sql .= ' WHERE t.entity IN ('.getEntity('contrat').')'; $sql .= ' WHERE t.entity IN ('.getEntity('contrat').')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; $sql .= " AND t.fk_soc = sc.fk_soc";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale }
if ($socids) {
$sql .= " AND t.fk_soc IN (".$socids.")";
}
if ($search_sale > 0) {
$sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
}
// Insert sale filter // Insert sale filter
if ($search_sale > 0) if ($search_sale > 0) {
{
$sql .= " AND sc.fk_user = ".$search_sale; $sql .= " AND sc.fk_user = ".$search_sale;
} }
// Add sql filters // Add sql filters
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);
} }
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@ -143,8 +152,7 @@ class Contracts extends DolibarrApi
$sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->order($sortfield, $sortorder);
if ($limit) { if ($limit) {
if ($page < 0) if ($page < 0) {
{
$page = 0; $page = 0;
} }
$offset = $limit * $page; $offset = $limit * $page;
@ -155,13 +163,11 @@ class Contracts extends DolibarrApi
dol_syslog("API Rest request"); dol_syslog("API Rest request");
$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);
$min = min($num, ($limit <= 0 ? $num : $limit)); $min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0; $i = 0;
while ($i < $min) while ($i < $min) {
{
$obj = $this->db->fetch_object($result); $obj = $this->db->fetch_object($result);
$contrat_static = new Contrat($this->db); $contrat_static = new Contrat($this->db);
if ($contrat_static->fetch($obj->rowid)) { if ($contrat_static->fetch($obj->rowid)) {
@ -196,12 +202,12 @@ class Contracts extends DolibarrApi
$this->contract->$field = $value; $this->contract->$field = $value;
} }
/*if (isset($request_data["lines"])) { /*if (isset($request_data["lines"])) {
$lines = array(); $lines = array();
foreach ($request_data["lines"] as $line) { foreach ($request_data["lines"] as $line) {
array_push($lines, (object) $line); array_push($lines, (object) $line);
} }
$this->contract->lines = $lines; $this->contract->lines = $lines;
}*/ }*/
if ($this->contract->create(DolibarrApiAccess::$user) < 0) { if ($this->contract->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors)); throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors));
} }
@ -491,7 +497,9 @@ class Contracts extends DolibarrApi
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
foreach ($request_data as $field => $value) { foreach ($request_data as $field => $value) {
if ($field == 'id') continue; if ($field == 'id') {
continue;
}
$this->contract->$field = $value; $this->contract->$field = $value;
} }
@ -667,8 +675,9 @@ class Contracts extends DolibarrApi
{ {
$contrat = array(); $contrat = array();
foreach (Contracts::$FIELDS as $field) { foreach (Contracts::$FIELDS as $field) {
if (!isset($data[$field])) if (!isset($data[$field])) {
throw new RestException(400, "$field field missing"); throw new RestException(400, "$field field missing");
}
$contrat[$field] = $data[$field]; $contrat[$field] = $data[$field];
} }
return $contrat; return $contrat;

File diff suppressed because it is too large Load Diff

View File

@ -43,7 +43,9 @@ $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'contrat', $id); $result = restrictedArea($user, 'contrat', $id);
$object = new Contrat($db); $object = new Contrat($db);
@ -56,19 +58,16 @@ $hookmanager->initHooks(array('contractcard', 'globalcard'));
* Actions * Actions
*/ */
if ($action == 'addcontact' && $user->rights->contrat->creer) if ($action == 'addcontact' && $user->rights->contrat->creer) {
{
$result = $object->fetch($id); $result = $object->fetch($id);
if ($result > 0 && $id > 0) if ($result > 0 && $id > 0) {
{
$contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
$typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
$result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
} }
if ($result >= 0) if ($result >= 0) {
{
header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
exit; exit;
} else { } else {
@ -84,10 +83,8 @@ if ($action == 'addcontact' && $user->rights->contrat->creer)
} }
// bascule du statut d'un contact // bascule du statut d'un contact
if ($action == 'swapstatut' && $user->rights->contrat->creer) if ($action == 'swapstatut' && $user->rights->contrat->creer) {
{ if ($object->fetch($id)) {
if ($object->fetch($id))
{
$result = $object->swapContactStatus(GETPOST('ligne')); $result = $object->swapContactStatus(GETPOST('ligne'));
} else { } else {
dol_print_error($db, $object->error); dol_print_error($db, $object->error);
@ -95,13 +92,11 @@ if ($action == 'swapstatut' && $user->rights->contrat->creer)
} }
// Delete contact // Delete contact
if ($action == 'deletecontact' && $user->rights->contrat->creer) if ($action == 'deletecontact' && $user->rights->contrat->creer) {
{
$object->fetch($id); $object->fetch($id);
$result = $object->delete_contact($_GET["lineid"]); $result = $object->delete_contact($_GET["lineid"]);
if ($result >= 0) if ($result >= 0) {
{
header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
exit; exit;
} }
@ -125,10 +120,8 @@ $userstatic = new User($db);
/* */ /* */
/* *************************************************************************** */ /* *************************************************************************** */
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{ if ($object->fetch($id, $ref) > 0) {
if ($object->fetch($id, $ref) > 0)
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$head = contract_prepare_head($object); $head = contract_prepare_head($object);
@ -146,9 +139,9 @@ if ($id > 0 || !empty($ref))
//if (! empty($modCodeContract->code_auto)) { //if (! empty($modCodeContract->code_auto)) {
$morehtmlref .= $object->ref; $morehtmlref .= $object->ref;
/*} else { /*} else {
$morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
$morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
}*/ }*/
$morehtmlref .= '<div class="refidno">'; $morehtmlref .= '<div class="refidno">';
// Ref customer // Ref customer
@ -213,8 +206,11 @@ if ($id > 0 || !empty($ref))
} }
$absolute_discount = $object->thirdparty->getAvailableDiscounts(); $absolute_discount = $object->thirdparty->getAvailableDiscounts();
print '. '; print '. ';
if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); if ($absolute_discount) {
else print $langs->trans("CompanyHasNoAbsoluteDiscount"); print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
} else {
print $langs->trans("CompanyHasNoAbsoluteDiscount");
}
print '.'; print '.';
print '</td></tr>'; print '</td></tr>';

View File

@ -46,8 +46,7 @@ $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
// Security check // Security check
if ($user->socid > 0) if ($user->socid > 0) {
{
unset($_GET["action"]); unset($_GET["action"]);
$action = ''; $action = '';
$socid = $user->socid; $socid = $user->socid;
@ -59,18 +58,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 = "ASC"; if (!$sortorder) {
if (!$sortfield) $sortfield = "name"; $sortorder = "ASC";
}
if (!$sortfield) {
$sortfield = "name";
}
$object = new Contrat($db); $object = new Contrat($db);
$object->fetch($id, $ref); $object->fetch($id, $ref);
if ($object->id > 0) if ($object->id > 0) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
} }
@ -97,8 +101,7 @@ $form = new Form($db);
llxHeader('', $langs->trans("Contract"), ""); llxHeader('', $langs->trans("Contract"), "");
if ($object->id) if ($object->id) {
{
$head = contract_prepare_head($object); $head = contract_prepare_head($object);
print dol_get_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract'); print dol_get_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract');
@ -107,8 +110,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'];
} }
@ -136,17 +138,18 @@ if ($object->id)
$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)'; if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
$morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
}
// 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 ($user->rights->contrat->creer) if ($user->rights->contrat->creer) {
{ 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> : ';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';
}
if ($action == 'classify') { if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';

View File

@ -46,7 +46,9 @@ $statut = GETPOST('statut') ?GETPOST('statut') : 1;
// Security check // Security check
$socid = 0; $socid = 0;
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'contrat', $id); $result = restrictedArea($user, 'contrat', $id);
$staticcompany = new Societe($db); $staticcompany = new Societe($db);
@ -78,11 +80,9 @@ print load_fiche_titre($langs->trans("ContractsArea"), '', 'contract');
print '<div class="fichecenter"><div class="fichethirdleft">'; print '<div class="fichecenter"><div class="fichethirdleft">';
if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo
{
// Search contract // Search contract
if (!empty($conf->contrat->enabled)) if (!empty($conf->contrat->enabled)) {
{
print '<form method="post" action="'.DOL_URL_ROOT.'/contrat/list.php">'; print '<form method="post" action="'.DOL_URL_ROOT.'/contrat/list.php">';
print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="token" value="'.newToken().'">';
@ -112,26 +112,28 @@ $vals = array();
$sql = "SELECT count(cd.rowid) as nb, cd.statut as status"; $sql = "SELECT count(cd.rowid) as nb, cd.statut as status";
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid"; $sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid";
$sql .= " AND (cd.statut != 4 OR (cd.statut = 4 AND (cd.date_fin_validite is null or cd.date_fin_validite >= '".$db->idate($now)."')))"; $sql .= " AND (cd.statut != 4 OR (cd.statut = 4 AND (cd.date_fin_validite is null or cd.date_fin_validite >= '".$db->idate($now)."')))";
$sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")";
if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; if ($user->socid) {
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; $sql .= ' AND c.fk_soc = '.$user->socid;
}
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
$sql .= " GROUP BY cd.statut"; $sql .= " GROUP BY cd.statut";
$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);
if ($obj) if ($obj) {
{
$nb[$obj->status] = $obj->nb; $nb[$obj->status] = $obj->nb;
if ($obj->status != 5) if ($obj->status != 5) {
{
$vals[$obj->status] = $obj->nb; $vals[$obj->status] = $obj->nb;
$totalinprocess += $obj->nb; $totalinprocess += $obj->nb;
} }
@ -147,28 +149,30 @@ if ($resql)
$sql = "SELECT count(cd.rowid) as nb, cd.statut as status"; $sql = "SELECT count(cd.rowid) as nb, cd.statut as status";
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid"; $sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid";
$sql .= " AND (cd.statut = 4 AND cd.date_fin_validite < '".$db->idate($now)."')"; $sql .= " AND (cd.statut = 4 AND cd.date_fin_validite < '".$db->idate($now)."')";
$sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")";
if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; if ($user->socid) {
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; $sql .= ' AND c.fk_soc = '.$user->socid;
}
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
$sql .= " GROUP BY cd.statut"; $sql .= " GROUP BY cd.statut";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
// 0 inactive, 4 active, 5 closed // 0 inactive, 4 active, 5 closed
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) if ($obj) {
{
$nb[$obj->status.true] = $obj->nb; $nb[$obj->status.true] = $obj->nb;
if ($obj->status != 5) if ($obj->status != 5) {
{
$vals[$obj->status.true] = $obj->nb; $vals[$obj->status.true] = $obj->nb;
$totalinprocess += $obj->nb; $totalinprocess += $obj->nb;
} }
@ -189,26 +193,34 @@ print '<div class="div-table-responsive-no-min">';
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("Services").'</th></tr>'."\n"; print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("Services").'</th></tr>'."\n";
$listofstatus = array(0, 4, 4, 5); $bool = false; $listofstatus = array(0, 4, 4, 5); $bool = false;
foreach ($listofstatus as $status) foreach ($listofstatus as $status) {
{
$dataseries[] = array($staticcontratligne->LibStatut($status, 1, ($bool ? 1 : 0)), (isset($nb[$status.$bool]) ? (int) $nb[$status.$bool] : 0)); $dataseries[] = array($staticcontratligne->LibStatut($status, 1, ($bool ? 1 : 0)), (isset($nb[$status.$bool]) ? (int) $nb[$status.$bool] : 0));
if ($status == ContratLigne::STATUS_INITIAL) $colorseries[$status.$bool] = '-'.$badgeStatus0; if ($status == ContratLigne::STATUS_INITIAL) {
if ($status == ContratLigne::STATUS_OPEN && !$bool) $colorseries[$status.$bool] = $badgeStatus4; $colorseries[$status.$bool] = '-'.$badgeStatus0;
if ($status == ContratLigne::STATUS_OPEN && $bool) $colorseries[$status.$bool] = $badgeStatus1; }
if ($status == ContratLigne::STATUS_CLOSED) $colorseries[$status.$bool] = $badgeStatus6; if ($status == ContratLigne::STATUS_OPEN && !$bool) {
$colorseries[$status.$bool] = $badgeStatus4;
}
if ($status == ContratLigne::STATUS_OPEN && $bool) {
$colorseries[$status.$bool] = $badgeStatus1;
}
if ($status == ContratLigne::STATUS_CLOSED) {
$colorseries[$status.$bool] = $badgeStatus6;
}
if (empty($conf->use_javascript_ajax)) if (empty($conf->use_javascript_ajax)) {
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).'</td>'; print '<td>'.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).'</td>';
print '<td class="right"><a href="services_list.php?mode='.$status.($bool ? '&filter=expired' : '').'">'.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'</a></td>'; print '<td class="right"><a href="services_list.php?mode='.$status.($bool ? '&filter=expired' : '').'">'.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'</a></td>';
print "</tr>\n"; print "</tr>\n";
} }
if ($status == 4 && !$bool) $bool = true; if ($status == 4 && !$bool) {
else $bool = false; $bool = true;
} else {
$bool = false;
}
} }
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print '<tr class="impair"><td class="center" colspan="2">'; print '<tr class="impair"><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';
@ -225,15 +237,16 @@ if (!empty($conf->use_javascript_ajax))
print '</td></tr>'; print '</td></tr>';
} }
$listofstatus = array(0, 4, 4, 5); $bool = false; $listofstatus = array(0, 4, 4, 5); $bool = false;
foreach ($listofstatus as $status) foreach ($listofstatus as $status) {
{ if (empty($conf->use_javascript_ajax)) {
if (empty($conf->use_javascript_ajax))
{
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).'</td>'; print '<td>'.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).'</td>';
print '<td class="right"><a href="services_list.php?mode='.$status.($bool ? '&filter=expired' : '').'">'.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'</a></td>'; print '<td class="right"><a href="services_list.php?mode='.$status.($bool ? '&filter=expired' : '').'">'.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'</a></td>';
if ($status == 4 && !$bool) $bool = true; if ($status == 4 && !$bool) {
else $bool = false; $bool = true;
} else {
$bool = false;
}
print "</tr>\n"; print "</tr>\n";
} }
} }
@ -245,36 +258,38 @@ print "</table></div><br>";
// Draft contracts // Draft contracts
if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) {
{
$sql = "SELECT c.rowid, c.ref,"; $sql = "SELECT c.rowid, c.ref,";
$sql .= " s.nom as name, s.rowid as socid"; $sql .= " s.nom as name, s.rowid as socid";
$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."societe as s";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= " WHERE s.rowid = c.fk_soc"; $sql .= " WHERE s.rowid = c.fk_soc";
$sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")";
$sql .= " AND c.statut = 0"; $sql .= " AND c.statut = 0";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($socid) $sql .= " AND c.fk_soc = ".$socid; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND c.fk_soc = ".$socid;
}
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($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="3">'.$langs->trans("DraftContracts").($num ? '<span class="badge marginleftonlyshort">'.$num.'</span>' : '').'</th></tr>'; print '<th colspan="3">'.$langs->trans("DraftContracts").($num ? '<span class="badge marginleftonlyshort">'.$num.'</span>' : '').'</th></tr>';
if ($num) if ($num) {
{
$companystatic = new Societe($db); $companystatic = new Societe($db);
$i = 0; $i = 0;
//$tot_ttc = 0; //$tot_ttc = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$staticcontrat->ref = $obj->ref; $staticcontrat->ref = $obj->ref;
@ -319,22 +334,27 @@ $sql .= ' sum('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AN
$sql .= ' sum('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed,'; $sql .= ' sum('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed,';
$sql .= " c.rowid as cid, c.ref, c.datec, c.tms, c.statut, s.nom as name, s.rowid as socid"; $sql .= " c.rowid as cid, c.ref, c.datec, c.tms, c.statut, s.nom as name, s.rowid as socid";
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s,"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
}
$sql .= " ".MAIN_DB_PREFIX."contrat as c"; $sql .= " ".MAIN_DB_PREFIX."contrat as c";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat";
$sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " WHERE c.fk_soc = s.rowid";
$sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")";
$sql .= " AND c.statut > 0"; $sql .= " AND c.statut > 0";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
$sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.statut, s.nom, s.rowid"; $sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.statut, s.nom, s.rowid";
$sql .= " ORDER BY c.tms DESC"; $sql .= " ORDER BY c.tms DESC";
$sql .= " LIMIT ".$max; $sql .= " LIMIT ".$max;
dol_syslog("contrat/index.php", LOG_DEBUG); dol_syslog("contrat/index.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);
$i = 0; $i = 0;
@ -347,8 +367,7 @@ if ($result)
print '<th class="center" width="80" colspan="4">'.$langs->trans("Services").'</th>'; print '<th class="center" width="80" colspan="4">'.$langs->trans("Services").'</th>';
print "</tr>\n"; print "</tr>\n";
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($result); $obj = $db->fetch_object($result);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
@ -356,7 +375,9 @@ if ($result)
$staticcontrat->ref = ($obj->ref ? $obj->ref : $obj->cid); $staticcontrat->ref = ($obj->ref ? $obj->ref : $obj->cid);
$staticcontrat->id = $obj->cid; $staticcontrat->id = $obj->cid;
print $staticcontrat->getNomUrl(1, 16); print $staticcontrat->getNomUrl(1, 16);
if ($obj->nb_late) print img_warning($langs->trans("Late")); if ($obj->nb_late) {
print img_warning($langs->trans("Late"));
}
print '</td>'; print '</td>';
print '<td>'; print '<td>';
$staticcompany->id = $obj->socid; $staticcompany->id = $obj->socid;
@ -388,19 +409,24 @@ $sql .= " s.nom as name,";
$sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
$sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c";
$sql .= ", ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."societe as s";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd";
$sql .= ") LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= ") LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
$sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")";
$sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND cd.fk_contrat = c.rowid";
$sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.fk_soc = s.rowid";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
$sql .= " ORDER BY cd.tms DESC"; $sql .= " ORDER BY cd.tms DESC";
$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;
@ -410,8 +436,7 @@ if ($resql)
print '<tr class="liste_titre"><th colspan="4">'.$langs->trans("LastModifiedServices", $max).'</th>'; print '<tr class="liste_titre"><th colspan="4">'.$langs->trans("LastModifiedServices", $max).'</th>';
print "</tr>\n"; print "</tr>\n";
while ($i < min($num, $max)) while ($i < min($num, $max)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
@ -422,8 +447,7 @@ if ($resql)
//if (1 == 1) print img_warning($langs->trans("Late")); //if (1 == 1) print img_warning($langs->trans("Late"));
print '</td>'; print '</td>';
print '<td>'; print '<td>';
if ($obj->fk_product > 0) if ($obj->fk_product > 0) {
{
$productstatic->id = $obj->fk_product; $productstatic->id = $obj->fk_product;
$productstatic->type = $obj->ptype; $productstatic->type = $obj->ptype;
$productstatic->ref = $obj->pref; $productstatic->ref = $obj->pref;
@ -431,8 +455,11 @@ if ($resql)
print $productstatic->getNomUrl(1, '', 20); print $productstatic->getNomUrl(1, '', 20);
} else { } else {
print '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$obj->fk_contrat.'">'.img_object($langs->trans("ShowService"), "service"); print '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$obj->fk_contrat.'">'.img_object($langs->trans("ShowService"), "service");
if ($obj->label) print ' '.dol_trunc($obj->label, 20).'</a>'; if ($obj->label) {
else print '</a> '.dol_trunc($obj->note, 20); print ' '.dol_trunc($obj->label, 20).'</a>';
} else {
print '</a> '.dol_trunc($obj->note, 20);
}
} }
print '</td>'; print '</td>';
print '<td>'; print '<td>';
@ -462,7 +489,9 @@ $sql .= " s.nom as name,";
$sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
$sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c";
$sql .= ", ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."societe as s";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd";
$sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
$sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")";
@ -470,13 +499,16 @@ $sql .= " AND c.statut = 1";
$sql .= " AND cd.statut = 0"; $sql .= " AND cd.statut = 0";
$sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND cd.fk_contrat = c.rowid";
$sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.fk_soc = s.rowid";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
$sql .= " ORDER BY cd.tms DESC"; $sql .= " ORDER BY cd.tms DESC";
$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;
@ -486,8 +518,7 @@ if ($resql)
print '<tr class="liste_titre"><th colspan="4">'.$langs->trans("NotActivatedServices").' <a href="'.DOL_URL_ROOT.'/contrat/services_list.php?mode=0"><span class="badge">'.$num.'</span></a></th>'; print '<tr class="liste_titre"><th colspan="4">'.$langs->trans("NotActivatedServices").' <a href="'.DOL_URL_ROOT.'/contrat/services_list.php?mode=0"><span class="badge">'.$num.'</span></a></th>';
print "</tr>\n"; print "</tr>\n";
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
@ -498,8 +529,7 @@ if ($resql)
print $staticcontrat->getNomUrl(1, 16); print $staticcontrat->getNomUrl(1, 16);
print '</td>'; print '</td>';
print '<td class="nowrap">'; print '<td class="nowrap">';
if ($obj->fk_product > 0) if ($obj->fk_product > 0) {
{
$productstatic->id = $obj->fk_product; $productstatic->id = $obj->fk_product;
$productstatic->type = $obj->ptype; $productstatic->type = $obj->ptype;
$productstatic->ref = $obj->pref; $productstatic->ref = $obj->pref;
@ -507,8 +537,11 @@ if ($resql)
print $productstatic->getNomUrl(1, '', 20); print $productstatic->getNomUrl(1, '', 20);
} else { } else {
print '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$obj->fk_contrat.'">'.img_object($langs->trans("ShowService"), "service"); print '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$obj->fk_contrat.'">'.img_object($langs->trans("ShowService"), "service");
if ($obj->label) print ' '.dol_trunc($obj->label, 20).'</a>'; if ($obj->label) {
else print '</a> '.dol_trunc($obj->note, 20); print ' '.dol_trunc($obj->label, 20).'</a>';
} else {
print '</a> '.dol_trunc($obj->note, 20);
}
} }
print '</td>'; print '</td>';
print '<td>'; print '<td>';
@ -537,7 +570,9 @@ $sql .= " s.nom as name,";
$sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
$sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c";
$sql .= ", ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."societe as s";
if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd";
$sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
$sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")";
@ -546,13 +581,16 @@ $sql .= " AND cd.statut = 4";
$sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'";
$sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND cd.fk_contrat = c.rowid";
$sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.fk_soc = s.rowid";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($socid) $sql .= " AND s.rowid = ".$socid; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
if ($socid) {
$sql .= " AND s.rowid = ".$socid;
}
$sql .= " ORDER BY cd.tms DESC"; $sql .= " ORDER BY cd.tms DESC";
$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;
@ -562,8 +600,7 @@ if ($resql)
print '<tr class="liste_titre"><th colspan="4">'.$langs->trans("ListOfExpiredServices").' <a href="'.DOL_URL_ROOT.'/contrat/services_list.php?mode=4&amp;filter=expired"><span class="badge">'.$num.'</span></a></th>'; print '<tr class="liste_titre"><th colspan="4">'.$langs->trans("ListOfExpiredServices").' <a href="'.DOL_URL_ROOT.'/contrat/services_list.php?mode=4&amp;filter=expired"><span class="badge">'.$num.'</span></a></th>';
print "</tr>\n"; print "</tr>\n";
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
@ -574,8 +611,7 @@ if ($resql)
print $staticcontrat->getNomUrl(1, 16); print $staticcontrat->getNomUrl(1, 16);
print '</td>'; print '</td>';
print '<td class="nowrap">'; print '<td class="nowrap">';
if ($obj->fk_product > 0) if ($obj->fk_product > 0) {
{
$productstatic->id = $obj->fk_product; $productstatic->id = $obj->fk_product;
$productstatic->type = $obj->ptype; $productstatic->type = $obj->ptype;
$productstatic->ref = $obj->pref; $productstatic->ref = $obj->pref;
@ -583,8 +619,11 @@ if ($resql)
print $productstatic->getNomUrl(1, '', 20); print $productstatic->getNomUrl(1, '', 20);
} else { } else {
print '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$obj->fk_contrat.'">'.img_object($langs->trans("ShowService"), "service"); print '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$obj->fk_contrat.'">'.img_object($langs->trans("ShowService"), "service");
if ($obj->label) print ' '.dol_trunc($obj->label, 20).'</a>'; if ($obj->label) {
else print '</a> '.dol_trunc($obj->note, 20); print ' '.dol_trunc($obj->label, 20).'</a>';
} else {
print '</a> '.dol_trunc($obj->note, 20);
}
} }
print '</td>'; print '</td>';
print '<td>'; print '<td>';

View File

@ -76,16 +76,24 @@ $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 = 'c.ref'; if (!$sortfield) {
if (!$sortorder) $sortorder = 'DESC'; $sortfield = 'c.ref';
}
if (!$sortorder) {
$sortorder = 'DESC';
}
// Security check // Security check
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'contrat', $id); $result = restrictedArea($user, 'contrat', $id);
$diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id; $diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id;
@ -93,7 +101,9 @@ $diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user-
$staticcontrat = new Contrat($db); $staticcontrat = new Contrat($db);
$staticcontratligne = new ContratLigne($db); $staticcontratligne = new ContratLigne($db);
if ($search_status == '') $search_status = 1; if ($search_status == '') {
$search_status = 1;
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$object = new Contrat($db); $object = new Contrat($db);
@ -112,7 +122,9 @@ $fieldstosearchall = array(
's.nom'=>"ThirdParty", 's.nom'=>"ThirdParty",
'c.note_public'=>'NotePublic', 'c.note_public'=>'NotePublic',
); );
if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate"; if (empty($user->socid)) {
$fieldstosearchall["c.note_private"] = "NotePrivate";
}
$arrayfields = array( $arrayfields = array(
'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1, 'position'=>10), 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1, 'position'=>10),
@ -142,18 +154,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
* Action * Action
*/ */
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('socid'=>$socid); $parameters = array('socid'=>$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');
}
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 test are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
{
$day = ''; $day = '';
$month = ''; $month = '';
$year = ''; $year = '';
@ -180,8 +197,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
$search_array_options = array(); $search_array_options = array();
} }
if (empty($reshook)) if (empty($reshook)) {
{
$objectclass = 'Contrat'; $objectclass = 'Contrat';
$objectlabel = 'Contracts'; $objectlabel = 'Contracts';
$permissiontoread = $user->rights->contrat->lire; $permissiontoread = $user->rights->contrat->lire;
@ -216,7 +232,9 @@ $sql .= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AN
$sql .= ' SUM('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed'; $sql .= ' SUM('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed';
// 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();
@ -226,34 +244,60 @@ $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) {
$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
}
$sql .= ", ".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."contrat as c";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat";
if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; if ($search_product_category > 0) {
if ($search_user > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
{ }
if ($search_user > 0) {
$sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec";
$sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc";
} }
$sql .= " WHERE c.fk_soc = s.rowid "; $sql .= " WHERE c.fk_soc = s.rowid ";
$sql .= ' AND c.entity IN ('.getEntity('contract').')'; $sql .= ' AND c.entity IN ('.getEntity('contract').')';
if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) {
if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')';
if ($socid) $sql .= " AND s.rowid = ".$db->escape($socid); }
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($search_product_category > 0) {
$sql .= " AND cp.fk_categorie = ".$search_product_category;
}
if ($socid) {
$sql .= " AND s.rowid = ".$db->escape($socid);
}
if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
}
$sql .= dolSqlDateFilter('c.date_contrat', $day, $month, $year); $sql .= dolSqlDateFilter('c.date_contrat', $day, $month, $year);
if ($search_name) $sql .= natural_search('s.nom', $search_name); if ($search_name) {
if ($search_email) $sql .= natural_search('s.email', $search_email); $sql .= natural_search('s.nom', $search_name);
if ($search_contract) $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); }
if (!empty($search_ref_customer)) $sql .= natural_search(array('c.ref_customer'), $search_ref_customer); if ($search_email) {
if (!empty($search_ref_supplier)) $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); $sql .= natural_search('s.email', $search_email);
if ($search_sale > 0) }
{ if ($search_contract) {
$sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract);
}
if (!empty($search_ref_customer)) {
$sql .= natural_search(array('c.ref_customer'), $search_ref_customer);
}
if (!empty($search_ref_supplier)) {
$sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier);
}
if ($search_sale > 0) {
$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale;
} }
if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); if ($sall) {
if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; $sql .= natural_search(array_keys($fieldstosearchall), $sall);
}
if ($search_user > 0) {
$sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user;
}
// Add where from extra fields // 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
@ -266,34 +310,36 @@ $sql .= " typent.code,";
$sql .= " state.code_departement, state.nom"; $sql .= " state.code_departement, state.nom";
// 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 : ''); foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : '');
}
} }
// Add where from hooks // Add where from hooks
$parameters = array(); $parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
if ($search_dfyear > 0 && $search_op2df) if ($search_dfyear > 0 && $search_op2df) {
{ if ($search_op2df == '<=') {
if ($search_op2df == '<=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'"; $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'";
elseif ($search_op2df == '>=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; } elseif ($search_op2df == '>=') {
else $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'";
} else {
$sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'";
}
} }
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
$totalnboflines = 0; $totalnboflines = 0;
$result = $db->query($sql); $result = $db->query($sql);
if ($result) if ($result) {
{
$totalnboflines = $db->num_rows($result); $totalnboflines = $db->num_rows($result);
} }
$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;
} }
@ -302,8 +348,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
$sql .= $db->plimit($limit + 1, $offset); $sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -311,8 +356,7 @@ if (!$resql)
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
// 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) && $sall && !$page) if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall && !$page) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$id = $obj->rowid; $id = $obj->rowid;
header("Location: ".DOL_URL_ROOT.'/contrat/card.php?id='.$id); header("Location: ".DOL_URL_ROOT.'/contrat/card.php?id='.$id);
@ -329,31 +373,66 @@ $i = 0;
$arrayofselected = is_array($toselect) ? $toselect : array(); $arrayofselected = is_array($toselect) ? $toselect : array();
if ($socid > 0) if ($socid > 0) {
{
$soc = new Societe($db); $soc = new Societe($db);
$soc->fetch($socid); $soc->fetch($socid);
if (empty($search_name)) $search_name = $soc->name; if (empty($search_name)) {
$search_name = $soc->name;
}
} }
$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 ($search_contract != '') $param .= '&search_contract='.urlencode($search_contract); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_name != '') $param .= '&search_name='.urlencode($search_name); $param .= '&limit='.urlencode($limit);
if ($search_email != '') $param .= '&search_email='.urlencode($search_email); }
if ($search_ref_customer != '') $param .= '&search_ref_customer='.urlencode($search_ref_customer); if ($sall != '') {
if ($search_ref_supplier != '') $param .= '&search_ref_supplier='.urlencode($search_ref_supplier); $param .= '&sall='.urlencode($sall);
if ($search_op2df != '') $param .= '&search_op2df='.urlencode($search_op2df); }
if ($search_dfyear != '') $param .= '&search_dfyear='.urlencode($search_dfyear); if ($search_contract != '') {
if ($search_dfmonth != '') $param .= '&search_dfmonth='.urlencode($search_dfmonth); $param .= '&search_contract='.urlencode($search_contract);
if ($search_sale != '') $param .= '&search_sale='.urlencode($search_sale); }
if ($search_user != '') $param .= '&search_user='.urlencode($search_user); if ($search_name != '') {
if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); $param .= '&search_name='.urlencode($search_name);
if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); }
if ($show_files) $param .= '&show_files='.urlencode($show_files); if ($search_email != '') {
if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); $param .= '&search_email='.urlencode($search_email);
}
if ($search_ref_customer != '') {
$param .= '&search_ref_customer='.urlencode($search_ref_customer);
}
if ($search_ref_supplier != '') {
$param .= '&search_ref_supplier='.urlencode($search_ref_supplier);
}
if ($search_op2df != '') {
$param .= '&search_op2df='.urlencode($search_op2df);
}
if ($search_dfyear != '') {
$param .= '&search_dfyear='.urlencode($search_dfyear);
}
if ($search_dfmonth != '') {
$param .= '&search_dfmonth='.urlencode($search_dfmonth);
}
if ($search_sale != '') {
$param .= '&search_sale='.urlencode($search_sale);
}
if ($search_user != '') {
$param .= '&search_user='.urlencode($search_user);
}
if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) {
$param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty);
}
if ($search_product_category != '') {
$param .= '&search_product_category='.urlencode($search_product_category);
}
if ($show_files) {
$param .= '&show_files='.urlencode($show_files);
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields // 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';
@ -363,16 +442,24 @@ $arrayofmassactions = array(
'builddoc'=>$langs->trans("PDFMerge"), 'builddoc'=>$langs->trans("PDFMerge"),
'presend'=>$langs->trans("SendByMail"), 'presend'=>$langs->trans("SendByMail"),
); );
if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($user->rights->contrat->supprimer) {
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
}
if (in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
$url = DOL_URL_ROOT.'/contrat/card.php?action=create'; $url = DOL_URL_ROOT.'/contrat/card.php?action=create';
if (!empty($socid)) $url .= '&socid='.$socid; if (!empty($socid)) {
$url .= '&socid='.$socid;
}
$newcardbutton = dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $url, '', $user->rights->contrat->creer); $newcardbutton = dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $url, '', $user->rights->contrat->creer);
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">';
@ -388,17 +475,17 @@ $objecttmp = new Contrat($db);
$trackid = 'con'.$object->id; $trackid = 'con'.$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>';
} }
$moreforfilter = ''; $moreforfilter = '';
// If the user can view prospects other than his' // If the user can view prospects other than his'
if ($user->rights->societe->client->voir || $socid) if ($user->rights->societe->client->voir || $socid) {
{
$langs->load("commercial"); $langs->load("commercial");
$moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="divsearchfield">';
$moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': ';
@ -406,16 +493,14 @@ if ($user->rights->societe->client->voir || $socid)
$moreforfilter .= '</div>'; $moreforfilter .= '</div>';
} }
// If the user can view other users // If the user can view other users
if ($user->rights->user->user->lire) if ($user->rights->user->user->lire) {
{
$moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="divsearchfield">';
$moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': ';
$moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
$moreforfilter .= '</div>'; $moreforfilter .= '</div>';
} }
// If the user can view categories of products // If the user can view categories of products
if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) {
{
include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
$moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="divsearchfield">';
$moreforfilter .= $langs->trans('IncludingProductWithTag').': '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': ';
@ -426,11 +511,13 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($use
$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>';
@ -438,77 +525,75 @@ if (!empty($moreforfilter))
$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";
print '<tr class="liste_titre_filter">'; print '<tr class="liste_titre_filter">';
if (!empty($arrayfields['c.ref']['checked'])) if (!empty($arrayfields['c.ref']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">'; print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['c.ref_customer']['checked'])) if (!empty($arrayfields['c.ref_customer']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">'; print '<input type="text" class="flat" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['c.ref_supplier']['checked'])) if (!empty($arrayfields['c.ref_supplier']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat" size="6" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'">'; print '<input type="text" class="flat" size="6" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['s.nom']['checked'])) if (!empty($arrayfields['s.nom']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat" size="8" name="search_name" value="'.dol_escape_htmltag($search_name).'">'; print '<input type="text" class="flat" size="8" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['s.email']['checked'])) if (!empty($arrayfields['s.email']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat" size="6" name="search_email" value="'.dol_escape_htmltag($search_email).'">'; print '<input type="text" class="flat" size="6" name="search_email" value="'.dol_escape_htmltag($search_email).'">';
print '</td>'; print '</td>';
} }
// Town // Town
if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>'; if (!empty($arrayfields['s.town']['checked'])) {
print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_town" value="'.$search_town.'"></td>';
}
// Zip // Zip
if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>'; if (!empty($arrayfields['s.zip']['checked'])) {
print '<td class="liste_titre"><input class="flat" type="text" size="6" name="search_zip" value="'.$search_zip.'"></td>';
}
// State // State
if (!empty($arrayfields['state.nom']['checked'])) if (!empty($arrayfields['state.nom']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
print '</td>'; print '</td>';
} }
// Country // Country
if (!empty($arrayfields['country.code_iso']['checked'])) if (!empty($arrayfields['country.code_iso']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100');
print '</td>'; print '</td>';
} }
// Company type // Company type
if (!empty($arrayfields['typent.code']['checked'])) if (!empty($arrayfields['typent.code']['checked'])) {
{
print '<td class="liste_titre maxwidthonsmartphone center">'; print '<td class="liste_titre maxwidthonsmartphone center">';
print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1);
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['sale_representative']['checked'])) if (!empty($arrayfields['sale_representative']['checked'])) {
{
print '<td class="liste_titre"></td>'; print '<td class="liste_titre"></td>';
} }
if (!empty($arrayfields['c.date_contrat']['checked'])) if (!empty($arrayfields['c.date_contrat']['checked'])) {
{
// Date contract // Date contract
print '<td class="liste_titre center nowraponall">'; print '<td class="liste_titre center nowraponall">';
//print $langs->trans('Month').': '; //print $langs->trans('Month').': ';
if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.$day.'">'; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.$day.'">';
}
print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="month" value="'.$month.'">'; print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="month" value="'.$month.'">';
//print '&nbsp;'.$langs->trans('Year').': '; //print '&nbsp;'.$langs->trans('Year').': ';
$syear = $year; $syear = $year;
@ -523,20 +608,17 @@ $parameters = array('arrayfields'=>$arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook $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['c.datec']['checked'])) if (!empty($arrayfields['c.datec']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Date modification // Date modification
if (!empty($arrayfields['c.tms']['checked'])) if (!empty($arrayfields['c.tms']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// First end date // First end date
if (!empty($arrayfields['lower_planned_end_date']['checked'])) if (!empty($arrayfields['lower_planned_end_date']['checked'])) {
{
print '<td class="liste_titre nowraponall center">'; print '<td class="liste_titre nowraponall center">';
$arrayofoperators = array('0'=>'', '='=>'=', '<='=>'<=', '>='=>'>='); $arrayofoperators = array('0'=>'', '='=>'=', '<='=>'<=', '>='=>'>=');
print $form->selectarray('search_op2df', $arrayofoperators, $search_op2df, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth50imp'); print $form->selectarray('search_op2df', $arrayofoperators, $search_op2df, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth50imp');
@ -547,8 +629,7 @@ if (!empty($arrayfields['lower_planned_end_date']['checked']))
print '</td>'; print '</td>';
} }
// Status // Status
if (!empty($arrayfields['status']['checked'])) if (!empty($arrayfields['status']['checked'])) {
{
print '<td class="liste_titre right" colspan="4"></td>'; print '<td class="liste_titre right" colspan="4"></td>';
} }
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
@ -558,18 +639,42 @@ print '</td>';
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['c.ref']['checked'])) {
if (!empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['c.ref_customer']['checked'])) {
if (!empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); }
if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['c.ref_supplier']['checked'])) {
if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); }
if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['s.nom']['checked'])) {
if (!empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center '); }
if (!empty($arrayfields['s.email']['checked'])) {
print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['s.town']['checked'])) {
print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['s.zip']['checked'])) {
print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['state.nom']['checked'])) {
print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['country.code_iso']['checked'])) {
print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['typent.code']['checked'])) {
print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['sale_representative']['checked'])) {
print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder);
}
if (!empty($arrayfields['c.date_contrat']['checked'])) {
print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center ');
}
// Extra fields // 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';
// Hook fields // Hook fields
@ -598,8 +703,7 @@ $totalarray = array();
$typenArray = array(); $typenArray = array();
$cacheCountryIDCode = array(); $cacheCountryIDCode = array();
while ($i < min($num, $limit)) while ($i < min($num, $limit)) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$contracttmp->ref = $obj->ref; $contracttmp->ref = $obj->ref;
@ -632,11 +736,12 @@ while ($i < min($num, $limit))
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Ref // Ref
if (!empty($arrayfields['c.ref']['checked'])) if (!empty($arrayfields['c.ref']['checked'])) {
{
print '<td class="nowraponall">'; print '<td class="nowraponall">';
print $contracttmp->getNomUrl(1); print $contracttmp->getNomUrl(1);
if ($obj->nb_late) print img_warning($langs->trans("Late")); if ($obj->nb_late) {
print img_warning($langs->trans("Late"));
}
if (!empty($obj->note_private) || !empty($obj->note_public)) { if (!empty($obj->note_private) || !empty($obj->note_public)) {
print ' <span class="note">'; print ' <span class="note">';
print '<a href="'.DOL_URL_ROOT.'/contrat/note.php?id='.$obj->rowid.'&save_lastsearch_values=1">'.img_picto($langs->trans("ViewPrivateNote"), 'note').'</a>'; print '<a href="'.DOL_URL_ROOT.'/contrat/note.php?id='.$obj->rowid.'&save_lastsearch_values=1">'.img_picto($langs->trans("ViewPrivateNote"), 'note').'</a>';
@ -652,16 +757,13 @@ while ($i < min($num, $limit))
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['c.ref_customer']['checked'])) if (!empty($arrayfields['c.ref_customer']['checked'])) {
{
print '<td>'.$contracttmp->getFormatedCustomerRef($obj->ref_customer).'</td>'; print '<td>'.$contracttmp->getFormatedCustomerRef($obj->ref_customer).'</td>';
} }
if (!empty($arrayfields['c.ref_supplier']['checked'])) if (!empty($arrayfields['c.ref_supplier']['checked'])) {
{
print '<td>'.$obj->ref_supplier.'</td>'; print '<td>'.$obj->ref_supplier.'</td>';
} }
if (!empty($arrayfields['s.nom']['checked'])) if (!empty($arrayfields['s.nom']['checked'])) {
{
print '<td class="tdoverflowmax150">'; print '<td class="tdoverflowmax150">';
if ($obj->socid > 0) { if ($obj->socid > 0) {
// TODO Use a cache for this string // TODO Use a cache for this string
@ -669,57 +771,63 @@ while ($i < min($num, $limit))
} }
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['s.email']['checked'])) if (!empty($arrayfields['s.email']['checked'])) {
{
print '<td>'.$obj->email.'</td>'; print '<td>'.$obj->email.'</td>';
} }
// Town // Town
if (!empty($arrayfields['s.town']['checked'])) if (!empty($arrayfields['s.town']['checked'])) {
{
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->town; print $obj->town;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Zip // Zip
if (!empty($arrayfields['s.zip']['checked'])) if (!empty($arrayfields['s.zip']['checked'])) {
{
print '<td class="nocellnopadd">'; print '<td class="nocellnopadd">';
print $obj->zip; print $obj->zip;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// State // State
if (!empty($arrayfields['state.nom']['checked'])) if (!empty($arrayfields['state.nom']['checked'])) {
{
print "<td>".$obj->state_name."</td>\n"; print "<td>".$obj->state_name."</td>\n";
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Country // Country
if (!empty($arrayfields['country.code_iso']['checked'])) if (!empty($arrayfields['country.code_iso']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
print $socstatic->country; print $socstatic->country;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Type ent // Type ent
if (!empty($arrayfields['typent.code']['checked'])) if (!empty($arrayfields['typent.code']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); if (count($typenArray) == 0) {
$typenArray = $formcompany->typent_array(1);
}
print $typenArray[$obj->typent_code]; print $typenArray[$obj->typent_code];
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
if (!empty($arrayfields['sale_representative']['checked'])) if (!empty($arrayfields['sale_representative']['checked'])) {
{
// Sales representatives // Sales representatives
print '<td>'; print '<td>';
if ($obj->socid > 0) if ($obj->socid > 0) {
{
$listsalesrepresentatives = $socstatic->getSalesRepresentatives($user); $listsalesrepresentatives = $socstatic->getSalesRepresentatives($user);
if ($listsalesrepresentatives < 0) dol_print_error($db); if ($listsalesrepresentatives < 0) {
dol_print_error($db);
}
$nbofsalesrepresentative = count($listsalesrepresentatives); $nbofsalesrepresentative = count($listsalesrepresentatives);
if ($nbofsalesrepresentative > 6) { if ($nbofsalesrepresentative > 6) {
// We print only number // We print only number
@ -756,8 +864,7 @@ while ($i < min($num, $limit))
print '</td>'; print '</td>';
} }
// Date // Date
if (!empty($arrayfields['c.date_contrat']['checked'])) if (!empty($arrayfields['c.date_contrat']['checked'])) {
{
print '<td class="center">'.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzserver').'</td>'; print '<td class="center">'.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzserver').'</td>';
} }
// Extra fields // Extra fields
@ -767,32 +874,34 @@ while ($i < min($num, $limit))
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListValue', $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['c.datec']['checked'])) if (!empty($arrayfields['c.datec']['checked'])) {
{
print '<td class="center nowrap">'; print '<td class="center nowrap">';
print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date modification // Date modification
if (!empty($arrayfields['c.tms']['checked'])) if (!empty($arrayfields['c.tms']['checked'])) {
{
print '<td class="center nowrap">'; print '<td class="center nowrap">';
print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date lower end date // Date lower end date
if (!empty($arrayfields['lower_planned_end_date']['checked'])) if (!empty($arrayfields['lower_planned_end_date']['checked'])) {
{
print '<td class="center nowrapforall">'; print '<td class="center nowrapforall">';
print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser'); print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Status // Status
if (!empty($arrayfields['status']['checked'])) if (!empty($arrayfields['status']['checked'])) {
{
print '<td class="center">'.($obj->nb_initial > 0 ? $obj->nb_initial : '').'</td>'; print '<td class="center">'.($obj->nb_initial > 0 ? $obj->nb_initial : '').'</td>';
print '<td class="center">'.($obj->nb_running > 0 ? $obj->nb_running : '').'</td>'; print '<td class="center">'.($obj->nb_running > 0 ? $obj->nb_running : '').'</td>';
print '<td class="center">'.($obj->nb_expired > 0 ? $obj->nb_expired : '').'</td>'; print '<td class="center">'.($obj->nb_expired > 0 ? $obj->nb_expired : '').'</td>';
@ -800,14 +909,17 @@ while ($i < min($num, $limit))
} }
// 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++;
@ -824,7 +936,9 @@ print '</div>';
print '</form>'; print '</form>';
$hidegeneratedfilelistifempty = 1; $hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
// Show list of available documents // Show list of available documents
$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;

View File

@ -41,7 +41,9 @@ $id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha'); $ref = GETPOST('ref', 'alpha');
// Security check // Security check
if ($user->socid) $socid = $user->socid; if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'contrat', $id); $result = restrictedArea($user, 'contrat', $id);
$object = new Contrat($db); $object = new Contrat($db);
@ -70,8 +72,7 @@ llxHeader('', $langs->trans("Contract"), "");
$form = new Form($db); $form = new Form($db);
if ($id > 0 || !empty($ref)) if ($id > 0 || !empty($ref)) {
{
$object->fetch_thirdparty(); $object->fetch_thirdparty();
$head = contract_prepare_head($object); $head = contract_prepare_head($object);
@ -89,9 +90,9 @@ if ($id > 0 || !empty($ref))
//if (! empty($modCodeContract->code_auto)) { //if (! empty($modCodeContract->code_auto)) {
$morehtmlref .= $object->ref; $morehtmlref .= $object->ref;
/*} else { /*} else {
$morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
$morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
}*/ }*/
$morehtmlref .= '<div class="refidno">'; $morehtmlref .= '<div class="refidno">';
// Ref customer // Ref customer
@ -104,15 +105,14 @@ if ($id > 0 || !empty($ref))
// Thirdparty // Thirdparty
$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); $morehtmlref .= '<br>'.$langs->trans('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 ($user->rights->contrat->creer) if ($user->rights->contrat->creer) {
{ 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> : ';
$morehtmlref .= ' : '; $morehtmlref .= ' : ';
}
if ($action == 'classify') { if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@ -150,12 +150,18 @@ if ($id > 0 || !empty($ref))
// Ligne info remises tiers // Ligne info remises tiers
print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">'; print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); if ($object->thirdparty->remise_percent) {
else print $langs->trans("CompanyHasNoRelativeDiscount"); print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent);
} else {
print $langs->trans("CompanyHasNoRelativeDiscount");
}
$absolute_discount = $object->thirdparty->getAvailableDiscounts(); $absolute_discount = $object->thirdparty->getAvailableDiscounts();
print '. '; print '. ';
if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); if ($absolute_discount) {
else print $langs->trans("CompanyHasNoAbsoluteDiscount"); print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
} else {
print $langs->trans("CompanyHasNoAbsoluteDiscount");
}
print '.'; print '.';
print '</td></tr>'; print '</td></tr>';

View File

@ -39,12 +39,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 = "c.rowid"; if (!$sortfield) {
if (!$sortorder) $sortorder = "ASC"; $sortfield = "c.rowid";
}
if (!$sortorder) {
$sortorder = "ASC";
}
$mode = GETPOST("mode"); $mode = GETPOST("mode");
$filter = GETPOST("filter"); $filter = GETPOST("filter");
@ -90,22 +96,32 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
// Security check // Security check
$contratid = GETPOST('id', 'int'); $contratid = GETPOST('id', 'int');
if (!empty($user->socid)) $socid = $user->socid; if (!empty($user->socid)) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'contrat', $contratid); $result = restrictedArea($user, 'contrat', $contratid);
if ($search_status != '') if ($search_status != '') {
{
$tmp = explode('&', $search_status); $tmp = explode('&', $search_status);
$mode = $tmp[0]; $mode = $tmp[0];
if (empty($tmp[1])) $filter = ''; if (empty($tmp[1])) {
else { $filter = '';
if ($tmp[1] == 'filter=notexpired') $filter = 'notexpired'; } else {
if ($tmp[1] == 'filter=expired') $filter = 'expired'; if ($tmp[1] == 'filter=notexpired') {
$filter = 'notexpired';
}
if ($tmp[1] == 'filter=expired') {
$filter = 'expired';
}
} }
} else { } else {
$search_status = $mode; $search_status = $mode;
if ($filter == 'expired') $search_status .= '&filter=expired'; if ($filter == 'expired') {
if ($filter == 'notexpired') $search_status .= '&filter=notexpired'; $search_status .= '&filter=expired';
}
if ($filter == 'notexpired') {
$search_status .= '&filter=notexpired';
}
} }
$staticcontrat = new Contrat($db); $staticcontrat = new Contrat($db);
@ -142,21 +158,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
* Actions * Actions
*/ */
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (GETPOST('cancel', 'alpha')) {
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } $action = 'list'; $massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') {
$massaction = '';
}
$parameters = array('socid'=>$socid); $parameters = array('socid'=>$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)) {
{
// 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';
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
{ $search_product_category = 0;
$search_product_category = 0;
$search_name = ""; $search_name = "";
$search_contract = ""; $search_contract = "";
$search_service = ""; $search_service = "";
@ -197,7 +217,9 @@ $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut, c.ref_customer, c.ref
$sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,"; $sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,";
$sql .= " cd.rowid, cd.description, cd.statut,"; $sql .= " cd.rowid, cd.description, cd.statut,";
$sql .= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " sc.fk_soc, sc.fk_user,";
}
$sql .= " cd.date_ouverture_prevue,"; $sql .= " cd.date_ouverture_prevue,";
$sql .= " cd.date_ouverture,"; $sql .= " cd.date_ouverture,";
$sql .= " cd.date_fin_validite,"; $sql .= " cd.date_fin_validite,";
@ -211,7 +233,9 @@ $sql .= " cd.subprice,";
$sql .= " cd.tms as date_update"; $sql .= " cd.tms as date_update";
// 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();
@ -219,50 +243,102 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N
$sql .= $hookmanager->resPrint; $sql .= $hookmanager->resPrint;
$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,";
$sql .= " ".MAIN_DB_PREFIX."societe as s,"; $sql .= " ".MAIN_DB_PREFIX."societe as s,";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; if (!$user->rights->societe->client->voir && !$socid) {
$sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
}
$sql .= " ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " ".MAIN_DB_PREFIX."contratdet as cd";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)";
}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; if ($search_product_category > 0) {
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
}
$sql .= " WHERE c.entity = ".$conf->entity; $sql .= " WHERE c.entity = ".$conf->entity;
$sql .= " AND c.rowid = cd.fk_contrat"; $sql .= " AND c.rowid = cd.fk_contrat";
if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; if ($search_product_category > 0) {
$sql .= " AND cp.fk_categorie = ".$search_product_category;
}
$sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.fk_soc = s.rowid";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if (!$user->rights->societe->client->voir && !$socid) {
if ($mode == "0") $sql .= " AND cd.statut = 0"; $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
if ($mode == "4") $sql .= " AND cd.statut = 4"; }
if ($mode == "5") $sql .= " AND cd.statut = 5"; if ($mode == "0") {
if ($filter == "expired") $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; $sql .= " AND cd.statut = 0";
if ($filter == "notexpired") $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'"; }
if ($search_name) $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'"; if ($mode == "4") {
if ($search_contract) $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' "; $sql .= " AND cd.statut = 4";
if ($search_service) $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')"; }
if ($socid > 0) $sql .= " AND s.rowid = ".$socid; if ($mode == "5") {
$sql .= " AND cd.statut = 5";
}
if ($filter == "expired") {
$sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'";
}
if ($filter == "notexpired") {
$sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
}
if ($search_name) {
$sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
}
if ($search_contract) {
$sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
}
if ($search_service) {
$sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
}
if ($socid > 0) {
$sql .= " AND s.rowid = ".$socid;
}
$filter_dateouvertureprevue_start = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear); $filter_dateouvertureprevue_start = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
$filter_dateouvertureprevue_end = dol_mktime(23, 59, 59, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear); $filter_dateouvertureprevue_end = dol_mktime(23, 59, 59, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
if ($filter_dateouvertureprevue_start != '' && $filter_opouvertureprevue == -1) $filter_opouvertureprevue = ' BETWEEN '; if ($filter_dateouvertureprevue_start != '' && $filter_opouvertureprevue == -1) {
$filter_opouvertureprevue = ' BETWEEN ';
}
$filter_date1_start = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year); $filter_date1_start = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
$filter_date1_end = dol_mktime(23, 59, 59, $op1month, $op1day, $op1year); $filter_date1_end = dol_mktime(23, 59, 59, $op1month, $op1day, $op1year);
if ($filter_date1_start != '' && $filter_op1 == -1) $filter_op1 = ' BETWEEN '; if ($filter_date1_start != '' && $filter_op1 == -1) {
$filter_op1 = ' BETWEEN ';
}
$filter_date2_start = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year); $filter_date2_start = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
$filter_date2_end = dol_mktime(23, 59, 59, $op2month, $op2day, $op2year); $filter_date2_end = dol_mktime(23, 59, 59, $op2month, $op2day, $op2year);
if ($filter_date2_start != '' && $filter_op2 == -1) $filter_op2 = ' BETWEEN '; if ($filter_date2_start != '' && $filter_op2 == -1) {
$filter_op2 = ' BETWEEN ';
}
$filter_datecloture_start = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear); $filter_datecloture_start = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
$filter_datecloture_end = dol_mktime(23, 59, 59, $opcloturemonth, $opclotureday, $opclotureyear); $filter_datecloture_end = dol_mktime(23, 59, 59, $opcloturemonth, $opclotureday, $opclotureyear);
if ($filter_datecloture_start != '' && $filter_opcloture == -1) $filter_opcloture = ' BETWEEN '; if ($filter_datecloture_start != '' && $filter_opcloture == -1) {
$filter_opcloture = ' BETWEEN ';
}
if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_opouvertureprevue != ' BETWEEN ' && $filter_dateouvertureprevue_start != '') $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue_start)."'"; if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_opouvertureprevue != ' BETWEEN ' && $filter_dateouvertureprevue_start != '') {
if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_dateouvertureprevue_end)."'"; $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue_start)."'";
if (!empty($filter_op1) && $filter_op1 != -1 && $filter_op1 != ' BETWEEN ' && $filter_date1_start != '') $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1_start)."'"; }
if (!empty($filter_op1) && $filter_op1 == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_date1_end)."'"; if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue == ' BETWEEN ') {
if (!empty($filter_op2) && $filter_op2 != -1 && $filter_op2 != ' BETWEEN ' && $filter_date2_start != '') $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2_start)."'"; $sql .= " AND '".$db->idate($filter_dateouvertureprevue_end)."'";
if (!empty($filter_op2) && $filter_op2 == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_date2_end)."'"; }
if (!empty($filter_opcloture) && $filter_opcloture != ' BETWEEN ' && $filter_opcloture != -1 && $filter_datecloture_start != '') $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture_start)."'"; if (!empty($filter_op1) && $filter_op1 != -1 && $filter_op1 != ' BETWEEN ' && $filter_date1_start != '') {
if (!empty($filter_opcloture) && $filter_opcloture == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_datecloture_end)."'"; $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1_start)."'";
}
if (!empty($filter_op1) && $filter_op1 == ' BETWEEN ') {
$sql .= " AND '".$db->idate($filter_date1_end)."'";
}
if (!empty($filter_op2) && $filter_op2 != -1 && $filter_op2 != ' BETWEEN ' && $filter_date2_start != '') {
$sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2_start)."'";
}
if (!empty($filter_op2) && $filter_op2 == ' BETWEEN ') {
$sql .= " AND '".$db->idate($filter_date2_end)."'";
}
if (!empty($filter_opcloture) && $filter_opcloture != ' BETWEEN ' && $filter_opcloture != -1 && $filter_datecloture_start != '') {
$sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture_start)."'";
}
if (!empty($filter_opcloture) && $filter_opcloture == ' BETWEEN ') {
$sql .= " AND '".$db->idate($filter_datecloture_end)."'";
}
// Add where from extra fields // 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';
$sql .= $db->order($sortfield, $sortorder); $sql .= $db->order($sortfield, $sortorder);
@ -270,12 +346,10 @@ $sql .= $db->order($sortfield, $sortorder);
//print $sql; //print $sql;
$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;
} }
@ -286,8 +360,7 @@ $sql .= $db->plimit($limit + 1, $offset);
//print $sql; //print $sql;
dol_syslog("contrat/services_list.php", LOG_DEBUG); dol_syslog("contrat/services_list.php", LOG_DEBUG);
$resql = $db->query($sql); $resql = $db->query($sql);
if (!$resql) if (!$resql) {
{
dol_print_error($db); dol_print_error($db);
exit; exit;
} }
@ -297,31 +370,63 @@ $num = $db->num_rows($resql);
/* /*
if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) 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->id; $id = $obj->id;
header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1');
exit; exit;
}*/ }*/
llxHeader(null, $langs->trans("Services")); llxHeader(null, $langs->trans("Services"));
$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='.$limit; $param .= '&contextpage='.urlencode($contextpage);
if ($search_contract) $param .= '&amp;search_contract='.urlencode($search_contract); }
if ($search_name) $param .= '&amp;search_name='.urlencode($search_name); if ($limit > 0 && $limit != $conf->liste_limit) {
if ($search_service) $param .= '&amp;search_service='.urlencode($search_service); $param .= '&limit='.$limit;
if ($mode) $param .= '&amp;mode='.urlencode($mode); }
if ($filter) $param .= '&amp;filter='.urlencode($filter); if ($search_contract) {
if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param .= '&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue); $param .= '&amp;search_contract='.urlencode($search_contract);
if (!empty($filter_op1) && $filter_op1 != -1) $param .= '&amp;filter_op1='.urlencode($filter_op1); }
if (!empty($filter_op2) && $filter_op2 != -1) $param .= '&amp;filter_op2='.urlencode($filter_op2); if ($search_name) {
if (!empty($filter_opcloture) && $filter_opcloture != -1) $param .= '&amp;filter_opcloture='.urlencode($filter_opcloture); $param .= '&amp;search_name='.urlencode($search_name);
if ($filter_dateouvertureprevue != '') $param .= '&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear; }
if ($filter_date1 != '') $param .= '&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year; if ($search_service) {
if ($filter_date2 != '') $param .= '&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year; $param .= '&amp;search_service='.urlencode($search_service);
if ($filter_datecloture != '') $param .= '&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year; }
if ($optioncss != '') $param .= '&optioncss='.$optioncss; if ($mode) {
$param .= '&amp;mode='.urlencode($mode);
}
if ($filter) {
$param .= '&amp;filter='.urlencode($filter);
}
if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) {
$param .= '&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
}
if (!empty($filter_op1) && $filter_op1 != -1) {
$param .= '&amp;filter_op1='.urlencode($filter_op1);
}
if (!empty($filter_op2) && $filter_op2 != -1) {
$param .= '&amp;filter_op2='.urlencode($filter_op2);
}
if (!empty($filter_opcloture) && $filter_opcloture != -1) {
$param .= '&amp;filter_opcloture='.urlencode($filter_opcloture);
}
if ($filter_dateouvertureprevue != '') {
$param .= '&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
}
if ($filter_date1 != '') {
$param .= '&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
}
if ($filter_date2 != '') {
$param .= '&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
}
if ($filter_datecloture != '') {
$param .= '&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
}
if ($optioncss != '') {
$param .= '&optioncss='.$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';
@ -335,7 +440,9 @@ $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">';
@ -345,24 +452,32 @@ print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
$title = $langs->trans("ListOfServices"); $title = $langs->trans("ListOfServices");
if ($mode == "0") $title = $langs->trans("ListOfInactiveServices"); // Must use == "0" if ($mode == "0") {
if ($mode == "4" && $filter != "expired") $title = $langs->trans("ListOfRunningServices"); $title = $langs->trans("ListOfInactiveServices"); // Must use == "0"
if ($mode == "4" && $filter == "expired") $title = $langs->trans("ListOfExpiredServices"); }
if ($mode == "5") $title = $langs->trans("ListOfClosedServices"); if ($mode == "4" && $filter != "expired") {
$title = $langs->trans("ListOfRunningServices");
}
if ($mode == "4" && $filter == "expired") {
$title = $langs->trans("ListOfExpiredServices");
}
if ($mode == "5") {
$title = $langs->trans("ListOfClosedServices");
}
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'contract', 0, '', '', $limit); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'contract', 0, '', '', $limit);
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>';
} }
$morefilter = ''; $morefilter = '';
// If the user can view categories of products // If the user can view categories of products
if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) {
{
include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
$moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= '<div class="divsearchfield">';
$moreforfilter .= $langs->trans('IncludingProductWithTag').': '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': ';
@ -373,12 +488,14 @@ if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights-
$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>';
@ -392,33 +509,62 @@ print '<div class="div-table-responsive">';
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 (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['c.ref']['checked'])) {
if (!empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['cd.qty']['checked'])) print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap '); }
if (!empty($arrayfields['cd.total_ht']['checked'])) print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap '); if (!empty($arrayfields['p.description']['checked'])) {
if (!empty($arrayfields['cd.total_tva']['checked'])) print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap '); print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['cd.tva_tx']['checked'])) print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap '); }
if (!empty($arrayfields['cd.subprice']['checked'])) print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap '); if (!empty($arrayfields['cd.qty']['checked'])) {
if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder); print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center '); }
if (!empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['cd.total_ht']['checked'])) {
if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center '); print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
if (!empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center '); }
if (!empty($arrayfields['cd.total_tva']['checked'])) {
print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
if (!empty($arrayfields['cd.tva_tx']['checked'])) {
print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
if (!empty($arrayfields['cd.subprice']['checked'])) {
print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
if (!empty($arrayfields['s.nom']['checked'])) {
print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder);
}
if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) {
print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['cd.date_ouverture']['checked'])) {
print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['cd.date_fin_validite']['checked'])) {
print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center ');
}
if (!empty($arrayfields['cd.date_cloture']['checked'])) {
print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center ');
}
// Extra fields // 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';
// Hook fields // Hook fields
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint; print $hookmanager->resPrint;
if (!empty($arrayfields['cd.datec']['checked'])) print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); if (!empty($arrayfields['cd.datec']['checked'])) {
if (!empty($arrayfields['cd.tms']['checked'])) print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right '); }
if (!empty($arrayfields['cd.tms']['checked'])) {
print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
if (!empty($arrayfields['status']['checked'])) {
print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right ');
}
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
print "</tr>\n"; print "</tr>\n";
print '<tr class="liste_titre">'; print '<tr class="liste_titre">';
if (!empty($arrayfields['c.ref']['checked'])) if (!empty($arrayfields['c.ref']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="hidden" name="filter" value="'.$filter.'">'; print '<input type="hidden" name="filter" value="'.$filter.'">';
print '<input type="hidden" name="mode" value="'.$mode.'">'; print '<input type="hidden" name="mode" value="'.$mode.'">';
@ -426,49 +572,41 @@ if (!empty($arrayfields['c.ref']['checked']))
print '</td>'; print '</td>';
} }
// Service label // Service label
if (!empty($arrayfields['p.description']['checked'])) if (!empty($arrayfields['p.description']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">'; print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">';
print '</td>'; print '</td>';
} }
// detail lines // detail lines
if (!empty($arrayfields['cd.qty']['checked'])) if (!empty($arrayfields['cd.qty']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.total_ht']['checked'])) if (!empty($arrayfields['cd.total_ht']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.total_tva']['checked'])) if (!empty($arrayfields['cd.total_tva']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.tva_tx']['checked'])) if (!empty($arrayfields['cd.tva_tx']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.subprice']['checked'])) if (!empty($arrayfields['cd.subprice']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
// Third party // Third party
if (!empty($arrayfields['s.nom']['checked'])) if (!empty($arrayfields['s.nom']['checked'])) {
{
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">'; print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
$arrayofoperators = array('<'=>'<', '>'=>'>'); $arrayofoperators = array('<'=>'<', '>'=>'>');
print $form->selectarray('filter_opouvertureprevue', $arrayofoperators, $filter_opouvertureprevue, 1); print $form->selectarray('filter_opouvertureprevue', $arrayofoperators, $filter_opouvertureprevue, 1);
@ -477,8 +615,7 @@ if (!empty($arrayfields['cd.date_ouverture_prevue']['checked']))
print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0); print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0);
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.date_ouverture']['checked'])) if (!empty($arrayfields['cd.date_ouverture']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
$arrayofoperators = array('<'=>'<', '>'=>'>'); $arrayofoperators = array('<'=>'<', '>'=>'>');
print $form->selectarray('filter_op1', $arrayofoperators, $filter_op1, 1); print $form->selectarray('filter_op1', $arrayofoperators, $filter_op1, 1);
@ -487,8 +624,7 @@ if (!empty($arrayfields['cd.date_ouverture']['checked']))
print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0); print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0);
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.date_fin_validite']['checked'])) if (!empty($arrayfields['cd.date_fin_validite']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
$arrayofoperators = array('<'=>'<', '>'=>'>'); $arrayofoperators = array('<'=>'<', '>'=>'>');
print $form->selectarray('filter_op2', $arrayofoperators, $filter_op2, 1); print $form->selectarray('filter_op2', $arrayofoperators, $filter_op2, 1);
@ -497,8 +633,7 @@ if (!empty($arrayfields['cd.date_fin_validite']['checked']))
print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0); print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0);
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.date_cloture']['checked'])) if (!empty($arrayfields['cd.date_cloture']['checked'])) {
{
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
$arrayofoperators = array('<'=>'<', '>'=>'>'); $arrayofoperators = array('<'=>'<', '>'=>'>');
print $form->selectarray('filter_opcloture', $arrayofoperators, $filter_opcloture, 1); print $form->selectarray('filter_opcloture', $arrayofoperators, $filter_opcloture, 1);
@ -514,20 +649,17 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
$parameters = array('arrayfields'=>$arrayfields); $parameters = array('arrayfields'=>$arrayfields);
$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;
if (!empty($arrayfields['cd.datec']['checked'])) if (!empty($arrayfields['cd.datec']['checked'])) {
{
// Date creation // Date creation
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['cd.tms']['checked'])) if (!empty($arrayfields['cd.tms']['checked'])) {
{
// Date modification // Date modification
print '<td class="liste_titre">'; print '<td class="liste_titre">';
print '</td>'; print '</td>';
} }
if (!empty($arrayfields['status']['checked'])) if (!empty($arrayfields['status']['checked'])) {
{
// Status // Status
print '<td class="liste_titre right">'; print '<td class="liste_titre right">';
$arrayofstatus = array( $arrayofstatus = array(
@ -552,8 +684,7 @@ $productstatic = new Product($db);
$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);
$contractstatic->id = $obj->cid; $contractstatic->id = $obj->cid;
@ -570,118 +701,142 @@ while ($i < min($num, $limit))
print '<tr class="oddeven">'; print '<tr class="oddeven">';
// Ref // Ref
if (!empty($arrayfields['c.ref']['checked'])) if (!empty($arrayfields['c.ref']['checked'])) {
{
print '<td class="nowraponall">'; print '<td class="nowraponall">';
print $contractstatic->getNomUrl(1, 16); print $contractstatic->getNomUrl(1, 16);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Service // Service
if (!empty($arrayfields['p.description']['checked'])) if (!empty($arrayfields['p.description']['checked'])) {
{
print '<td>'; print '<td>';
if ($obj->pid > 0) if ($obj->pid > 0) {
{
$productstatic->id = $obj->pid; $productstatic->id = $obj->pid;
$productstatic->type = $obj->ptype; $productstatic->type = $obj->ptype;
$productstatic->ref = $obj->pref; $productstatic->ref = $obj->pref;
$productstatic->entity = $obj->pentity; $productstatic->entity = $obj->pentity;
print $productstatic->getNomUrl(1, '', 24); print $productstatic->getNomUrl(1, '', 24);
print $obj->label ? ' - '.dol_trunc($obj->label, 16) : ''; print $obj->label ? ' - '.dol_trunc($obj->label, 16) : '';
if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description); if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) {
print '<br>'.dol_nl2br($obj->description);
}
} else { } else {
if ($obj->type == 0) print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24); if ($obj->type == 0) {
if ($obj->type == 1) print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24); print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24);
}
if ($obj->type == 1) {
print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24);
}
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
if (!empty($arrayfields['cd.qty']['checked'])) if (!empty($arrayfields['cd.qty']['checked'])) {
{
print '<td>'; print '<td>';
print $obj->qty; print $obj->qty;
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
if (!empty($arrayfields['cd.total_ht']['checked'])) if (!empty($arrayfields['cd.total_ht']['checked'])) {
{
print '<td class="right">'; print '<td class="right">';
print price($obj->total_ht); print price($obj->total_ht);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht'; $totalarray['nbfield']++;
}
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht';
}
$totalarray['val']['cd.total_ht'] += $obj->total_ht; $totalarray['val']['cd.total_ht'] += $obj->total_ht;
} }
if (!empty($arrayfields['cd.total_tva']['checked'])) if (!empty($arrayfields['cd.total_tva']['checked'])) {
{
print '<td class="right">'; print '<td class="right">';
print price($obj->total_tva); print price($obj->total_tva);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva'; $totalarray['nbfield']++;
}
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva';
}
$totalarray['val']['cd.total_tva'] += $obj->total_tva; $totalarray['val']['cd.total_tva'] += $obj->total_tva;
} }
if (!empty($arrayfields['cd.tva_tx']['checked'])) if (!empty($arrayfields['cd.tva_tx']['checked'])) {
{
print '<td class="right">'; print '<td class="right">';
print price2num($obj->tva_tx).'%'; print price2num($obj->tva_tx).'%';
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
if (!empty($arrayfields['cd.subprice']['checked'])) if (!empty($arrayfields['cd.subprice']['checked'])) {
{
print '<td class="right">'; print '<td class="right">';
print price($obj->subprice); print price($obj->subprice);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Third party // Third party
if (!empty($arrayfields['s.nom']['checked'])) if (!empty($arrayfields['s.nom']['checked'])) {
{
print '<td>'; print '<td>';
print $companystatic->getNomUrl(1, 'customer', 28); print $companystatic->getNomUrl(1, 'customer', 28);
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Start date // Start date
if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
print ($obj->date_ouverture_prevue ?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour') : '&nbsp;'); print ($obj->date_ouverture_prevue ?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour') : '&nbsp;');
if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) {
print ' '.img_picto($langs->trans("Late"), "warning"); print ' '.img_picto($langs->trans("Late"), "warning");
else print '&nbsp;&nbsp;&nbsp;&nbsp;'; } else {
print '&nbsp;&nbsp;&nbsp;&nbsp;';
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
if (!empty($arrayfields['cd.date_ouverture']['checked'])) if (!empty($arrayfields['cd.date_ouverture']['checked'])) {
{
print '<td class="center">'.($obj->date_ouverture ?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour') : '&nbsp;').'</td>'; print '<td class="center">'.($obj->date_ouverture ?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour') : '&nbsp;').'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// End date // End date
if (!empty($arrayfields['cd.date_fin_validite']['checked'])) if (!empty($arrayfields['cd.date_fin_validite']['checked'])) {
{
print '<td class="center">'.($obj->date_fin_validite ?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour') : '&nbsp;'); print '<td class="center">'.($obj->date_fin_validite ?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour') : '&nbsp;');
if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) {
{
$warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24; $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
print img_warning($textlate); print img_warning($textlate);
} else print '&nbsp;&nbsp;&nbsp;&nbsp;'; } else {
print '&nbsp;&nbsp;&nbsp;&nbsp;';
}
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Close date (real end date) // Close date (real end date)
if (!empty($arrayfields['cd.date_cloture']['checked'])) if (!empty($arrayfields['cd.date_cloture']['checked'])) {
{
print '<td class="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>'; print '<td class="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Extra fields // Extra fields
@ -691,45 +846,50 @@ while ($i < min($num, $limit))
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook $reshook = $hookmanager->executeHooks('printFieldListValue', $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['cd.datec']['checked'])) if (!empty($arrayfields['cd.datec']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Date modification // Date modification
if (!empty($arrayfields['cd.tms']['checked'])) if (!empty($arrayfields['cd.tms']['checked'])) {
{
print '<td class="center">'; print '<td class="center">';
print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// Status // Status
if (!empty($arrayfields['status']['checked'])) if (!empty($arrayfields['status']['checked'])) {
{
print '<td class="right">'; print '<td class="right">';
if ($obj->cstatut == 0) if ($obj->cstatut == 0) {
{
// If contract is draft, we say line is also draft // If contract is draft, we say line is also draft
print $contractstatic->LibStatut(0, 5); print $contractstatic->LibStatut(0, 5);
} else { } else {
print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now) ? 1 : 0); print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now) ? 1 : 0);
} }
print '</td>'; print '</td>';
if (!$i) $totalarray['nbfield']++; if (!$i) {
$totalarray['nbfield']++;
}
} }
// 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++;

View File

@ -17,8 +17,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;
} }
@ -37,24 +36,24 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock'];
$langs->load("contracts"); $langs->load("contracts");
$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("Contract"); ?></td> <td><?php echo $langs->trans("Contract"); ?></td>
<td><?php echo $objectlink->getNomUrl(1); ?></td> <td><?php echo $objectlink->getNomUrl(1); ?></td>
<td></td> <td></td>
<td class="center"><?php echo dol_print_date($objectlink->date_contrat, 'day'); ?></td> <td class="center"><?php echo dol_print_date($objectlink->date_contrat, 'day'); ?></td>
<td class="right"><?php <td class="right"><?php
// Price of contract is not shown by default because a contract is a list of service with // Price of contract is not shown by default because a contract is a list of service with
// start and end date that change with time andd that may be different that the period of reference for price. // start and end date that change with time andd that may be different that the period of reference for price.
// So price of a contract does often means nothing. Prices is on the different invoices done on same contract. // So price of a contract does often means nothing. Prices is on the different invoices done on same contract.
if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) {
{
$totalcontrat = 0; $totalcontrat = 0;
foreach ($objectlink->lines as $linecontrat) { foreach ($objectlink->lines as $linecontrat) {
$totalcontrat = $totalcontrat + $linecontrat->total_ht; $totalcontrat = $totalcontrat + $linecontrat->total_ht;

View File

@ -2,7 +2,7 @@
/* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net> /* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2010 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2010 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr> * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -44,24 +44,44 @@ function project_prepare_head(Project $project)
$head[$h][1] = $langs->trans("Project"); $head[$h][1] = $langs->trans("Project");
$head[$h][2] = 'project'; $head[$h][2] = 'project';
$h++; $h++;
$nbContacts = 0;
// Enable caching of project count Contacts
require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
$cachekey = 'count_contacts_project_'.$object->id;
$dataretrieved = dol_getcache($cachekey);
$nbContact = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); if (!is_null($dataretrieved)) {
$nbContacts = $dataretrieved;
} else {
$nbContacts = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external'));
dol_setcache($cachekey, $nbContact, 120); // If setting cache fails, this is not a problem, so we do not test result.
}
$head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$project->id; $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$project->id;
$head[$h][1] = $langs->trans("ProjectContact"); $head[$h][1] = $langs->trans("ProjectContact");
if ($nbContact > 0) { if ($nbContacts > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbContact.'</span>'; $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbContacts.'</span>';
} }
$head[$h][2] = 'contact'; $head[$h][2] = 'contact';
$h++; $h++;
if (empty($conf->global->PROJECT_HIDE_TASKS)) { if (empty($conf->global->PROJECT_HIDE_TASKS)) {
// Then tab for sub level of projet, i mean tasks // Then tab for sub level of projet, i mean tasks
$nbTasks = 0;
// Enable caching of project count Tasks
require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
$cachekey = 'count_tasks_project_'.$object->id;
$dataretrieved = dol_getcache($cachekey);
if (!is_null($dataretrieved)) {
$nbTasks = $dataretrieved;
} else {
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
$taskstatic = new Task($db);
$nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0));
dol_setcache($cachekey, $nbTasks, 120); // If setting cache fails, this is not a problem, so we do not test result.
}
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$project->id; $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$project->id;
$head[$h][1] = $langs->trans("Tasks"); $head[$h][1] = $langs->trans("Tasks");
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
$taskstatic = new Task($db);
$nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0));
if ($nbTasks > 0) { if ($nbTasks > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbTasks).'</span>'; $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbTasks).'</span>';
} }
@ -69,20 +89,28 @@ function project_prepare_head(Project $project)
$h++; $h++;
$nbTimeSpent = 0; $nbTimeSpent = 0;
$sql = "SELECT t.rowid"; // Enable caching of project count Timespent
//$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u"; $cachekey = 'count_timespent_project_'.$object->id;
//$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; $dataretrieved = dol_getcache($cachekey);
$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt"; if (!is_null($dataretrieved)) {
$sql .= " WHERE t.fk_task = pt.rowid"; $nbTimeSpent = $dataretrieved;
$sql .= " AND pt.fk_projet =".$project->id;
$resql = $db->query($sql);
if ($resql) {
$obj = $db->fetch_object($resql);
if ($obj) {
$nbTimeSpent = 1;
}
} else { } else {
dol_print_error($db); $sql = "SELECT t.rowid";
//$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u";
//$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt";
$sql .= " WHERE t.fk_task = pt.rowid";
$sql .= " AND pt.fk_projet =".$project->id;
$resql = $db->query($sql);
if ($resql) {
$obj = $db->fetch_object($resql);
if ($obj) {
$nbTimeSpent = 1;
dol_setcache($cachekey, $nbTimeSpent, 120); // If setting cache fails, this is not a problem, so we do not test result.
}
} else {
dol_print_error($db);
}
} }
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$project->id; $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$project->id;
@ -98,73 +126,78 @@ function project_prepare_head(Project $project)
|| !empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->commande->enabled)
|| !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled)
|| !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) {
$count = 0; $nbElements = 0;
// Enable caching of thirdrparty count Contacts
if (!empty($conf->propal->enabled)) { $cachekey = 'count_elements_project_'.$object->id;
$count += $project->getElementCount('propal', 'propal'); $dataretrieved = dol_getcache($cachekey);
if (!is_null($dataretrieved)) {
$nbElements = $dataretrieved;
} else {
if (!empty($conf->propal->enabled)) {
$count += $project->getElementCount('propal', 'propal');
}
if (!empty($conf->commande->enabled)) {
$count += $project->getElementCount('order', 'commande');
}
if (!empty($conf->facture->enabled)) {
$count += $project->getElementCount('invoice', 'facture');
}
if (!empty($conf->facture->enabled)) {
$count += $project->getElementCount('invoice_predefined', 'facture_rec');
}
if (!empty($conf->supplier_proposal->enabled)) {
$count += $project->getElementCount('proposal_supplier', 'supplier_proposal');
}
if (!empty($conf->supplier_order->enabled)) {
$count += $project->getElementCount('order_supplier', 'commande_fournisseur');
}
if (!empty($conf->supplier_invoice->enabled)) {
$count += $project->getElementCount('invoice_supplier', 'facture_fourn');
}
if (!empty($conf->contrat->enabled)) {
$count += $project->getElementCount('contract', 'contrat');
}
if (!empty($conf->ficheinter->enabled)) {
$count += $project->getElementCount('intervention', 'fichinter');
}
if (!empty($conf->expedition->enabled)) {
$count += $project->getElementCount('shipping', 'expedition');
}
if (!empty($conf->mrp->enabled)) {
$count += $project->getElementCount('mrp', 'mrp_mo', 'fk_project');
}
if (!empty($conf->deplacement->enabled)) {
$count += $project->getElementCount('trip', 'deplacement');
}
if (!empty($conf->expensereport->enabled)) {
$count += $project->getElementCount('expensereport', 'expensereport');
}
if (!empty($conf->don->enabled)) {
$count += $project->getElementCount('donation', 'don');
}
if (!empty($conf->loan->enabled)) {
$count += $project->getElementCount('loan', 'loan');
}
if (!empty($conf->tax->enabled)) {
$count += $project->getElementCount('chargesociales', 'chargesociales');
}
if (!empty($conf->projet->enabled)) {
$count += $project->getElementCount('project_task', 'projet_task');
}
if (!empty($conf->stock->enabled)) {
$count += $project->getElementCount('stock_mouvement', 'stock');
}
if (!empty($conf->salaries->enabled)) {
$count += $project->getElementCount('salaries', 'payment_salary');
}
if (!empty($conf->banque->enabled)) {
$count += $project->getElementCount('variouspayment', 'payment_various');
}
} }
if (!empty($conf->commande->enabled)) {
$count += $project->getElementCount('order', 'commande');
}
if (!empty($conf->facture->enabled)) {
$count += $project->getElementCount('invoice', 'facture');
}
if (!empty($conf->facture->enabled)) {
$count += $project->getElementCount('invoice_predefined', 'facture_rec');
}
if (!empty($conf->supplier_proposal->enabled)) {
$count += $project->getElementCount('proposal_supplier', 'supplier_proposal');
}
if (!empty($conf->supplier_order->enabled)) {
$count += $project->getElementCount('order_supplier', 'commande_fournisseur');
}
if (!empty($conf->supplier_invoice->enabled)) {
$count += $project->getElementCount('invoice_supplier', 'facture_fourn');
}
if (!empty($conf->contrat->enabled)) {
$count += $project->getElementCount('contract', 'contrat');
}
if (!empty($conf->ficheinter->enabled)) {
$count += $project->getElementCount('intervention', 'fichinter');
}
if (!empty($conf->expedition->enabled)) {
$count += $project->getElementCount('shipping', 'expedition');
}
if (!empty($conf->mrp->enabled)) {
$count += $project->getElementCount('mrp', 'mrp_mo', 'fk_project');
}
if (!empty($conf->deplacement->enabled)) {
$count += $project->getElementCount('trip', 'deplacement');
}
if (!empty($conf->expensereport->enabled)) {
$count += $project->getElementCount('expensereport', 'expensereport');
}
if (!empty($conf->don->enabled)) {
$count += $project->getElementCount('donation', 'don');
}
if (!empty($conf->loan->enabled)) {
$count += $project->getElementCount('loan', 'loan');
}
if (!empty($conf->tax->enabled)) {
$count += $project->getElementCount('chargesociales', 'chargesociales');
}
if (!empty($conf->projet->enabled)) {
$count += $project->getElementCount('project_task', 'projet_task');
}
if (!empty($conf->stock->enabled)) {
$count += $project->getElementCount('stock_mouvement', 'stock');
}
if (!empty($conf->salaries->enabled)) {
$count += $project->getElementCount('salaries', 'payment_salary');
}
if (!empty($conf->banque->enabled)) {
$count += $project->getElementCount('variouspayment', 'payment_various');
}
$head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$project->id; $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$project->id;
$head[$h][1] = $langs->trans("ProjectOverview"); $head[$h][1] = $langs->trans("ProjectOverview");
if ($count > 0) { if ($nbElements > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$count.'</span>'; $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbElements.'</span>';
} }
$head[$h][2] = 'element'; $head[$h][2] = 'element';
$h++; $h++;
@ -207,22 +240,44 @@ function project_prepare_head(Project $project)
$h++; $h++;
} }
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Attached files and Links
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $totalAttached = 0;
$upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref); // Enable caching of thirdrparty count attached files and links
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
$nbLinks = Link::count($db, $project->element, $project->id); $cachekey = 'count_attached_project_'.$object->id;
$dataretrieved = dol_getcache($cachekey);
if (!is_null($dataretrieved)) {
$totalAttached = $dataretrieved;
} else {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref);
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
$nbLinks = Link::count($db, $project->element, $project->id);
$totalAttached = $nbFiles + $nbLinks;
dol_setcache($cachekey, $totalAttached, 120); // If setting cache fails, this is not a problem, so we do not test result.
}
$head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$project->id; $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$project->id;
$head[$h][1] = $langs->trans('Documents'); $head[$h][1] = $langs->trans('Documents');
if (($nbFiles + $nbLinks) > 0) { if (($totalAttached) > 0) {
$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>'; $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($totalAttached).'</span>';
} }
$head[$h][2] = 'document'; $head[$h][2] = 'document';
$h++; $h++;
// Manage discussion // Manage discussion
if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) {
$nbComments = $project->getNbComments(); $nbComments = 0;
// Enable caching of thirdrparty count attached files and links
require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
$cachekey = 'count_attached_project_'.$object->id;
$dataretrieved = dol_getcache($cachekey);
if (!is_null($dataretrieved)) {
$nbComments = $dataretrieved;
} else {
$nbComments = $project->getNbComments();
dol_setcache($cachekey, $nbComments, 120); // If setting cache fails, this is not a problem, so we do not test result.
}
$head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$project->id; $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$project->id;
$head[$h][1] = $langs->trans("CommentLink"); $head[$h][1] = $langs->trans("CommentLink");
if ($nbComments > 0) { if ($nbComments > 0) {

View File

@ -125,3 +125,5 @@ ModuleReceiptPrinterMustBeEnabled=Module Receipt printer must have been enabled
AllowDelayedPayment=Allow delayed payment AllowDelayedPayment=Allow delayed payment
PrintPaymentMethodOnReceipts=Print payment method on tickets|receipts PrintPaymentMethodOnReceipts=Print payment method on tickets|receipts
WeighingScale=Weighing scale WeighingScale=Weighing scale
ShowPriceHT = Display the price excluding tax column
ShowPriceHTOnReceipt = Display the price excluding tax column on receipt

View File

@ -4590,7 +4590,7 @@ class Product extends CommonObject
$result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1)); $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
} }
if ($this->type == Product::TYPE_SERVICE) { if ($this->type == Product::TYPE_SERVICE) {
$result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddinright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1)); $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
} }
} }
$result .= $newref; $result .= $newref;

View File

@ -4,7 +4,7 @@
* Copyright (C) 2014 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2014 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr> * Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr>
* Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr> * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -353,12 +353,12 @@ print '<input type="hidden" name="mode" value="'.$mode.'">';
print '<div class="inline-block valignmiddle" style="padding-right: 20px;">'; print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
print '<span class="fieldrequired">'.$langs->trans('Date').'</span> '.$form->selectDate(($date ? $date : -1), 'date'); print '<span class="fieldrequired">'.$langs->trans('Date').'</span> '.$form->selectDate(($date ? $date : -1), 'date');
print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddinrightonly">&nbsp;</span> '; print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddingrightonly">&nbsp;</span> ';
print img_picto('', 'product').' '; print img_picto('', 'product').' ';
print $langs->trans('Product').'</span> '; print $langs->trans('Product').'</span> ';
$form->select_produits($productid, 'productid', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300'); $form->select_produits($productid, 'productid', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'maxwidth300');
print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddinrightonly">&nbsp;</span> '; print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddingrightonly">&nbsp;</span> ';
print img_picto('', 'stock').' '; print img_picto('', 'stock').' ';
print $langs->trans('Warehouse').'</span> '; print $langs->trans('Warehouse').'</span> ';
print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? $fk_warehouse : 'ifone'), 'fk_warehouse', '', 1); print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? $fk_warehouse : 'ifone'), 'fk_warehouse', '', 1);

View File

@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
// Load translation files required by the page // Load translation files required by the page
$langs->load('projects', 'enevntorganization'); $langs->load('projects', 'eventorganization');
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');
$id = GETPOST('id', 'int'); $id = GETPOST('id', 'int');
@ -45,7 +45,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ
// Security check // Security check
$socid = 0; $socid = 0;
if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. if ($user->socid > 0) {
$socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement.
}
$result = restrictedArea($user, 'eventorganization', $id); $result = restrictedArea($user, 'eventorganization', $id);
$permissiontoread = $user->rights->eventorganization->read; $permissiontoread = $user->rights->eventorganization->read;

View File

@ -1602,6 +1602,7 @@ class Societe extends CommonObject
$sql .= ', e.libelle as effectif'; $sql .= ', e.libelle as effectif';
$sql .= ', c.code as country_code, c.label as country'; $sql .= ', c.code as country_code, c.label as country';
$sql .= ', d.code_departement as state_code, d.nom as state'; $sql .= ', d.code_departement as state_code, d.nom as state';
$sql .= ', r.rowid as region_id, r.code_region as region_code';
$sql .= ', st.libelle as stcomm, st.picto as stcomm_picto'; $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
$sql .= ', te.code as typent_code'; $sql .= ', te.code as typent_code';
$sql .= ', i.libelle as label_incoterms'; $sql .= ', i.libelle as label_incoterms';
@ -1612,6 +1613,7 @@ class Societe extends CommonObject
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise as sr ON sr.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise as sr ON sr.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))';
@ -1689,6 +1691,8 @@ class Societe extends CommonObject
$this->state_id = $obj->state_id; $this->state_id = $obj->state_id;
$this->state_code = $obj->state_code; $this->state_code = $obj->state_code;
$this->region_id = $obj->region_id;
$this->region_code = $obj->region_code;
$this->state = ($obj->state != '-' ? $obj->state : ''); $this->state = ($obj->state != '-' ? $obj->state : '');
$transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm); $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);

View File

@ -2,6 +2,7 @@
/* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net> /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2019 Andreu Bisquerra Gaya <jove@bisquerra.com> * Copyright (C) 2019 Andreu Bisquerra Gaya <jove@bisquerra.com>
* Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -233,6 +234,14 @@ print '<td colspan="2">';
print $form->selectyesno("TAKEPOS_AUTO_PRINT_TICKETS", $conf->global->TAKEPOS_AUTO_PRINT_TICKETS, 1); print $form->selectyesno("TAKEPOS_AUTO_PRINT_TICKETS", $conf->global->TAKEPOS_AUTO_PRINT_TICKETS, 1);
print "</td></tr>\n"; print "</td></tr>\n";
// Show price without vat
print '<tr class="oddeven"><td>';
print $langs->trans('ShowPriceHTOnReceipt');
print '<td colspan="2">';
print ajax_constantonoff("TAKEPOS_SHOW_HT_RECEIPT", array(), $conf->entity, 0, 0, 1, 0);
print "</td></tr>\n";
if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) { if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) {
print '<tr class="oddeven"><td>'; print '<tr class="oddeven"><td>';
print $langs->trans('WeighingScale'); print $langs->trans('WeighingScale');

View File

@ -1,6 +1,7 @@
<?php <?php
/* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net> /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2011-2017 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -371,6 +372,13 @@ print '<td colspan="2">';
print ajax_constantonoff("TAKEPOS_DELAYED_PAYMENT", array(), $conf->entity, 0, 0, 1, 0); print ajax_constantonoff("TAKEPOS_DELAYED_PAYMENT", array(), $conf->entity, 0, 0, 1, 0);
print "</td></tr>\n"; print "</td></tr>\n";
// Show price without vat
print '<tr class="oddeven"><td>';
print $langs->trans('ShowPriceHT');
print '<td colspan="2">';
print ajax_constantonoff("TAKEPOS_SHOW_HT", array(), $conf->entity, 0, 0, 1, 0);
print "</td></tr>\n";
// Numbering module // Numbering module
//print '<tr class="oddeven"><td>'; //print '<tr class="oddeven"><td>';
//print $langs->trans("BillsNumberingModule"); //print $langs->trans("BillsNumberingModule");

View File

@ -1,6 +1,7 @@
<?php <?php
/** /**
* Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com> * Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com>
* Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -1120,7 +1121,10 @@ print '<!-- invoice.php place='.(int) $place.' invoice='.$invoice->ref.' mobilep
print '<div class="div-table-responsive-no-min invoice">'; print '<div class="div-table-responsive-no-min invoice">';
print '<table id="tablelines" class="noborder noshadow postablelines" width="100%">'; print '<table id="tablelines" class="noborder noshadow postablelines" width="100%">';
if ($sectionwithinvoicelink && ($mobilepage == "invoice" || $mobilepage == "")) { if ($sectionwithinvoicelink && ($mobilepage == "invoice" || $mobilepage == "")) {
print '<tr><td colspan="4">'.$sectionwithinvoicelink.'</td></tr>'; if (!empty($conf->global->TAKEPOS_SHOW_HT)) { print '<tr><td colspan="5">'.$sectionwithinvoicelink.'</td></tr>'; }
else {
print '<tr><td colspan="4">'.$sectionwithinvoicelink.'</td></tr>';
}
} }
print '<tr class="liste_titre nodrag nodrop">'; print '<tr class="liste_titre nodrag nodrop">';
print '<td class="linecoldescription">'; print '<td class="linecoldescription">';
@ -1154,6 +1158,23 @@ if ($_SESSION["basiclayout"] != 1)
{ {
print '<td class="linecolqty right">'.$langs->trans('ReductionShort').'</td>'; print '<td class="linecolqty right">'.$langs->trans('ReductionShort').'</td>';
print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>'; print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
if ($conf->global->TAKEPOS_SHOW_HT) {
print '<td class="linecolht right nowraponall">';
print '<span class="opacitymedium small">' . $langs->trans('TotalHTShort') . '</span><br>';
// In phone version only show when it is invoice page
if ($mobilepage == "invoice" || $mobilepage == "") {
print '<span id="linecolht-span-total" style="font-size:1.3em; font-weight: bold;">' . price($invoice->total_ht, 1, '', 1, -1, -1, $conf->currency) . '</span>';
if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
//Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
include_once DOL_DOCUMENT_ROOT . '/multicurrency/class/multicurrency.class.php';
$multicurrency = new MultiCurrency($db);
$multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
print '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">(' . price($invoice->total_ht * $multicurrency->rate->rate) . ' ' . $_SESSION["takeposcustomercurrency"] . ')</span>';
}
print '</td>';
}
print '</td>';
}
print '<td class="linecolht right nowraponall">'; print '<td class="linecolht right nowraponall">';
print '<span class="opacitymedium small">'.$langs->trans('TotalTTCShort').'</span><br>'; print '<span class="opacitymedium small">'.$langs->trans('TotalTTCShort').'</span><br>';
// In phone version only show when it is invoice page // In phone version only show when it is invoice page
@ -1373,6 +1394,18 @@ if ($placeid > 0)
} }
$htmlforlines .= '</td>'; $htmlforlines .= '</td>';
if ($conf->global->TAKEPOS_SHOW_HT) {
$htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
$htmlforlines .= price($line->total_ht, 1, '', 1, -1, -1, $conf->currency);
if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
//Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
$multicurrency = new MultiCurrency($db);
$multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
$htmlforlines .= '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($line->total_ht * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
}
$htmlforlines .= '</td>';
}
$htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">'; $htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
$htmlforlines .= price($line->total_ttc, 1, '', 1, -1, -1, $conf->currency); $htmlforlines .= price($line->total_ttc, 1, '', 1, -1, -1, $conf->currency);
if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) { if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
@ -1390,10 +1423,15 @@ if ($placeid > 0)
print $htmlforlines; print $htmlforlines;
} }
} else { } else {
print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td></tr>'; print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td>';
if (!empty($conf->global->TAKEPOS_SHOW_HT)){ print '<td></td>'; }
print '</tr>';
} }
} else { // No invoice generated yet } else { // No invoice generated yet
print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td></tr>'; print '<tr class="drag drop oddeven"><td class="left"><span class="opacitymedium">'.$langs->trans("Empty").'</span></td><td></td><td></td><td></td>';
if (!empty($conf->global->TAKEPOS_SHOW_HT)){ print '<td></td>'; }
print '</tr>';
} }
print '</table>'; print '</table>';

View File

@ -4,6 +4,7 @@
* Copyright (C) 2012 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2012 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com> * Copyright (C) 2018 Andreu Bisquerra <jove@bisquerra.com>
* Copyright (C) 2019 Josep Lluís Amador <joseplluis@lliuretic.cat> * Copyright (C) 2019 Josep Lluís Amador <joseplluis@lliuretic.cat>
* Copyright (C) 2021 Nicolas ZABOURI <info@inovea-conseil.com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -139,6 +140,9 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER)
<th class="center"><?php print $langs->trans("Label"); ?></th> <th class="center"><?php print $langs->trans("Label"); ?></th>
<th class="right"><?php print $langs->trans("Qty"); ?></th> <th class="right"><?php print $langs->trans("Qty"); ?></th>
<th class="right"><?php if ($gift != 1) print $langs->trans("Price"); ?></th> <th class="right"><?php if ($gift != 1) print $langs->trans("Price"); ?></th>
<?php if (!empty($conf->global->TAKEPOS_SHOW_HT_RECEIPT)) { ?>
<th class="right"><?php if ($gift != 1) print $langs->trans("TotalHT"); ?></th>
<?php } ?>
<th class="right"><?php if ($gift != 1) print $langs->trans("TotalTTC"); ?></th> <th class="right"><?php if ($gift != 1) print $langs->trans("TotalTTC"); ?></th>
</tr> </tr>
</thead> </thead>
@ -154,6 +158,12 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER)
</td> </td>
<td class="right"><?php echo $line->qty; ?></td> <td class="right"><?php echo $line->qty; ?></td>
<td class="right"><?php if ($gift != 1) echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); ?></td> <td class="right"><?php if ($gift != 1) echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); ?></td>
<?php
if (!empty($conf->global->TAKEPOS_SHOW_HT_RECEIPT)) { ?>
<td class="right"><?php if ($gift != 1) echo price($line->total_ht, 1); ?></td>
<?php
}
?>
<td class="right"><?php if ($gift != 1) echo price($line->total_ttc, 1); ?></td> <td class="right"><?php if ($gift != 1) echo price($line->total_ttc, 1); ?></td>
</tr> </tr>
<?php <?php

View File

@ -25,8 +25,9 @@ $langs->loadLangs(array("admin", "products"));
$action = GETPOST('action', 'alphanohtml'); $action = GETPOST('action', 'alphanohtml');
// Security check // Security check
if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) {
accessforbidden(); accessforbidden();
}
$error = 0; $error = 0;

View File

@ -16,11 +16,21 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOREQUIREMENU')) {
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';

View File

@ -15,11 +15,21 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOREQUIREMENU')) {
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';

View File

@ -16,12 +16,24 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disable token renewal if (!defined('NOTOKENRENEWAL')) {
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', '1'); // Disable token renewal
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); }
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); if (!defined('NOREQUIREMENU')) {
if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); define('NOREQUIREMENU', '1');
if (!defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); }
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
if (!defined('NOREQUIRETRAN')) {
define('NOREQUIRETRAN', '1');
}
require '../../main.inc.php'; require '../../main.inc.php';

View File

@ -41,7 +41,9 @@ if ($object->fetch($id) < 1) {
* Actions * Actions
*/ */
if ($cancel) $action = ''; if ($cancel) {
$action = '';
}
if ($action) { if ($action) {
if ($action == 'update') { if ($action == 'update') {
@ -60,19 +62,16 @@ if ($action) {
$objectval->ref = $ref; $objectval->ref = $ref;
$objectval->value = GETPOST('value', 'alpha'); $objectval->value = GETPOST('value', 'alpha');
if (empty($objectval->ref)) if (empty($objectval->ref)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors');
} }
if (empty($objectval->value)) if (empty($objectval->value)) {
{
$error++; $error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
} }
if (!$error) if (!$error) {
{
if ($objectval->update($user) > 0) { if ($objectval->update($user) > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
} else { } else {
@ -102,8 +101,7 @@ if ($confirm == 'yes') {
header('Location: '.dol_buildpath('/variants/list.php', 2)); header('Location: '.dol_buildpath('/variants/list.php', 2));
} }
exit(); exit();
} elseif ($action == 'confirm_deletevalue') } elseif ($action == 'confirm_deletevalue') {
{
if ($objectval->fetch($valueid) > 0) { if ($objectval->fetch($valueid) > 0) {
if ($objectval->delete($user) < 1) { if ($objectval->delete($user) < 1) {
setEventMessages($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors'); setEventMessages($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors');

View File

@ -116,8 +116,7 @@ class ProductAttribute extends CommonObject
$sql = 'SELECT rowid, ref, ref_ext, label, rang FROM '.MAIN_DB_PREFIX."product_attribute WHERE entity IN (".getEntity('product').')'; $sql = 'SELECT rowid, ref, ref_ext, label, rang FROM '.MAIN_DB_PREFIX."product_attribute WHERE entity IN (".getEntity('product').')';
$sql .= $this->db->order('rang', 'asc'); $sql .= $this->db->order('rang', 'asc');
$query = $this->db->query($sql); $query = $this->db->query($sql);
if ($query) if ($query) {
{
while ($result = $this->db->fetch_object($query)) { while ($result = $this->db->fetch_object($query)) {
$tmp = new ProductAttribute($this->db); $tmp = new ProductAttribute($this->db);
$tmp->id = $result->rowid; $tmp->id = $result->rowid;
@ -128,8 +127,9 @@ class ProductAttribute extends CommonObject
$return[] = $tmp; $return[] = $tmp;
} }
} else {
dol_print_error($this->db);
} }
else dol_print_error($this->db);
return $return; return $return;
} }
@ -159,8 +159,7 @@ class ProductAttribute extends CommonObject
VALUES ('".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->escape($this->label)."', ".(int) $this->entity.", ".(int) $this->rang.")"; VALUES ('".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->escape($this->label)."', ".(int) $this->entity.", ".(int) $this->rang.")";
$query = $this->db->query($sql); $query = $this->db->query($sql);
if ($query) if ($query) {
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute'); $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute');
return $this->id; return $this->id;

View File

@ -174,8 +174,7 @@ class ProductCombination
*/ */
if ($fk_price_level > 0) { if ($fk_price_level > 0) {
$combination_price_levels[$fk_price_level] = ProductCombinationLevel::createFromParent($this->db, $this, $fk_price_level); $combination_price_levels[$fk_price_level] = ProductCombinationLevel::createFromParent($this->db, $this, $fk_price_level);
} } else {
else {
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
$combination_price_levels[$i] = ProductCombinationLevel::createFromParent($this->db, $this, $i); $combination_price_levels[$i] = ProductCombinationLevel::createFromParent($this->db, $this, $i);
} }
@ -227,8 +226,7 @@ class ProductCombination
if ($error) { if ($error) {
return $error * -1; return $error * -1;
} } else {
else {
return 1; return 1;
} }
} }
@ -327,7 +325,9 @@ class ProductCombination
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) { if ($resql) {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) $nb = $obj->nb; if ($obj) {
$nb = $obj->nb;
}
} }
return $nb; return $nb;
@ -507,8 +507,7 @@ class ProductCombination
// MultiPrix // MultiPrix
if (!empty($conf->global->PRODUIT_MULTIPRICES)) { if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
{
if ($parent->multiprices[$i] != '' || isset($this->combination_price_levels[$i]->variation_price)) { if ($parent->multiprices[$i] != '' || isset($this->combination_price_levels[$i]->variation_price)) {
$new_type = $parent->multiprices_base_type[$i]; $new_type = $parent->multiprices_base_type[$i];
$new_min_price = $parent->multiprices_min[$i]; $new_min_price = $parent->multiprices_min[$i];
@ -710,8 +709,7 @@ class ProductCombination
//Final price impact //Final price impact
if (!is_array($forced_pricevar)) { if (!is_array($forced_pricevar)) {
$price_impact[1] = (float) $forced_pricevar; // If false, return 0 $price_impact[1] = (float) $forced_pricevar; // If false, return 0
} } else {
else {
$price_impact = $forced_pricevar; $price_impact = $forced_pricevar;
} }
@ -766,8 +764,7 @@ class ProductCombination
// Manage Price levels // Manage Price levels
if ($conf->global->PRODUIT_MULTIPRICES) { if ($conf->global->PRODUIT_MULTIPRICES) {
for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
{
$price_impact[$i] += (float) price2num($variations[$currcombattr][$currcombval]['price']); $price_impact[$i] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
} }
} }
@ -827,8 +824,7 @@ class ProductCombination
$newproduct->barcode = -1; $newproduct->barcode = -1;
$result = $newproduct->create($user); $result = $newproduct->create($user);
if ($result < 0) if ($result < 0) {
{
//In case the error is not related with an already existing product //In case the error is not related with an already existing product
if ($newproduct->error != 'ErrorProductAlreadyExists') { if ($newproduct->error != 'ErrorProductAlreadyExists') {
$this->error[] = $newproduct->error; $this->error[] = $newproduct->error;
@ -868,8 +864,7 @@ class ProductCombination
} }
} else { } else {
$result = $newproduct->update($newproduct->id, $user); $result = $newproduct->update($newproduct->id, $user);
if ($result < 0) if ($result < 0) {
{
$this->db->rollback(); $this->db->rollback();
return -1; return -1;
} }
@ -877,8 +872,7 @@ class ProductCombination
$newcomb->fk_product_child = $newproduct->id; $newcomb->fk_product_child = $newproduct->id;
if ($newcomb->update($user) < 0) if ($newcomb->update($user) < 0) {
{
$this->error = $newcomb->error; $this->error = $newcomb->error;
$this->errors = $newcomb->errors; $this->errors = $newcomb->errors;
$this->db->rollback(); $this->db->rollback();
@ -926,8 +920,7 @@ class ProductCombination
$combination->variation_price_percentage, $combination->variation_price_percentage,
$combination->variation_price, $combination->variation_price,
$combination->variation_weight $combination->variation_weight
) < 0) ) < 0) {
{
return -1; return -1;
} }
} }
@ -955,12 +948,10 @@ class ProductCombination
$i = 0; $i = 0;
while ($i < $num) while ($i < $num) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj->label) if ($obj->label) {
{
$label .= ' '.$obj->label; $label .= ' '.$obj->label;
} }
$i++; $i++;

View File

@ -58,8 +58,7 @@ $prodattr = new ProductAttribute($db);
$prodattr_val = new ProductAttributeValue($db); $prodattr_val = new ProductAttributeValue($db);
$object = new Product($db); $object = new Product($db);
if ($id > 0 || $ref) if ($id > 0 || $ref) {
{
$object->fetch($id, $ref); $object->fetch($id, $ref);
} }
@ -80,16 +79,13 @@ if (!$object->isProduct() && !$object->isService()) {
header('Location: '.dol_buildpath('/product/card.php?id='.$object->id, 2)); header('Location: '.dol_buildpath('/product/card.php?id='.$object->id, 2));
exit(); exit();
} }
if ($action == 'add') if ($action == 'add') {
{
unset($selectedvariant); unset($selectedvariant);
unset($_SESSION['addvariant_'.$object->id]); unset($_SESSION['addvariant_'.$object->id]);
} }
if ($action == 'create' && GETPOST('selectvariant', 'alpha')) // We click on select combination if ($action == 'create' && GETPOST('selectvariant', 'alpha')) { // We click on select combination
{
$action = 'add'; $action = 'add';
if (GETPOST('attribute') != '-1' && GETPOST('value') != '-1') if (GETPOST('attribute') != '-1' && GETPOST('value') != '-1') {
{
$selectedvariant[GETPOST('attribute').':'.GETPOST('value')] = GETPOST('attribute').':'.GETPOST('value'); $selectedvariant[GETPOST('attribute').':'.GETPOST('value')] = GETPOST('attribute').':'.GETPOST('value');
$_SESSION['addvariant_'.$object->id] = $selectedvariant; $_SESSION['addvariant_'.$object->id] = $selectedvariant;
} }
@ -101,8 +97,7 @@ $prodcomb2val = new ProductCombination2ValuePair($db);
$productCombination2ValuePairs1 = array(); $productCombination2ValuePairs1 = array();
if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha')) // We click on Create all defined combinations if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha')) { // We click on Create all defined combinations
{
//$features = GETPOST('features', 'array'); //$features = GETPOST('features', 'array');
$features = $_SESSION['addvariant_'.$object->id]; $features = $_SESSION['addvariant_'.$object->id];
@ -121,8 +116,7 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST(
// for conf PRODUIT_MULTIPRICES // for conf PRODUIT_MULTIPRICES
if ($conf->global->PRODUIT_MULTIPRICES) { if ($conf->global->PRODUIT_MULTIPRICES) {
$level_price_impact = array_map('price2num', $level_price_impact); $level_price_impact = array_map('price2num', $level_price_impact);
} } else {
else {
$level_price_impact = array(1 => $price_impact); $level_price_impact = array(1 => $price_impact);
$level_price_impact_percent = array(1 => $price_impact_percent); $level_price_impact_percent = array(1 => $price_impact_percent);
} }
@ -156,11 +150,9 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST(
// sanit_feature is an array with 1 (and only 1) value per attribute. // sanit_feature is an array with 1 (and only 1) value per attribute.
// For example: Color->blue, Size->Small, Option->2 // For example: Color->blue, Size->Small, Option->2
//var_dump($sanit_features); //var_dump($sanit_features);
if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $sanit_features)) if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $sanit_features)) {
{
$result = $prodcomb->createProductCombination($user, $object, $sanit_features, array(), $level_price_impact_percent, $level_price_impact, $weight_impact, $reference); $result = $prodcomb->createProductCombination($user, $object, $sanit_features, array(), $level_price_impact_percent, $level_price_impact, $weight_impact, $reference);
if ($result > 0) if ($result > 0) {
{
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
unset($_SESSION['addvariant_'.$object->id]); unset($_SESSION['addvariant_'.$object->id]);
@ -243,8 +235,7 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST(
$prodcomb->variation_price = $level_price_impact[1]; $prodcomb->variation_price = $level_price_impact[1];
$prodcomb->variation_price_percentage = (bool) $level_price_impact_percent[1]; $prodcomb->variation_price_percentage = (bool) $level_price_impact_percent[1];
} } else {
else {
$level_price_impact = array(1 => $price_impact); $level_price_impact = array(1 => $price_impact);
$level_price_impact_percent = array(1 => $price_impact_percent); $level_price_impact_percent = array(1 => $price_impact_percent);
@ -330,12 +321,13 @@ if ($action === 'confirm_deletecombination') {
$form = new Form($db); $form = new Form($db);
if (!empty($id) || !empty($ref)) if (!empty($id) || !empty($ref)) {
{
llxHeader("", "", $langs->trans("CardProduct".$object->type)); llxHeader("", "", $langs->trans("CardProduct".$object->type));
$showbarcode = empty($conf->barcode->enabled) ? 0 : 1; $showbarcode = empty($conf->barcode->enabled) ? 0 : 1;
if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0; if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
$showbarcode = 0;
}
$head = product_prepare_head($object); $head = product_prepare_head($object);
$titre = $langs->trans("CardProduct".$object->type); $titre = $langs->trans("CardProduct".$object->type);
@ -357,17 +349,25 @@ if (!empty($id) || !empty($ref))
print '<tr><td class="titlefield">'.$langs->trans("DefaultTaxRate").'</td><td>'; print '<tr><td class="titlefield">'.$langs->trans("DefaultTaxRate").'</td><td>';
$positiverates = ''; $positiverates = '';
if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); if (price2num($object->tva_tx)) {
if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx);
if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); }
if (empty($positiverates)) $positiverates = '0'; if (price2num($object->localtax1_type)) {
$positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx);
}
if (price2num($object->localtax2_type)) {
$positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx);
}
if (empty($positiverates)) {
$positiverates = '0';
}
echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr);
/* /*
if ($object->default_vat_code) if ($object->default_vat_code)
{ {
print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
} }
else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/ else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/
print '</td></tr>'; print '</td></tr>';
// Price // Price
@ -390,8 +390,7 @@ if (!empty($id) || !empty($ref))
// Weight // Weight
print '<tr><td>'.$langs->trans("Weight").'</td><td>'; print '<tr><td>'.$langs->trans("Weight").'</td><td>';
if ($object->weight != '') if ($object->weight != '') {
{
print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units); print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units);
} else { } else {
print '&nbsp;'; print '&nbsp;';
@ -466,14 +465,14 @@ if (!empty($id) || !empty($ref))
foreach ($productCombination2ValuePairs1 as $pc2v) { foreach ($productCombination2ValuePairs1 as $pc2v) {
$prodattr_val->fetch($pc2v->fk_prod_attr_val); $prodattr_val->fetch($pc2v->fk_prod_attr_val);
?> ?>
variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>); variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = { variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>], attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
value: { value: {
id: <?php echo $pc2v->fk_prod_attr_val ?>, id: <?php echo $pc2v->fk_prod_attr_val ?>,
label: '<?php echo $prodattr_val->value ?>' label: '<?php echo $prodattr_val->value ?>'
} }
}; };
<?php <?php
} }
?> ?>
@ -604,8 +603,7 @@ if (!empty($id) || !empty($ref))
print '<table class="border" style="width: 100%">'; print '<table class="border" style="width: 100%">';
// When in edit mode // When in edit mode
if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
{
?> ?>
<tr> <tr>
<td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Combination') ?></label></td> <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Combination') ?></label></td>
@ -616,8 +614,7 @@ if (!empty($id) || !empty($ref))
$result1 = $prodattr->fetch($val->fk_prod_attr); $result1 = $prodattr->fetch($val->fk_prod_attr);
$result2 = $prodattr_val->fetch($val->fk_prod_attr_val); $result2 = $prodattr_val->fetch($val->fk_prod_attr_val);
//print 'rr'.$result1.' '.$result2; //print 'rr'.$result1.' '.$result2;
if ($result1 > 0 && $result2 > 0) if ($result1 > 0 && $result2 > 0) {
{
print $prodattr->label.' - '.$prodattr_val->value.'<br>'; print $prodattr->label.' - '.$prodattr_val->value.'<br>';
// TODO Add delete link // TODO Add delete link
} }
@ -651,8 +648,7 @@ if (!empty($id) || !empty($ref))
} else { } else {
$prodcomb->fetchCombinationPriceLevels(); $prodcomb->fetchCombinationPriceLevels();
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
{
print '<tr>'; print '<tr>';
print '<td><label for="level_price_impact_'.$i.'">'.$langs->trans('ImpactOnPriceLevel', $i).'</label>'; print '<td><label for="level_price_impact_'.$i.'">'.$langs->trans('ImpactOnPriceLevel', $i).'</label>';
if ($i === 1) { if ($i === 1) {
@ -703,7 +699,9 @@ if (!empty($id) || !empty($ref))
?> ?>
<div style="text-align: center"> <div style="text-align: center">
<input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) print ' disabled="disabled"'; ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save"> <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
print ' disabled="disabled"';
} ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
&nbsp; &nbsp;
<input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel"> <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
</div> </div>
@ -732,8 +730,7 @@ if (!empty($id) || !empty($ref))
$comb2val = new ProductCombination2ValuePair($db); $comb2val = new ProductCombination2ValuePair($db);
if ($productCombinations) if ($productCombinations) {
{
?> ?>
<script type="text/javascript"> <script type="text/javascript">
@ -767,8 +764,7 @@ if (!empty($id) || !empty($ref))
print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
if ($productCombinations) if ($productCombinations) {
{
print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>'; print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
} }
@ -791,8 +787,8 @@ if (!empty($id) || !empty($ref))
// List of mass actions available // List of mass actions available
/* /*
$arrayofmassactions = array( $arrayofmassactions = array(
'presend'=>$langs->trans("SendByMail"), 'presend'=>$langs->trans("SendByMail"),
'builddoc'=>$langs->trans("PDFMerge"), 'builddoc'=>$langs->trans("PDFMerge"),
); );
if ($user->rights->product->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); if ($user->rights->product->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();
@ -800,8 +796,7 @@ if (!empty($id) || !empty($ref))
*/ */
$aaa = ''; $aaa = '';
if (count($productCombinations)) if (count($productCombinations)) {
{
$aaa = '<label for="massaction">'.$langs->trans('BulkActions').'</label>'; $aaa = '<label for="massaction">'.$langs->trans('BulkActions').'</label>';
$aaa .= '<select id="bulk_action" name="massaction" class="flat">'; $aaa .= '<select id="bulk_action" name="massaction" class="flat">';
$aaa .= ' <option value="nothing">&nbsp;</option>'; $aaa .= ' <option value="nothing">&nbsp;</option>';
@ -826,11 +821,13 @@ if (!empty($id) || !empty($ref))
<td class="liste_titre"><?php echo $langs->trans('Product') ?></td> <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
<td class="liste_titre"><?php echo $langs->trans('Combination') ?></td> <td class="liste_titre"><?php echo $langs->trans('Combination') ?></td>
<td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td> <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
<?php if ($object->isProduct()) print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>'; ?> <?php if ($object->isProduct()) {
print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
} ?>
<td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td> <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
<td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td> <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
<td class="liste_titre"></td> <td class="liste_titre"></td>
<?php <?php
print '<td class="liste_titre center">'; print '<td class="liste_titre center">';
$searchpicto = $form->showCheckAddButtons('checkforselect', 1); $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
print $searchpicto; print $searchpicto;
@ -839,10 +836,8 @@ if (!empty($id) || !empty($ref))
</tr> </tr>
<?php <?php
if (count($productCombinations)) if (count($productCombinations)) {
{ foreach ($productCombinations as $currcomb) {
foreach ($productCombinations as $currcomb)
{
$prodstatic->fetch($currcomb->fk_product_child); $prodstatic->fetch($currcomb->fk_product_child);
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td>'.$prodstatic->getNomUrl(1).'</td>'; print '<td>'.$prodstatic->getNomUrl(1).'</td>';
@ -869,10 +864,11 @@ if (!empty($id) || !empty($ref))
print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&valueid='.$currcomb->id.'">'.img_delete().'</a>'; print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&valueid='.$currcomb->id.'">'.img_delete().'</a>';
print '</td>'; print '</td>';
print '<td class="nowrap center">'; print '<td class="nowrap center">';
if ($productCombinations || $massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined if ($productCombinations || $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($prodstatic->id, $arrayofselected)) $selected = 1; if (in_array($prodstatic->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>'; print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
} }
print '</td>'; print '</td>';

View File

@ -40,8 +40,7 @@ if ($action == 'add') {
$resid = $prodattr->create($user); $resid = $prodattr->create($user);
if ($resid > 0) { if ($resid > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
if ($backtopage) if ($backtopage) {
{
header('Location: '.$backtopage); header('Location: '.$backtopage);
} else { } else {
header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$resid.'&backtopage='.urlencode($backtopage)); header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$resid.'&backtopage='.urlencode($backtopage));

View File

@ -41,8 +41,7 @@ if ($object->fetch($id) < 1) {
* Actions * Actions
*/ */
if ($cancel) if ($cancel) {
{
$action = ''; $action = '';
header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id); header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id);
exit(); exit();
@ -56,8 +55,7 @@ if ($cancel)
* View * View
*/ */
if ($action == 'add') if ($action == 'add') {
{
if (empty($ref) || empty($value)) { if (empty($ref) || empty($value)) {
setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors'); setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors');
} else { } else {

View File

@ -56,8 +56,7 @@ $variants = $object->fetchAll();
llxHeader('', $title); llxHeader('', $title);
$newcardbutton = ''; $newcardbutton = '';
if ($user->rights->produit->creer) if ($user->rights->produit->creer) {
{
$newcardbutton .= dolGetButtonTitle($langs->trans('Create'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/create.php'); $newcardbutton .= dolGetButtonTitle($langs->trans('Create'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/create.php');
} }

View File

@ -29,26 +29,24 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
$langs->load("admin"); $langs->load("admin");
if (!$user->admin) if (!$user->admin) {
accessforbidden(); accessforbidden();
}
$actionsave = GETPOST("save"); $actionsave = GETPOST("save");
// Sauvegardes parametres // Sauvegardes parametres
if ($actionsave) if ($actionsave) {
{
$i = 0; $i = 0;
$db->begin(); $db->begin();
$i += dolibarr_set_const($db, 'WEBSERVICES_KEY', GETPOST("WEBSERVICES_KEY"), 'chaine', 0, '', $conf->entity); $i += dolibarr_set_const($db, 'WEBSERVICES_KEY', GETPOST("WEBSERVICES_KEY"), 'chaine', 0, '', $conf->entity);
if ($i >= 1) if ($i >= 1) {
{
$db->commit(); $db->commit();
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
} } else {
else {
$db->rollback(); $db->rollback();
setEventMessages($langs->trans("Error"), null, 'errors'); setEventMessages($langs->trans("Error"), null, 'errors');
} }
@ -84,8 +82,9 @@ print "</tr>";
print '<tr class="oddeven">'; print '<tr class="oddeven">';
print '<td class="fieldrequired">'.$langs->trans("KeyForWebServicesAccess").'</td>'; print '<td class="fieldrequired">'.$langs->trans("KeyForWebServicesAccess").'</td>';
print '<td><input type="text" class="flat" id="WEBSERVICES_KEY" name="WEBSERVICES_KEY" value="'.(GETPOST('WEBSERVICES_KEY') ?GETPOST('WEBSERVICES_KEY') : (!empty($conf->global->WEBSERVICES_KEY) ? $conf->global->WEBSERVICES_KEY : '')).'" size="40">'; print '<td><input type="text" class="flat" id="WEBSERVICES_KEY" name="WEBSERVICES_KEY" value="'.(GETPOST('WEBSERVICES_KEY') ?GETPOST('WEBSERVICES_KEY') : (!empty($conf->global->WEBSERVICES_KEY) ? $conf->global->WEBSERVICES_KEY : '')).'" size="40">';
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"'); print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"');
}
print '</td>'; print '</td>';
print '<td>&nbsp;</td>'; print '<td>&nbsp;</td>';
print '</tr>'; print '</tr>';
@ -118,9 +117,10 @@ $webservices = array(
// WSDL // WSDL
print '<u>'.$langs->trans("WSDLCanBeDownloadedHere").':</u><br>'; print '<u>'.$langs->trans("WSDLCanBeDownloadedHere").':</u><br>';
foreach ($webservices as $name => $right) foreach ($webservices as $name => $right) {
{ if (!empty($right) && !verifCond($right)) {
if (!empty($right) && !verifCond($right)) continue; continue;
}
$url = DOL_MAIN_URL_ROOT.'/webservices/server_'.$name.'.php?wsdl'; $url = DOL_MAIN_URL_ROOT.'/webservices/server_'.$name.'.php?wsdl';
print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n"; print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
} }
@ -129,9 +129,10 @@ print '<br>';
// Endpoint // Endpoint
print '<u>'.$langs->trans("EndPointIs").':</u><br>'; print '<u>'.$langs->trans("EndPointIs").':</u><br>';
foreach ($webservices as $name => $right) foreach ($webservices as $name => $right) {
{ if (!empty($right) && !verifCond($right)) {
if (!empty($right) && !verifCond($right)) continue; continue;
}
$url = DOL_MAIN_URL_ROOT.'/webservices/server_'.$name.'.php'; $url = DOL_MAIN_URL_ROOT.'/webservices/server_'.$name.'.php';
print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n"; print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
} }
@ -141,8 +142,7 @@ print '<br>';
print '<br>'; print '<br>';
print $langs->trans("OnlyActiveElementsAreShown", DOL_URL_ROOT.'/admin/modules.php'); print $langs->trans("OnlyActiveElementsAreShown", DOL_URL_ROOT.'/admin/modules.php');
if (!empty($conf->use_javascript_ajax)) if (!empty($conf->use_javascript_ajax)) {
{
print "\n".'<script type="text/javascript">'; print "\n".'<script type="text/javascript">';
print '$(document).ready(function () { print '$(document).ready(function () {
$("#generate_token").click(function() { $("#generate_token").click(function() {

View File

@ -38,8 +38,7 @@ $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces"); dol_syslog("Call Dolibarr webservices interfaces");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';

View File

@ -23,7 +23,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require "../master.inc.php"; require "../master.inc.php";
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -37,8 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
dol_syslog("Call ActionComm webservices interfaces"); dol_syslog("Call ActionComm webservices interfaces");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -122,18 +123,21 @@ $extrafield_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_array = array(); $extrafield_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_array)) $actioncomm_fields = array_merge($actioncomm_fields, $extrafield_array); if (is_array($extrafield_array)) {
$actioncomm_fields = array_merge($actioncomm_fields, $extrafield_array);
}
// Define other specific objects // Define other specific objects
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
@ -255,7 +259,9 @@ function getActionComm($authentication, $id)
dol_syslog("Function: getActionComm login=".$authentication['login']." id=".$id); dol_syslog("Function: getActionComm login=".$authentication['login']." id=".$id);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -263,22 +269,18 @@ function getActionComm($authentication, $id)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if ($error || (!$id)) if ($error || (!$id)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->agenda->allactions->read) if ($fuser->rights->agenda->allactions->read) {
{
$actioncomm = new ActionComm($db); $actioncomm = new ActionComm($db);
$result = $actioncomm->fetch($id); $result = $actioncomm->fetch($id);
if ($result > 0) if ($result > 0) {
{
$actioncomm_result_fields = array( $actioncomm_result_fields = array(
'id' => $actioncomm->id, 'id' => $actioncomm->id,
'ref'=> $actioncomm->ref, 'ref'=> $actioncomm->ref,
@ -315,10 +317,8 @@ function getActionComm($authentication, $id)
//Get extrafield values //Get extrafield values
$actioncomm->fetch_optionals(); $actioncomm->fetch_optionals();
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$actioncomm_result_fields = array_merge($actioncomm_result_fields, array('options_'.$key => $actioncomm->array_options['options_'.$key])); $actioncomm_result_fields = array_merge($actioncomm_result_fields, array('options_'.$key => $actioncomm->array_options['options_'.$key]));
} }
} }
@ -327,20 +327,17 @@ function getActionComm($authentication, $id)
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'actioncomm'=>$actioncomm_result_fields); 'actioncomm'=>$actioncomm_result_fields);
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -360,7 +357,9 @@ function getListActionCommType($authentication)
dol_syslog("Function: getListActionCommType login=".$authentication['login']); dol_syslog("Function: getListActionCommType login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -368,18 +367,15 @@ function getListActionCommType($authentication)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->agenda->myactions->read) if ($fuser->rights->agenda->myactions->read) {
{
$cactioncomm = new CActionComm($db); $cactioncomm = new CActionComm($db);
$result = $cactioncomm->liste_array('', 'code'); $result = $cactioncomm->liste_array('', 'code');
if ($result > 0) if ($result > 0) {
{
$resultarray = array(); $resultarray = array();
foreach ($cactioncomm->liste_array as $code=>$libeller) { foreach ($cactioncomm->liste_array as $code => $libeller) {
$resultarray[] = array('code'=>$code, 'libelle'=>$libeller); $resultarray[] = array('code'=>$code, 'libelle'=>$libeller);
} }
@ -396,8 +392,7 @@ function getListActionCommType($authentication)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -420,7 +415,9 @@ function createActionComm($authentication, $actioncomm)
dol_syslog("Function: createActionComm login=".$authentication['login']); dol_syslog("Function: createActionComm login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -428,8 +425,7 @@ function createActionComm($authentication, $actioncomm)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if (!$error) if (!$error) {
{
$newobject = new ActionComm($db); $newobject = new ActionComm($db);
$newobject->datep = $actioncomm['datep']; $newobject->datep = $actioncomm['datep'];
@ -454,10 +450,8 @@ function createActionComm($authentication, $actioncomm)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$newobject->array_options[$key] = $actioncomm[$key]; $newobject->array_options[$key] = $actioncomm[$key];
} }
@ -466,17 +460,14 @@ function createActionComm($authentication, $actioncomm)
$db->begin(); $db->begin();
$result = $newobject->create($fuser); $result = $newobject->create($fuser);
if ($result <= 0) if ($result <= 0) {
{
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -484,8 +475,7 @@ function createActionComm($authentication, $actioncomm)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -507,7 +497,9 @@ function updateActionComm($authentication, $actioncomm)
dol_syslog("Function: updateActionComm login=".$authentication['login']); dol_syslog("Function: updateActionComm login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -519,8 +511,7 @@ function updateActionComm($authentication, $actioncomm)
$error++; $errorcode = 'KO'; $errorlabel = "Actioncomm id is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Actioncomm id is mandatory.";
} }
if (!$error) if (!$error) {
{
$objectfound = false; $objectfound = false;
$object = new ActionComm($db); $object = new ActionComm($db);
@ -551,10 +542,8 @@ function updateActionComm($authentication, $actioncomm)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$object->array_options[$key] = $actioncomm[$key]; $object->array_options[$key] = $actioncomm[$key];
} }
@ -568,16 +557,13 @@ function updateActionComm($authentication, $actioncomm)
} }
} }
if ((!$error) && ($objectfound)) if ((!$error) && ($objectfound)) {
{
$db->commit(); $db->commit();
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'id'=>$object->id 'id'=>$object->id
); );
} } elseif ($objectfound) {
elseif ($objectfound)
{
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -589,8 +575,7 @@ function updateActionComm($authentication, $actioncomm)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -21,7 +21,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require "../master.inc.php"; require "../master.inc.php";
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -32,8 +34,7 @@ require_once DOL_DOCUMENT_ROOT."/categories/class/categorie.class.php";
dol_syslog("Call Dolibarr webservices interfaces"); dol_syslog("Call Dolibarr webservices interfaces");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -109,12 +110,12 @@ $server->wsdl->addComplexType(
* Image of product * Image of product
*/ */
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'PhotosArray', 'PhotosArray',
'complexType', 'complexType',
'array', 'array',
'sequence', 'sequence',
'', '',
array( array(
'image' => array( 'image' => array(
'name' => 'image', 'name' => 'image',
'type' => 'tns:image', 'type' => 'tns:image',
@ -128,12 +129,12 @@ $server->wsdl->addComplexType(
* An image * An image
*/ */
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'image', 'image',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'photo' => array('name'=>'photo', 'type'=>'xsd:string'), 'photo' => array('name'=>'photo', 'type'=>'xsd:string'),
'photo_vignette' => array('name'=>'photo_vignette', 'type'=>'xsd:string'), 'photo_vignette' => array('name'=>'photo_vignette', 'type'=>'xsd:string'),
'imgWidth' => array('name'=>'imgWidth', 'type'=>'xsd:string'), 'imgWidth' => array('name'=>'imgWidth', 'type'=>'xsd:string'),
@ -194,30 +195,28 @@ function getCategory($authentication, $id)
dol_syslog("Function: getCategory login=".$authentication['login']." id=".$id); dol_syslog("Function: getCategory login=".$authentication['login']." id=".$id);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if (!$error && !$id) if (!$error && !$id) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id must be provided."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id must be provided.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
$nbmax = 10; $nbmax = 10;
if ($fuser->rights->categorie->lire) if ($fuser->rights->categorie->lire) {
{
$categorie = new Categorie($db); $categorie = new Categorie($db);
$result = $categorie->fetch($id); $result = $categorie->fetch($id);
if ($result > 0) if ($result > 0) {
{
$dir = (!empty($conf->categorie->dir_output) ? $conf->categorie->dir_output : $conf->service->dir_output); $dir = (!empty($conf->categorie->dir_output) ? $conf->categorie->dir_output : $conf->service->dir_output);
$pdir = get_exdir($categorie->id, 2, 0, 0, $categorie, 'category').$categorie->id."/photos/"; $pdir = get_exdir($categorie->id, 2, 0, 0, $categorie, 'category').$categorie->id."/photos/";
$dir = $dir.'/'.$pdir; $dir = $dir.'/'.$pdir;
@ -235,10 +234,8 @@ function getCategory($authentication, $id)
); );
$cats = $categorie->get_filles(); $cats = $categorie->get_filles();
if (count($cats) > 0) if (count($cats) > 0) {
{ foreach ($cats as $fille) {
foreach ($cats as $fille)
{
$dir = (!empty($conf->categorie->dir_output) ? $conf->categorie->dir_output : $conf->service->dir_output); $dir = (!empty($conf->categorie->dir_output) ? $conf->categorie->dir_output : $conf->service->dir_output);
$pdir = get_exdir($fille->id, 2, 0, 0, $categorie, 'category').$fille->id."/photos/"; $pdir = get_exdir($fille->id, 2, 0, 0, $categorie, 'category').$fille->id."/photos/";
$dir = $dir.'/'.$pdir; $dir = $dir.'/'.$pdir;
@ -261,20 +258,17 @@ function getCategory($authentication, $id)
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'categorie'=> $cat 'categorie'=> $cat
); );
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -21,7 +21,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require "../master.inc.php"; require "../master.inc.php";
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -33,8 +35,7 @@ require_once DOL_DOCUMENT_ROOT."/core/class/extrafields.class.php";
dol_syslog("Call Contact webservices interfaces"); dol_syslog("Call Contact webservices interfaces");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -127,18 +128,21 @@ $extrafield_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_array = array(); $extrafield_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_array)) $contact_fields = array_merge($contact_fields, $extrafield_array); if (is_array($extrafield_array)) {
$contact_fields = array_merge($contact_fields, $extrafield_array);
}
// Define other specific objects // Define other specific objects
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
@ -247,7 +251,9 @@ function getContact($authentication, $id, $ref_ext)
dol_syslog("Function: getContact login=".$authentication['login']." id=".$id." ref_ext=".$ref_ext); dol_syslog("Function: getContact login=".$authentication['login']." id=".$id." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -255,24 +261,20 @@ function getContact($authentication, $id, $ref_ext)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && ($id && $ref_ext)) if (!$error && ($id && $ref_ext)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
$contact = new Contact($db); $contact = new Contact($db);
$result = $contact->fetch($id, 0, $ref_ext); $result = $contact->fetch($id, 0, $ref_ext);
if ($result > 0) if ($result > 0) {
{
// Only internal user who have contact read permission // Only internal user who have contact read permission
// Or for external user who have contact read permission, with restrict on socid // Or for external user who have contact read permission, with restrict on socid
if ( if ($fuser->rights->societe->contact->lire && !$fuser->socid
$fuser->rights->societe->contact->lire && !$fuser->socid
|| ($fuser->rights->societe->contact->lire && ($fuser->socid == $contact->socid)) || ($fuser->rights->societe->contact->lire && ($fuser->socid == $contact->socid))
) { ) {
$contact_result_fields = array( $contact_result_fields = array(
@ -319,10 +321,8 @@ function getContact($authentication, $id, $ref_ext)
//Get extrafield values //Get extrafield values
$contact->fetch_optionals(); $contact->fetch_optionals();
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$contact_result_fields = array_merge($contact_result_fields, array('options_'.$key => $contact->array_options['options_'.$key])); $contact_result_fields = array_merge($contact_result_fields, array('options_'.$key => $contact->array_options['options_'.$key]));
} }
} }
@ -332,20 +332,17 @@ function getContact($authentication, $id, $ref_ext)
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'contact'=>$contact_result_fields 'contact'=>$contact_result_fields
); );
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref_ext='.$ref_ext;
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -368,7 +365,9 @@ function createContact($authentication, $contact)
dol_syslog("Function: createContact login=".$authentication['login']); dol_syslog("Function: createContact login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -376,13 +375,11 @@ function createContact($authentication, $contact)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (empty($contact['lastname'])) if (empty($contact['lastname'])) {
{
$error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory.";
} }
if (!$error) if (!$error) {
{
$newobject = new Contact($db); $newobject = new Contact($db);
$newobject->id = $contact['id']; $newobject->id = $contact['id'];
@ -424,10 +421,8 @@ function createContact($authentication, $contact)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$newobject->array_options[$key] = $contact[$key]; $newobject->array_options[$key] = $contact[$key];
} }
@ -439,17 +434,14 @@ function createContact($authentication, $contact)
$db->begin(); $db->begin();
$result = $newobject->create($fuser); $result = $newobject->create($fuser);
if ($result <= 0) if ($result <= 0) {
{
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -457,8 +449,7 @@ function createContact($authentication, $contact)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -478,7 +469,9 @@ function getContactsForThirdParty($authentication, $idthirdparty)
dol_syslog("Function: getContactsForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); dol_syslog("Function: getContactsForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -486,14 +479,12 @@ function getContactsForThirdParty($authentication, $idthirdparty)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && empty($idthirdparty)) if (!$error && empty($idthirdparty)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided';
} }
if (!$error) if (!$error) {
{
$linesinvoice = array(); $linesinvoice = array();
$sql = "SELECT c.rowid, c.fk_soc, c.civility as civility_id, c.lastname, c.firstname, c.statut as status,"; $sql = "SELECT c.rowid, c.fk_soc, c.civility as civility_id, c.lastname, c.firstname, c.statut as status,";
@ -515,12 +506,10 @@ function getContactsForThirdParty($authentication, $idthirdparty)
$sql .= " WHERE c.fk_soc = ".$idthirdparty; $sql .= " WHERE c.fk_soc = ".$idthirdparty;
$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) {
{
// En attendant remplissage par boucle // En attendant remplissage par boucle
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
@ -580,15 +569,13 @@ function getContactsForThirdParty($authentication, $idthirdparty)
'contacts'=>$linescontact 'contacts'=>$linescontact
); );
} } else {
else {
$error++; $error++;
$errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror();
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -611,7 +598,9 @@ function updateContact($authentication, $contact)
dol_syslog("Function: updateContact login=".$authentication['login']); dol_syslog("Function: updateContact login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -623,14 +612,12 @@ function updateContact($authentication, $contact)
$error++; $errorcode = 'KO'; $errorlabel = "Contact id or ref_ext is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Contact id or ref_ext is mandatory.";
} }
// Check parameters // Check parameters
if (!$error && ($id && $ref_ext)) if (!$error && ($id && $ref_ext)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref_ext can't be all provided. You must choose one of them.";
} }
if (!$error) if (!$error) {
{
$objectfound = false; $objectfound = false;
include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
@ -650,7 +637,9 @@ function updateContact($authentication, $contact)
$object->town = $contact['town']; $object->town = $contact['town'];
$object->country_id = $contact['country_id']; $object->country_id = $contact['country_id'];
if ($contact['country_code']) $object->country_id = getCountry($contact['country_code'], 3); if ($contact['country_code']) {
$object->country_id = getCountry($contact['country_code'], 3);
}
$object->province_id = $contact['province_id']; $object->province_id = $contact['province_id'];
@ -671,10 +660,8 @@ function updateContact($authentication, $contact)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$object->array_options[$key] = $contact[$key]; $object->array_options[$key] = $contact[$key];
} }
@ -688,16 +675,13 @@ function updateContact($authentication, $contact)
} }
} }
if ((!$error) && ($objectfound)) if ((!$error) && ($objectfound)) {
{
$db->commit(); $db->commit();
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'id'=>$object->id 'id'=>$object->id
); );
} } elseif ($objectfound) {
elseif ($objectfound)
{
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -709,8 +693,7 @@ function updateContact($authentication, $contact)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -21,7 +21,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require '../master.inc.php'; require '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -38,8 +40,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -112,16 +113,16 @@ $server->wsdl->addComplexType(
); );
/*$server->wsdl->addComplexType( /*$server->wsdl->addComplexType(
'LinesArray', 'LinesArray',
'complexType', 'complexType',
'array', 'array',
'', '',
'SOAP-ENC:Array', 'SOAP-ENC:Array',
array(), array(),
array( array(
array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:line[]') array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:line[]')
), ),
'tns:line' 'tns:line'
);*/ );*/
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'LinesArray2', 'LinesArray2',
@ -176,16 +177,16 @@ $server->wsdl->addComplexType(
); );
/* /*
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'InvoicesArray', 'InvoicesArray',
'complexType', 'complexType',
'array', 'array',
'', '',
'SOAP-ENC:Array', 'SOAP-ENC:Array',
array(), array(),
array( array(
array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:invoice[]') array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:invoice[]')
), ),
'tns:invoice' 'tns:invoice'
);*/ );*/
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'InvoicesArray2', 'InvoicesArray2',
@ -252,16 +253,16 @@ $server->register(
'WS to create an invoice' 'WS to create an invoice'
); );
$server->register( $server->register(
'createInvoiceFromOrder', 'createInvoiceFromOrder',
// Entry values // Entry values
array('authentication'=>'tns:authentication', 'id_order'=>'xsd:string', 'ref_order'=>'xsd:string', 'ref_ext_order'=>'xsd:string'), array('authentication'=>'tns:authentication', 'id_order'=>'xsd:string', 'ref_order'=>'xsd:string', 'ref_ext_order'=>'xsd:string'),
// Exit values // Exit values
array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'),
$ns, $ns,
$ns.'#createInvoiceFromOrder', $ns.'#createInvoiceFromOrder',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to create an invoice from an order' 'WS to create an invoice from an order'
); );
$server->register( $server->register(
'updateInvoice', 'updateInvoice',
@ -292,7 +293,9 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
dol_syslog("Function: getInvoice login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); dol_syslog("Function: getInvoice login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -300,26 +303,21 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->facture->lire) if ($fuser->rights->facture->lire) {
{
$invoice = new Facture($db); $invoice = new Facture($db);
$result = $invoice->fetch($id, $ref, $ref_ext); $result = $invoice->fetch($id, $ref, $ref_ext);
if ($result > 0) if ($result > 0) {
{
$linesresp = array(); $linesresp = array();
$i = 0; $i = 0;
foreach ($invoice->lines as $line) foreach ($invoice->lines as $line) {
{
//var_dump($line); exit; //var_dump($line); exit;
$linesresp[] = array( $linesresp[] = array(
'id'=>$line->id, 'id'=>$line->id,
@ -346,7 +344,7 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'invoice'=>array( 'invoice'=>array(
'id' => $invoice->id, 'id' => $invoice->id,
'ref' => $invoice->ref, 'ref' => $invoice->ref,
'ref_ext' => $invoice->ref_ext ? $invoice->ref_ext : '', // If not defined, field is not added into soap 'ref_ext' => $invoice->ref_ext ? $invoice->ref_ext : '', // If not defined, field is not added into soap
'thirdparty_id' => $invoice->socid, 'thirdparty_id' => $invoice->socid,
'fk_user_author' => $invoice->user_author ? $invoice->user_author : '', 'fk_user_author' => $invoice->user_author ? $invoice->user_author : '',
@ -369,20 +367,17 @@ function getInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
'payment_mode_id' => $invoice->mode_reglement_id ? $invoice->mode_reglement_id : '', 'payment_mode_id' => $invoice->mode_reglement_id ? $invoice->mode_reglement_id : '',
'lines' => $linesresp 'lines' => $linesresp
)); ));
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -403,7 +398,9 @@ function getInvoicesForThirdParty($authentication, $idthirdparty)
dol_syslog("Function: getInvoicesForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); dol_syslog("Function: getInvoicesForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -411,31 +408,31 @@ function getInvoicesForThirdParty($authentication, $idthirdparty)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
// Check parameters // Check parameters
if (!$error && empty($idthirdparty)) if (!$error && empty($idthirdparty)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter idthirdparty is not provided'; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter idthirdparty is not provided';
} }
if (!$error) if (!$error) {
{
$linesinvoice = array(); $linesinvoice = array();
$sql = 'SELECT f.rowid as facid, ref as ref, ref_ext, type, fk_statut as status, total_ttc, total, tva'; $sql = 'SELECT f.rowid as facid, ref as ref, ref_ext, type, fk_statut as status, total_ttc, total, tva';
$sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
$sql .= " WHERE f.entity IN (".getEntity('invoice').")"; $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
if ($idthirdparty != 'all') $sql .= " AND f.fk_soc = ".$db->escape($idthirdparty); if ($idthirdparty != 'all') {
$sql .= " AND f.fk_soc = ".$db->escape($idthirdparty);
}
$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) {
{
// En attendant remplissage par boucle // En attendant remplissage par boucle
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
@ -443,18 +440,15 @@ function getInvoicesForThirdParty($authentication, $idthirdparty)
$invoice->fetch($obj->facid); $invoice->fetch($obj->facid);
// Sécurité pour utilisateur externe // Sécurité pour utilisateur externe
if ($socid && ($socid != $invoice->socid)) if ($socid && ($socid != $invoice->socid)) {
{
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = $invoice->socid.' User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = $invoice->socid.' User does not have permission for this request';
} }
if (!$error) if (!$error) {
{
// Define lines of invoice // Define lines of invoice
$linesresp = array(); $linesresp = array();
foreach ($invoice->lines as $line) foreach ($invoice->lines as $line) {
{
$linesresp[] = array( $linesresp[] = array(
'id'=>$line->id, 'id'=>$line->id,
'type'=>$line->product_type, 'type'=>$line->product_type,
@ -508,15 +502,13 @@ function getInvoicesForThirdParty($authentication, $idthirdparty)
'invoices'=>$linesinvoice 'invoices'=>$linesinvoice
); );
} } else {
else {
$error++; $error++;
$errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror();
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -539,7 +531,9 @@ function createInvoice($authentication, $invoice)
dol_syslog("Function: createInvoice login=".$authentication['login']." id=".$invoice['id'].", ref=".$invoice['ref'].", ref_ext=".$invoice['ref_ext']); dol_syslog("Function: createInvoice login=".$authentication['login']." id=".$invoice['id'].", ref=".$invoice['ref'].", ref_ext=".$invoice['ref_ext']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -552,8 +546,7 @@ function createInvoice($authentication, $invoice)
$error++; $errorcode = 'KO'; $errorlabel = "Invoice id or ref or ref_ext is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Invoice id or ref or ref_ext is mandatory.";
} }
if (!$error) if (!$error) {
{
$new_invoice = new Facture($db); $new_invoice = new Facture($db);
$new_invoice->socid = $invoice['thirdparty_id']; $new_invoice->socid = $invoice['thirdparty_id'];
$new_invoice->type = $invoice['type']; $new_invoice->type = $invoice['type'];
@ -571,16 +564,19 @@ function createInvoice($authentication, $invoice)
if ($res > 0) { if ($res > 0) {
$new_invoice->mode_reglement_id = !empty($invoice['payment_mode_id']) ? $invoice['payment_mode_id'] : $soc->mode_reglement_id; $new_invoice->mode_reglement_id = !empty($invoice['payment_mode_id']) ? $invoice['payment_mode_id'] : $soc->mode_reglement_id;
$new_invoice->cond_reglement_id = $soc->cond_reglement_id; $new_invoice->cond_reglement_id = $soc->cond_reglement_id;
} else {
$new_invoice->mode_reglement_id = $invoice['payment_mode_id'];
} }
else $new_invoice->mode_reglement_id = $invoice['payment_mode_id'];
// Trick because nusoap does not store data with same structure if there is one or several lines // Trick because nusoap does not store data with same structure if there is one or several lines
$arrayoflines = array(); $arrayoflines = array();
if (isset($invoice['lines']['line'][0])) $arrayoflines = $invoice['lines']['line']; if (isset($invoice['lines']['line'][0])) {
else $arrayoflines = $invoice['lines']; $arrayoflines = $invoice['lines']['line'];
} else {
$arrayoflines = $invoice['lines'];
}
foreach ($arrayoflines as $line) foreach ($arrayoflines as $line) {
{
// $key can be 'line' or '0','1',... // $key can be 'line' or '0','1',...
$newline = new FactureLigne($db); $newline = new FactureLigne($db);
$newline->product_type = $line['type']; $newline->product_type = $line['type'];
@ -603,27 +599,22 @@ function createInvoice($authentication, $invoice)
$db->begin(); $db->begin();
$result = $new_invoice->create($fuser, 0, dol_stringtotime($invoice['date_due'], 'dayrfc')); $result = $new_invoice->create($fuser, 0, dol_stringtotime($invoice['date_due'], 'dayrfc'));
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
if (!$error && $invoice['status'] == Facture::STATUS_VALIDATED) // We want invoice to have status validated if (!$error && $invoice['status'] == Facture::STATUS_VALIDATED) { // We want invoice to have status validated
{
$result = $new_invoice->validate($fuser); $result = $new_invoice->validate($fuser);
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$new_invoice->id, $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$new_invoice->id,
'ref'=>$new_invoice->ref, 'ref_ext'=>$new_invoice->ref_ext); 'ref'=>$new_invoice->ref, 'ref_ext'=>$new_invoice->ref_ext);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -632,8 +623,7 @@ function createInvoice($authentication, $invoice)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -655,14 +645,18 @@ function createInvoiceFromOrder($authentication, $id_order = '', $ref_order = ''
dol_syslog("Function: createInvoiceFromOrder login=".$authentication['login']." id=".$id_order.", ref=".$ref_order.", ref_ext=".$ref_ext_order); dol_syslog("Function: createInvoiceFromOrder login=".$authentication['login']." id=".$id_order.", ref=".$ref_order.", ref_ext=".$ref_ext_order);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
// Check parameters // Check parameters
if (empty($id_order) && empty($ref_order) && empty($ref_ext_order)) { if (empty($id_order) && empty($ref_order) && empty($ref_ext_order)) {
@ -670,51 +664,41 @@ function createInvoiceFromOrder($authentication, $id_order = '', $ref_order = ''
} }
////////////////////// //////////////////////
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->commande->lire) if ($fuser->rights->commande->lire) {
{
$order = new Commande($db); $order = new Commande($db);
$result = $order->fetch($id_order, $ref_order, $ref_ext_order); $result = $order->fetch($id_order, $ref_order, $ref_ext_order);
if ($result > 0) if ($result > 0) {
{
// Security for external user // Security for external user
if ($socid && ($socid != $order->socid)) if ($socid && ($socid != $order->socid)) {
{
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = $order->socid.'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = $order->socid.'User does not have permission for this request';
} }
if (!$error) if (!$error) {
{
$newobject = new Facture($db); $newobject = new Facture($db);
$result = $newobject->createFromOrder($order, $fuser); $result = $newobject->createFromOrder($order, $fuser);
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
dol_syslog("Webservice server_invoice:: invoice creation from order failed", LOG_ERR); dol_syslog("Webservice server_invoice:: invoice creation from order failed", LOG_ERR);
} }
} }
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id_order.' nor ref='.$ref_order.' nor ref_ext='.$ref_ext_order; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id_order.' nor ref='.$ref_order.' nor ref_ext='.$ref_ext_order;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} } else {
else {
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref, 'ref_ext'=>$newobject->ref_ext); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref, 'ref_ext'=>$newobject->ref_ext);
} }
@ -735,7 +719,9 @@ function updateInvoice($authentication, $invoice)
dol_syslog("Function: updateInvoice login=".$authentication['login']." id=".$invoice['id']. dol_syslog("Function: updateInvoice login=".$authentication['login']." id=".$invoice['id'].
", ref=".$invoice['ref'].", ref_ext=".$invoice['ref_ext']); ", ref=".$invoice['ref'].", ref_ext=".$invoice['ref_ext']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -748,8 +734,7 @@ function updateInvoice($authentication, $invoice)
$error++; $errorcode = 'KO'; $errorlabel = "Invoice id or ref or ref_ext is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Invoice id or ref or ref_ext is mandatory.";
} }
if (!$error) if (!$error) {
{
$objectfound = false; $objectfound = false;
$object = new Facture($db); $object = new Facture($db);
@ -760,18 +745,14 @@ function updateInvoice($authentication, $invoice)
$db->begin(); $db->begin();
if (isset($invoice['status'])) if (isset($invoice['status'])) {
{ if ($invoice['status'] == Facture::STATUS_DRAFT) {
if ($invoice['status'] == Facture::STATUS_DRAFT)
{
$result = $object->setDraft($fuser); $result = $object->setDraft($fuser);
} }
if ($invoice['status'] == Facture::STATUS_VALIDATED) if ($invoice['status'] == Facture::STATUS_VALIDATED) {
{
$result = $object->validate($fuser); $result = $object->validate($fuser);
if ($result >= 0) if ($result >= 0) {
{
// Define output language // Define output language
$outputlangs = $langs; $outputlangs = $langs;
$object->generateDocument($object->model_pdf, $outputlangs); $object->generateDocument($object->model_pdf, $outputlangs);
@ -806,8 +787,7 @@ function updateInvoice($authentication, $invoice)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -22,7 +22,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require '../master.inc.php'; require '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -36,8 +38,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -56,12 +57,12 @@ $server->wsdl->schemaTargetNamespace = $ns;
// Define WSDL Authentication object // Define WSDL Authentication object
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'authentication', 'authentication',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'), 'dolibarrkey' => array('name'=>'dolibarrkey', 'type'=>'xsd:string'),
'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'), 'sourceapplication' => array('name'=>'sourceapplication', 'type'=>'xsd:string'),
'login' => array('name'=>'login', 'type'=>'xsd:string'), 'login' => array('name'=>'login', 'type'=>'xsd:string'),
@ -71,12 +72,12 @@ $server->wsdl->addComplexType(
); );
// Define WSDL Return object // Define WSDL Return object
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'result', 'result',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
array( array(
'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'), 'result_code' => array('name'=>'result_code', 'type'=>'xsd:string'),
'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'), 'result_label' => array('name'=>'result_label', 'type'=>'xsd:string'),
) )
@ -120,27 +121,30 @@ $extrafield_line_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_line_array = array(); $extrafield_line_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
//$value=$object->array_options["options_".$key]; //$value=$object->array_options["options_".$key];
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_line_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); $extrafield_line_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_line_array)) $line_fields = array_merge($line_fields, $extrafield_line_array); if (is_array($extrafield_line_array)) {
$line_fields = array_merge($line_fields, $extrafield_line_array);
}
// Define other specific objects // Define other specific objects
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'line', 'line',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
$line_fields $line_fields
); );
/*$server->wsdl->addComplexType( /*$server->wsdl->addComplexType(
@ -159,12 +163,12 @@ $server->wsdl->addComplexType(
'tns:line' 'tns:line'
);*/ );*/
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'LinesArray2', 'LinesArray2',
'complexType', 'complexType',
'array', 'array',
'sequence', 'sequence',
'', '',
array( array(
'line' => array( 'line' => array(
'name' => 'line', 'name' => 'line',
'type' => 'tns:line', 'type' => 'tns:line',
@ -224,26 +228,29 @@ $extrafield_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_array = array(); $extrafield_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
//$value=$object->array_options["options_".$key]; //$value=$object->array_options["options_".$key];
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_array)) $order_fields = array_merge($order_fields, $extrafield_array); if (is_array($extrafield_array)) {
$order_fields = array_merge($order_fields, $extrafield_array);
}
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'order', 'order',
'complexType', 'complexType',
'struct', 'struct',
'all', 'all',
'', '',
$order_fields $order_fields
); );
/* /*
@ -263,12 +270,12 @@ $server->wsdl->addComplexType(
'tns:order' 'tns:order'
);*/ );*/
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'OrdersArray2', 'OrdersArray2',
'complexType', 'complexType',
'array', 'array',
'sequence', 'sequence',
'', '',
array( array(
'order' => array( 'order' => array(
'name' => 'order', 'name' => 'order',
'type' => 'tns:order', 'type' => 'tns:order',
@ -289,58 +296,58 @@ $styleuse = 'encoded'; // encoded/literal/literal wrapped
// Register WSDL // Register WSDL
$server->register( $server->register(
'getOrder', 'getOrder',
array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Entry values array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Entry values
array('result'=>'tns:result', 'order'=>'tns:order'), // Exit values array('result'=>'tns:result', 'order'=>'tns:order'), // Exit values
$ns, $ns,
$ns.'#getOrder', $ns.'#getOrder',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to get a particular invoice' 'WS to get a particular invoice'
); );
$server->register( $server->register(
'getOrdersForThirdParty', 'getOrdersForThirdParty',
array('authentication'=>'tns:authentication', 'idthirdparty'=>'xsd:string'), // Entry values array('authentication'=>'tns:authentication', 'idthirdparty'=>'xsd:string'), // Entry values
array('result'=>'tns:result', 'orders'=>'tns:OrdersArray2'), // Exit values array('result'=>'tns:result', 'orders'=>'tns:OrdersArray2'), // Exit values
$ns, $ns,
$ns.'#getOrdersForThirdParty', $ns.'#getOrdersForThirdParty',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to get all orders of a third party' 'WS to get all orders of a third party'
); );
$server->register( $server->register(
'createOrder', 'createOrder',
array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values
array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string'), // Exit values array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string'), // Exit values
$ns, $ns,
$ns.'#createOrder', $ns.'#createOrder',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to create an order' 'WS to create an order'
); );
$server->register( $server->register(
'updateOrder', 'updateOrder',
array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values array('authentication'=>'tns:authentication', 'order'=>'tns:order'), // Entry values
array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Exit values array('result'=>'tns:result', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), // Exit values
$ns, $ns,
$ns.'#updateOrder', $ns.'#updateOrder',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to update an order' 'WS to update an order'
); );
$server->register( $server->register(
'validOrder', 'validOrder',
array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'id_warehouse'=>'xsd:string'), // Entry values array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'id_warehouse'=>'xsd:string'), // Entry values
array('result'=>'tns:result'), // Exit values array('result'=>'tns:result'), // Exit values
$ns, $ns,
$ns.'#validOrder', $ns.'#validOrder',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to valid an order' 'WS to valid an order'
); );
/** /**
@ -358,7 +365,9 @@ function getOrder($authentication, $id = '', $ref = '', $ref_ext = '')
dol_syslog("Function: getOrder login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); dol_syslog("Function: getOrder login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -368,38 +377,33 @@ function getOrder($authentication, $id = '', $ref = '', $ref_ext = '')
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
// Check parameters // Check parameters
if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->commande->lire) if ($fuser->rights->commande->lire) {
{
$order = new Commande($db); $order = new Commande($db);
$result = $order->fetch($id, $ref, $ref_ext); $result = $order->fetch($id, $ref, $ref_ext);
if ($result > 0) if ($result > 0) {
{
// Security for external user // Security for external user
if ($socid && $socid != $order->socid) if ($socid && $socid != $order->socid) {
{
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
if (!$error) if (!$error) {
{
$linesresp = array(); $linesresp = array();
$i = 0; $i = 0;
foreach ($order->lines as $line) foreach ($order->lines as $line) {
{
//var_dump($line); exit; //var_dump($line); exit;
$linesresp[] = array( $linesresp[] = array(
'id'=>$line->rowid, 'id'=>$line->rowid,
@ -473,22 +477,19 @@ function getOrder($authentication, $id = '', $ref = '', $ref_ext = '')
'lines' => $linesresp 'lines' => $linesresp
)); ));
} }
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorcode = 'NOT_FOUND';
$errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorcode = 'PERMISSION_DENIED';
$errorlabel = 'User does not have permission for this request'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -509,7 +510,9 @@ function getOrdersForThirdParty($authentication, $idthirdparty)
dol_syslog("Function: getOrdersForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); dol_syslog("Function: getOrdersForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -517,32 +520,32 @@ function getOrdersForThirdParty($authentication, $idthirdparty)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
// Check parameters // Check parameters
if (!$error && empty($idthirdparty)) if (!$error && empty($idthirdparty)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided';
} }
if (!$error) if (!$error) {
{
$linesorders = array(); $linesorders = array();
$sql = 'SELECT c.rowid as orderid'; $sql = 'SELECT c.rowid as orderid';
$sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c'; $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
$sql .= " WHERE c.entity = ".$conf->entity; $sql .= " WHERE c.entity = ".$conf->entity;
if ($idthirdparty != 'all') $sql .= " AND c.fk_soc = ".$db->escape($idthirdparty); if ($idthirdparty != 'all') {
$sql .= " AND c.fk_soc = ".$db->escape($idthirdparty);
}
$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) {
{
// En attendant remplissage par boucle // En attendant remplissage par boucle
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
@ -550,19 +553,16 @@ function getOrdersForThirdParty($authentication, $idthirdparty)
$order->fetch($obj->orderid); $order->fetch($obj->orderid);
// Sécurité pour utilisateur externe // Sécurité pour utilisateur externe
if ($socid && ($socid != $order->socid)) if ($socid && ($socid != $order->socid)) {
{
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorcode = 'PERMISSION_DENIED';
$errorlabel = $order->socid.' User does not have permission for this request'; $errorlabel = $order->socid.' User does not have permission for this request';
} }
if (!$error) if (!$error) {
{
// Define lines of invoice // Define lines of invoice
$linesresp = array(); $linesresp = array();
foreach ($order->lines as $line) foreach ($order->lines as $line) {
{
$linesresp[] = array( $linesresp[] = array(
'id'=>$line->rowid, 'id'=>$line->rowid,
'type'=>$line->product_type, 'type'=>$line->product_type,
@ -638,15 +638,13 @@ function getOrdersForThirdParty($authentication, $idthirdparty)
'orders'=>$linesorders 'orders'=>$linesorders
); );
} } else {
else {
$error++; $error++;
$errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror();
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -671,7 +669,9 @@ function createOrder($authentication, $order)
dol_syslog("Function: createOrder login=".$authentication['login']." socid :".$order['socid']); dol_syslog("Function: createOrder login=".$authentication['login']." socid :".$order['socid']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -683,8 +683,7 @@ function createOrder($authentication, $order)
// Check parameters // Check parameters
if (!$error) if (!$error) {
{
$newobject = new Commande($db); $newobject = new Commande($db);
$newobject->socid = $order['thirdparty_id']; $newobject->socid = $order['thirdparty_id'];
$newobject->type = $order['type']; $newobject->type = $order['type'];
@ -706,10 +705,8 @@ function createOrder($authentication, $order)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$newobject->array_options[$key] = $order[$key]; $newobject->array_options[$key] = $order[$key];
} }
@ -717,11 +714,13 @@ function createOrder($authentication, $order)
// Trick because nusoap does not store data with same structure if there is one or several lines // Trick because nusoap does not store data with same structure if there is one or several lines
$arrayoflines = array(); $arrayoflines = array();
if (isset($order['lines']['line'][0])) $arrayoflines = $order['lines']['line']; if (isset($order['lines']['line'][0])) {
else $arrayoflines = $order['lines']; $arrayoflines = $order['lines']['line'];
} else {
$arrayoflines = $order['lines'];
}
foreach ($arrayoflines as $key => $line) foreach ($arrayoflines as $key => $line) {
{
// $key can be 'line' or '0','1',... // $key can be 'line' or '0','1',...
$newline = new OrderLine($db); $newline = new OrderLine($db);
@ -744,10 +743,8 @@ function createOrder($authentication, $order)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$newline->array_options[$key] = $line[$key]; $newline->array_options[$key] = $line[$key];
} }
@ -761,30 +758,25 @@ function createOrder($authentication, $order)
dol_syslog("Webservice server_order:: order creation start", LOG_DEBUG); dol_syslog("Webservice server_order:: order creation start", LOG_DEBUG);
$result = $newobject->create($fuser); $result = $newobject->create($fuser);
dol_syslog('Webservice server_order:: order creation done with $result='.$result, LOG_DEBUG); dol_syslog('Webservice server_order:: order creation done with $result='.$result, LOG_DEBUG);
if ($result < 0) if ($result < 0) {
{
dol_syslog("Webservice server_order:: order creation failed", LOG_ERR); dol_syslog("Webservice server_order:: order creation failed", LOG_ERR);
$error++; $error++;
} }
if ($order['status'] == 1) // We want order to have status validated if ($order['status'] == 1) { // We want order to have status validated
{
dol_syslog("Webservice server_order:: order validation start", LOG_DEBUG); dol_syslog("Webservice server_order:: order validation start", LOG_DEBUG);
$result = $newobject->valid($fuser); $result = $newobject->valid($fuser);
if ($result < 0) if ($result < 0) {
{
dol_syslog("Webservice server_order:: order validation failed", LOG_ERR); dol_syslog("Webservice server_order:: order validation failed", LOG_ERR);
$error++; $error++;
} }
} }
if ($result >= 0) if ($result >= 0) {
{
dol_syslog("Webservice server_order:: order creation & validation succeeded, commit", LOG_DEBUG); dol_syslog("Webservice server_order:: order creation & validation succeeded, commit", LOG_DEBUG);
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref);
} } else {
else {
dol_syslog("Webservice server_order:: order creation or validation failed, rollback", LOG_ERR); dol_syslog("Webservice server_order:: order creation or validation failed, rollback", LOG_ERR);
$db->rollback(); $db->rollback();
$error++; $error++;
@ -793,8 +785,7 @@ function createOrder($authentication, $order)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -821,45 +812,40 @@ function validOrder($authentication, $id = '', $id_warehouse = 0)
$errorcode = ''; $errorcode = '';
$errorlabel = ''; $errorlabel = '';
$error = 0; $error = 0;
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->commande->lire) if ($fuser->rights->commande->lire) {
{
$order = new Commande($db); $order = new Commande($db);
$result = $order->fetch($id); $result = $order->fetch($id);
$order->fetch_thirdparty(); $order->fetch_thirdparty();
$db->begin(); $db->begin();
if ($result > 0) if ($result > 0) {
{
$result = $order->valid($fuser, $id_warehouse); $result = $order->valid($fuser, $id_warehouse);
if ($result >= 0) if ($result >= 0) {
{
// Define output language // Define output language
$outputlangs = $langs; $outputlangs = $langs;
$order->generateDocument($order->model_pdf, $outputlangs); $order->generateDocument($order->model_pdf, $outputlangs);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
$errorlabel = $order->error; $errorlabel = $order->error;
} }
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
$errorlabel = $order->error; $errorlabel = $order->error;
} }
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -867,11 +853,9 @@ function validOrder($authentication, $id = '', $id_warehouse = 0)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} } else {
else {
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>'')); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''));
} }
@ -892,7 +876,9 @@ function updateOrder($authentication, $order)
dol_syslog("Function: updateOrder login=".$authentication['login']); dol_syslog("Function: updateOrder login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -904,8 +890,7 @@ function updateOrder($authentication, $order)
$error++; $errorcode = 'KO'; $errorlabel = "Order id or ref or ref_ext is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Order id or ref or ref_ext is mandatory.";
} }
if (!$error) if (!$error) {
{
$objectfound = false; $objectfound = false;
include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
@ -918,27 +903,33 @@ function updateOrder($authentication, $order)
$db->begin(); $db->begin();
if (isset($order['status'])) if (isset($order['status'])) {
{ if ($order['status'] == -1) {
if ($order['status'] == -1) $result = $object->cancel($fuser); $result = $object->cancel($fuser);
if ($order['status'] == 1) }
{ if ($order['status'] == 1) {
$result = $object->valid($fuser); $result = $object->valid($fuser);
if ($result >= 0) if ($result >= 0) {
{
// Define output language // Define output language
$outputlangs = $langs; $outputlangs = $langs;
$object->generateDocument($order->model_pdf, $outputlangs); $object->generateDocument($order->model_pdf, $outputlangs);
} }
} }
if ($order['status'] == 0) $result = $object->set_reopen($fuser); if ($order['status'] == 0) {
if ($order['status'] == 3) $result = $object->cloture($fuser); $result = $object->set_reopen($fuser);
}
if ($order['status'] == 3) {
$result = $object->cloture($fuser);
}
} }
if (isset($order['billed'])) if (isset($order['billed'])) {
{ if ($order['billed']) {
if ($order['billed']) $result = $object->classifyBilled($fuser); $result = $object->classifyBilled($fuser);
if (!$order['billed']) $result = $object->classifyUnBilled($fuser); }
if (!$order['billed']) {
$result = $object->classifyUnBilled($fuser);
}
} }
$elementtype = 'commande'; $elementtype = 'commande';
@ -947,13 +938,10 @@ function updateOrder($authentication, $order)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
if (isset($order[$key])) if (isset($order[$key])) {
{
$result = $object->setValueFrom($key, $order[$key], 'commande_extrafields'); $result = $object->setValueFrom($key, $order[$key], 'commande_extrafields');
} }
} }
@ -964,8 +952,7 @@ function updateOrder($authentication, $order)
} }
} }
if ((!$error) && ($objectfound)) if ((!$error) && ($objectfound)) {
{
$db->commit(); $db->commit();
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
@ -973,9 +960,7 @@ function updateOrder($authentication, $order)
'ref'=>$object->ref, 'ref'=>$object->ref,
'ref_ext'=>$object->ref_ext 'ref_ext'=>$object->ref_ext
); );
} } elseif ($objectfound) {
elseif ($objectfound)
{
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -987,8 +972,7 @@ function updateOrder($authentication, $order)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -20,7 +20,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require '../master.inc.php'; require '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -35,8 +37,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -149,7 +150,9 @@ function getVersions($authentication)
dol_syslog("Function: getVersions login=".$authentication['login']); dol_syslog("Function: getVersions login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -159,8 +162,7 @@ function getVersions($authentication)
// Check parameters // Check parameters
if (!$error) if (!$error) {
{
$objectresp['result'] = array('result_code'=>'OK', 'result_label'=>''); $objectresp['result'] = array('result_code'=>'OK', 'result_label'=>'');
$objectresp['dolibarr'] = version_dolibarr(); $objectresp['dolibarr'] = version_dolibarr();
$objectresp['os'] = version_os(); $objectresp['os'] = version_os();
@ -168,8 +170,7 @@ function getVersions($authentication)
$objectresp['webserver'] = version_webserver(); $objectresp['webserver'] = version_webserver();
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -192,7 +193,9 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
dol_syslog("Function: getDocument login=".$authentication['login'].' - modulepart='.$modulepart.' - file='.$file); dol_syslog("Function: getDocument login=".$authentication['login'].' - modulepart='.$modulepart.' - file='.$file);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
@ -208,24 +211,26 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
// Check parameters // Check parameters
if (!$error && (!$file || !$modulepart)) if (!$error && (!$file || !$modulepart)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter file and modulepart must be both provided."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter file and modulepart must be both provided.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
// Suppression de la chaine de caractere ../ dans $original_file // Suppression de la chaine de caractere ../ dans $original_file
$original_file = str_replace("../", "/", $original_file); $original_file = str_replace("../", "/", $original_file);
// find the subdirectory name as the reference // find the subdirectory name as the reference
if (empty($refname)) $refname = basename(dirname($original_file)."/"); if (empty($refname)) {
$refname = basename(dirname($original_file)."/");
}
// Security check // Security check
$check_access = dol_check_secure_access_document($modulepart, $original_file, $conf->entity, $fuser, $refname); $check_access = dol_check_secure_access_document($modulepart, $original_file, $conf->entity, $fuser, $refname);
@ -234,20 +239,15 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
$original_file = $check_access['original_file']; $original_file = $check_access['original_file'];
// Basic protection (against external users only) // Basic protection (against external users only)
if ($fuser->socid > 0) if ($fuser->socid > 0) {
{ if ($sqlprotectagainstexternals) {
if ($sqlprotectagainstexternals)
{
$resql = $db->query($sqlprotectagainstexternals); $resql = $db->query($sqlprotectagainstexternals);
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);
if ($fuser->socid != $obj->fk_soc) if ($fuser->socid != $obj->fk_soc) {
{
$accessallowed = 0; $accessallowed = 0;
break; break;
} }
@ -259,8 +259,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
// Security: // Security:
// Limite acces si droits non corrects // Limite acces si droits non corrects
if (!$accessallowed) if (!$accessallowed) {
{
$errorcode = 'NOT_PERMITTED'; $errorcode = 'NOT_PERMITTED';
$errorlabel = 'Access not allowed'; $errorlabel = 'Access not allowed';
$error++; $error++;
@ -269,8 +268,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
// Security: // Security:
// On interdit les remontees de repertoire ainsi que les pipe dans // On interdit les remontees de repertoire ainsi que les pipe dans
// les noms de fichiers. // les noms de fichiers.
if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
{
dol_syslog("Refused to deliver file ".$original_file); dol_syslog("Refused to deliver file ".$original_file);
$errorcode = 'REFUSED'; $errorcode = 'REFUSED';
$errorlabel = ''; $errorlabel = '';
@ -279,10 +277,8 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
clearstatcache(); clearstatcache();
if (!$error) if (!$error) {
{ if (file_exists($original_file)) {
if (file_exists($original_file))
{
dol_syslog("Function: getDocument $original_file content-type=$type"); dol_syslog("Function: getDocument $original_file content-type=$type");
$f = fopen($original_file, 'r'); $f = fopen($original_file, 'r');
@ -300,8 +296,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'document'=>$objectret 'document'=>$objectret
); );
} } else {
else {
dol_syslog("File doesn't exist ".$original_file); dol_syslog("File doesn't exist ".$original_file);
$errorcode = 'NOT_FOUND'; $errorcode = 'NOT_FOUND';
$errorlabel = ''; $errorlabel = '';
@ -310,8 +305,7 @@ function getDocument($authentication, $modulepart, $file, $refname = '')
} }
} }
if ($error) if ($error) {
{
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel) 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)
); );

View File

@ -42,8 +42,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
@ -147,7 +146,9 @@ function createPayment($authentication, $payment)
dol_syslog("Function: createPayment login=".$authentication['login']." id=".$payment->id. dol_syslog("Function: createPayment login=".$authentication['login']." id=".$payment->id.
", ref=".$payment->ref.", ref_ext=".$payment->ref_ext); ", ref=".$payment->ref.", ref_ext=".$payment->ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -163,8 +164,7 @@ function createPayment($authentication, $payment)
$errorlabel = "You must specify the amount and the third party's ID."; $errorlabel = "You must specify the amount and the third party's ID.";
} }
if (!$error) if (!$error) {
{
$soc = new Societe($db); $soc = new Societe($db);
$soc->fetch($payment['thirdparty_id']); $soc->fetch($payment['thirdparty_id']);
@ -188,17 +188,14 @@ function createPayment($authentication, $payment)
$new_payment->addPaymentToBank($fuser, 'payment', $payment['int_label'], $payment['bank_account'], $payment['emitter'], $payment['bank_source']); $new_payment->addPaymentToBank($fuser, 'payment', $payment['int_label'], $payment['bank_account'], $payment['emitter'], $payment['bank_source']);
} }
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$new_payment->id); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$new_payment->id);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -207,8 +204,7 @@ function createPayment($authentication, $payment)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -712,7 +712,9 @@ function updateProductOrService($authentication, $product)
$newobject->seuil_stock_alerte = isset($product['stock_alert']) ? $product['stock_alert'] : null; $newobject->seuil_stock_alerte = isset($product['stock_alert']) ? $product['stock_alert'] : null;
$newobject->country_id = isset($product['country_id']) ? $product['country_id'] : 0; $newobject->country_id = isset($product['country_id']) ? $product['country_id'] : 0;
if (!empty($product['country_code'])) $newobject->country_id = getCountry($product['country_code'], 3); if (!empty($product['country_code'])) {
$newobject->country_id = getCountry($product['country_code'], 3);
}
$newobject->customcode = isset($product['customcode']) ? $product['customcode'] : ''; $newobject->customcode = isset($product['customcode']) ? $product['customcode'] : '';
$newobject->canvas = isset($product['canvas']) ? $product['canvas'] : ''; $newobject->canvas = isset($product['canvas']) ? $product['canvas'] : '';

View File

@ -21,7 +21,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require '../master.inc.php'; require '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -37,8 +39,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -131,8 +132,7 @@ $server->wsdl->addComplexType(
); );
$project_elements = array(); $project_elements = array();
foreach ($listofreferent as $key => $label) foreach ($listofreferent as $key => $label) {
{
$project_elements[$key] = array('name'=>$key, 'type'=>'tns:elementsArray'); $project_elements[$key] = array('name'=>$key, 'type'=>'tns:elementsArray');
} }
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
@ -169,18 +169,21 @@ $extrafield_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_array = array(); $extrafield_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key=>$label)
{
//$value=$object->array_options["options_".$key]; //$value=$object->array_options["options_".$key];
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_array)) $project_fields = array_merge($project_fields, $extrafield_array); if (is_array($extrafield_array)) {
$project_fields = array_merge($project_fields, $extrafield_array);
}
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
'project', 'project',
@ -240,7 +243,9 @@ function createProject($authentication, $project)
dol_syslog("Function: createProject login=".$authentication['login']); dol_syslog("Function: createProject login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -248,18 +253,15 @@ function createProject($authentication, $project)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (empty($project['ref'])) if (empty($project['ref'])) {
{
$error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->projet->creer) if ($fuser->rights->projet->creer) {
{
$newobject = new Project($db); $newobject = new Project($db);
$newobject->ref = $project['ref']; $newobject->ref = $project['ref'];
$newobject->title = $project['label']; $newobject->title = $project['label'];
@ -277,10 +279,8 @@ function createProject($authentication, $project)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
$newobject->array_options[$key] = $project[$key]; $newobject->array_options[$key] = $project[$key];
} }
@ -289,39 +289,32 @@ function createProject($authentication, $project)
$db->begin(); $db->begin();
$result = $newobject->create($fuser); $result = $newobject->create($fuser);
if (!$error && $result > 0) if (!$error && $result > 0) {
{
// Add myself as project leader // Add myself as project leader
$result = $newobject->add_contact($fuser->id, 'PROJECTLEADER', 'internal'); $result = $newobject->add_contact($fuser->id, 'PROJECTLEADER', 'internal');
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
} }
} } else {
else {
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
$errorlabel = $newobject->error; $errorlabel = $newobject->error;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -342,7 +335,9 @@ function getProject($authentication, $id = '', $ref = '')
dol_syslog("Function: getProject login=".$authentication['login']." id=".$id." ref=".$ref); dol_syslog("Function: getProject login=".$authentication['login']." id=".$id." ref=".$ref);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -350,22 +345,18 @@ function getProject($authentication, $id = '', $ref = '')
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && (($id && $ref))) if (!$error && (($id && $ref))) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id and ref can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->projet->lire) if ($fuser->rights->projet->lire) {
{
$project = new Project($db); $project = new Project($db);
$result = $project->fetch($id, $ref); $result = $project->fetch($id, $ref);
if ($result > 0) if ($result > 0) {
{
$project_result_fields = array( $project_result_fields = array(
'id' => $project->id, 'id' => $project->id,
'ref' => $project->ref, 'ref' => $project->ref,
@ -386,11 +377,9 @@ function getProject($authentication, $id = '', $ref = '')
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
//Get extrafield values //Get extrafield values
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{
$project->fetch_optionals(); $project->fetch_optionals();
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
{
$project_result_fields = array_merge($project_result_fields, array('options_'.$key => $project->array_options['options_'.$key])); $project_result_fields = array_merge($project_result_fields, array('options_'.$key => $project->array_options['options_'.$key]));
} }
} }
@ -398,14 +387,11 @@ function getProject($authentication, $id = '', $ref = '')
//Get linked elements //Get linked elements
global $listofreferent; global $listofreferent;
$elements = array(); $elements = array();
foreach ($listofreferent as $key => $tablename) foreach ($listofreferent as $key => $tablename) {
{
$elements[$key] = array(); $elements[$key] = array();
$element_array = $project->get_element_list($key, $tablename); $element_array = $project->get_element_list($key, $tablename);
if (count($element_array) > 0 && is_array($element_array)) if (count($element_array) > 0 && is_array($element_array)) {
{ foreach ($element_array as $element) {
foreach ($element_array as $element)
{
$tmp = explode('_', $element); $tmp = explode('_', $element);
$idofelement = count($tmp) > 0 ? $tmp[0] : ""; $idofelement = count($tmp) > 0 ? $tmp[0] : "";
$idofelementuser = count($tmp) > 1 ? $tmp[1] : ""; $idofelementuser = count($tmp) > 1 ? $tmp[1] : "";
@ -420,20 +406,17 @@ function getProject($authentication, $id = '', $ref = '')
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'project'=>$project_result_fields 'project'=>$project_result_fields
); );
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -20,7 +20,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require '../master.inc.php'; require '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -34,8 +36,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -229,7 +230,9 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
dol_syslog("Function: getSupplierInvoice login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); dol_syslog("Function: getSupplierInvoice login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -237,26 +240,21 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->fournisseur->facture->lire) if ($fuser->rights->fournisseur->facture->lire) {
{
$invoice = new FactureFournisseur($db); $invoice = new FactureFournisseur($db);
$result = $invoice->fetch($id, $ref, $ref_ext); $result = $invoice->fetch($id, $ref, $ref_ext);
if ($result > 0) if ($result > 0) {
{
$linesresp = array(); $linesresp = array();
$i = 0; $i = 0;
foreach ($invoice->lines as $line) foreach ($invoice->lines as $line) {
{
//var_dump($line); exit; //var_dump($line); exit;
$linesresp[] = array( $linesresp[] = array(
'id'=>$line->rowid, 'id'=>$line->rowid,
@ -275,7 +273,7 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'invoice'=>array( 'invoice'=>array(
'id' => $invoice->id, 'id' => $invoice->id,
'ref' => $invoice->ref, 'ref' => $invoice->ref,
'ref_supplier'=>$invoice->ref_supplier, 'ref_supplier'=>$invoice->ref_supplier,
'ref_ext' => $invoice->ref_ext, 'ref_ext' => $invoice->ref_ext,
'fk_user_author' => $invoice->fk_user_author, 'fk_user_author' => $invoice->fk_user_author,
@ -302,20 +300,17 @@ function getSupplierInvoice($authentication, $id = '', $ref = '', $ref_ext = '')
// '1'=>array('id'=>333,'type'=>1)), // '1'=>array('id'=>333,'type'=>1)),
)); ));
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -337,7 +332,9 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty)
dol_syslog("Function: getSupplierInvoicesForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty); dol_syslog("Function: getSupplierInvoicesForThirdParty login=".$authentication['login']." idthirdparty=".$idthirdparty);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -346,14 +343,12 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty)
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && empty($idthirdparty)) if (!$error && empty($idthirdparty)) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided'; $errorcode = 'BAD_PARAMETERS'; $errorlabel = 'Parameter id is not provided';
} }
if (!$error) if (!$error) {
{
$linesinvoice = array(); $linesinvoice = array();
$sql .= 'SELECT f.rowid as facid'; $sql .= 'SELECT f.rowid as facid';
@ -363,22 +358,21 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty)
//$sql.=" WHERE f.fk_soc = s.rowid AND nom = '".$db->escape($idthirdparty)."'"; //$sql.=" WHERE f.fk_soc = s.rowid AND nom = '".$db->escape($idthirdparty)."'";
//$sql.=" WHERE f.fk_soc = s.rowid AND nom = '".$db->escape($idthirdparty)."'"; //$sql.=" WHERE f.fk_soc = s.rowid AND nom = '".$db->escape($idthirdparty)."'";
$sql .= " WHERE f.entity = ".$conf->entity; $sql .= " WHERE f.entity = ".$conf->entity;
if ($idthirdparty != 'all') $sql .= " AND f.fk_soc = ".$db->escape($idthirdparty); if ($idthirdparty != 'all') {
$sql .= " AND f.fk_soc = ".$db->escape($idthirdparty);
}
$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) {
{
// En attendant remplissage par boucle // En attendant remplissage par boucle
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$invoice = new FactureFournisseur($db); $invoice = new FactureFournisseur($db);
$result = $invoice->fetch($obj->facid); $result = $invoice->fetch($obj->facid);
if ($result < 0) if ($result < 0) {
{
$error++; $error++;
$errorcode = $result; $errorlabel = $invoice->error; $errorcode = $result; $errorlabel = $invoice->error;
break; break;
@ -386,9 +380,8 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty)
// Define lines of invoice // Define lines of invoice
$linesresp = array(); $linesresp = array();
foreach ($invoice->lines as $line) foreach ($invoice->lines as $line) {
{ $linesresp[] = array(
$linesresp[] = array(
'id'=>$line->rowid, 'id'=>$line->rowid,
'type'=>$line->product_type, 'type'=>$line->product_type,
'desc'=>dol_htmlcleanlastbr($line->description), 'desc'=>dol_htmlcleanlastbr($line->description),
@ -397,10 +390,10 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty)
'total'=>$line->total_ttc, 'total'=>$line->total_ttc,
'vat_rate'=>$line->tva_tx, 'vat_rate'=>$line->tva_tx,
'qty'=>$line->qty, 'qty'=>$line->qty,
'product_ref'=>$line->product_ref, 'product_ref'=>$line->product_ref,
'product_label'=>$line->product_label, 'product_label'=>$line->product_label,
'product_desc'=>$line->product_desc, 'product_desc'=>$line->product_desc,
); );
} }
// Now define invoice // Now define invoice
@ -439,15 +432,13 @@ function getSupplierInvoicesForThirdParty($authentication, $idthirdparty)
'invoices'=>$linesinvoice 'invoices'=>$linesinvoice
); );
} } else {
else {
$error++; $error++;
$errorcode = $db->lasterrno(); $errorlabel = $db->lasterror(); $errorcode = $db->lasterrno(); $errorlabel = $db->lasterror();
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -20,7 +20,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require_once '../master.inc.php'; require_once '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -36,8 +38,7 @@ dol_syslog("Call Dolibarr webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -130,20 +131,23 @@ $extrafield_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_array = array(); $extrafield_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
//$value=$object->array_options["options_".$key]; //$value=$object->array_options["options_".$key];
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type); $extrafield_array['options_'.$key] = array('name'=>'options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_array)) $thirdparty_fields = array_merge($thirdparty_fields, $extrafield_array); if (is_array($extrafield_array)) {
$thirdparty_fields = array_merge($thirdparty_fields, $extrafield_array);
}
// Define other specific objects // Define other specific objects
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
@ -265,16 +269,16 @@ $server->register(
// Register WSDL // Register WSDL
$server->register( $server->register(
'deleteThirdParty', 'deleteThirdParty',
// Entry values // Entry values
array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'), array('authentication'=>'tns:authentication', 'id'=>'xsd:string', 'ref'=>'xsd:string', 'ref_ext'=>'xsd:string'),
// Exit values // Exit values
array('result'=>'tns:result', 'id'=>'xsd:string'), array('result'=>'tns:result', 'id'=>'xsd:string'),
$ns, $ns,
$ns.'#deleteThirdParty', $ns.'#deleteThirdParty',
$styledoc, $styledoc,
$styleuse, $styleuse,
'WS to delete a thirdparty from its id, ref or ref_ext' 'WS to delete a thirdparty from its id, ref or ref_ext'
); );
@ -294,7 +298,9 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
dol_syslog("Function: getThirdParty login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); dol_syslog("Function: getThirdParty login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -302,27 +308,23 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->societe->lire) if ($fuser->rights->societe->lire) {
{
$thirdparty = new Societe($db); $thirdparty = new Societe($db);
$result = $thirdparty->fetch($id, $ref, $ref_ext); $result = $thirdparty->fetch($id, $ref, $ref_ext);
if ($result > 0) if ($result > 0) {
{
$thirdparty_result_fields = array( $thirdparty_result_fields = array(
'id' => $thirdparty->id, 'id' => $thirdparty->id,
'ref' => $thirdparty->name, 'ref' => $thirdparty->name,
'ref_ext' => $thirdparty->ref_ext, 'ref_ext' => $thirdparty->ref_ext,
'status' => $thirdparty->status, 'status' => $thirdparty->status,
'client' => $thirdparty->client, 'client' => $thirdparty->client,
'supplier' => $thirdparty->fournisseur, 'supplier' => $thirdparty->fournisseur,
'customer_code' => $thirdparty->code_client, 'customer_code' => $thirdparty->code_client,
@ -351,7 +353,7 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
'profid5' => $thirdparty->idprof5, 'profid5' => $thirdparty->idprof5,
'profid6' => $thirdparty->idprof6, 'profid6' => $thirdparty->idprof6,
'capital' => $thirdparty->capital, 'capital' => $thirdparty->capital,
'barcode' => $thirdparty->barcode, 'barcode' => $thirdparty->barcode,
'vat_used' => $thirdparty->tva_assuj, 'vat_used' => $thirdparty->tva_assuj,
'vat_number' => $thirdparty->tva_intra, 'vat_number' => $thirdparty->tva_intra,
'note_private' => $thirdparty->note_private, 'note_private' => $thirdparty->note_private,
@ -366,10 +368,8 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
//Get extrafield values //Get extrafield values
$thirdparty->fetch_optionals(); $thirdparty->fetch_optionals();
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
if (isset($thirdparty->array_options['options_'.$key])) { if (isset($thirdparty->array_options['options_'.$key])) {
$thirdparty_result_fields = array_merge($thirdparty_result_fields, array('options_'.$key => $thirdparty->array_options['options_'.$key])); $thirdparty_result_fields = array_merge($thirdparty_result_fields, array('options_'.$key => $thirdparty->array_options['options_'.$key]));
} }
@ -380,20 +380,17 @@ function getThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'thirdparty'=>$thirdparty_result_fields); 'thirdparty'=>$thirdparty_result_fields);
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -417,7 +414,9 @@ function createThirdParty($authentication, $thirdparty)
dol_syslog("Function: createThirdParty login=".$authentication['login']); dol_syslog("Function: createThirdParty login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -425,14 +424,12 @@ function createThirdParty($authentication, $thirdparty)
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (empty($thirdparty['ref'])) if (empty($thirdparty['ref'])) {
{
$error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Name is mandatory.";
} }
if (!$error) if (!$error) {
{
include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
$newobject = new Societe($db); $newobject = new Societe($db);
@ -454,7 +451,9 @@ function createThirdParty($authentication, $thirdparty)
$newobject->town = $thirdparty['town']; $newobject->town = $thirdparty['town'];
$newobject->country_id = $thirdparty['country_id']; $newobject->country_id = $thirdparty['country_id'];
if ($thirdparty['country_code']) $newobject->country_id = getCountry($thirdparty['country_code'], 3); if ($thirdparty['country_code']) {
$newobject->country_id = getCountry($thirdparty['country_code'], 3);
}
$newobject->province_id = $thirdparty['province_id']; $newobject->province_id = $thirdparty['province_id'];
//if ($thirdparty['province_code']) $newobject->province_code=getCountry($thirdparty['province_code'],3); //if ($thirdparty['province_code']) $newobject->province_code=getCountry($thirdparty['province_code'],3);
@ -484,10 +483,8 @@ function createThirdParty($authentication, $thirdparty)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
if (isset($thirdparty[$key])) { if (isset($thirdparty[$key])) {
$newobject->array_options[$key] = $thirdparty[$key]; $newobject->array_options[$key] = $thirdparty[$key];
@ -503,22 +500,20 @@ function createThirdParty($authentication, $thirdparty)
$newobject->name_bis = $thirdparty['lastname']; $newobject->name_bis = $thirdparty['lastname'];
$result = $newobject->create_individual($fuser); $result = $newobject->create_individual($fuser);
} }
if ($result <= 0) if ($result <= 0) {
{
$error++; $error++;
} }
if (!$error) if (!$error) {
{
$db->commit(); $db->commit();
// Patch to add capability to associate (one) sale representative // Patch to add capability to associate (one) sale representative
if (!empty($thirdparty['commid']) && $thirdparty['commid'] > 0) if (!empty($thirdparty['commid']) && $thirdparty['commid'] > 0) {
$newobject->add_commercial($fuser, $thirdparty["commid"]); $newobject->add_commercial($fuser, $thirdparty["commid"]);
}
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''), 'id'=>$newobject->id, 'ref'=>$newobject->ref);
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -526,8 +521,7 @@ function createThirdParty($authentication, $thirdparty)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -549,7 +543,9 @@ function updateThirdParty($authentication, $thirdparty)
dol_syslog("Function: updateThirdParty login=".$authentication['login']); dol_syslog("Function: updateThirdParty login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -561,8 +557,7 @@ function updateThirdParty($authentication, $thirdparty)
$error++; $errorcode = 'KO'; $errorlabel = "Thirdparty id is mandatory."; $error++; $errorcode = 'KO'; $errorlabel = "Thirdparty id is mandatory.";
} }
if (!$error) if (!$error) {
{
$objectfound = false; $objectfound = false;
include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
@ -591,7 +586,9 @@ function updateThirdParty($authentication, $thirdparty)
$object->town = $thirdparty['town']; $object->town = $thirdparty['town'];
$object->country_id = $thirdparty['country_id']; $object->country_id = $thirdparty['country_id'];
if ($thirdparty['country_code']) $object->country_id = getCountry($thirdparty['country_code'], 3); if ($thirdparty['country_code']) {
$object->country_id = getCountry($thirdparty['country_code'], 3);
}
$object->province_id = $thirdparty['province_id']; $object->province_id = $thirdparty['province_id'];
//if ($thirdparty['province_code']) $newobject->province_code=getCountry($thirdparty['province_code'],3); //if ($thirdparty['province_code']) $newobject->province_code=getCountry($thirdparty['province_code'],3);
@ -620,10 +617,8 @@ function updateThirdParty($authentication, $thirdparty)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$key = 'options_'.$key; $key = 'options_'.$key;
if (isset($thirdparty[$key])) { if (isset($thirdparty[$key])) {
$object->array_options[$key] = $thirdparty[$key]; $object->array_options[$key] = $thirdparty[$key];
@ -639,16 +634,13 @@ function updateThirdParty($authentication, $thirdparty)
} }
} }
if ((!$error) && ($objectfound)) if ((!$error) && ($objectfound)) {
{
$db->commit(); $db->commit();
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
'id'=>$object->id 'id'=>$object->id
); );
} } elseif ($objectfound) {
elseif ($objectfound)
{
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
@ -660,8 +652,7 @@ function updateThirdParty($authentication, $thirdparty)
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -683,7 +674,9 @@ function getListOfThirdParties($authentication, $filterthirdparty)
dol_syslog("Function: getListOfThirdParties login=".$authentication['login']); dol_syslog("Function: getListOfThirdParties login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -694,20 +687,26 @@ function getListOfThirdParties($authentication, $filterthirdparty)
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error) if (!$error) {
{
$sql = "SELECT s.rowid as socRowid, s.nom as ref, s.ref_ext, s.address, s.zip, s.town, c.label as country, s.phone, s.fax, s.url, extra.*"; $sql = "SELECT s.rowid as socRowid, s.nom as ref, s.ref_ext, s.address, s.zip, s.town, c.label as country, s.phone, s.fax, s.url, extra.*";
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON s.fk_pays = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON s.fk_pays = c.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as extra ON s.rowid=fk_object"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as extra ON s.rowid=fk_object";
$sql .= " WHERE entity=".$conf->entity; $sql .= " WHERE entity=".$conf->entity;
foreach ($filterthirdparty as $key => $val) foreach ($filterthirdparty as $key => $val) {
{ if ($key == 'name' && $val != '') {
if ($key == 'name' && $val != '') $sql .= " AND s.name LIKE '%".$db->escape($val)."%'"; $sql .= " AND s.name LIKE '%".$db->escape($val)."%'";
if ($key == 'client' && (int) $val > 0) $sql .= " AND s.client = ".$db->escape($val); }
if ($key == 'supplier' && (int) $val > 0) $sql .= " AND s.fournisseur = ".$db->escape($val); if ($key == 'client' && (int) $val > 0) {
if ($key == 'category' && (int) $val > 0) $sql .= " AND s.rowid IN (SELECT fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_categorie=".$db->escape($val).") "; $sql .= " AND s.client = ".$db->escape($val);
}
if ($key == 'supplier' && (int) $val > 0) {
$sql .= " AND s.fournisseur = ".$db->escape($val);
}
if ($key == 'category' && (int) $val > 0) {
$sql .= " AND s.rowid IN (SELECT fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_categorie=".$db->escape($val).") ";
}
} }
dol_syslog("Function: getListOfThirdParties", LOG_DEBUG); dol_syslog("Function: getListOfThirdParties", LOG_DEBUG);
@ -718,20 +717,16 @@ function getListOfThirdParties($authentication, $filterthirdparty)
$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) {
{
$extrafieldsOptions = array(); $extrafieldsOptions = array();
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
if (isset($obj->{$key})) { if (isset($obj->{$key})) {
$extrafieldsOptions['options_'.$key] = $obj->{$key}; $extrafieldsOptions['options_'.$key] = $obj->{$key};
} }
@ -753,22 +748,19 @@ function getListOfThirdParties($authentication, $filterthirdparty)
$i++; $i++;
} }
} } else {
else {
$error++; $error++;
$errorcode = $db->lasterrno(); $errorcode = $db->lasterrno();
$errorlabel = $db->lasterror(); $errorlabel = $db->lasterror();
} }
} }
if ($error) if ($error) {
{
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel),
'thirdparties'=>$arraythirdparties 'thirdparties'=>$arraythirdparties
); );
} } else {
else {
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => 'OK', 'result_label' => ''), 'result'=>array('result_code' => 'OK', 'result_label' => ''),
'thirdparties'=>$arraythirdparties 'thirdparties'=>$arraythirdparties
@ -793,7 +785,9 @@ function deleteThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
dol_syslog("Function: deleteThirdParty login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); dol_syslog("Function: deleteThirdParty login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -801,56 +795,47 @@ function deleteThirdParty($authentication, $id = '', $ref = '', $ref_ext = '')
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) {
{
dol_syslog("Function: deleteThirdParty checkparam"); dol_syslog("Function: deleteThirdParty checkparam");
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
dol_syslog("Function: deleteThirdParty 1"); dol_syslog("Function: deleteThirdParty 1");
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->societe->lire && $fuser->rights->societe->supprimer) if ($fuser->rights->societe->lire && $fuser->rights->societe->supprimer) {
{
$thirdparty = new Societe($db); $thirdparty = new Societe($db);
$result = $thirdparty->fetch($id, $ref, $ref_ext); $result = $thirdparty->fetch($id, $ref, $ref_ext);
if ($result > 0) if ($result > 0) {
{
$db->begin(); $db->begin();
$result = $thirdparty->delete($thirdparty->id, $fuser); $result = $thirdparty->delete($thirdparty->id, $fuser);
if ($result > 0) if ($result > 0) {
{
$db->commit(); $db->commit();
$objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>'')); $objectresp = array('result'=>array('result_code'=>'OK', 'result_label'=>''));
} } else {
else {
$db->rollback(); $db->rollback();
$error++; $error++;
$errorcode = 'KO'; $errorcode = 'KO';
$errorlabel = $thirdparty->error; $errorlabel = $thirdparty->error;
dol_syslog("Function: deleteThirdParty cant delete"); dol_syslog("Function: deleteThirdParty cant delete");
} }
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }

View File

@ -20,7 +20,9 @@
* \brief File that is entry point to call Dolibarr WebServices * \brief File that is entry point to call Dolibarr WebServices
*/ */
if (!defined("NOCSRFCHECK")) define("NOCSRFCHECK", '1'); if (!defined("NOCSRFCHECK")) {
define("NOCSRFCHECK", '1');
}
require_once '../master.inc.php'; require_once '../master.inc.php';
require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
@ -36,8 +38,7 @@ dol_syslog("Call User webservices interfaces");
$langs->load("main"); $langs->load("main");
// Enable and test if module web services is enabled // Enable and test if module web services is enabled
if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) if (empty($conf->global->MAIN_MODULE_WEBSERVICES)) {
{
$langs->load("admin"); $langs->load("admin");
dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled"); dol_syslog("Call Dolibarr webservices interfaces with module webservices disabled");
print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>'; print $langs->trans("WarningModuleNotActive", 'WebServices').'.<br><br>';
@ -193,19 +194,22 @@ $extrafield_array = null;
if (is_array($extrafields) && count($extrafields) > 0) { if (is_array($extrafields) && count($extrafields) > 0) {
$extrafield_array = array(); $extrafield_array = array();
} }
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$type = $extrafields->attributes[$elementtype]['type'][$key]; $type = $extrafields->attributes[$elementtype]['type'][$key];
if ($type == 'date' || $type == 'datetime') {$type = 'xsd:dateTime'; } if ($type == 'date' || $type == 'datetime') {
else {$type = 'xsd:string'; } $type = 'xsd:dateTime';
} else {
$type = 'xsd:string';
}
$extrafield_array['contact_options_'.$key] = array('name'=>'contact_options_'.$key, 'type'=>$type); $extrafield_array['contact_options_'.$key] = array('name'=>'contact_options_'.$key, 'type'=>$type);
} }
} }
if (is_array($extrafield_array)) $thirdpartywithuser_fields = array_merge($thirdpartywithuser_fields, $extrafield_array); if (is_array($extrafield_array)) {
$thirdpartywithuser_fields = array_merge($thirdpartywithuser_fields, $extrafield_array);
}
$server->wsdl->addComplexType( $server->wsdl->addComplexType(
@ -312,7 +316,9 @@ function getUser($authentication, $id, $ref = '', $ref_ext = '')
dol_syslog("Function: getUser login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext); dol_syslog("Function: getUser login=".$authentication['login']." id=".$id." ref=".$ref." ref_ext=".$ref_ext);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -320,25 +326,21 @@ function getUser($authentication, $id, $ref = '', $ref_ext = '')
$error = 0; $error = 0;
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) if (!$error && (($id && $ref) || ($id && $ref_ext) || ($ref && $ref_ext))) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter id, ref and ref_ext can't be both provided. You must choose one or other but not both.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->user->user->lire if ($fuser->rights->user->user->lire
|| ($fuser->rights->user->self->creer && $id && $id == $fuser->id) || ($fuser->rights->user->self->creer && $id && $id == $fuser->id)
|| ($fuser->rights->user->self->creer && $ref && $ref == $fuser->login) || ($fuser->rights->user->self->creer && $ref && $ref == $fuser->login)
|| ($fuser->rights->user->self->creer && $ref_ext && $ref_ext == $fuser->ref_ext)) || ($fuser->rights->user->self->creer && $ref_ext && $ref_ext == $fuser->ref_ext)) {
{
$user = new User($db); $user = new User($db);
$result = $user->fetch($id, $ref, $ref_ext); $result = $user->fetch($id, $ref, $ref_ext);
if ($result > 0) if ($result > 0) {
{
// Create // Create
$objectresp = array( $objectresp = array(
'result'=>array('result_code'=>'OK', 'result_label'=>''), 'result'=>array('result_code'=>'OK', 'result_label'=>''),
@ -371,20 +373,17 @@ function getUser($authentication, $id, $ref = '', $ref_ext = '')
'canvas' => $user->canvas 'canvas' => $user->canvas
) )
); );
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext; $errorcode = 'NOT_FOUND'; $errorlabel = 'Object not found for id='.$id.' nor ref='.$ref.' nor ref_ext='.$ref_ext;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)); $objectresp = array('result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel));
} }
@ -403,7 +402,9 @@ function getListOfGroups($authentication)
dol_syslog("Function: getListOfGroups login=".$authentication['login']); dol_syslog("Function: getListOfGroups login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
// Init and check authentication // Init and check authentication
$objectresp = array(); $objectresp = array();
@ -413,47 +414,39 @@ function getListOfGroups($authentication)
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
// Check parameters // Check parameters
if (!$error) if (!$error) {
{
$sql = "SELECT g.rowid, g.nom as name, g.entity, g.datec, COUNT(DISTINCT ugu.fk_user) as nb"; $sql = "SELECT g.rowid, g.nom as name, g.entity, g.datec, COUNT(DISTINCT ugu.fk_user) as nb";
$sql .= " FROM ".MAIN_DB_PREFIX."usergroup as g"; $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as g";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_usergroup = g.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_usergroup = g.rowid";
if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity))) {
{
$sql .= " WHERE g.entity IS NOT NULL"; $sql .= " WHERE g.entity IS NOT NULL";
} } else {
else {
$sql .= " WHERE g.entity IN (0,".$conf->entity.")"; $sql .= " WHERE g.entity IN (0,".$conf->entity.")";
} }
$sql .= " GROUP BY g.rowid, g.nom, g.entity, g.datec"; $sql .= " GROUP BY g.rowid, g.nom, g.entity, g.datec";
$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);
$arraygroups[] = array('id'=>$obj->rowid, 'name'=>$obj->name, 'datec'=>$obj->datec, 'nb'=>$obj->nb); $arraygroups[] = array('id'=>$obj->rowid, 'name'=>$obj->name, 'datec'=>$obj->datec, 'nb'=>$obj->nb);
$i++; $i++;
} }
} } else {
else {
$error++; $error++;
$errorcode = $db->lasterrno(); $errorcode = $db->lasterrno();
$errorlabel = $db->lasterror(); $errorlabel = $db->lasterror();
} }
} }
if ($error) if ($error) {
{
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel), 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel),
'groups'=>$arraygroups 'groups'=>$arraygroups
); );
} } else {
else {
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => 'OK', 'result_label' => ''), 'result'=>array('result_code' => 'OK', 'result_label' => ''),
'groups'=>$arraygroups 'groups'=>$arraygroups
@ -477,7 +470,9 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
dol_syslog("Function: createUserFromThirdparty login=".$authentication['login']); dol_syslog("Function: createUserFromThirdparty login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
@ -485,20 +480,19 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
if (!$error && !$thirdpartywithuser) if (!$error && !$thirdpartywithuser) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter thirdparty must be provided."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter thirdparty must be provided.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->societe->creer) if ($fuser->rights->societe->creer) {
{
$thirdparty = new Societe($db); $thirdparty = new Societe($db);
// If a contact / company already exists with the email, return the corresponding socid // If a contact / company already exists with the email, return the corresponding socid
@ -510,16 +504,13 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
$sql .= $db->plimit(1); $sql .= $db->plimit(1);
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
// If a company or contact is found with the same email we return an error // If a company or contact is found with the same email we return an error
$row = $db->fetch_object($resql); $row = $db->fetch_object($resql);
if ($row) if ($row) {
{
$error++; $error++;
$errorcode = 'ALREADY_EXIST'; $errorlabel = 'Object not create : company or contact exists '.$thirdpartywithuser['email']; $errorcode = 'ALREADY_EXIST'; $errorlabel = 'Object not create : company or contact exists '.$thirdpartywithuser['email'];
} } else {
else {
$db->begin(); $db->begin();
/* /*
* Company creation * Company creation
@ -541,11 +532,9 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
$sql .= " AND code='".$db->escape($thirdparty->country_code)."'"; $sql .= " AND code='".$db->escape($thirdparty->country_code)."'";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
if ($num) if ($num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$thirdparty->country_id = $obj->rowid; $thirdparty->country_id = $obj->rowid;
} }
@ -567,8 +556,7 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
$socid_return = $thirdparty->create($fuser); $socid_return = $thirdparty->create($fuser);
if ($socid_return > 0) if ($socid_return > 0) {
{
$thirdparty->fetch($socid_return); $thirdparty->fetch($socid_return);
/* /*
@ -597,10 +585,8 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
// fetch optionals attributes and labels // fetch optionals attributes and labels
$extrafields = new ExtraFields($db); $extrafields = new ExtraFields($db);
$extrafields->fetch_name_optionals_label($elementtype, true); $extrafields->fetch_name_optionals_label($elementtype, true);
if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) if (isset($extrafields->attributes[$elementtype]['label']) && is_array($extrafields->attributes[$elementtype]['label']) && count($extrafields->attributes[$elementtype]['label'])) {
{ foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label) {
foreach ($extrafields->attributes[$elementtype]['label'] as $key => $label)
{
$key = 'contact_options_'.$key; $key = 'contact_options_'.$key;
$key = substr($key, 8); // Remove 'contact_' prefix $key = substr($key, 8); // Remove 'contact_' prefix
$contact->array_options[$key] = $thirdpartywithuser[$key]; $contact->array_options[$key] = $thirdpartywithuser[$key];
@ -609,8 +595,7 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
$contact_id = $contact->create($fuser); $contact_id = $contact->create($fuser);
if ($contact_id > 0) if ($contact_id > 0) {
{
/* /*
* User creation * User creation
* *
@ -618,19 +603,17 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
$edituser = new User($db); $edituser = new User($db);
$id = $edituser->create_from_contact($contact, $thirdpartywithuser["login"]); $id = $edituser->create_from_contact($contact, $thirdpartywithuser["login"]);
if ($id > 0) if ($id > 0) {
{
$edituser->setPassword($fuser, trim($thirdpartywithuser['password'])); $edituser->setPassword($fuser, trim($thirdpartywithuser['password']));
if ($thirdpartywithuser['group_id'] > 0) if ($thirdpartywithuser['group_id'] > 0) {
$edituser->SetInGroup($thirdpartywithuser['group_id'], $conf->entity); $edituser->SetInGroup($thirdpartywithuser['group_id'], $conf->entity);
} }
else { } else {
$error++; $error++;
$errorcode = 'NOT_CREATE'; $errorlabel = 'Object not create : '.$edituser->error; $errorcode = 'NOT_CREATE'; $errorlabel = 'Object not create : '.$edituser->error;
} }
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_CREATE'; $errorlabel = 'Object not create : '.$contact->error; $errorcode = 'NOT_CREATE'; $errorlabel = 'Object not create : '.$contact->error;
} }
@ -656,8 +639,7 @@ function createUserFromThirdparty($authentication, $thirdpartywithuser)
} }
} }
if ($error) if ($error) {
{
$db->rollback(); $db->rollback();
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel) 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)
@ -682,7 +664,9 @@ function setUserPassword($authentication, $shortuser)
dol_syslog("Function: setUserPassword login=".$authentication['login']); dol_syslog("Function: setUserPassword login=".$authentication['login']);
if ($authentication['entity']) $conf->entity = $authentication['entity']; if ($authentication['entity']) {
$conf->entity = $authentication['entity'];
}
$objectresp = array(); $objectresp = array();
$errorcode = ''; $errorlabel = ''; $errorcode = ''; $errorlabel = '';
@ -690,50 +674,43 @@ function setUserPassword($authentication, $shortuser)
$fuser = check_authentication($authentication, $error, $errorcode, $errorlabel); $fuser = check_authentication($authentication, $error, $errorcode, $errorlabel);
if ($fuser->socid) $socid = $fuser->socid; if ($fuser->socid) {
$socid = $fuser->socid;
}
if (!$error && !$shortuser) if (!$error && !$shortuser) {
{
$error++; $error++;
$errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter shortuser must be provided."; $errorcode = 'BAD_PARAMETERS'; $errorlabel = "Parameter shortuser must be provided.";
} }
if (!$error) if (!$error) {
{
$fuser->getrights(); $fuser->getrights();
if ($fuser->rights->user->user->password || $fuser->rights->user->self->password) if ($fuser->rights->user->user->password || $fuser->rights->user->self->password) {
{
$userstat = new User($db); $userstat = new User($db);
$res = $userstat->fetch('', $shortuser['login']); $res = $userstat->fetch('', $shortuser['login']);
if ($res) if ($res) {
{
$res = $userstat->setPassword($userstat, $shortuser['password']); $res = $userstat->setPassword($userstat, $shortuser['password']);
if ($res) if ($res) {
{
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => 'OK', 'result_label' => ''), 'result'=>array('result_code' => 'OK', 'result_label' => ''),
); );
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_MODIFIED'; $errorlabel = 'Error when changing password'; $errorcode = 'NOT_MODIFIED'; $errorlabel = 'Error when changing password';
} }
} } else {
else {
$error++; $error++;
$errorcode = 'NOT_FOUND'; $errorlabel = 'User not found'; $errorcode = 'NOT_FOUND'; $errorlabel = 'User not found';
} }
} } else {
else {
$error++; $error++;
$errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request'; $errorcode = 'PERMISSION_DENIED'; $errorlabel = 'User does not have permission for this request';
} }
} }
if ($error) if ($error) {
{
$objectresp = array( $objectresp = array(
'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel) 'result'=>array('result_code' => $errorcode, 'result_label' => $errorlabel)
); );

View File

@ -244,7 +244,9 @@ class Website extends CommonObject
if (is_array($tmplangarray)) { if (is_array($tmplangarray)) {
dol_mkdir($conf->website->dir_output.'/'.$this->ref); dol_mkdir($conf->website->dir_output.'/'.$this->ref);
foreach ($tmplangarray as $val) { foreach ($tmplangarray as $val) {
if (trim($val) == $this->lang) continue; if (trim($val) == $this->lang) {
continue;
}
dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val)); dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
} }
} }
@ -540,7 +542,9 @@ class Website extends CommonObject
if (is_array($tmplangarray)) { if (is_array($tmplangarray)) {
dol_mkdir($conf->website->dir_output.'/'.$this->ref); dol_mkdir($conf->website->dir_output.'/'.$this->ref);
foreach ($tmplangarray as $val) { foreach ($tmplangarray as $val) {
if (trim($val) == $this->lang) continue; if (trim($val) == $this->lang) {
continue;
}
dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val)); dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val));
} }
} }
@ -603,8 +607,7 @@ class Website extends CommonObject
} }
} }
if (!$error && !empty($this->ref)) if (!$error && !empty($this->ref)) {
{
$pathofwebsite = DOL_DATA_ROOT.'/website/'.$this->ref; $pathofwebsite = DOL_DATA_ROOT.'/website/'.$this->ref;
dol_delete_dir_recursive($pathofwebsite); dol_delete_dir_recursive($pathofwebsite);
@ -645,8 +648,7 @@ class Website extends CommonObject
$object = new self($this->db); $object = new self($this->db);
// Check no site with ref exists // Check no site with ref exists
if ($object->fetch(0, $newref) > 0) if ($object->fetch(0, $newref) > 0) {
{
$this->error = 'ErrorNewRefIsAlreadyUsed'; $this->error = 'ErrorNewRefIsAlreadyUsed';
return -1; return -1;
} }
@ -678,7 +680,9 @@ class Website extends CommonObject
$object->fk_user_creat = $user->id; $object->fk_user_creat = $user->id;
$object->position = ((int) $object->position) + 1; $object->position = ((int) $object->position) + 1;
$object->status = self::STATUS_DRAFT; $object->status = self::STATUS_DRAFT;
if (empty($object->lang)) $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages if (empty($object->lang)) {
$object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages
}
// Create clone // Create clone
$object->context['createfromclone'] = 'createfromclone'; $object->context['createfromclone'] = 'createfromclone';
@ -690,15 +694,13 @@ class Website extends CommonObject
dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
} }
if (!$error) if (!$error) {
{
dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2); dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2);
// Check symlink to medias and restore it if ko // Check symlink to medias and restore it if ko
$pathtomedias = DOL_DATA_ROOT.'/medias'; // Target $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target
$pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name
if (!is_link(dol_osencode($pathtomediasinwebsite))) if (!is_link(dol_osencode($pathtomediasinwebsite))) {
{
dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists
$result = symlink($pathtomedias, $pathtomediasinwebsite); $result = symlink($pathtomedias, $pathtomediasinwebsite);
@ -718,8 +720,7 @@ class Website extends CommonObject
// Duplicate pages // Duplicate pages
$objectpages = new WebsitePage($this->db); $objectpages = new WebsitePage($this->db);
$listofpages = $objectpages->fetchAll($fromid); $listofpages = $objectpages->fetchAll($fromid);
foreach ($listofpages as $pageid => $objectpageold) foreach ($listofpages as $pageid => $objectpageold) {
{
// Delete old file // Delete old file
$filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php'; $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php';
dol_delete_file($filetplold); dol_delete_file($filetplold);
@ -728,43 +729,41 @@ class Website extends CommonObject
$objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1); $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1);
//print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>'; //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>';
if (is_object($objectpagenew) && $objectpagenew->pageurl) if (is_object($objectpagenew) && $objectpagenew->pageurl) {
{
$filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php'; $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php';
$filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php'; $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php';
// Save page alias // Save page alias
$result = dolSavePageAlias($filealias, $object, $objectpagenew); $result = dolSavePageAlias($filealias, $object, $objectpagenew);
if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); if (!$result) {
setEventMessages('Failed to write file '.$filealias, null, 'errors');
}
$result = dolSavePageContent($filetplnew, $object, $objectpagenew); $result = dolSavePageContent($filetplnew, $object, $objectpagenew);
if (!$result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors'); if (!$result) {
setEventMessages('Failed to write file '.$filetplnew, null, 'errors');
}
if ($pageid == $oldidforhome) if ($pageid == $oldidforhome) {
{
$newidforhome = $objectpagenew->id; $newidforhome = $objectpagenew->id;
} }
} } else {
else {
setEventMessages($objectpageold->error, $objectpageold->errors, 'errors'); setEventMessages($objectpageold->error, $objectpageold->errors, 'errors');
$error++; $error++;
} }
} }
} }
if (!$error) if (!$error) {
{
// Restore id of home page // Restore id of home page
$object->fk_default_home = $newidforhome; $object->fk_default_home = $newidforhome;
$res = $object->update($user); $res = $object->update($user);
if (!($res > 0)) if (!($res > 0)) {
{
$error++; $error++;
setEventMessages($object->error, $object->errors, 'errors'); setEventMessages($object->error, $object->errors, 'errors');
} }
if (!$error) if (!$error) {
{
$filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php'; $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php';
$filewrapper = $pathofwebsitenew.'/wrapper.php'; $filewrapper = $pathofwebsitenew.'/wrapper.php';
@ -821,10 +820,11 @@ class Website extends CommonObject
$linkstart = $linkend = ''; $linkstart = $linkend = '';
if ($withpicto) if ($withpicto) {
{
$result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend); $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
if ($withpicto != 2) $result .= ' '; if ($withpicto != 2) {
$result .= ' ';
}
} }
$result .= $linkstart.$this->ref.$linkend; $result .= $linkstart.$this->ref.$linkend;
return $result; return $result;
@ -854,8 +854,7 @@ class Website extends CommonObject
// phpcs:enable // phpcs:enable
global $langs; global $langs;
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('Disabled'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled');
@ -865,7 +864,9 @@ class Website extends CommonObject
} }
$statusType = 'status5'; $statusType = 'status5';
if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) {
$statusType = 'status4';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }
@ -909,16 +910,14 @@ class Website extends CommonObject
$website = $this; $website = $this;
if (empty($website->id) || empty($website->ref)) if (empty($website->id) || empty($website->ref)) {
{
setEventMessages("Website id or ref is not defined", null, 'errors'); setEventMessages("Website id or ref is not defined", null, 'errors');
return ''; return '';
} }
dol_syslog("Create temp dir ".$conf->website->dir_temp); dol_syslog("Create temp dir ".$conf->website->dir_temp);
dol_mkdir($conf->website->dir_temp); dol_mkdir($conf->website->dir_temp);
if (!is_writable($conf->website->dir_temp)) if (!is_writable($conf->website->dir_temp)) {
{
setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors'); setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors');
return ''; return '';
} }
@ -928,8 +927,7 @@ class Website extends CommonObject
dol_syslog("Clear temp dir ".$destdir); dol_syslog("Clear temp dir ".$destdir);
$count = 0; $countreallydeleted = 0; $count = 0; $countreallydeleted = 0;
$counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted); $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted);
if ($counttodelete != $countreallydeleted) if ($counttodelete != $countreallydeleted) {
{
setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors'); setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors');
return ''; return '';
} }
@ -987,8 +985,7 @@ class Website extends CommonObject
// Build sql file // Build sql file
$filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql'; $filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql';
$fp = fopen($filesql, "w"); $fp = fopen($filesql, "w");
if (empty($fp)) if (empty($fp)) {
{
setEventMessages("Failed to create file ".$filesql, null, 'errors'); setEventMessages("Failed to create file ".$filesql, null, 'errors');
return ''; return '';
} }
@ -998,20 +995,16 @@ class Website extends CommonObject
// Assign ->newid and ->newfk_page // Assign ->newid and ->newfk_page
$i = 1; $i = 1;
foreach ($listofpages as $pageid => $objectpageold) foreach ($listofpages as $pageid => $objectpageold) {
{
$objectpageold->newid = $i; $objectpageold->newid = $i;
$i++; $i++;
} }
$i = 1; $i = 1;
foreach ($listofpages as $pageid => $objectpageold) foreach ($listofpages as $pageid => $objectpageold) {
{
// Search newid // Search newid
$newfk_page = 0; $newfk_page = 0;
foreach ($listofpages as $pageid2 => $objectpageold2) foreach ($listofpages as $pageid2 => $objectpageold2) {
{ if ($pageid2 == $objectpageold->fk_page) {
if ($pageid2 == $objectpageold->fk_page)
{
$newfk_page = $objectpageold2->newid; $newfk_page = $objectpageold2->newid;
break; break;
} }
@ -1019,8 +1012,7 @@ class Website extends CommonObject
$objectpageold->newfk_page = $newfk_page; $objectpageold->newfk_page = $newfk_page;
$i++; $i++;
} }
foreach ($listofpages as $pageid => $objectpageold) foreach ($listofpages as $pageid => $objectpageold) {
{
$allaliases = $objectpageold->pageurl; $allaliases = $objectpageold->pageurl;
$allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : ''); $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : '');
@ -1081,8 +1073,7 @@ class Website extends CommonObject
// Add line to update home page id during import // Add line to update home page id during import
//var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit; //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit;
if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) // This is the record with home page if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) { // This is the record with home page
{
// Warning: We must keep llx_ here. It is a generic SQL. // Warning: We must keep llx_ here. It is a generic SQL.
$line = "UPDATE llx_website SET fk_default_home = ".($objectpageold->newid > 0 ? $this->db->escape($objectpageold->newid)."__+MAX_llx_website_page__" : "null")." WHERE rowid = __WEBSITE_ID__;"; $line = "UPDATE llx_website SET fk_default_home = ".($objectpageold->newid > 0 ? $this->db->escape($objectpageold->newid)."__+MAX_llx_website_page__" : "null")." WHERE rowid = __WEBSITE_ID__;";
$line .= "\n"; $line .= "\n";
@ -1091,8 +1082,9 @@ class Website extends CommonObject
} }
fclose($fp); fclose($fp);
if (!empty($conf->global->MAIN_UMASK)) if (!empty($conf->global->MAIN_UMASK)) {
@chmod($filesql, octdec($conf->global->MAIN_UMASK)); @chmod($filesql, octdec($conf->global->MAIN_UMASK));
}
// Build zip file // Build zip file
$filedir = $conf->website->dir_temp.'/'.$website->ref.'/.'; $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.';
@ -1102,11 +1094,9 @@ class Website extends CommonObject
dol_delete_file($fileglob, 0); dol_delete_file($fileglob, 0);
$result = dol_compress_file($filedir, $filename, 'zip'); $result = dol_compress_file($filedir, $filename, 'zip');
if ($result > 0) if ($result > 0) {
{
return $filename; return $filename;
} } else {
else {
global $errormsg; global $errormsg;
$this->error = $errormsg; $this->error = $errormsg;
return ''; return '';
@ -1127,8 +1117,7 @@ class Website extends CommonObject
$error = 0; $error = 0;
$object = $this; $object = $this;
if (empty($object->ref)) if (empty($object->ref)) {
{
$this->error = 'Function importWebSite called on object not loaded (object->ref is empty)'; $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)';
return -1; return -1;
} }
@ -1137,16 +1126,14 @@ class Website extends CommonObject
dol_mkdir($conf->website->dir_temp.'/'.$object->ref); dol_mkdir($conf->website->dir_temp.'/'.$object->ref);
$filename = basename($pathtofile); $filename = basename($pathtofile);
if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) {
{
$this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.'; $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.';
return -1; return -1;
} }
$result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref); $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref);
if (!empty($result['error'])) if (!empty($result['error'])) {
{
$this->errors[] = 'Failed to unzip file '.$pathtofile.'.'; $this->errors[] = 'Failed to unzip file '.$pathtofile.'.';
return -1; return -1;
} }
@ -1172,8 +1159,7 @@ class Website extends CommonObject
// Now generate the master.inc.php page // Now generate the master.inc.php page
$filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php'; $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php';
$result = dolSaveMasterFile($filemaster); $result = dolSaveMasterFile($filemaster);
if (!$result) if (!$result) {
{
$this->errors[] = 'Failed to write file '.$filemaster; $this->errors[] = 'Failed to write file '.$filemaster;
$error++; $error++;
} }
@ -1190,16 +1176,14 @@ class Website extends CommonObject
// Search the $maxrowid because we need it later // Search the $maxrowid because we need it later
$sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page'; $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page';
$resql = $this->db->query($sqlgetrowid); $resql = $this->db->query($sqlgetrowid);
if ($resql) if ($resql) {
{
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
$maxrowid = $obj->max; $maxrowid = $obj->max;
} }
// Load sql record // Load sql record
$runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1); // The maxrowid of table is searched into this function two $runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1); // The maxrowid of table is searched into this function two
if ($runsql <= 0) if ($runsql <= 0) {
{
$this->errors[] = 'Failed to load sql file '.$sqlfile; $this->errors[] = 'Failed to load sql file '.$sqlfile;
$error++; $error++;
} }
@ -1208,16 +1192,13 @@ class Website extends CommonObject
// Make replacement of IDs // Make replacement of IDs
$fp = fopen($sqlfile, "r"); $fp = fopen($sqlfile, "r");
if ($fp) if ($fp) {
{ while (!feof($fp)) {
while (!feof($fp))
{
$reg = array(); $reg = array();
// Warning fgets with second parameter that is null or 0 hang. // Warning fgets with second parameter that is null or 0 hang.
$buf = fgets($fp, 65000); $buf = fgets($fp, 65000);
if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) {
{
$oldid = $reg[1]; $oldid = $reg[1];
$newid = ($reg[2] + $maxrowid); $newid = ($reg[2] + $maxrowid);
$aliasesarray = explode(',', $reg[3]); $aliasesarray = explode(',', $reg[3]);
@ -1237,12 +1218,9 @@ class Website extends CommonObject
} }
// Regenerate alternative aliases pages // Regenerate alternative aliases pages
if (is_array($aliasesarray)) if (is_array($aliasesarray)) {
{ foreach ($aliasesarray as $aliasshortcuttocreate) {
foreach ($aliasesarray as $aliasshortcuttocreate) if (trim($aliasshortcuttocreate)) {
{
if (trim($aliasshortcuttocreate))
{
$filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php'; $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php';
$result = dolSavePageAlias($filealias, $object, $objectpagestatic); $result = dolSavePageAlias($filealias, $object, $objectpagestatic);
if (!$result) { if (!$result) {
@ -1274,12 +1252,10 @@ class Website extends CommonObject
$pathofwebsite = $conf->website->dir_output.'/'.$object->ref; $pathofwebsite = $conf->website->dir_output.'/'.$object->ref;
dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php'); dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php');
if ($error) if ($error) {
{
$this->db->rollback(); $this->db->rollback();
return -1; return -1;
} } else {
else {
$this->db->commit(); $this->db->commit();
return $object->id; return $object->id;
} }
@ -1298,8 +1274,7 @@ class Website extends CommonObject
$error = 0; $error = 0;
$object = $this; $object = $this;
if (empty($object->ref)) if (empty($object->ref)) {
{
$this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)'; $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)';
return -1; return -1;
} }
@ -1386,7 +1361,9 @@ class Website extends CommonObject
{ {
global $websitepagefile, $website; global $websitepagefile, $website;
if (!is_object($weblangs)) return 'ERROR componentSelectLang called with parameter $weblangs not defined'; if (!is_object($weblangs)) {
return 'ERROR componentSelectLang called with parameter $weblangs not defined';
}
$arrayofspecialmainlanguages = array( $arrayofspecialmainlanguages = array(
'en'=>'en_US', 'en'=>'en_US',
@ -1419,51 +1396,55 @@ class Website extends CommonObject
$tmppage = new WebsitePage($this->db); $tmppage = new WebsitePage($this->db);
$pageid = 0; $pageid = 0;
if (!empty($websitepagefile)) if (!empty($websitepagefile)) {
{
$websitepagefileshort = basename($websitepagefile); $websitepagefileshort = basename($websitepagefile);
if ($websitepagefileshort == 'index.php') $pageid = $website->fk_default_home; if ($websitepagefileshort == 'index.php') {
else $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort); $pageid = $website->fk_default_home;
if ($pageid > 0) } else {
{ $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort);
}
if ($pageid > 0) {
$tmppage->fetch($pageid); $tmppage->fetch($pageid);
} }
} }
// Fill $languagecodes array with existing translation, nothing if none // Fill $languagecodes array with existing translation, nothing if none
if (!is_array($languagecodes) && $pageid > 0) if (!is_array($languagecodes) && $pageid > 0) {
{
$languagecodes = array(); $languagecodes = array();
$sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page"; $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page";
$sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp"; $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp";
$sql .= " WHERE wp.fk_website = ".$website->id; $sql .= " WHERE wp.fk_website = ".$website->id;
$sql .= " AND (wp.fk_page = ".$pageid." OR wp.rowid = ".$pageid; $sql .= " AND (wp.fk_page = ".$pageid." OR wp.rowid = ".$pageid;
if ($tmppage->fk_page > 0) $sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page; if ($tmppage->fk_page > 0) {
$sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page;
}
$sql .= ")"; $sql .= ")";
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql) {
{ while ($obj = $this->db->fetch_object($resql)) {
while ($obj = $this->db->fetch_object($resql))
{
$newlang = $obj->lang; $newlang = $obj->lang;
if ($obj->rowid == $pageid) $newlang = $obj->lang; if ($obj->rowid == $pageid) {
if (!in_array($newlang, $languagecodes)) $languagecodes[] = $newlang; $newlang = $obj->lang;
}
if (!in_array($newlang, $languagecodes)) {
$languagecodes[] = $newlang;
}
} }
} }
} }
// Now $languagecodes is always an array. Example array('en', 'fr', 'es'); // Now $languagecodes is always an array. Example array('en', 'fr', 'es');
$languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container
if (!empty($websitepagefile)) if (!empty($websitepagefile)) {
{
$pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile)); $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile));
if ($pageid > 0) if ($pageid > 0) {
{
$pagelang = substr($tmppage->lang, 0, 2); $pagelang = substr($tmppage->lang, 0, 2);
$languagecodeselected = substr($pagelang, 0, 2); $languagecodeselected = substr($pagelang, 0, 2);
if (!in_array($pagelang, $languagecodes)) $languagecodes[] = $pagelang; // We add language code of page into combo list if (!in_array($pagelang, $languagecodes)) {
$languagecodes[] = $pagelang; // We add language code of page into combo list
}
} }
} }
@ -1474,7 +1455,9 @@ class Website extends CommonObject
$url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url
//$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url
$url .= (preg_match('/\?/', $url) ? '&' : '?').'l='; $url .= (preg_match('/\?/', $url) ? '&' : '?').'l=';
if (!preg_match('/^\//', $url)) $url = '/'.$url; if (!preg_match('/^\//', $url)) {
$url = '/'.$url;
}
$HEIGHTOPTION = 40; $HEIGHTOPTION = 40;
$MAXHEIGHT = 4 * $HEIGHTOPTION; $MAXHEIGHT = 4 * $HEIGHTOPTION;
@ -1504,8 +1487,7 @@ class Website extends CommonObject
$out .= '</style>'; $out .= '</style>';
$out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">'; $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">';
if ($languagecodeselected) if ($languagecodeselected) {
{
// Convert $languagecodeselected into a long language code // Convert $languagecodeselected into a long language code
if (strlen($languagecodeselected) == 2) { if (strlen($languagecodeselected) == 2) {
$languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]); $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]);
@ -1513,28 +1495,34 @@ class Website extends CommonObject
$countrycode = strtolower(substr($languagecodeselected, -2)); $countrycode = strtolower(substr($languagecodeselected, -2));
$label = $weblangs->trans("Language_".$languagecodeselected); $label = $weblangs->trans("Language_".$languagecodeselected);
if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); if ($countrycode == 'us') {
$label = preg_replace('/\s*\(.*\)/', '', $label);
}
$out .= '<a href="'.$url.substr($languagecodeselected, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>'; $out .= '<a href="'.$url.substr($languagecodeselected, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
$out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
$out .= '</li></a>'; $out .= '</li></a>';
} }
$i = 0; $i = 0;
if (is_array($languagecodes)) if (is_array($languagecodes)) {
{ foreach ($languagecodes as $languagecode) {
foreach ($languagecodes as $languagecode)
{
// Convert $languagecode into a long language code // Convert $languagecode into a long language code
if (strlen($languagecode) == 2) { if (strlen($languagecode) == 2) {
$languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]); $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]);
} }
if ($languagecode == $languagecodeselected) continue; // Already output if ($languagecode == $languagecodeselected) {
continue; // Already output
}
$countrycode = strtolower(substr($languagecode, -2)); $countrycode = strtolower(substr($languagecode, -2));
$label = $weblangs->trans("Language_".$languagecode); $label = $weblangs->trans("Language_".$languagecode);
if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); if ($countrycode == 'us') {
$label = preg_replace('/\s*\(.*\)/', '', $label);
}
$out .= '<a href="'.$url.substr($languagecode, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>'; $out .= '<a href="'.$url.substr($languagecode, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>';
if (empty($i) && empty($languagecodeselected)) $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; if (empty($i) && empty($languagecodeselected)) {
$out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />';
}
$out .= '</li></a>'; $out .= '</li></a>';
$i++; $i++;
} }

View File

@ -106,9 +106,9 @@ class WebsitePage extends CommonObject
*/ */
public $author_alias; public $author_alias;
/** /**
* @var string path of external object * @var string path of external object
*/ */
public $object_type; public $object_type;
/** /**
@ -229,7 +229,9 @@ class WebsitePage extends CommonObject
{ {
$this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1); $this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1);
$this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1);
if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' if ($this->aliasalt) {
$this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,'
}
// Remove spaces and be sure we have main language only // Remove spaces and be sure we have main language only
$this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
@ -281,12 +283,12 @@ class WebsitePage extends CommonObject
$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
//$sql .= ' WHERE entity IN ('.getEntity('website').')'; // entity is on website level //$sql .= ' WHERE entity IN ('.getEntity('website').')'; // entity is on website level
$sql .= ' WHERE 1 = 1'; $sql .= ' WHERE 1 = 1';
if ($id > 0) if ($id > 0) {
{
$sql .= ' AND t.rowid = '.$id; $sql .= ' AND t.rowid = '.$id;
} } else {
else { if ($id < 0) {
if ($id < 0) $sql .= ' AND t.rowid <> '.abs($id); $sql .= ' AND t.rowid <> '.abs($id);
}
if (null !== $website_id) { if (null !== $website_id) {
$sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'"; $sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'";
if ($page) { if ($page) {
@ -295,12 +297,18 @@ class WebsitePage extends CommonObject
$tmppage = explode('/', $page); $tmppage = explode('/', $page);
if (!empty($tmppage[1])) { if (!empty($tmppage[1])) {
$pagetouse = $tmppage[1]; $pagetouse = $tmppage[1];
if (strlen($tmppage[0])) $langtouse = $tmppage[0]; if (strlen($tmppage[0])) {
$langtouse = $tmppage[0];
}
} }
$sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'"; $sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'";
if ($langtouse) $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'"; if ($langtouse) {
$sql .= " AND t.lang = '".$this->db->escape($langtouse)."'";
}
}
if ($aliasalt) {
$sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')";
} }
if ($aliasalt) $sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')";
} }
} }
$sql .= $this->db->plimit(1); $sql .= $this->db->plimit(1);
@ -419,7 +427,9 @@ class WebsitePage extends CommonObject
$listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'"; $listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'";
} }
$stringtouse = $key." IN (".join(',', $listoflang).")"; $stringtouse = $key." IN (".join(',', $listoflang).")";
if ($foundnull) $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; if ($foundnull) {
$stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)';
}
$sqlwhere[] = $stringtouse; $sqlwhere[] = $stringtouse;
} else { } else {
$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
@ -441,8 +451,7 @@ class WebsitePage extends CommonObject
if ($resql) { if ($resql) {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql)) {
{
$record = new self($this->db); $record = new self($this->db);
$record->id = $obj->rowid; $record->id = $obj->rowid;
@ -520,7 +529,9 @@ class WebsitePage extends CommonObject
$listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'"; $listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'";
} }
$stringtouse = $key." IN (".join(',', $listoflang).")"; $stringtouse = $key." IN (".join(',', $listoflang).")";
if ($foundnull) $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; if ($foundnull) {
$stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)';
}
$sqlwhere[] = $stringtouse; $sqlwhere[] = $stringtouse;
} else { } else {
$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
@ -561,7 +572,9 @@ class WebsitePage extends CommonObject
{ {
$this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1); $this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1);
$this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1);
if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' if ($this->aliasalt) {
$this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,'
}
// Remove spaces and be sure we have main language only // Remove spaces and be sure we have main language only
$this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en
@ -595,8 +608,7 @@ class WebsitePage extends CommonObject
// Delete all child tables // Delete all child tables
if (!$error) { if (!$error) {
foreach ($this->childtablesoncascade as $table) foreach ($this->childtablesoncascade as $table) {
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
$sql .= " WHERE fk_website_page = ".(int) $this->id; $sql .= " WHERE fk_website_page = ".(int) $this->id;
@ -611,19 +623,16 @@ class WebsitePage extends CommonObject
if (!$error) { if (!$error) {
$result = $this->deleteCommon($user, $trigger); $result = $this->deleteCommon($user, $trigger);
if ($result <= 0) if ($result <= 0) {
{
$error++; $error++;
} }
} }
if (!$error) if (!$error) {
{
$websiteobj = new Website($this->db); $websiteobj = new Website($this->db);
$result = $websiteobj->fetch($this->fk_website); $result = $websiteobj->fetch($this->fk_website);
if ($result > 0) if ($result > 0) {
{
global $dolibarr_main_data_root; global $dolibarr_main_data_root;
$pathofwebsite = $dolibarr_main_data_root.'/website/'.$websiteobj->ref; $pathofwebsite = $dolibarr_main_data_root.'/website/'.$websiteobj->ref;
@ -696,10 +705,17 @@ class WebsitePage extends CommonObject
$object->date_creation = $now; $object->date_creation = $now;
$object->title = ($newtitle == '1' ? $object->title : ($newtitle ? $newtitle : $object->title)); $object->title = ($newtitle == '1' ? $object->title : ($newtitle ? $newtitle : $object->title));
$object->description = $object->title; $object->description = $object->title;
if (!empty($newlang)) $object->lang = $newlang; if (!empty($newlang)) {
if ($istranslation) $object->fk_page = $fromid; $object->lang = $newlang;
else $object->fk_page = 0; }
if (!empty($newwebsite)) $object->fk_website = $newwebsite; if ($istranslation) {
$object->fk_page = $fromid;
} else {
$object->fk_page = 0;
}
if (!empty($newwebsite)) {
$object->fk_website = $newwebsite;
}
$object->import_key = ''; $object->import_key = '';
// Create clone // Create clone
@ -755,17 +771,16 @@ class WebsitePage extends CommonObject
$url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id; $url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id;
$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.'"' : '');
$linkstart = '<a href="'.$url.'"'; $linkstart = '<a href="'.$url.'"';
$linkstart .= $linkclose.'>'; $linkstart .= $linkclose.'>';
@ -774,8 +789,12 @@ class WebsitePage extends CommonObject
//$linkstart = $linkend = ''; //$linkstart = $linkend = '';
$result .= $linkstart; $result .= $linkstart;
if ($withpicto) $result .= img_picto(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); if ($withpicto) {
if ($withpicto != 2) $result .= $this->ref; $result .= img_picto(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
}
if ($withpicto != 2) {
$result .= $this->ref;
}
$result .= $linkend; $result .= $linkend;
return $result; return $result;
@ -805,8 +824,7 @@ class WebsitePage extends CommonObject
// phpcs:enable // phpcs:enable
global $langs; global $langs;
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('Disabled'); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled');
@ -816,7 +834,9 @@ class WebsitePage extends CommonObject
} }
$statusType = 'status5'; $statusType = 'status5';
if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) {
$statusType = 'status4';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,12 @@
<?php <?php
// BEGIN PHP File wrapper.php - DO NOT MODIFY - It is just a copy of file website/samples/wrapper.php // BEGIN PHP File wrapper.php - DO NOT MODIFY - It is just a copy of file website/samples/wrapper.php
$websitekey = basename(__DIR__); $websitekey = basename(__DIR__);
if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) die("Sample file for website module. Can be called directly."); if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) {
if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load master if not already loaded die("Sample file for website module. Can be called directly.");
}
if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
require_once './master.inc.php';
} // Load master if not already loaded
include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
$encoding = ''; $encoding = '';
@ -17,42 +21,36 @@ $limit = GETPOST('limit', 'int');
// Parameters for RSS // Parameters for RSS
$rss = GETPOST('rss', 'aZ09'); $rss = GETPOST('rss', 'aZ09');
if ($rss) $original_file = 'blog.rss'; if ($rss) {
$original_file = 'blog.rss';
}
// If we have a hash public (hashp), we guess the original_file. // If we have a hash public (hashp), we guess the original_file.
if (!empty($hashp)) if (!empty($hashp)) {
{
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
$ecmfile = new EcmFiles($db); $ecmfile = new EcmFiles($db);
$result = $ecmfile->fetch(0, '', '', '', $hashp); $result = $ecmfile->fetch(0, '', '', '', $hashp);
if ($result > 0) if ($result > 0) {
{
$tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory
// filepath can be 'users/X' or 'X/propale/PR11111' // filepath can be 'users/X' or 'X/propale/PR11111'
if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part. if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
{
$tmp = explode('/', $tmp[1], 2); $tmp = explode('/', $tmp[1], 2);
} }
$moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path
if ($modulepart) // Not required, so often not defined, for link using public hashp parameter. if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter.
{ if ($moduleparttocheck == $modulepart) {
if ($moduleparttocheck == $modulepart)
{
// We remove first level of directory // We remove first level of directory
$original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
//var_dump($original_file); exit; //var_dump($original_file); exit;
} } else {
else {
print 'Bad link. File is from another module part.'; print 'Bad link. File is from another module part.';
} }
} } else {
else {
$modulepart = $moduleparttocheck; $modulepart = $moduleparttocheck;
$original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir
} }
} } else {
else {
print "ErrorFileNotFoundWithSharedLink"; print "ErrorFileNotFoundWithSharedLink";
exit; exit;
} }
@ -60,21 +58,29 @@ if (!empty($hashp))
// Define attachment (attachment=true to force choice popup 'open'/'save as') // Define attachment (attachment=true to force choice popup 'open'/'save as')
$attachment = true; $attachment = true;
if (preg_match('/\.(html|htm)$/i', $original_file)) $attachment = false; if (preg_match('/\.(html|htm)$/i', $original_file)) {
if (isset($_GET["attachment"])) $attachment = (GETPOST("attachment", 'alphanohtml') ? true : false); $attachment = false;
if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) $attachment = false; }
if (isset($_GET["attachment"])) {
$attachment = (GETPOST("attachment", 'alphanohtml') ? true : false);
}
if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) {
$attachment = false;
}
// Define mime type // Define mime type
$type = 'application/octet-stream'; $type = 'application/octet-stream';
if (GETPOSTISSET('type')) $type = GETPOST('type', 'alpha'); if (GETPOSTISSET('type')) {
else $type = dol_mimetype($original_file); $type = GETPOST('type', 'alpha');
} else {
$type = dol_mimetype($original_file);
}
// Security: Delete string ../ into $original_file // Security: Delete string ../ into $original_file
$original_file = str_replace("../", "/", $original_file); $original_file = str_replace("../", "/", $original_file);
// Cache or not // Cache or not
if (GETPOST("cache", 'aZ09') || image_format_supported($original_file) >= 0) if (GETPOST("cache", 'aZ09') || image_format_supported($original_file) >= 0) {
{
// Important: Following code is to avoid page request by browser and PHP CPU at // Important: Following code is to avoid page request by browser and PHP CPU at
// each Dolibarr page access. // each Dolibarr page access.
header('Cache-Control: max-age=3600, public, must-revalidate'); header('Cache-Control: max-age=3600, public, must-revalidate');
@ -99,7 +105,9 @@ if ($rss) {
$website->fetch('', $websitekey); $website->fetch('', $websitekey);
$filters = array('type_container'=>'blogpost'); $filters = array('type_container'=>'blogpost');
if ($l) $filters['lang'] = $l; if ($l) {
$filters['lang'] = $l;
}
$MAXNEWS = ($limit ? $limit : 20); $MAXNEWS = ($limit ? $limit : 20);
$arrayofblogs = $websitepage->fetchAll($website->id, 'DESC', 'date_creation', $MAXNEWS, 0, $filters); $arrayofblogs = $websitepage->fetchAll($website->id, 'DESC', 'date_creation', $MAXNEWS, 0, $filters);
@ -118,8 +126,7 @@ if ($rss) {
dol_syslog("build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); dol_syslog("build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG);
// Clean parameters // Clean parameters
if (!$filename) if (!$filename) {
{
$extension = 'rss'; $extension = 'rss';
$filename = $format.'.'.$extension; $filename = $format.'.'.$extension;
} }
@ -132,19 +139,16 @@ if ($rss) {
$buildfile = true; $buildfile = true;
if ($cachedelay) if ($cachedelay) {
{
$nowgmt = dol_now(); $nowgmt = dol_now();
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) {
{
dol_syslog("build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled"); dol_syslog("build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled");
$buildfile = false; $buildfile = false;
} }
} }
if ($buildfile) if ($buildfile) {
{
$langs->load("other"); $langs->load("other");
$title = $desc = $langs->transnoentities('LatestBlogPosts'); $title = $desc = $langs->transnoentities('LatestBlogPosts');
@ -155,18 +159,17 @@ if ($rss) {
// Write file // Write file
$result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp, '', $website->virtualhost.'/wrapper.php?rss=1'.($l ? '&l='.$l : ''), $l); $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp, '', $website->virtualhost.'/wrapper.php?rss=1'.($l ? '&l='.$l : ''), $l);
if ($result >= 0) if ($result >= 0) {
{ if (dol_move($outputfiletmp, $outputfile, 0, 1)) {
if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1; $result = 1;
else { } else {
$error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile; $error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile;
dol_syslog("build_exportfile ".$error, LOG_ERR); dol_syslog("build_exportfile ".$error, LOG_ERR);
dol_delete_file($outputfiletmp, 0, 1); dol_delete_file($outputfiletmp, 0, 1);
print $error; print $error;
exit(-1); exit(-1);
} }
} } else {
else {
dol_syslog("build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); dol_syslog("build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR);
dol_delete_file($outputfiletmp, 0, 1); dol_delete_file($outputfiletmp, 0, 1);
$langs->load("errors"); $langs->load("errors");
@ -175,56 +178,63 @@ if ($rss) {
} }
} }
if ($result >= 0) if ($result >= 0) {
{
$attachment = false; $attachment = false;
if (isset($_GET["attachment"])) $attachment = $_GET["attachment"]; if (isset($_GET["attachment"])) {
$attachment = $_GET["attachment"];
}
//$attachment = false; //$attachment = false;
$contenttype = 'application/rss+xml'; $contenttype = 'application/rss+xml';
if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"]; if (isset($_GET["contenttype"])) {
$contenttype = $_GET["contenttype"];
}
//$contenttype='text/plain'; //$contenttype='text/plain';
$outputencoding = 'UTF-8'; $outputencoding = 'UTF-8';
if ($contenttype) header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); if ($contenttype) {
if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : ''));
}
if ($attachment) {
header('Content-Disposition: attachment; filename="'.$filename.'"');
}
// Ajout directives pour resoudre bug IE // Ajout directives pour resoudre bug IE
//header('Cache-Control: Public, must-revalidate'); //header('Cache-Control: Public, must-revalidate');
//header('Pragma: public'); //header('Pragma: public');
if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); if ($cachedelay) {
else header('Cache-Control: private, must-revalidate'); header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate');
} else {
header('Cache-Control: private, must-revalidate');
}
// Clean parameters // Clean parameters
$outputfile = $dir_temp.'/'.$filename; $outputfile = $dir_temp.'/'.$filename;
$result = readfile($outputfile); $result = readfile($outputfile);
if (!$result) print 'File '.$outputfile.' was empty.'; if (!$result) {
print 'File '.$outputfile.' was empty.';
}
// header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename)); // header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename));
exit; exit;
} }
} } elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) {
// Get logos // Get logos
elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file))
{
readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file)); readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file));
} } else {
else {
// Find the subdirectory name as the reference // Find the subdirectory name as the reference
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname); $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname);
$accessallowed = $check_access['accessallowed']; $accessallowed = $check_access['accessallowed'];
$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
$fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name
if ($hashp) if ($hashp) {
{
$accessallowed = 1; // When using hashp, link is public so we force $accessallowed $accessallowed = 1; // When using hashp, link is public so we force $accessallowed
$sqlprotectagainstexternals = ''; $sqlprotectagainstexternals = '';
} }
// Security: // Security:
// Limit access if permissions are wrong // Limit access if permissions are wrong
if (!$accessallowed) if (!$accessallowed) {
{
print 'Access forbidden'; print 'Access forbidden';
exit; exit;
} }
@ -238,8 +248,7 @@ else {
$fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset
// This test if file exists should be useless. We keep it to find bug more easily // This test if file exists should be useless. We keep it to find bug more easily
if (!file_exists($fullpath_original_file_osencoded)) if (!file_exists($fullpath_original_file_osencoded)) {
{
print "ErrorFileDoesNotExists: ".$original_file; print "ErrorFileDoesNotExists: ".$original_file;
exit; exit;
} }
@ -248,13 +257,20 @@ else {
//top_httphead($type); //top_httphead($type);
header('Content-Type: '.$type); header('Content-Type: '.$type);
header('Content-Description: File Transfer'); header('Content-Description: File Transfer');
if ($encoding) header('Content-Encoding: '.$encoding); if ($encoding) {
header('Content-Encoding: '.$encoding);
}
// Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open) // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); if ($attachment) {
else header('Content-Disposition: inline; filename="'.$filename.'"'); header('Content-Disposition: attachment; filename="'.$filename.'"');
} else {
header('Content-Disposition: inline; filename="'.$filename.'"');
}
header('Content-Length: '.dol_filesize($fullpath_original_file)); header('Content-Length: '.dol_filesize($fullpath_original_file));
readfile($fullpath_original_file_osencoded); readfile($fullpath_original_file_osencoded);
} }
if (is_object($db)) $db->close(); if (is_object($db)) {
$db->close();
}
// END PHP // END PHP

View File

@ -53,12 +53,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';
}
// Security check - Protection if external user // Security check - Protection if external user
//if ($user->socid > 0) accessforbidden(); //if ($user->socid > 0) accessforbidden();
@ -80,10 +83,11 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ
$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;
$permissiontoadd = $user->rights->website->write; $permissiontoadd = $user->rights->website->write;
@ -130,8 +134,7 @@ 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("WebsiteAccount"))); print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("WebsiteAccount")));
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@ -163,8 +166,7 @@ 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("WebsiteAccount")); print load_fiche_titre($langs->trans("WebsiteAccount"));
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@ -194,9 +196,10 @@ 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'))) {
{ if ($object->fk_soc > 0 && empty($socid)) {
if ($object->fk_soc > 0 && empty($socid)) $socid = $object->fk_soc; $socid = $object->fk_soc;
}
$res = $object->fetch_optionals(); $res = $object->fetch_optionals();
@ -213,8 +216,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;
@ -223,8 +229,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Object card // Object card
// ------------------------------------------------------------ // ------------------------------------------------------------
$linkback = ''; $linkback = '';
if ($socid) $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListForThirdParty").'</a>'; if ($socid) {
if ($fk_website) $linkback = '<a href="'.DOL_URL_ROOT.'/website/website_card.php?fk_website='.$fk_website.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListForThirdParty").'</a>';
}
if ($fk_website) {
$linkback = '<a href="'.DOL_URL_ROOT.'/website/website_card.php?fk_website='.$fk_website.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
}
$morehtmlref = '<div class="refidno">'; $morehtmlref = '<div class="refidno">';
/* /*
@ -236,41 +246,43 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// 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 ($user->rights->website->creer) if ($user->rights->website->creer)
{ {
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->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">'; $morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>'; $morehtmlref.='</form>';
} else { } else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
} }
} }
} else { } else {
if (! empty($object->fk_project)) { if (! empty($object->fk_project)) {
$proj = new Project($db); $proj = new Project($db);
$proj->fetch($object->fk_project); $proj->fetch($object->fk_project);
$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
$morehtmlref.=$proj->ref; $morehtmlref.=$proj->ref;
$morehtmlref.='</a>'; $morehtmlref.='</a>';
} else { } else {
$morehtmlref.=''; $morehtmlref.='';
} }
} }
} }
*/ */
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
if ($socid > 0) $object->next_prev_filter = 'te.fk_soc = '.$socid; if ($socid > 0) {
$object->next_prev_filter = 'te.fk_soc = '.$socid;
}
dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref); dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref);
@ -301,36 +313,35 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '<div class="tabsAction">'."\n"; 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 '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'."\n"; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'."\n";
} }
if ($user->rights->website->write) if ($user->rights->website->write) {
{
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n";
} }
/* /*
if ($user->rights->sellyoursaas->create) if ($user->rights->sellyoursaas->create)
{
if ($object->status == 1)
{
print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a></div>'."\n";
}
else
{
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a></div>'."\n";
}
}
*/
if ($user->rights->website->delete)
{ {
if ($object->status == 1)
{
print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a></div>'."\n";
}
else
{
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a></div>'."\n";
}
}
*/
if ($user->rights->website->delete) {
print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n";
} }
} }
@ -343,21 +354,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$action = 'presend'; $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
print '</div><div class="fichehalfright"><div class="ficheaddleft">'; print '</div><div class="fichehalfright"><div class="ficheaddleft">';
/* /*
$MAXEVENT = 10; $MAXEVENT = 10;
// List of actions on element // List of actions on element
include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
$formactions = new FormActions($db); $formactions = new FormActions($db);
$somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT);
*/ */
print '</div></div></div>'; print '</div></div></div>';
} }

View File

@ -34,7 +34,9 @@ require_once '../lib/zapier.lib.php';
$langs->loadLangs(array("errors", "admin", "zapier@zapier")); $langs->loadLangs(array("errors", "admin", "zapier@zapier"));
// Access control // Access control
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
// Parameters // Parameters
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');

View File

@ -33,7 +33,9 @@ require_once '../lib/zapier.lib.php';
$langs->loadLangs(array("admin", "zapier@zapier")); $langs->loadLangs(array("admin", "zapier@zapier"));
// Access control // Access control
if (!$user->admin) accessforbidden(); if (!$user->admin) {
accessforbidden();
}
// Parameters // Parameters
$action = GETPOST('action', 'aZ09'); $action = GETPOST('action', 'aZ09');

View File

@ -37,7 +37,7 @@ class ZapierApi extends DolibarrApi
/** /**
* @var array $FIELDS Mandatory fields, checked when create and update object * @var array $FIELDS Mandatory fields, checked when create and update object
*/ */
static $FIELDS = array( public static $FIELDS = array(
'url', 'url',
); );
@ -163,7 +163,9 @@ class ZapierApi extends DolibarrApi
} }
$sql .= " FROM ".MAIN_DB_PREFIX."hook_mytable as t"; $sql .= " FROM ".MAIN_DB_PREFIX."hook_mytable 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
@ -270,33 +272,33 @@ class ZapierApi extends DolibarrApi
// * @url PUT /hooks/{id} // * @url PUT /hooks/{id}
// */ // */
/*public function put($id, $request_data = null) /*public function put($id, $request_data = null)
{ {
if (! DolibarrApiAccess::$user->rights->zapier->write) { if (! DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401); throw new RestException(401);
} }
$result = $this->hook->fetch($id); $result = $this->hook->fetch($id);
if( ! $result ) { if( ! $result ) {
throw new RestException(404, 'Hook not found'); throw new RestException(404, 'Hook not found');
} }
if( ! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) { if( ! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
} }
foreach($request_data as $field => $value) { foreach($request_data as $field => $value) {
if ($field == 'id') { if ($field == 'id') {
continue; continue;
} }
$this->hook->$field = $value; $this->hook->$field = $value;
} }
if ($this->hook->update($id, DolibarrApiAccess::$user) > 0) { if ($this->hook->update($id, DolibarrApiAccess::$user) > 0) {
return $this->get($id); return $this->get($id);
} else { } else {
throw new RestException(500, $this->hook->error); throw new RestException(500, $this->hook->error);
} }
}*/ }*/
/** /**
* Delete hook * Delete hook

View File

@ -385,13 +385,13 @@ class Hook extends CommonObject
* @return int <0 if KO, 0 if not found, >0 if OK * @return int <0 if KO, 0 if not found, >0 if OK
*/ */
/*public function fetchLines() /*public function fetchLines()
{ {
$this->lines=array(); $this->lines=array();
// Load lines with object MyObjectLine // Load lines with object MyObjectLine
return count($this->lines)?1:0; return count($this->lines)?1:0;
}*/ }*/
/** /**
* Load list of objects in memory from the database. * Load list of objects in memory from the database.
@ -542,11 +542,11 @@ class Hook extends CommonObject
$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
/* /*
$hookmanager->initHooks(array('hookdao')); $hookmanager->initHooks(array('hookdao'));
$parameters=array('id'=>$this->id); $parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint; if ($reshook > 0) $linkclose = $hookmanager->resPrint;
*/ */
} else { } else {
$linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
} }
@ -621,7 +621,9 @@ class Hook extends CommonObject
} }
$statusType = 'status5'; $statusType = 'status5';
if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; if ($status == self::STATUS_VALIDATED) {
$statusType = 'status4';
}
return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
} }
@ -720,11 +722,11 @@ class Hook extends CommonObject
/* /*
class MyObjectLine class MyObjectLine
{ {
// @var int ID // @var int ID
public $id; public $id;
// @var mixed Sample line property 1 // @var mixed Sample line property 1
public $prop1; public $prop1;
// @var mixed Sample line property 2 // @var mixed Sample line property 2
public $prop2; public $prop2;
} }
*/ */

View File

@ -43,7 +43,9 @@ $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));
} }
@ -58,12 +60,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 MyObject($db); $object = new MyObject($db);
@ -76,7 +84,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->mymodule->multidir_output[$object->entity]."/".$object->id; if ($id > 0 || !empty($ref)) {
$upload_dir = $conf->mymodule->multidir_output[$object->entity]."/".$object->id;
}
@ -86,7 +96,9 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$obj
$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
@ -118,7 +130,9 @@ if ($object->id > 0) {
$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 = myobjectPrepareHead($object); $head = myobjectPrepareHead($object);
@ -143,31 +157,31 @@ if ($object->id > 0) {
if ($user->rights->mymodule->creer) if ($user->rights->mymodule->creer)
{ {
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> : ';
$morehtmlref.=' : '; $morehtmlref.=' : ';
if ($action == 'classify') { if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">'; $morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>'; $morehtmlref.='</form>';
} else { } else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
} }
} else { } else {
if (! empty($object->fk_project)) { if (! empty($object->fk_project)) {
$proj = new Project($db); $proj = new Project($db);
$proj->fetch($object->fk_project); $proj->fetch($object->fk_project);
$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
$morehtmlref.=$proj->ref; $morehtmlref.=$proj->ref;
$morehtmlref.='</a>'; $morehtmlref.='</a>';
} else { } else {
$morehtmlref.=''; $morehtmlref.='';
} }
} }
}*/ }*/
$morehtmlref .= '</div>'; $morehtmlref .= '</div>';
@ -194,7 +208,9 @@ if ($object->id > 0) {
$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');
@ -216,8 +232,12 @@ if ($object->id > 0) {
if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
$param = '&socid='.$socid; $param = '&socid='.$socid;
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 ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.$limit;
}
print load_fiche_titre($langs->trans("ActionsOnMyObject"), '', ''); print load_fiche_titre($langs->trans("ActionsOnMyObject"), '', '');

Some files were not shown because too many files have changed in this diff Show More