Merge pull request #15241 from Dolibarr/scrutinizer-patch-1

Scrutinizer Auto-Fixes
This commit is contained in:
Laurent Destailleur 2020-10-31 18:52:05 +01:00 committed by GitHub
commit 64cfe6a9de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
100 changed files with 8931 additions and 8931 deletions

View File

@ -138,7 +138,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
if (empty($reshook))
{
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 tests are required to be compatible with all browsers
{
@ -172,55 +172,55 @@ if (empty($reshook))
if (!empty($search_date_start)) {
$filter['t.doc_date>='] = $search_date_start;
$param .= '&search_date_startmonth=' . GETPOST('search_date_startmonth', 'int') . '&search_date_startday=' . GETPOST('search_date_startday', 'int') . '&search_date_startyear=' . GETPOST('search_date_startyear', 'int');
$param .= '&search_date_startmonth='.GETPOST('search_date_startmonth', 'int').'&search_date_startday='.GETPOST('search_date_startday', 'int').'&search_date_startyear='.GETPOST('search_date_startyear', 'int');
}
if (!empty($search_date_end)) {
$filter['t.doc_date<='] = $search_date_end;
$param .= '&search_date_endmonth=' . GETPOST('search_date_endmonth', 'int') . '&search_date_endday=' . GETPOST('search_date_endday', 'int') . '&search_date_endyear=' . GETPOST('search_date_endyear', 'int');
$param .= '&search_date_endmonth='.GETPOST('search_date_endmonth', 'int').'&search_date_endday='.GETPOST('search_date_endday', 'int').'&search_date_endyear='.GETPOST('search_date_endyear', 'int');
}
if (!empty($search_doc_date)) {
$filter['t.doc_date'] = $search_doc_date;
$param .= '&doc_datemonth=' . GETPOST('doc_datemonth', 'int') . '&doc_dateday=' . GETPOST('doc_dateday', 'int') . '&doc_dateyear=' . GETPOST('doc_dateyear', 'int');
$param .= '&doc_datemonth='.GETPOST('doc_datemonth', 'int').'&doc_dateday='.GETPOST('doc_dateday', 'int').'&doc_dateyear='.GETPOST('doc_dateyear', 'int');
}
if (!empty($search_accountancy_code_start)) {
$filter['t.subledger_account>='] = $search_accountancy_code_start;
$param .= '&search_accountancy_code_start=' . urlencode($search_accountancy_code_start);
$param .= '&search_accountancy_code_start='.urlencode($search_accountancy_code_start);
}
if (!empty($search_accountancy_code_end)) {
$filter['t.subledger_account<='] = $search_accountancy_code_end;
$param .= '&search_accountancy_code_end=' . urlencode($search_accountancy_code_end);
$param .= '&search_accountancy_code_end='.urlencode($search_accountancy_code_end);
}
if (!empty($search_label_account)) {
$filter['t.label_compte'] = $search_label_account;
$param .= '&search_label_compte=' . urlencode($search_label_account);
$param .= '&search_label_compte='.urlencode($search_label_account);
}
if (!empty($search_mvt_num)) {
$filter['t.piece_num'] = $search_mvt_num;
$param .= '&search_mvt_num=' . urlencode($search_mvt_num);
$param .= '&search_mvt_num='.urlencode($search_mvt_num);
}
if (!empty($search_doc_ref)) {
$filter['t.doc_ref'] = $search_doc_ref;
$param .= '&search_doc_ref=' . urlencode($search_doc_ref);
$param .= '&search_doc_ref='.urlencode($search_doc_ref);
}
if (!empty($search_label_operation)) {
$filter['t.label_operation'] = $search_label_operation;
$param .= '&search_label_operation=' . urlencode($search_label_operation);
$param .= '&search_label_operation='.urlencode($search_label_operation);
}
if (!empty($search_direction)) {
$filter['t.sens'] = $search_direction;
$param .= '&search_direction=' . urlencode($search_direction);
$param .= '&search_direction='.urlencode($search_direction);
}
if (!empty($search_ledger_code)) {
$filter['t.code_journal'] = $search_ledger_code;
$param .= '&search_ledger_code=' . urlencode($search_ledger_code);
$param .= '&search_ledger_code='.urlencode($search_ledger_code);
}
if (!empty($search_debit)) {
$filter['t.debit'] = $search_debit;
$param .= '&search_debit=' . urlencode($search_debit);
$param .= '&search_debit='.urlencode($search_debit);
}
if (!empty($search_credit)) {
$filter['t.credit'] = $search_credit;
$param .= '&search_credit=' . urlencode($search_credit);
$param .= '&search_credit='.urlencode($search_credit);
}
if (!empty($search_lettering_code)) {
$filter['t.lettering_code'] = $search_lettering_code;
@ -423,7 +423,7 @@ print '<tr class="liste_titre_filter">';
// Code journal
if (!empty($arrayfields['t.code_journal']['checked'])) {
print '<td class="liste_titre center"><input type="text" name="search_ledger_code" size="3" value="' . dol_escape_htmltag($search_ledger_code) . '"></td>';
print '<td class="liste_titre center"><input type="text" name="search_ledger_code" size="3" value="'.dol_escape_htmltag($search_ledger_code).'"></td>';
}
// Date document
if (!empty($arrayfields['t.doc_date']['checked'])) {
@ -443,19 +443,19 @@ if (!empty($arrayfields['t.piece_num']['checked']))
}
// Ref document
if (!empty($arrayfields['t.doc_ref']['checked'])) {
print '<td class="liste_titre"><input type="text" size="7" class="flat" name="search_doc_ref" value="' . dol_escape_htmltag($search_doc_ref) . '"/></td>';
print '<td class="liste_titre"><input type="text" size="7" class="flat" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"/></td>';
}
// Label operation
if (!empty($arrayfields['t.label_operation']['checked'])) {
print '<td class="liste_titre"><input type="text" size="7" class="flat" name="search_label_operation" value="' . dol_escape_htmltag($search_label_operation) . '"/></td>';
print '<td class="liste_titre"><input type="text" size="7" class="flat" name="search_label_operation" value="'.dol_escape_htmltag($search_label_operation).'"/></td>';
}
// Debit
if (!empty($arrayfields['t.debit']['checked'])) {
print '<td class="liste_titre right"><input type="text" class="flat" name="search_debit" size="4" value="' . dol_escape_htmltag($search_debit) . '"></td>';
print '<td class="liste_titre right"><input type="text" class="flat" name="search_debit" size="4" value="'.dol_escape_htmltag($search_debit).'"></td>';
}
// Credit
if (!empty($arrayfields['t.credit']['checked'])) {
print '<td class="liste_titre right"><input type="text" class="flat" name="search_credit" size="4" value="' . dol_escape_htmltag($search_credit) . '"></td>';
print '<td class="liste_titre right"><input type="text" class="flat" name="search_credit" size="4" value="'.dol_escape_htmltag($search_credit).'"></td>';
}
// Lettering code
if (!empty($arrayfields['t.lettering_code']['checked']))
@ -531,7 +531,7 @@ while ($i < min($num, $limit))
$balance = $sous_total_debit - $sous_total_credit;
print '<tr class="liste_total">';
print '<td class="right" colspan="'.$colspan.'">'.$langs->trans("Balance").':</td>';
if ($balance > 0 )
if ($balance > 0)
{
print '<td class="nowraponall right">';
print price($sous_total_debit - $sous_total_credit);
@ -662,7 +662,7 @@ while ($i < min($num, $limit))
if (!empty($arrayfields['t.label_operation']['checked'])) {
// Affiche un lien vers la facture client/fournisseur
$doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref);
print strlen(length_accounta($line->subledger_account)) == 0 ? '<td>' . $line->label_operation . '</td>' : '<td>' . $line->label_operation . '<br><span style="font-size:0.8em">(' . length_accounta($line->subledger_account) . ')</span></td>';
print strlen(length_accounta($line->subledger_account)) == 0 ? '<td>'.$line->label_operation.'</td>' : '<td>'.$line->label_operation.'<br><span style="font-size:0.8em">('.length_accounta($line->subledger_account).')</span></td>';
if (!$i) $totalarray['nbfield']++;
}
@ -677,7 +677,7 @@ while ($i < min($num, $limit))
// Amount credit
if (!empty($arrayfields['t.credit']['checked'])) {
print '<td class="nowrap right">' . ($line->credit ? price($line->credit) : '') . '</td>';
print '<td class="nowrap right">'.($line->credit ? price($line->credit) : '').'</td>';
if (!$i) $totalarray['nbfield']++;
if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredit';
$totalarray['val']['totalcredit'] += $line->credit;
@ -730,7 +730,7 @@ print '</tr>';
$balance = $sous_total_debit - $sous_total_credit;
print '<tr class="liste_total">';
print '<td class="right" colspan="'.$colspan.'">'.$langs->trans("Balance").':</td>';
if ($balance > 0 )
if ($balance > 0)
{
print '<td class="nowraponall right">';
print price($sous_total_debit - $sous_total_credit);

View File

@ -837,12 +837,12 @@ class BookKeeping extends CommonObject
$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
}
// Affichage par compte comptable
if (!empty($option)) {
$sql .= ' AND t.subledger_account IS NOT NULL';
$sql .= ' ORDER BY t.subledger_account ASC';
} else {
$sql .= ' ORDER BY t.numero_compte ASC';
}
if (!empty($option)) {
$sql .= ' AND t.subledger_account IS NOT NULL';
$sql .= ' ORDER BY t.subledger_account ASC';
} else {
$sql .= ' ORDER BY t.numero_compte ASC';
}
if (!empty($sortfield)) {
$sql .= ', '.$sortfield.' '.$sortorder;

View File

@ -32,477 +32,477 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
*/
class Members extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'morphy',
'typeid'
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'morphy',
'typeid'
);
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
}
/**
* Get properties of a member object
*
* Return an array with member informations
*
* @param int $id ID of member
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
/**
* Get properties of a member object
*
* Return an array with member informations
*
* @param int $id ID of member
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($member);
}
return $this->_cleanObjectDatas($member);
}
/**
* Get properties of a member object by linked thirdparty
*
* Return an array with member informations
*
* @param int $thirdparty ID of third party
*
* @return array|mixed Data without useless information
*
* @url GET thirdparty/{thirdparty}
*
* @throws RestException 401
* @throws RestException 404
*/
public function getByThirdparty($thirdparty)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
/**
* Get properties of a member object by linked thirdparty
*
* Return an array with member informations
*
* @param int $thirdparty ID of third party
*
* @return array|mixed Data without useless information
*
* @url GET thirdparty/{thirdparty}
*
* @throws RestException 401
* @throws RestException 404
*/
public function getByThirdparty($thirdparty)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch('', '', $thirdparty);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch('', '', $thirdparty);
if (!$result) {
throw new RestException(404, 'member not found');
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($member);
}
return $this->_cleanObjectDatas($member);
}
/**
* Get properties of a member object by linked thirdparty email
*
* Return an array with member informations
*
* @param string $email Email of third party
*
* @return array|mixed Data without useless information
*
* @url GET thirdparty/email/{email}
*
* @throws RestException 401
* @throws RestException 404
*/
public function getByThirdpartyEmail($email)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
/**
* Get properties of a member object by linked thirdparty email
*
* Return an array with member informations
*
* @param string $email Email of third party
*
* @return array|mixed Data without useless information
*
* @url GET thirdparty/email/{email}
*
* @throws RestException 401
* @throws RestException 404
*/
public function getByThirdpartyEmail($email)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$thirdparty = new Societe($this->db);
$result = $thirdparty->fetch('', '', '', '', '', '', '', '', '', '', $email);
if (!$result) {
throw new RestException(404, 'thirdparty not found');
}
$thirdparty = new Societe($this->db);
$result = $thirdparty->fetch('', '', '', '', '', '', '', '', '', '', $email);
if (!$result) {
throw new RestException(404, 'thirdparty not found');
}
$member = new Adherent($this->db);
$result = $member->fetch('', '', $thirdparty->id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch('', '', $thirdparty->id);
if (!$result) {
throw new RestException(404, 'member not found');
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($member);
}
return $this->_cleanObjectDatas($member);
}
/**
* Get properties of a member object by linked thirdparty barcode
*
* Return an array with member informations
*
* @param string $barcode Barcode of third party
*
* @return array|mixed Data without useless information
*
* @url GET thirdparty/barcode/{barcode}
*
* @throws RestException 401
* @throws RestException 404
*/
public function getByThirdpartyBarcode($barcode)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
/**
* Get properties of a member object by linked thirdparty barcode
*
* Return an array with member informations
*
* @param string $barcode Barcode of third party
*
* @return array|mixed Data without useless information
*
* @url GET thirdparty/barcode/{barcode}
*
* @throws RestException 401
* @throws RestException 404
*/
public function getByThirdpartyBarcode($barcode)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$thirdparty = new Societe($this->db);
$result = $thirdparty->fetch('', '', '', $barcode);
if (!$result) {
throw new RestException(404, 'thirdparty not found');
}
$thirdparty = new Societe($this->db);
$result = $thirdparty->fetch('', '', '', $barcode);
if (!$result) {
throw new RestException(404, 'thirdparty not found');
}
$member = new Adherent($this->db);
$result = $member->fetch('', '', $thirdparty->id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch('', '', $thirdparty->id);
if (!$result) {
throw new RestException(404, 'member not found');
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($member);
}
return $this->_cleanObjectDatas($member);
}
/**
* List members
*
* Get a list of members
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $typeid ID of the type of member
/**
* List members
*
* Get a list of members
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $typeid ID of the type of member
* @param int $category Use this param to filter list by category
* @param string $sqlfilters Other criteria to filter answers separated by a comma.
* Example: "(t.ref:like:'SO-%') and ((t.date_creation:<:'20160101') or (t.nature:is:NULL))"
* @return array Array of member objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '')
{
global $db, $conf;
* @param string $sqlfilters Other criteria to filter answers separated by a comma.
* Example: "(t.ref:like:'SO-%') and ((t.date_creation:<:'20160101') or (t.nature:is:NULL))"
* @return array Array of member objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent as t";
if ($category > 0) {
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_member as c";
}
$sql .= ' WHERE t.entity IN ('.getEntity('adherent').')';
if (!empty($typeid)) {
$sql .= ' AND t.fk_adherent_type='.$typeid;
}
// Select members of given category
if ($category > 0) {
}
$sql .= ' WHERE t.entity IN ('.getEntity('adherent').')';
if (!empty($typeid)) {
$sql .= ' AND t.fk_adherent_type='.$typeid;
}
// Select members of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category);
$sql .= " AND c.fk_member = t.rowid ";
}
// Add sql filters
if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
}
// Add sql filters
if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
if ($result) {
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) {
$obj = $this->db->fetch_object($result);
$member = new Adherent($this->db);
if ($member->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($member);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No member found');
}
$result = $this->db->query($sql);
if ($result) {
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) {
$obj = $this->db->fetch_object($result);
$member = new Adherent($this->db);
if ($member->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($member);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No member found');
}
return $obj_ret;
}
return $obj_ret;
}
/**
* Create member object
*
* @param array $request_data Request data
* @return int ID of member
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
/**
* Create member object
*
* @param array $request_data Request data
* @return int ID of member
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
$member = new Adherent($this->db);
foreach ($request_data as $field => $value) {
$member->$field = $value;
}
if ($member->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors));
}
return $member->id;
}
$member = new Adherent($this->db);
foreach ($request_data as $field => $value) {
$member->$field = $value;
}
if ($member->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors));
}
return $member->id;
}
/**
* Update member
*
* @param int $id ID of member to update
* @param array $request_data Datas
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->creer) {
throw new RestException(401);
}
/**
* Update member
*
* @param int $id ID of member to update
* @param array $request_data Datas
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->creer) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
// Process the status separately because it must be updated using
// the validate() and resiliate() methods of the class Adherent.
if ($field == 'statut') {
if ($value == '0') {
$result = $member->resiliate(DolibarrApiAccess::$user);
if ($result < 0) {
throw new RestException(500, 'Error when resiliating member: '.$member->error);
}
} elseif ($value == '1') {
$result = $member->validate(DolibarrApiAccess::$user);
if ($result < 0) {
throw new RestException(500, 'Error when validating member: '.$member->error);
}
}
} else {
$member->$field = $value;
}
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
// Process the status separately because it must be updated using
// the validate() and resiliate() methods of the class Adherent.
if ($field == 'statut') {
if ($value == '0') {
$result = $member->resiliate(DolibarrApiAccess::$user);
if ($result < 0) {
throw new RestException(500, 'Error when resiliating member: '.$member->error);
}
} elseif ($value == '1') {
$result = $member->validate(DolibarrApiAccess::$user);
if ($result < 0) {
throw new RestException(500, 'Error when validating member: '.$member->error);
}
}
} else {
$member->$field = $value;
}
}
// If there is no error, update() returns the number of affected rows
// so if the update is a no op, the return value is zero.
if ($member->update(DolibarrApiAccess::$user) >= 0) {
return $this->get($id);
} else {
throw new RestException(500, $member->error);
}
}
// If there is no error, update() returns the number of affected rows
// so if the update is a no op, the return value is zero.
if ($member->update(DolibarrApiAccess::$user) >= 0) {
return $this->get($id);
} else {
throw new RestException(500, $member->error);
}
}
/**
* Delete member
*
* @param int $id member ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->supprimer) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
/**
* Delete member
*
* @param int $id member ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->supprimer) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$member->delete($member->id, DolibarrApiAccess::$user)) {
throw new RestException(401, 'error when deleting member');
}
if (!$member->delete($member->id, DolibarrApiAccess::$user)) {
throw new RestException(401, 'error when deleting member');
}
return array(
'success' => array(
'code' => 200,
'message' => 'member deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'member deleted'
)
);
}
/**
* Validate fields before creating an object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$member = array();
foreach (Members::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$member[$field] = $data[$field];
}
return $member;
}
/**
* Validate fields before creating an object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$member = array();
foreach (Members::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$member[$field] = $data[$field];
}
return $member;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// Remove the subscriptions because they are handled as a subresource.
unset($object->subscriptions);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
// Remove the subscriptions because they are handled as a subresource.
unset($object->subscriptions);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->total_ht);
unset($object->total_ttc);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ht);
unset($object->total_ttc);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
return $object;
}
return $object;
}
/**
* List subscriptions of a member
*
* Get a list of subscriptions
*
* @param int $id ID of member
* @return array Array of subscription objects
*
* @throws RestException
*
* @url GET {id}/subscriptions
*/
public function getSubscriptions($id)
{
$obj_ret = array();
/**
* List subscriptions of a member
*
* Get a list of subscriptions
*
* @param int $id ID of member
* @return array Array of subscription objects
*
* @throws RestException
*
* @url GET {id}/subscriptions
*/
public function getSubscriptions($id)
{
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->adherent->cotisation->lire) {
throw new RestException(401);
}
if (!DolibarrApiAccess::$user->rights->adherent->cotisation->lire) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$obj_ret = array();
foreach ($member->subscriptions as $subscription) {
$obj_ret[] = $this->_cleanObjectDatas($subscription);
}
return $obj_ret;
}
$obj_ret = array();
foreach ($member->subscriptions as $subscription) {
$obj_ret[] = $this->_cleanObjectDatas($subscription);
}
return $obj_ret;
}
/**
* Add a subscription for a member
*
* @param int $id ID of member
* @param int $start_date Start date {@from body} {@type timestamp}
* @param int $end_date End date {@from body} {@type timestamp}
* @param float $amount Amount (may be 0) {@from body}
* @param string $label Label {@from body}
* @return int ID of subscription
*
* @url POST {id}/subscriptions
*/
public function createSubscription($id, $start_date, $end_date, $amount, $label = '')
{
if (!DolibarrApiAccess::$user->rights->adherent->cotisation->creer) {
throw new RestException(401);
}
/**
* Add a subscription for a member
*
* @param int $id ID of member
* @param int $start_date Start date {@from body} {@type timestamp}
* @param int $end_date End date {@from body} {@type timestamp}
* @param float $amount Amount (may be 0) {@from body}
* @param string $label Label {@from body}
* @return int ID of subscription
*
* @url POST {id}/subscriptions
*/
public function createSubscription($id, $start_date, $end_date, $amount, $label = '')
{
if (!DolibarrApiAccess::$user->rights->adherent->cotisation->creer) {
throw new RestException(401);
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
$member = new Adherent($this->db);
$result = $member->fetch($id);
if (!$result) {
throw new RestException(404, 'member not found');
}
return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date);
}
return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date);
}
/**
* Get categories for a member
*
* @param int $id ID of member
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
*
* @return mixed
*
* @url GET {id}/categories
*/
/**
* Get categories for a member
*
* @param int $id ID of member
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
*
* @return mixed
*
* @url GET {id}/categories
*/
public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
{
if (!DolibarrApiAccess::$user->rights->categorie->lire) {

View File

@ -27,289 +27,289 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
*/
class MembersTypes extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'label',
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'label',
);
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
}
/**
* Get properties of a member type object
*
* Return an array with member type informations
*
* @param int $id ID of member type
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
/**
* Get properties of a member type object
*
* Return an array with member type informations
*
* @param int $id ID of member type
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$membertype = new AdherentType($this->db);
$result = $membertype->fetch($id);
if (!$result) {
throw new RestException(404, 'member type not found');
}
$membertype = new AdherentType($this->db);
$result = $membertype->fetch($id);
if (!$result) {
throw new RestException(404, 'member type not found');
}
if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($membertype);
}
return $this->_cleanObjectDatas($membertype);
}
/**
* List members types
*
* Get a list of members types
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.libelle:like:'SO-%') and (t.subscription:=:'1')"
* @return array Array of member type objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
global $db, $conf;
/**
* List members types
*
* Get a list of members types
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.libelle:like:'SO-%') and (t.subscription:=:'1')"
* @return array Array of member type objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
if (!DolibarrApiAccess::$user->rights->adherent->lire) {
throw new RestException(401);
}
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t";
$sql .= ' WHERE t.entity IN ('.getEntity('member_type').')';
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t";
$sql .= ' WHERE t.entity IN ('.getEntity('member_type').')';
// Add sql filters
if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
// Add sql filters
if ($sqlfilters) {
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
if ($result) {
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) {
$obj = $this->db->fetch_object($result);
$membertype = new AdherentType($this->db);
if ($membertype->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($membertype);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve member type list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No member type found');
}
$result = $this->db->query($sql);
if ($result) {
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min) {
$obj = $this->db->fetch_object($result);
$membertype = new AdherentType($this->db);
if ($membertype->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($membertype);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve member type list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No member type found');
}
return $obj_ret;
}
return $obj_ret;
}
/**
* Create member type object
*
* @param array $request_data Request data
* @return int ID of member type
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->configurer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
/**
* Create member type object
*
* @param array $request_data Request data
* @return int ID of member type
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->configurer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
$membertype = new AdherentType($this->db);
foreach ($request_data as $field => $value) {
$membertype->$field = $value;
}
if ($membertype->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating member type', array_merge(array($membertype->error), $membertype->errors));
}
return $membertype->id;
}
$membertype = new AdherentType($this->db);
foreach ($request_data as $field => $value) {
$membertype->$field = $value;
}
if ($membertype->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating member type', array_merge(array($membertype->error), $membertype->errors));
}
return $membertype->id;
}
/**
* Update member type
*
* @param int $id ID of member type to update
* @param array $request_data Datas
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->configurer) {
throw new RestException(401);
}
/**
* Update member type
*
* @param int $id ID of member type to update
* @param array $request_data Datas
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->adherent->configurer) {
throw new RestException(401);
}
$membertype = new AdherentType($this->db);
$result = $membertype->fetch($id);
if (!$result) {
throw new RestException(404, 'member type not found');
}
$membertype = new AdherentType($this->db);
$result = $membertype->fetch($id);
if (!$result) {
throw new RestException(404, 'member type not found');
}
if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
// Process the status separately because it must be updated using
// the validate() and resiliate() methods of the class AdherentType.
$membertype->$field = $value;
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
// Process the status separately because it must be updated using
// the validate() and resiliate() methods of the class AdherentType.
$membertype->$field = $value;
}
// If there is no error, update() returns the number of affected rows
// so if the update is a no op, the return value is zero.
if ($membertype->update(DolibarrApiAccess::$user) >= 0) {
return $this->get($id);
} else {
throw new RestException(500, $membertype->error);
}
}
// If there is no error, update() returns the number of affected rows
// so if the update is a no op, the return value is zero.
if ($membertype->update(DolibarrApiAccess::$user) >= 0) {
return $this->get($id);
} else {
throw new RestException(500, $membertype->error);
}
}
/**
* Delete member type
*
* @param int $id member type ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->configurer) {
throw new RestException(401);
}
$membertype = new AdherentType($this->db);
$result = $membertype->fetch($id);
if (!$result) {
throw new RestException(404, 'member type not found');
}
/**
* Delete member type
*
* @param int $id member type ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->adherent->configurer) {
throw new RestException(401);
}
$membertype = new AdherentType($this->db);
$result = $membertype->fetch($id);
if (!$result) {
throw new RestException(404, 'member type not found');
}
if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$membertype->delete()) {
throw new RestException(401, 'error when deleting member type');
}
if (!$membertype->delete()) {
throw new RestException(401, 'error when deleting member type');
}
return array(
'success' => array(
'code' => 200,
'message' => 'member type deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'member type deleted'
)
);
}
/**
* Validate fields before creating an object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$membertype = array();
foreach (MembersTypes::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$membertype[$field] = $data[$field];
}
return $membertype;
}
/**
* Validate fields before creating an object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$membertype = array();
foreach (MembersTypes::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$membertype[$field] = $data[$field];
}
return $membertype;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->array_options);
unset($object->linkedObjectsIds);
unset($object->context);
unset($object->canvas);
unset($object->fk_project);
unset($object->contact);
unset($object->contact_id);
unset($object->thirdparty);
unset($object->user);
unset($object->origin);
unset($object->origin_id);
unset($object->ref_ext);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->model_pdf);
unset($object->fk_account);
unset($object->note_public);
unset($object->note_private);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->array_options);
unset($object->linkedObjectsIds);
unset($object->context);
unset($object->canvas);
unset($object->fk_project);
unset($object->contact);
unset($object->contact_id);
unset($object->thirdparty);
unset($object->user);
unset($object->origin);
unset($object->origin_id);
unset($object->ref_ext);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->model_pdf);
unset($object->fk_account);
unset($object->note_public);
unset($object->note_private);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
return $object;
}
return $object;
}
}

View File

@ -145,79 +145,79 @@ if (empty($conf->use_javascript_ajax))
{
setEventMessages(array($langs->trans("NotAvailable"), $langs->trans("JavascriptDisabled")), null, 'errors');
} else {
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td colspan="2">'.$langs->trans("ActivateFCKeditor").'</td>';
print '<td class="center" width="100">'.$langs->trans("Action").'</td>';
print "</tr>\n";
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td colspan="2">'.$langs->trans("ActivateFCKeditor").'</td>';
print '<td class="center" width="100">'.$langs->trans("Action").'</td>';
print "</tr>\n";
// Modules
foreach ($modules as $const => $desc)
{
// Si condition non remplie, on ne propose pas l'option
if (!$conditions[$const]) continue;
// Modules
foreach ($modules as $const => $desc)
{
// Si condition non remplie, on ne propose pas l'option
if (!$conditions[$const]) continue;
print '<tr class="oddeven">';
print '<td width="16">'.img_object("", $picto[$const]).'</td>';
print '<td>'.$langs->trans($desc).'</td>';
print '<td class="center" width="100">';
$constante = 'FCKEDITOR_ENABLE_'.$const;
$value = (isset($conf->global->$constante) ? $conf->global->$constante : 0);
if ($value == 0)
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=activate_'.strtolower($const).'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>';
} elseif ($value == 1)
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=disable_'.strtolower($const).'">'.img_picto($langs->trans("Enabled"), 'switch_on').'</a>';
}
print '<tr class="oddeven">';
print '<td width="16">'.img_object("", $picto[$const]).'</td>';
print '<td>'.$langs->trans($desc).'</td>';
print '<td class="center" width="100">';
$constante = 'FCKEDITOR_ENABLE_'.$const;
$value = (isset($conf->global->$constante) ? $conf->global->$constante : 0);
if ($value == 0)
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=activate_'.strtolower($const).'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>';
} elseif ($value == 1)
{
print '<a href="'.$_SERVER['PHP_SELF'].'?action=disable_'.strtolower($const).'">'.img_picto($langs->trans("Enabled"), 'switch_on').'</a>';
}
print "</td>";
print '</tr>';
}
print "</td>";
print '</tr>';
}
print '</table>'."\n";
print '</table>'."\n";
print '<br>'."\n";
print '<form name="formtest" method="POST" action="'.$_SERVER["PHP_SELF"].'">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
// Skins
show_skin(null, 1);
print '<br>'."\n";
show_skin(null, 1);
print '<br>'."\n";
$listofmodes = array('dolibarr_mailings', 'dolibarr_notes', 'dolibarr_details', 'dolibarr_readonly', 'Full', 'Full_inline');
$linkstomode = '';
foreach ($listofmodes as $newmode)
{
if ($linkstomode) $linkstomode .= ' - ';
$linkstomode .= '<a href="'.$_SERVER["PHP_SELF"].'?mode='.$newmode.'">';
if ($mode == $newmode) $linkstomode .= '<strong>';
$linkstomode .= $newmode;
if ($mode == $newmode) $linkstomode .= '</strong>';
$linkstomode .= '</a>';
}
$linkstomode .= '';
$listofmodes = array('dolibarr_mailings', 'dolibarr_notes', 'dolibarr_details', 'dolibarr_readonly', 'Full', 'Full_inline');
$linkstomode = '';
foreach ($listofmodes as $newmode)
{
if ($linkstomode) $linkstomode .= ' - ';
$linkstomode .= '<a href="'.$_SERVER["PHP_SELF"].'?mode='.$newmode.'">';
if ($mode == $newmode) $linkstomode .= '<strong>';
$linkstomode .= $newmode;
if ($mode == $newmode) $linkstomode .= '</strong>';
$linkstomode .= '</a>';
}
$linkstomode .= '';
print load_fiche_titre($langs->trans("TestSubmitForm"), $linkstomode, '');
print '<input type="hidden" name="mode" value="'.dol_escape_htmltag($mode).'">';
if ($mode != 'Full_inline')
{
$uselocalbrowser = true;
$readonly = ($mode == 'dolibarr_readonly' ? 1 : 0);
$editor = new DolEditor('formtestfield', isset($conf->global->FCKEDITOR_TEST) ? $conf->global->FCKEDITOR_TEST : 'Test', '', 200, $mode, 'In', true, $uselocalbrowser, 1, 120, 8, $readonly);
$editor->Create();
} else {
print '<div style="border: 1px solid #888;" contenteditable="true">';
print $conf->global->FCKEDITOR_TEST;
print '</div>';
}
print '<br><div class="center"><input class="button" type="submit" name="save" value="'.$langs->trans("Save").'"></div>'."\n";
print '<div id="divforlog"></div>';
print '</form>'."\n";
print '<input type="hidden" name="mode" value="'.dol_escape_htmltag($mode).'">';
if ($mode != 'Full_inline')
{
$uselocalbrowser = true;
$readonly = ($mode == 'dolibarr_readonly' ? 1 : 0);
$editor = new DolEditor('formtestfield', isset($conf->global->FCKEDITOR_TEST) ? $conf->global->FCKEDITOR_TEST : 'Test', '', 200, $mode, 'In', true, $uselocalbrowser, 1, 120, 8, $readonly);
$editor->Create();
} else {
print '<div style="border: 1px solid #888;" contenteditable="true">';
print $conf->global->FCKEDITOR_TEST;
print '</div>';
}
print '<br><div class="center"><input class="button" type="submit" name="save" value="'.$langs->trans("Save").'"></div>'."\n";
print '<div id="divforlog"></div>';
print '</form>'."\n";
// Add env of ckeditor
// This is to show how CKEditor detect browser to understand why editor is disabled or not. To help debug.
/*
// Add env of ckeditor
// This is to show how CKEditor detect browser to understand why editor is disabled or not. To help debug.
/*
print '<br><script language="javascript">
function jsdump(obj, id) {
var out = \'\';

View File

@ -208,7 +208,7 @@ unset($objMod);
$i = 0;
foreach ($orders as $tmpkey => $tmpvalue)
{
$tmpMod = $modules[$tmpkey];
$tmpMod = $modules[$tmpkey];
if ($tmpMod->numero == $id)
{
$key = $i;

View File

@ -270,13 +270,13 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $
print '</tr>';
// sort list
if ($sortfield == "name" && $sortorder == "asc") usort($moduleList, function (stdClass $a, stdClass $b) {
if ($sortfield == "name" && $sortorder == "asc") usort($moduleList, function(stdClass $a, stdClass $b) {
return strcasecmp($a->name, $b->name); });
if ($sortfield == "name" && $sortorder == "desc") usort($moduleList, function (stdClass $a, stdClass $b) {
if ($sortfield == "name" && $sortorder == "desc") usort($moduleList, function(stdClass $a, stdClass $b) {
return strcasecmp($b->name, $a->name); });
if ($sortfield == "version" && $sortorder == "asc") usort($moduleList, function (stdClass $a, stdClass $b) {
if ($sortfield == "version" && $sortorder == "asc") usort($moduleList, function(stdClass $a, stdClass $b) {
return strcasecmp($a->version, $b->version); });
if ($sortfield == "version" && $sortorder == "desc") usort($moduleList, function (stdClass $a, stdClass $b) {
if ($sortfield == "version" && $sortorder == "desc") usort($moduleList, function(stdClass $a, stdClass $b) {
return strcasecmp($b->version, $a->version); });
if ($sortfield == "id" && $sortorder == "asc") usort($moduleList, "compareIdAsc");
if ($sortfield == "id" && $sortorder == "desc") usort($moduleList, "compareIdDesc");

View File

@ -139,7 +139,7 @@ if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['w
}
// remove not available workflows (based on activated modules and global defined keys)
$workflowcodes = array_filter($workflowcodes, function ($var) {
$workflowcodes = array_filter($workflowcodes, function($var) {
return $var['enabled']; });
/*

View File

@ -18,7 +18,7 @@
// Create the autoloader for Luracast
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
call_user_func(function () {
call_user_func(function() {
$loader = Luracast\Restler\AutoLoader::instance();
spl_autoload_register($loader);
return $loader;

View File

@ -45,7 +45,7 @@ if (!$res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
call_user_func(function () {
call_user_func(function() {
$loader = Luracast\Restler\AutoLoader::instance();
spl_autoload_register($loader);
return $loader;

View File

@ -36,315 +36,315 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
*/
class Boms extends DolibarrApi
{
/**
* @var BOM $bom {@type BOM}
*/
public $bom;
/**
* @var BOM $bom {@type BOM}
*/
public $bom;
/**
* Constructor
*/
public function __construct()
{
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->bom = new BOM($this->db);
}
$this->bom = new BOM($this->db);
}
/**
* Get properties of a bom object
*
* Return an array with bom informations
*
* @param int $id ID of bom
* @return array|mixed data without useless information
/**
* Get properties of a bom object
*
* @url GET {id}
* @throws RestException
*/
public function get($id)
{
* Return an array with bom informations
*
* @param int $id ID of bom
* @return array|mixed data without useless information
*
* @url GET {id}
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->bom->read) {
throw new RestException(401);
}
$result = $this->bom->fetch($id);
if (!$result) {
throw new RestException(404, 'BOM not found');
}
$result = $this->bom->fetch($id);
if (!$result) {
throw new RestException(404, 'BOM not found');
}
if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->bom);
}
}
/**
* List boms
*
* Get a list of boms
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of order objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
global $db, $conf;
/**
* List boms
*
* Get a list of boms
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of order objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$tmpobject = new BOM($this->db);
$obj_ret = array();
$tmpobject = new BOM($this->db);
$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
$restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
$restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
$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)
$sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t";
$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)
$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
$sql .= " WHERE 1 = 1";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
$sql .= " WHERE 1 = 1";
// Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
// Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid;
if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($restrictonsocid && $search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid;
if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($restrictonsocid && $search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
if ($result)
{
$num = $this->db->num_rows($result);
$i = 0;
while ($i < $num)
{
$obj = $this->db->fetch_object($result);
$bom_static = new BOM($this->db);
if ($bom_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($bom_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve bom list');
}
if (!count($obj_ret)) {
throw new RestException(404, 'No bom found');
}
$result = $this->db->query($sql);
if ($result)
{
$num = $this->db->num_rows($result);
$i = 0;
while ($i < $num)
{
$obj = $this->db->fetch_object($result);
$bom_static = new BOM($this->db);
if ($bom_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($bom_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve bom list');
}
if (!count($obj_ret)) {
throw new RestException(404, 'No bom found');
}
return $obj_ret;
}
}
/**
* Create bom object
*
* @param array $request_data Request datas
* @return int ID of bom
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->bom->write) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
/**
* Create bom object
*
* @param array $request_data Request datas
* @return int ID of bom
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->bom->write) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach ($request_data as $field => $value) {
$this->bom->$field = $value;
}
if (!$this->bom->create(DolibarrApiAccess::$user)) {
throw new RestException(500, "Error creating BOM", array_merge(array($this->bom->error), $this->bom->errors));
}
return $this->bom->id;
}
foreach ($request_data as $field => $value) {
$this->bom->$field = $value;
}
if (!$this->bom->create(DolibarrApiAccess::$user)) {
throw new RestException(500, "Error creating BOM", array_merge(array($this->bom->error), $this->bom->errors));
}
return $this->bom->id;
}
/**
* Update bom
*
* @param int $id Id of bom to update
* @param array $request_data Datas
*
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->bom->write) {
throw new RestException(401);
}
/**
* Update bom
*
* @param int $id Id of bom to update
* @param array $request_data Datas
*
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->bom->write) {
throw new RestException(401);
}
$result = $this->bom->fetch($id);
if (!$result) {
throw new RestException(404, 'BOM not found');
}
$result = $this->bom->fetch($id);
if (!$result) {
throw new RestException(404, 'BOM not found');
}
if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->bom->$field = $value;
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->bom->$field = $value;
}
if ($this->bom->update(DolibarrApiAccess::$user) > 0) {
return $this->get($id);
} else {
throw new RestException(500, $this->bom->error);
}
}
if ($this->bom->update(DolibarrApiAccess::$user) > 0) {
return $this->get($id);
} else {
throw new RestException(500, $this->bom->error);
}
}
/**
* Delete bom
*
* @param int $id BOM ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->bom->delete) {
/**
* Delete bom
*
* @param int $id BOM ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->bom->delete) {
throw new RestException(401);
}
$result = $this->bom->fetch($id);
if (!$result) {
throw new RestException(404, 'BOM not found');
}
$result = $this->bom->fetch($id);
if (!$result) {
throw new RestException(404, 'BOM not found');
}
if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
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);
}
return array(
'success' => array(
'code' => 200,
'message' => 'BOM deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'BOM deleted'
)
);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->rowid);
unset($object->canvas);
unset($object->rowid);
unset($object->canvas);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->statut);
unset($object->state);
unset($object->state_id);
unset($object->state_code);
unset($object->region);
unset($object->region_code);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->fk_account);
unset($object->comments);
unset($object->note);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->shipping_method_id);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->statut);
unset($object->state);
unset($object->state_id);
unset($object->state_code);
unset($object->region);
unset($object->region_code);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->fk_account);
unset($object->comments);
unset($object->note);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->shipping_method_id);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
// If object has lines, remove $db property
if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines);
for ($i = 0; $i < $nboflines; $i++)
{
$this->_cleanObjectDatas($object->lines[$i]);
// If object has lines, remove $db property
if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines);
for ($i = 0; $i < $nboflines; $i++)
{
$this->_cleanObjectDatas($object->lines[$i]);
unset($object->lines[$i]->lines);
unset($object->lines[$i]->note);
}
}
unset($object->lines[$i]->lines);
unset($object->lines[$i]->note);
}
}
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array of data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$myobject = array();
foreach ($this->bom->fields as $field => $propfield) {
if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$myobject[$field] = $data[$field];
}
return $myobject;
}
/**
* Validate fields before create or update object
*
* @param array $data Array of data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$myobject = array();
foreach ($this->bom->fields as $field => $propfield) {
if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$myobject[$field] = $data[$field];
}
return $myobject;
}
}

View File

@ -54,10 +54,10 @@ foreach ($linkedObjectBlock as $key => $objectlink)
echo '<td class="linkedcol-name nowraponall" >'.$objectlink->getNomUrl(1).'</td>';
echo '<td class="linkedcol-ref" align="center">';
$result=$product_static->fetch($objectlink->fk_product);
if ($result<0) {
$result = $product_static->fetch($objectlink->fk_product);
if ($result < 0) {
setEventMessage($product_static->error, 'errors');
} elseif ($result>0) {
} elseif ($result > 0) {
$product_static->getNomUrl(1);
}
print '</td>';

View File

@ -390,20 +390,20 @@ if (empty($reshook) && $action == 'add')
if ($user->id != $object->userownerid) $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view.
// Create reminders
if ($addreminder == 'on') {
$actionCommReminder = new ActionCommReminder($db);
if ($addreminder == 'on') {
$actionCommReminder = new ActionCommReminder($db);
$dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit);
$dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit);
$actionCommReminder->dateremind = $dateremind;
$actionCommReminder->typeremind = $remindertype;
$actionCommReminder->offsetunit = $offsetunit;
$actionCommReminder->offsetvalue = $offsetvalue;
$actionCommReminder->status = $actionCommReminder::STATUS_TODO;
$actionCommReminder->fk_actioncomm = $object->id;
if ($remindertype == 'email') $actionCommReminder->fk_email_template = $modelmail;
$actionCommReminder->dateremind = $dateremind;
$actionCommReminder->typeremind = $remindertype;
$actionCommReminder->offsetunit = $offsetunit;
$actionCommReminder->offsetvalue = $offsetvalue;
$actionCommReminder->status = $actionCommReminder::STATUS_TODO;
$actionCommReminder->fk_actioncomm = $object->id;
if ($remindertype == 'email') $actionCommReminder->fk_email_template = $modelmail;
// the notification must be created for every user assigned to the event
// the notification must be created for every user assigned to the event
foreach ($object->userassigned as $userassigned)
{
$actionCommReminder->fk_user = $userassigned['id'];
@ -488,17 +488,17 @@ if (empty($reshook) && $action == 'update')
$object->datef = $datef;
$object->percentage = $percentage;
$object->priority = GETPOST("priority", "int");
$object->fulldayevent = GETPOST("fullday") ? 1 : 0;
$object->location = GETPOST('location', "alphanohtml");
$object->fulldayevent = GETPOST("fullday") ? 1 : 0;
$object->location = GETPOST('location', "alphanohtml");
$object->socid = GETPOST("socid", "int");
$socpeopleassigned = GETPOST("socpeopleassigned", 'array');
$object->socpeopleassigned = array();
foreach ($socpeopleassigned as $cid) $object->socpeopleassigned[$cid] = array('id' => $cid);
$object->contact_id = GETPOST("contactid", 'int');
if (empty($object->contact_id) && !empty($object->socpeopleassigned)) {
reset($object->socpeopleassigned);
$object->contact_id = key($object->socpeopleassigned);
}
if (empty($object->contact_id) && !empty($object->socpeopleassigned)) {
reset($object->socpeopleassigned);
$object->contact_id = key($object->socpeopleassigned);
}
$object->fk_project = GETPOST("projectid", 'int');
$object->note_private = trim(GETPOST("note", "restricthtml"));
$object->fk_element = GETPOST("fk_element", "int");
@ -951,39 +951,39 @@ if ($action == 'create')
// Title
print '<tr><td'.(empty($conf->global->AGENDA_USE_EVENT_TYPE) ? ' class="fieldrequired titlefieldcreate"' : '').'>'.$langs->trans("Label").'</td><td><input type="text" id="label" name="label" class="soixantepercent" value="'.GETPOST('label').'"></td></tr>';
// Full day
print '<tr><td>'.$langs->trans("EventOnFullDay").'</td><td><input type="checkbox" id="fullday" name="fullday" '.(GETPOST('fullday') ? ' checked' : '').'></td></tr>';
// Full day
print '<tr><td>'.$langs->trans("EventOnFullDay").'</td><td><input type="checkbox" id="fullday" name="fullday" '.(GETPOST('fullday') ? ' checked' : '').'></td></tr>';
$datep = ($datep ? $datep : $object->datep);
if (GETPOST('datep', 'int', 1)) $datep = dol_stringtotime(GETPOST('datep', 'int', 1), 0);
$datef = ($datef ? $datef : $object->datef);
if (GETPOST('datef', 'int', 1)) $datef = dol_stringtotime(GETPOST('datef', 'int', 1), 0);
if (empty($datef) && !empty($datep))
{
if (GETPOST("actioncode", 'aZ09') == 'AC_RDV' || empty($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT)) {
$datef = dol_time_plus_duree($datep, (empty($conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS) ? 1 : $conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS), 'h');
}
}
$datep = ($datep ? $datep : $object->datep);
if (GETPOST('datep', 'int', 1)) $datep = dol_stringtotime(GETPOST('datep', 'int', 1), 0);
$datef = ($datef ? $datef : $object->datef);
if (GETPOST('datef', 'int', 1)) $datef = dol_stringtotime(GETPOST('datef', 'int', 1), 0);
if (empty($datef) && !empty($datep))
{
if (GETPOST("actioncode", 'aZ09') == 'AC_RDV' || empty($conf->global->AGENDA_USE_EVENT_TYPE_DEFAULT)) {
$datef = dol_time_plus_duree($datep, (empty($conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS) ? 1 : $conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS), 'h');
}
}
// Date start
// Date start
print '<tr><td class="nowrap">';
print '<span class="fieldrequired">'.$langs->trans("DateActionStart").'</span>';
print ' - ';
print '<span id="dateend"'.(GETPOST("actioncode", 'aZ09') == 'AC_RDV' ? ' class="fieldrequired"' : '').'>'.$langs->trans("DateActionEnd").'</span>';
print '</td><td>';
if (GETPOST("afaire") == 1) {
print $form->selectDate($datep, 'ap', 1, 1, 0, "action", 1, 2, 0, 'fulldaystart'); // Empty value not allowed for start date and hours if "todo"
} else {
print $form->selectDate($datep, 'ap', 1, 1, 1, "action", 1, 2, 0, 'fulldaystart');
}
print ' <span class="hideonsmartphone">&nbsp; &nbsp; - &nbsp; &nbsp;</span> ';
print $form->selectDate($datep, 'ap', 1, 1, 0, "action", 1, 2, 0, 'fulldaystart'); // Empty value not allowed for start date and hours if "todo"
} else {
print $form->selectDate($datep, 'ap', 1, 1, 1, "action", 1, 2, 0, 'fulldaystart');
}
print ' <span class="hideonsmartphone">&nbsp; &nbsp; - &nbsp; &nbsp;</span> ';
//print ' - ';
if (GETPOST("afaire") == 1) {
print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend');
} else {
print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend');
}
print '</td></tr>';
if (GETPOST("afaire") == 1) {
print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend');
} else {
print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend');
}
print '</td></tr>';
// Date end
/*print '<tr><td>';

View File

@ -29,361 +29,361 @@
class AgendaEvents extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
);
/**
* @var ActionComm $actioncomm {@type ActionComm}
*/
public $actioncomm;
/**
* @var ActionComm $actioncomm {@type ActionComm}
*/
public $actioncomm;
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->actioncomm = new ActionComm($this->db);
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->actioncomm = new ActionComm($this->db);
}
/**
* Get properties of a Agenda Events object
*
* Return an array with Agenda Events informations
*
* @param int $id ID of Agenda Events
* @return array|mixed Data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
throw new RestException(401, "Insufficient rights to read an event");
}
if ($id == 0) {
$result = $this->actioncomm->initAsSpecimen();
} else {
$result = $this->actioncomm->fetch($id);
if ($result) {
$this->actioncomm->fetch_optionals();
$this->actioncomm->fetchObjectLinked();
}
}
if (!$result) {
throw new RestException(404, 'Agenda Events not found');
}
/**
* Get properties of a Agenda Events object
*
* Return an array with Agenda Events informations
*
* @param int $id ID of Agenda Events
* @return array|mixed Data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
throw new RestException(401, "Insufficient rights to read an event");
}
if ($id == 0) {
$result = $this->actioncomm->initAsSpecimen();
} else {
$result = $this->actioncomm->fetch($id);
if ($result) {
$this->actioncomm->fetch_optionals();
$this->actioncomm->fetchObjectLinked();
}
}
if (!$result) {
throw new RestException(404, 'Agenda Events not found');
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->read && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
throw new RestException(401, "Insufficient rights to read event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->read && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
throw new RestException(401, "Insufficient rights to read event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
if (!DolibarrApi::_checkAccessToResource('agenda', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->actioncomm);
}
if (!DolibarrApi::_checkAccessToResource('agenda', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->actioncomm);
}
/**
* List Agenda Events
*
* Get a list of Agenda Events
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $user_ids User ids filter field (owners of event). Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i}
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'%dol%') and (t.datec:<:'20160101')"
* @return array Array of Agenda Events objects
*/
public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '')
{
global $db, $conf;
/**
* List Agenda Events
*
* Get a list of Agenda Events
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $user_ids User ids filter field (owners of event). Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i}
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'%dol%') and (t.datec:<:'20160101')"
* @return array Array of Agenda Events objects
*/
public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
throw new RestException(401, "Insufficient rights to read events");
}
if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) {
throw new RestException(401, "Insufficient rights to read events");
}
// case of external user
$socid = 0;
if (!empty(DolibarrApiAccess::$user->socid)) $socid = DolibarrApiAccess::$user->socid;
// case of external user
$socid = 0;
if (!empty(DolibarrApiAccess::$user->socid)) $socid = DolibarrApiAccess::$user->socid;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
if (empty($conf->societe->enabled)) $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
if (empty($conf->societe->enabled)) $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
$sql = "SELECT t.id as rowid";
if (!empty($conf->societe->enabled))
if ((!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."actioncomm as t";
if (!empty($conf->societe->enabled))
if ((!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 t.entity IN ('.getEntity('agenda').')';
if (!empty($conf->societe->enabled))
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($user_ids) $sql .= " AND t.fk_user_action IN (".$user_ids.")";
if ($socid > 0) $sql .= " AND t.fk_soc = ".$socid;
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql = "SELECT t.id as rowid";
if (!empty($conf->societe->enabled))
if ((!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."actioncomm as t";
if (!empty($conf->societe->enabled))
if ((!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 t.entity IN ('.getEntity('agenda').')';
if (!empty($conf->societe->enabled))
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($user_ids) $sql .= " AND t.fk_user_action IN (".$user_ids.")";
if ($socid > 0) $sql .= " AND t.fk_soc = ".$socid;
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
$result = $this->db->query($sql);
if ($result)
{
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$actioncomm_static = new ActionComm($this->db);
if ($actioncomm_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($actioncomm_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No Agenda Event found');
}
return $obj_ret;
}
if ($result)
{
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$actioncomm_static = new ActionComm($this->db);
if ($actioncomm_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($actioncomm_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No Agenda Event found');
}
return $obj_ret;
}
/**
* Create Agenda Event object
*
* @param array $request_data Request data
* @return int ID of Agenda Event
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->create) {
throw new RestException(401, "Insufficient rights to create your Agenda Event");
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->create && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
throw new RestException(401, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
/**
* Create Agenda Event object
*
* @param array $request_data Request data
* @return int ID of Agenda Event
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->create) {
throw new RestException(401, "Insufficient rights to create your Agenda Event");
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->create && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
throw new RestException(401, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
// Check mandatory fields
$result = $this->_validate($request_data);
// Check mandatory fields
$result = $this->_validate($request_data);
foreach ($request_data as $field => $value) {
$this->actioncomm->$field = $value;
}
/*if (isset($request_data["lines"])) {
foreach ($request_data as $field => $value) {
$this->actioncomm->$field = $value;
}
/*if (isset($request_data["lines"])) {
$lines = array();
foreach ($request_data["lines"] as $line) {
array_push($lines, (object) $line);
}
$this->expensereport->lines = $lines;
}*/
if ($this->actioncomm->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating event", array_merge(array($this->actioncomm->error), $this->actioncomm->errors));
}
if ($this->actioncomm->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating event", array_merge(array($this->actioncomm->error), $this->actioncomm->errors));
}
return $this->actioncomm->id;
}
return $this->actioncomm->id;
}
/**
* Update Agenda Event general fields
*
* @param int $id Id of Agenda Event to update
* @param array $request_data Datas
*
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->create) {
throw new RestException(401, "Insufficient rights to create your Agenda Event");
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->create && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
throw new RestException(401, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
/**
* Update Agenda Event general fields
*
* @param int $id Id of Agenda Event to update
* @param array $request_data Datas
*
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->create) {
throw new RestException(401, "Insufficient rights to create your Agenda Event");
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->create && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
throw new RestException(401, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
$result = $this->actioncomm->fetch($id);
if ($result) {
$this->actioncomm->fetch_optionals();
$this->actioncomm->fetch_userassigned();
$this->actioncomm->oldcopy = clone $this->actioncomm;
}
if (!$result) {
throw new RestException(404, 'actioncomm not found');
}
$result = $this->actioncomm->fetch($id);
if ($result) {
$this->actioncomm->fetch_optionals();
$this->actioncomm->fetch_userassigned();
$this->actioncomm->oldcopy = clone $this->actioncomm;
}
if (!$result) {
throw new RestException(404, 'actioncomm not found');
}
if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->actioncomm->$field = $value;
}
if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->actioncomm->$field = $value;
}
if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) > 0)
return $this->get($id);
if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) > 0)
return $this->get($id);
return false;
}
return false;
}
/**
* Delete Agenda Event
*
* @param int $id Agenda Event ID
*
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->delete) {
throw new RestException(401, "Insufficient rights to delete your Agenda Event");
}
/**
* Delete Agenda Event
*
* @param int $id Agenda Event ID
*
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->agenda->myactions->delete) {
throw new RestException(401, "Insufficient rights to delete your Agenda Event");
}
$result = $this->actioncomm->fetch($id);
if ($result) {
$this->actioncomm->fetch_optionals();
$this->actioncomm->fetch_userassigned();
$this->actioncomm->oldcopy = clone $this->actioncomm;
}
$result = $this->actioncomm->fetch($id);
if ($result) {
$this->actioncomm->fetch_optionals();
$this->actioncomm->fetch_userassigned();
$this->actioncomm->oldcopy = clone $this->actioncomm;
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->delete && DolibarrApiAccess::$user->id != $this->actioncomm->userownerid) {
throw new RestException(401, "Insufficient rights to delete an Agenda Event of owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
if (!DolibarrApiAccess::$user->rights->agenda->allactions->delete && DolibarrApiAccess::$user->id != $this->actioncomm->userownerid) {
throw new RestException(401, "Insufficient rights to delete an Agenda Event of owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
}
if (!$result) {
throw new RestException(404, 'Agenda Event not found');
}
if (!$result) {
throw new RestException(404, 'Agenda Event not found');
}
if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$this->actioncomm->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete Agenda Event : '.$this->actioncomm->error);
}
if (!$this->actioncomm->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete Agenda Event : '.$this->actioncomm->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Agenda Event deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Agenda Event deleted'
)
);
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$event = array();
foreach (AgendaEvents::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$event[$field] = $data[$field];
}
return $event;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$event = array();
foreach (AgendaEvents::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$event[$field] = $data[$field];
}
return $event;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->note); // alreaydy into note_private
unset($object->usermod);
unset($object->libelle);
unset($object->context);
unset($object->canvas);
unset($object->contact);
unset($object->contact_id);
unset($object->thirdparty);
unset($object->user);
unset($object->origin);
unset($object->origin_id);
unset($object->ref_ext);
unset($object->statut);
unset($object->state_code);
unset($object->state_id);
unset($object->state);
unset($object->region);
unset($object->region_code);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->fk_account);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->contact);
unset($object->societe);
unset($object->note); // alreaydy into note_private
unset($object->usermod);
unset($object->libelle);
unset($object->context);
unset($object->canvas);
unset($object->contact);
unset($object->contact_id);
unset($object->thirdparty);
unset($object->user);
unset($object->origin);
unset($object->origin_id);
unset($object->ref_ext);
unset($object->statut);
unset($object->state_code);
unset($object->state_id);
unset($object->state);
unset($object->region);
unset($object->region_code);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->fk_account);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->contact);
unset($object->societe);
unset($object->actions);
unset($object->lines);
unset($object->actions);
unset($object->lines);
return $object;
}
return $object;
}
}

View File

@ -28,201 +28,201 @@
*/
class CActionComm
{
/**
* @var string Error code (or message)
*/
public $error = '';
/**
* @var string Error code (or message)
*/
public $error = '';
/**
* @var DoliDB Database handler.
*/
public $db;
/**
* @var DoliDB Database handler.
*/
public $db;
/**
* @var int ID
*/
public $id;
/**
* @var int ID
*/
public $id;
public $code;
public $type;
public $libelle; // deprecated
public $code;
public $type;
public $libelle; // deprecated
/**
* @var string Type of agenda event label
*/
public $label;
/**
* @var string Type of agenda event label
*/
public $label;
public $active;
public $color;
public $active;
public $color;
/**
* @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
*/
public $picto;
/**
* @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
*/
public $picto;
public $type_actions = array();
public $type_actions = array();
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Load action type from database
*
* @param int $id id or code of action type to read
* @return int 1=ok, 0=not found, -1=error
*/
public function fetch($id)
{
$sql = "SELECT id, code, type, libelle as label, color, active, picto";
$sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm";
if (is_numeric($id)) $sql .= " WHERE id=".$id;
else $sql .= " WHERE code='".$this->db->escape($id)."'";
/**
* Load action type from database
*
* @param int $id id or code of action type to read
* @return int 1=ok, 0=not found, -1=error
*/
public function fetch($id)
{
$sql = "SELECT id, code, type, libelle as label, color, active, picto";
$sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm";
if (is_numeric($id)) $sql .= " WHERE id=".$id;
else $sql .= " WHERE code='".$this->db->escape($id)."'";
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql);
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
if ($this->db->num_rows($resql))
{
$obj = $this->db->fetch_object($resql);
$this->id = $obj->id;
$this->code = $obj->code;
$this->type = $obj->type;
$this->libelle = $obj->label; // deprecated
$this->label = $obj->label;
$this->active = $obj->active;
$this->color = $obj->color;
$this->id = $obj->id;
$this->code = $obj->code;
$this->type = $obj->type;
$this->libelle = $obj->label; // deprecated
$this->label = $obj->label;
$this->active = $obj->active;
$this->color = $obj->color;
$this->db->free($resql);
return 1;
} else {
$this->db->free($resql);
return 0;
}
} else {
$this->error = $this->db->error();
return -1;
}
}
$this->db->free($resql);
return 1;
} else {
$this->db->free($resql);
return 0;
}
} else {
$this->error = $this->db->error();
return -1;
}
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return list of event types: array(id=>label) or array(code=>label)
*
* @param string|int $active 1 or 0 to filter on event state active or not ('' by default = no filter)
* @param string $idorcode 'id' or 'code'
* @param string $excludetype Type to exclude ('system' or 'systemauto')
* @param int $onlyautoornot 1=Group all type AC_XXX into 1 line AC_MANUAL. 0=Keep details of type, -1=Keep details and add a combined line "All manual"
* @param string $morefilter Add more SQL filter
* @param int $shortlabel 1=Get short label instead of long label
* @return mixed Array of all event types if OK, <0 if KO. Key of array is id or code depending on parameter $idorcode.
*/
public function liste_array($active = '', $idorcode = 'id', $excludetype = '', $onlyautoornot = 0, $morefilter = '', $shortlabel = 0)
{
// phpcs:enable
global $langs, $conf;
$langs->load("commercial");
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return list of event types: array(id=>label) or array(code=>label)
*
* @param string|int $active 1 or 0 to filter on event state active or not ('' by default = no filter)
* @param string $idorcode 'id' or 'code'
* @param string $excludetype Type to exclude ('system' or 'systemauto')
* @param int $onlyautoornot 1=Group all type AC_XXX into 1 line AC_MANUAL. 0=Keep details of type, -1=Keep details and add a combined line "All manual"
* @param string $morefilter Add more SQL filter
* @param int $shortlabel 1=Get short label instead of long label
* @return mixed Array of all event types if OK, <0 if KO. Key of array is id or code depending on parameter $idorcode.
*/
public function liste_array($active = '', $idorcode = 'id', $excludetype = '', $onlyautoornot = 0, $morefilter = '', $shortlabel = 0)
{
// phpcs:enable
global $langs, $conf;
$langs->load("commercial");
$repid = array();
$repcode = array();
$repid = array();
$repcode = array();
$sql = "SELECT id, code, libelle as label, module, type, color, picto";
$sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm";
$sql .= " WHERE 1=1";
if ($active != '') $sql .= " AND active=".$active;
if (!empty($excludetype)) $sql .= " AND type <> '".$this->db->escape($excludetype)."'";
if ($morefilter) $sql .= " AND ".$morefilter;
$sql .= " ORDER BY module, position, type";
$sql = "SELECT id, code, libelle as label, module, type, color, picto";
$sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm";
$sql .= " WHERE 1=1";
if ($active != '') $sql .= " AND active=".$active;
if (!empty($excludetype)) $sql .= " AND type <> '".$this->db->escape($excludetype)."'";
if ($morefilter) $sql .= " AND ".$morefilter;
$sql .= " ORDER BY module, position, type";
dol_syslog(get_class($this)."::liste_array", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
dol_syslog(get_class($this)."::liste_array", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
$qualified = 1;
$qualified = 1;
// $obj->type can be system, systemauto, module, moduleauto, xxx, xxxauto
if ($qualified && $onlyautoornot > 0 && preg_match('/^system/', $obj->type) && !preg_match('/^AC_OTH/', $obj->code)) $qualified = 0; // We discard detailed system events. We keep only the 2 generic lines (AC_OTH and AC_OTH_AUTO)
// $obj->type can be system, systemauto, module, moduleauto, xxx, xxxauto
if ($qualified && $onlyautoornot > 0 && preg_match('/^system/', $obj->type) && !preg_match('/^AC_OTH/', $obj->code)) $qualified = 0; // We discard detailed system events. We keep only the 2 generic lines (AC_OTH and AC_OTH_AUTO)
if ($qualified && $obj->module)
{
if ($obj->module == 'invoice' && !$conf->facture->enabled) $qualified = 0;
if ($obj->module == 'order' && !$conf->commande->enabled) $qualified = 0;
if ($obj->module == 'propal' && !$conf->propal->enabled) $qualified = 0;
if ($obj->module == 'invoice_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_invoice->enabled)) $qualified = 0;
if ($obj->module == 'order_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_order->enabled)) $qualified = 0;
if ($obj->module == 'shipping' && !$conf->expedition->enabled) $qualified = 0;
}
if ($qualified && $obj->module)
{
if ($obj->module == 'invoice' && !$conf->facture->enabled) $qualified = 0;
if ($obj->module == 'order' && !$conf->commande->enabled) $qualified = 0;
if ($obj->module == 'propal' && !$conf->propal->enabled) $qualified = 0;
if ($obj->module == 'invoice_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_invoice->enabled)) $qualified = 0;
if ($obj->module == 'order_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_order->enabled)) $qualified = 0;
if ($obj->module == 'shipping' && !$conf->expedition->enabled) $qualified = 0;
}
if ($qualified)
{
$keyfortrans = '';
$transcode = '';
$code = $obj->code;
if ($onlyautoornot > 0 && $code == 'AC_OTH') $code = 'AC_MANUAL';
if ($onlyautoornot > 0 && $code == 'AC_OTH_AUTO') $code = 'AC_AUTO';
if ($shortlabel)
{
$keyfortrans = "Action".$code.'Short';
$transcode = $langs->trans($keyfortrans);
}
if (empty($keyfortrans) || $keyfortrans == $transcode)
{
$keyfortrans = "Action".$code;
$transcode = $langs->trans($keyfortrans);
}
$label = (($transcode != $keyfortrans) ? $transcode : $langs->trans($obj->label));
if ($onlyautoornot == -1 && !empty($conf->global->AGENDA_USE_EVENT_TYPE) && !preg_match('/auto/i', $code))
{
$label = '&nbsp; '.$label;
$repid[-99] = $langs->trans("ActionAC_MANUAL");
$repcode['AC_NON_AUTO'] = $langs->trans("ActionAC_MANUAL");
}
$repid[$obj->id] = $label;
$repcode[$obj->code] = $label;
if ($onlyautoornot > 0 && preg_match('/^module/', $obj->type) && $obj->module) $repcode[$obj->code] .= ' ('.$langs->trans("Module").': '.$obj->module.')';
}
$i++;
}
}
if ($idorcode == 'id') $this->liste_array = $repid;
if ($idorcode == 'code') $this->liste_array = $repcode;
return $this->liste_array;
} else {
$this->error = $this->db->lasterror();
return -1;
}
}
if ($qualified)
{
$keyfortrans = '';
$transcode = '';
$code = $obj->code;
if ($onlyautoornot > 0 && $code == 'AC_OTH') $code = 'AC_MANUAL';
if ($onlyautoornot > 0 && $code == 'AC_OTH_AUTO') $code = 'AC_AUTO';
if ($shortlabel)
{
$keyfortrans = "Action".$code.'Short';
$transcode = $langs->trans($keyfortrans);
}
if (empty($keyfortrans) || $keyfortrans == $transcode)
{
$keyfortrans = "Action".$code;
$transcode = $langs->trans($keyfortrans);
}
$label = (($transcode != $keyfortrans) ? $transcode : $langs->trans($obj->label));
if ($onlyautoornot == -1 && !empty($conf->global->AGENDA_USE_EVENT_TYPE) && !preg_match('/auto/i', $code))
{
$label = '&nbsp; '.$label;
$repid[-99] = $langs->trans("ActionAC_MANUAL");
$repcode['AC_NON_AUTO'] = $langs->trans("ActionAC_MANUAL");
}
$repid[$obj->id] = $label;
$repcode[$obj->code] = $label;
if ($onlyautoornot > 0 && preg_match('/^module/', $obj->type) && $obj->module) $repcode[$obj->code] .= ' ('.$langs->trans("Module").': '.$obj->module.')';
}
$i++;
}
}
if ($idorcode == 'id') $this->liste_array = $repid;
if ($idorcode == 'code') $this->liste_array = $repcode;
return $this->liste_array;
} else {
$this->error = $this->db->lasterror();
return -1;
}
}
/**
* Return name of action type as a label translated
*
* @param int $withpicto 0=No picto, 1=Include picto into link, 2=Picto only
* @return string Label of action type
*/
public function getNomUrl($withpicto = 0)
{
global $langs;
/**
* Return name of action type as a label translated
*
* @param int $withpicto 0=No picto, 1=Include picto into link, 2=Picto only
* @return string Label of action type
*/
public function getNomUrl($withpicto = 0)
{
global $langs;
// Check if translation available
$transcode = $langs->trans("Action".$this->code);
if ($transcode != "Action".$this->code) return $transcode;
}
// Check if translation available
$transcode = $langs->trans("Action".$this->code);
if ($transcode != "Action".$this->code) return $transcode;
}
}

View File

@ -1500,7 +1500,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa
print '</div><div class="nowrap tagtd right">';
if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create)
{
print '<a class="cursoradd" href="'.$urltocreate.'">'; // Explicit link, usefull for nojs interfaces
print '<a class="cursoradd" href="'.$urltocreate.'">'; // Explicit link, usefull for nojs interfaces
print img_picto($langs->trans("NewAction"), 'edit_add.png');
print '</a>';
}

View File

@ -487,26 +487,26 @@ if ($object->id > 0)
print '</tr>';
}
if (!empty($conf->intracommreport->enabled))
{
// Transport mode by default
print '<tr><td class="nowrap">';
print '<table class="centpercent nobordernopadding"><tr><td class="nowrap">';
print $langs->trans('IntracommReportTransportMode');
print '<td>';
if (($action != 'edittransportmode') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edittransportmode&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
print '</tr></table>';
print '</td><td>';
if ($action == 'edittransportmode')
{
$form->formSelectTransportMode($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_transport_mode, 'fk_transport_mode', 1);
}
else {
$form->formSelectTransportMode($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_transport_mode, 'none');
}
print "</td>";
print '</tr>';
}
if (!empty($conf->intracommreport->enabled))
{
// Transport mode by default
print '<tr><td class="nowrap">';
print '<table class="centpercent nobordernopadding"><tr><td class="nowrap">';
print $langs->trans('IntracommReportTransportMode');
print '<td>';
if (($action != 'edittransportmode') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edittransportmode&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
print '</tr></table>';
print '</td><td>';
if ($action == 'edittransportmode')
{
$form->formSelectTransportMode($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_transport_mode, 'fk_transport_mode', 1);
}
else {
$form->formSelectTransportMode($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_transport_mode, 'none');
}
print "</td>";
print '</tr>';
}
// Categories
if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) {

View File

@ -501,9 +501,9 @@ if (empty($reshook))
$upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing');
if ($action == 'settitle') $object->title = trim(GETPOST('title', 'alpha'));
elseif ($action == 'setemail_from') $object->email_from = trim(GETPOST('email_from', 'none')); // Must allow 'name <email>'
elseif ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto', 'none')); // Must allow 'name <email>'
elseif ($action == 'setemail_errorsto') $object->email_errorsto = trim(GETPOST('email_errorsto', 'none')); // Must allow 'name <email>'
elseif ($action == 'setemail_from') $object->email_from = trim(GETPOST('email_from', 'none')); // Must allow 'name <email>'
elseif ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto', 'none')); // Must allow 'name <email>'
elseif ($action == 'setemail_errorsto') $object->email_errorsto = trim(GETPOST('email_errorsto', 'none')); // Must allow 'name <email>'
elseif ($action == 'settitle' && empty($object->title)) {
$mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTitle"));
} elseif ($action == 'setfrom' && empty($object->email_from)) {

View File

@ -846,8 +846,8 @@ class Proposals extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -950,8 +950,8 @@ class Orders extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -622,7 +622,7 @@ if (!empty($date_start) && !empty($date_stop))
if (empty($TData))
{
print '<tr class="oddeven"><td colspan="7">'.$langs->trans("NoItem").'</td>';
if (! empty($conf->multicurrency->enabled)) {
if (!empty($conf->multicurrency->enabled)) {
print '<td></td>';
}
print '</tr>';
@ -743,7 +743,7 @@ if (!empty($date_start) && !empty($date_stop))
$totalVAT_debit -= $data['amount_vat'];
}
if (! empty($conf->multicurrency->enabled)) {
if (!empty($conf->multicurrency->enabled)) {
print '<td class="center">'.$data['currency']."</td>\n";
}
@ -757,7 +757,7 @@ if (!empty($date_start) && !empty($date_stop))
print '<td align="right">'.price(price2num($totalIT_credit, 'MT')).'</td>';
print '<td align="right">'.price(price2num($totalVAT_credit, 'MT')).'</td>';
print '<td colspan="4"></td>';
if (! empty($conf->multicurrency->enabled)) {
if (!empty($conf->multicurrency->enabled)) {
print '<td></td>';
}
print "</tr>\n";
@ -768,7 +768,7 @@ if (!empty($date_start) && !empty($date_stop))
print '<td align="right">'.price(price2num($totalIT_debit, 'MT')).'</td>';
print '<td align="right">'.price(price2num($totalVAT_debit, 'MT')).'</td>';
print '<td colspan="4"></td>';
if (! empty($conf->multicurrency->enabled)) {
if (!empty($conf->multicurrency->enabled)) {
print '<td></td>';
}
print "</tr>\n";
@ -779,7 +779,7 @@ if (!empty($date_start) && !empty($date_stop))
print '<td align="right">'.price(price2num($totalIT_credit + $totalIT_debit, 'MT')).'</td>';
print '<td align="right">'.price(price2num($totalVAT_credit + $totalVAT_debit, 'MT')).'</td>';
print '<td colspan="4"></td>';
if (! empty($conf->multicurrency->enabled)) {
if (!empty($conf->multicurrency->enabled)) {
print '<td></td>';
}
print "</tr>\n";

View File

@ -30,407 +30,407 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
class BankAccounts extends DolibarrApi
{
/**
* array $FIELDS Mandatory fields, checked when creating an object
*/
static $FIELDS = array(
'ref',
'label',
'type',
'currency_code',
'country_id'
);
/**
* array $FIELDS Mandatory fields, checked when creating an object
*/
static $FIELDS = array(
'ref',
'label',
'type',
'currency_code',
'country_id'
);
/**
* Constructor
*/
public function __construct()
{
global $db;
$this->db = $db;
}
/**
* Constructor
*/
public function __construct()
{
global $db;
$this->db = $db;
}
/**
* Get the list of accounts.
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
/**
* Get the list of accounts.
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param int $category Use this param to filter list by category
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')"
* @return array List of account objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '')
{
$list = array();
if (!DolibarrApiAccess::$user->rights->banque->lire) {
throw new RestException(401);
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank_account as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_account as c";
}
$sql .= ' WHERE t.entity IN ('.getEntity('bank_account').')';
// Select accounts of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_account = t.rowid ";
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
dol_syslog("API Rest request");
$result = $this->db->query($sql);
if ($result) {
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
for ($i = 0; $i < $min; $i++) {
$obj = $this->db->fetch_object($result);
$account = new Account($this->db);
if ($account->fetch($obj->rowid) > 0) {
$list[] = $this->_cleanObjectDatas($account);
}
}
} else {
throw new RestException(503, 'Error when retrieving list of accounts: '.$this->db->lasterror());
}
return $list;
}
/**
* Get account by ID.
*
* @param int $id ID of account
* @return array Account object
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->banque->lire) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
return $this->_cleanObjectDatas($account);
}
/**
* Create account object
*
* @param array $request_data Request data
* @return int ID of account
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
$account = new Account($this->db);
foreach ($request_data as $field => $value) {
$account->$field = $value;
}
// Date of the initial balance (required to create an account).
$account->date_solde = time();
// courant and type are the same thing but the one used when
// creating an account is courant
$account->courant = $account->type;
if ($account->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating bank account', array_merge(array($account->error), $account->errors));
}
return $account->id;
}
/**
* Create an internal wire transfer between two bank accounts
*
* @param int $bankaccount_from_id BankAccount ID to use as the source of the internal wire transfer {@from body}{@required true}
* @param int $bankaccount_to_id BankAccount ID to use as the destination of the internal wire transfer {@from body}{@required true}
* @param string $date Date of the internal wire transfer (UNIX timestamp) {@from body}{@required true}{@type timestamp}
* @param string $description Description of the internal wire transfer {@from body}{@required true}
* @param float $amount Amount to transfer from the source to the destination BankAccount {@from body}{@required true}
* @param float $amount_to Amount to transfer to the destination BankAccount (only when accounts does not share the same currency) {@from body}{@required false}
*
* @url POST /transfer
*
* @return array
*
* @status 201
*
* @throws RestException 401 Unauthorized: User does not have permission to configure bank accounts
* @throws RestException 404 Not Found: Either the source or the destination bankaccount for the provided id does not exist
* @throws RestException 422 Unprocessable Entity: Refer to detailed exception message for the cause
* @throws RestException 500 Internal Server Error: Error(s) returned by the RDBMS
*/
public function transfer($bankaccount_from_id = 0, $bankaccount_to_id = 0, $date = null, $description = "", $amount = 0.0, $amount_to = 0.0)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
if ($bankaccount_from_id === $bankaccount_to_id) {
throw new RestException(422, 'bankaccount_from_id and bankaccount_to_id must be different !');
}
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$accountfrom = new Account($this->db);
$resultAccountFrom = $accountfrom->fetch($bankaccount_from_id);
if ($resultAccountFrom === 0) {
throw new RestException(404, 'The BankAccount for bankaccount_from_id provided does not exist.');
}
$accountto = new Account($this->db);
$resultAccountTo = $accountto->fetch($bankaccount_to_id);
if ($resultAccountTo === 0) {
throw new RestException(404, 'The BankAccount for bankaccount_to_id provided does not exist.');
}
if ($accountto->currency_code == $accountfrom->currency_code)
{
$amount_to = $amount;
} else {
if (!$amount_to || empty($amount_to))
{
throw new RestException(422, 'You must provide amount_to value since bankaccount_from and bankaccount_to does not share the same currency.');
}
}
$this->db->begin();
$error = 0;
$bank_line_id_from = 0;
$bank_line_id_to = 0;
$result = 0;
$user = DolibarrApiAccess::$user;
// By default, electronic transfert from bank to bank
$typefrom = 'PRE';
$typeto = 'VIR';
if ($accountto->courant == Account::TYPE_CASH || $accountfrom->courant == Account::TYPE_CASH)
{
// This is transfer of change
$typefrom = 'LIQ';
$typeto = 'LIQ';
}
/**
* Creating bank line records
*/
if (!$error) {
$bank_line_id_from = $accountfrom->addline($date, $typefrom, $description, -1 * price2num($amount), '', '', $user);
}
if (!($bank_line_id_from > 0)) {
$error++;
}
if (!$error) {
$bank_line_id_to = $accountto->addline($date, $typeto, $description, price2num($amount_to), '', '', $user);
}
if (!($bank_line_id_to > 0)) {
$error++;
}
/**
* Creating links between bank line record and its source
*/
$url = DOL_URL_ROOT.'/compta/bank/line.php?rowid=';
$label = '(banktransfert)';
$type = 'banktransfert';
if (!$error) {
$result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, $url, $label, $type);
}
if (!($result > 0)) {
$error++;
}
if (!$error) {
$result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, $url, $label, $type);
}
if (!($result > 0)) {
$error++;
}
if (!$error)
{
$this->db->commit();
return array(
'success' => array(
'code' => 201,
'message' => 'Internal wire transfer created successfully.'
)
);
} else {
$this->db->rollback();
throw new RestException(500, $accountfrom->error.' '.$accountto->error);
}
}
/**
* Update account
*
* @param int $id ID of account
* @param array $request_data data
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$account->$field = $value;
}
if ($account->update(DolibarrApiAccess::$user) > 0)
{
return $this->get($id);
} else {
throw new RestException(500, $account->error);
}
}
/**
* Delete account
*
* @param int $id ID of account
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
if ($account->delete(DolibarrApiAccess::$user) < 0) {
throw new RestException(401, 'error when deleting account');
}
return array(
'success' => array(
'code' => 200,
'message' => 'account deleted'
)
);
}
/**
* Validate fields before creating an object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$account = array();
foreach (BankAccounts::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$account[$field] = $data[$field];
}
return $account;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->rowid);
return $object;
}
/**
* Get the list of lines of the account.
*
* @param int $id ID of account
* @return array Array of AccountLine objects
*
* @throws RestException
*
* @url GET {id}/lines
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')"
*/
public function getLines($id, $sqlfilters = '')
{
$list = array();
* @return array List of account objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '')
{
$list = array();
if (!DolibarrApiAccess::$user->rights->banque->lire) {
throw new RestException(401);
}
if (!DolibarrApiAccess::$user->rights->banque->lire) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank_account as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_account as c";
}
$sql .= ' WHERE t.entity IN ('.getEntity('bank_account').')';
// Select accounts of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_account = t.rowid ";
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank ";
$sql .= " WHERE fk_account = ".$id;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
dol_syslog("API Rest request");
$result = $this->db->query($sql);
if ($result) {
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
for ($i = 0; $i < $min; $i++) {
$obj = $this->db->fetch_object($result);
$account = new Account($this->db);
if ($account->fetch($obj->rowid) > 0) {
$list[] = $this->_cleanObjectDatas($account);
}
}
} else {
throw new RestException(503, 'Error when retrieving list of accounts: '.$this->db->lasterror());
}
return $list;
}
/**
* Get account by ID.
*
* @param int $id ID of account
* @return array Account object
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->banque->lire) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
return $this->_cleanObjectDatas($account);
}
/**
* Create account object
*
* @param array $request_data Request data
* @return int ID of account
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
$account = new Account($this->db);
foreach ($request_data as $field => $value) {
$account->$field = $value;
}
// Date of the initial balance (required to create an account).
$account->date_solde = time();
// courant and type are the same thing but the one used when
// creating an account is courant
$account->courant = $account->type;
if ($account->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating bank account', array_merge(array($account->error), $account->errors));
}
return $account->id;
}
/**
* Create an internal wire transfer between two bank accounts
*
* @param int $bankaccount_from_id BankAccount ID to use as the source of the internal wire transfer {@from body}{@required true}
* @param int $bankaccount_to_id BankAccount ID to use as the destination of the internal wire transfer {@from body}{@required true}
* @param string $date Date of the internal wire transfer (UNIX timestamp) {@from body}{@required true}{@type timestamp}
* @param string $description Description of the internal wire transfer {@from body}{@required true}
* @param float $amount Amount to transfer from the source to the destination BankAccount {@from body}{@required true}
* @param float $amount_to Amount to transfer to the destination BankAccount (only when accounts does not share the same currency) {@from body}{@required false}
*
* @url POST /transfer
*
* @return array
*
* @status 201
*
* @throws RestException 401 Unauthorized: User does not have permission to configure bank accounts
* @throws RestException 404 Not Found: Either the source or the destination bankaccount for the provided id does not exist
* @throws RestException 422 Unprocessable Entity: Refer to detailed exception message for the cause
* @throws RestException 500 Internal Server Error: Error(s) returned by the RDBMS
*/
public function transfer($bankaccount_from_id = 0, $bankaccount_to_id = 0, $date = null, $description = "", $amount = 0.0, $amount_to = 0.0)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
if ($bankaccount_from_id === $bankaccount_to_id) {
throw new RestException(422, 'bankaccount_from_id and bankaccount_to_id must be different !');
}
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$accountfrom = new Account($this->db);
$resultAccountFrom = $accountfrom->fetch($bankaccount_from_id);
if ($resultAccountFrom === 0) {
throw new RestException(404, 'The BankAccount for bankaccount_from_id provided does not exist.');
}
$accountto = new Account($this->db);
$resultAccountTo = $accountto->fetch($bankaccount_to_id);
if ($resultAccountTo === 0) {
throw new RestException(404, 'The BankAccount for bankaccount_to_id provided does not exist.');
}
if ($accountto->currency_code == $accountfrom->currency_code)
{
$amount_to = $amount;
} else {
if (!$amount_to || empty($amount_to))
{
throw new RestException(422, 'You must provide amount_to value since bankaccount_from and bankaccount_to does not share the same currency.');
}
}
$this->db->begin();
$error = 0;
$bank_line_id_from = 0;
$bank_line_id_to = 0;
$result = 0;
$user = DolibarrApiAccess::$user;
// By default, electronic transfert from bank to bank
$typefrom = 'PRE';
$typeto = 'VIR';
if ($accountto->courant == Account::TYPE_CASH || $accountfrom->courant == Account::TYPE_CASH)
{
// This is transfer of change
$typefrom = 'LIQ';
$typeto = 'LIQ';
}
/**
* Creating bank line records
*/
if (!$error) {
$bank_line_id_from = $accountfrom->addline($date, $typefrom, $description, -1 * price2num($amount), '', '', $user);
}
if (!($bank_line_id_from > 0)) {
$error++;
}
if (!$error) {
$bank_line_id_to = $accountto->addline($date, $typeto, $description, price2num($amount_to), '', '', $user);
}
if (!($bank_line_id_to > 0)) {
$error++;
}
/**
* Creating links between bank line record and its source
*/
$url = DOL_URL_ROOT.'/compta/bank/line.php?rowid=';
$label = '(banktransfert)';
$type = 'banktransfert';
if (!$error) {
$result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, $url, $label, $type);
}
if (!($result > 0)) {
$error++;
}
if (!$error) {
$result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, $url, $label, $type);
}
if (!($result > 0)) {
$error++;
}
if (!$error)
{
$this->db->commit();
return array(
'success' => array(
'code' => 201,
'message' => 'Internal wire transfer created successfully.'
)
);
} else {
$this->db->rollback();
throw new RestException(500, $accountfrom->error.' '.$accountto->error);
}
}
/**
* Update account
*
* @param int $id ID of account
* @param array $request_data data
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$account->$field = $value;
}
if ($account->update(DolibarrApiAccess::$user) > 0)
{
return $this->get($id);
} else {
throw new RestException(500, $account->error);
}
}
/**
* Delete account
*
* @param int $id ID of account
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->banque->configurer) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
if ($account->delete(DolibarrApiAccess::$user) < 0) {
throw new RestException(401, 'error when deleting account');
}
return array(
'success' => array(
'code' => 200,
'message' => 'account deleted'
)
);
}
/**
* Validate fields before creating an object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$account = array();
foreach (BankAccounts::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$account[$field] = $data[$field];
}
return $account;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->rowid);
return $object;
}
/**
* Get the list of lines of the account.
*
* @param int $id ID of account
* @return array Array of AccountLine objects
*
* @throws RestException
*
* @url GET {id}/lines
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')"
*/
public function getLines($id, $sqlfilters = '')
{
$list = array();
if (!DolibarrApiAccess::$user->rights->banque->lire) {
throw new RestException(401);
}
$account = new Account($this->db);
$result = $account->fetch($id);
if (!$result) {
throw new RestException(404, 'account not found');
}
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank ";
$sql .= " WHERE fk_account = ".$id;
// Add sql filters
if ($sqlfilters)

File diff suppressed because it is too large Load Diff

View File

@ -189,9 +189,9 @@ if ($result)
print '</td>';
print '</tr>';
$columntitle= "WithdrawalsReceipts";
$columntitle = "WithdrawalsReceipts";
if ($type == 'bank-transfer') {
$columntitle= "BankTransferReceipts";
$columntitle = "BankTransferReceipts";
}
print '<tr class="liste_titre">';

View File

@ -263,11 +263,11 @@ if ($modecompta == 'CREANCES-DETTES')
}
}
$sql.= " AND (p.rowid IN ";
$sql .= " AND (p.rowid IN ";
$sql .= " (SELECT fk_product FROM ".MAIN_DB_PREFIX."categorie_product cp WHERE ";
if ($subcat) $sql .= "cp.fk_categorie IN (". $listofcatsql.")";
else $sql.="cp.fk_categorie = ".$selected_cat;
$sql.= "))";
if ($subcat) $sql .= "cp.fk_categorie IN (".$listofcatsql.")";
else $sql .= "cp.fk_categorie = ".$selected_cat;
$sql .= "))";
}
if ($selected_soc > 0) $sql .= " AND soc.rowid=".$selected_soc;
$sql .= " AND f.entity IN (".getEntity('invoice').")";

View File

@ -745,11 +745,11 @@ if (!is_array($x_coll) || !is_array($x_paye))
}
// Total to pay
print '<tr><td colspan="'.($span+2).'"></td></tr>';
print '<tr><td colspan="'.($span + 2).'"></td></tr>';
$diff = $x_coll_sum - $x_paye_sum;
print '<tr class="liste_total">';
print '<td class="liste_total" colspan="'.($span+1).'">'.$langs->trans("TotalToPay").($q ? ', '.$langs->trans("Quadri").' '.$q : '').'</td>';
print '<td class="liste_total" colspan="'.($span + 1).'">'.$langs->trans("TotalToPay").($q ? ', '.$langs->trans("Quadri").' '.$q : '').'</td>';
print '<td class="liste_total nowrap right"><b>'.price(price2num($diff, 'MT'))."</b></td>\n";
print "</tr>\n";

View File

@ -378,15 +378,15 @@ class Contact extends CommonObject
if ($this->socid > 0) $sql .= " ".$this->db->escape($this->socid).",";
else $sql .= "null,";
$sql .= "'".$this->db->escape($this->lastname)."',";
$sql .= "'".$this->db->escape($this->firstname)."',";
$sql .= " ".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "null").",";
$sql .= "'".$this->db->escape($this->firstname)."',";
$sql .= " ".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "null").",";
$sql .= " ".$this->db->escape($this->priv).",";
$sql .= " 0,";
$sql .= " ".$this->db->escape($this->statut).",";
$sql .= " ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null").",";
$sql .= " ".$this->db->escape($this->entity).",";
$sql .= "'".$this->db->escape($this->ref_ext)."',";
$sql .= " ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
$sql .= " ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null").",";
$sql .= " ".$this->db->escape($this->entity).",";
$sql .= "'".$this->db->escape($this->ref_ext)."',";
$sql .= " ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
$sql .= ")";
dol_syslog(get_class($this)."::create", LOG_DEBUG);

View File

@ -1488,8 +1488,8 @@ if ($action == 'create')
// Line in view mode
if ($action != 'editline' || GETPOST('rowid') != $objp->rowid)
{
$moreparam = '';
if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"';
$moreparam = '';
if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"';
print '<tr class="tdtop oddeven" '.$moreparam.'>';
// Label
if ($objp->fk_product > 0)
@ -1733,8 +1733,8 @@ if ($action == 'create')
if ($object->statut > 0)
{
$moreparam = '';
if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"';
$moreparam = '';
if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"';
print '<tr class="oddeven" '.$moreparam.'>';
print '<td class="tdhrthin" colspan="'.($conf->margin->enabled ? 7 : 6).'"><hr class="opacitymedium tdhrthin"></td>';
print "</tr>\n";
@ -2092,16 +2092,16 @@ if ($action == 'create')
//}
}
if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0)
{
if ($action == 'showclosedlines') print '<div class="inline-block divButAction"><a class="butAction" id="btnhideclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=hideclosedlines">'.$langs->trans("HideClosedServices").'</a></div>';
else print '<div class="inline-block divButAction"><a class="butAction" id="btnshowclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=showclosedlines">'.$langs->trans("ShowClosedServices").'</a></div>';
}
if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0)
{
if ($action == 'showclosedlines') print '<div class="inline-block divButAction"><a class="butAction" id="btnhideclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=hideclosedlines">'.$langs->trans("HideClosedServices").'</a></div>';
else print '<div class="inline-block divButAction"><a class="butAction" id="btnshowclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=showclosedlines">'.$langs->trans("ShowClosedServices").'</a></div>';
}
// Clone
if ($user->rights->contrat->creer) {
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object='.$object->element.'">'.$langs->trans("ToClone").'</a></div>';
}
// Clone
if ($user->rights->contrat->creer) {
print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object='.$object->element.'">'.$langs->trans("ToClone").'</a></div>';
}
// On peut supprimer entite si
// - Droit de creer + mode brouillon (erreur creation)

File diff suppressed because it is too large Load Diff

View File

@ -65,112 +65,112 @@ if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC))
}
} elseif (GETPOST('linkit', 'restricthtml') && !empty($conf->global->MAIN_UPLOAD_DOC))
{
$link = GETPOST('link', 'alpha');
if ($link)
{
if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') {
$link = 'http://'.$link;
}
dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link, '', 0);
}
$link = GETPOST('link', 'alpha');
if ($link)
{
if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') {
$link = 'http://'.$link;
}
dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link, '', 0);
}
}
// Delete file/link
if ($action == 'confirm_deletefile' && $confirm == 'yes')
{
$urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
if (GETPOST('section', 'alpha')) {
// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
} else // For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
$urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
if (GETPOST('section', 'alpha')) {
// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
} else // For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
{
$urlfile = basename($urlfile);
$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
$urlfile = basename($urlfile);
$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
if (!empty($upload_dirold)) $fileold = $upload_dirold."/".$urlfile;
}
$linkid = GETPOST('linkid', 'int');
$linkid = GETPOST('linkid', 'int');
if ($urlfile) {
// delete of a file
$dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
$dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
if ($urlfile) {
// delete of a file
$dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
$dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
$ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
if (!empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
$ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
if (!empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
// If it exists, remove thumb.
$regs = array();
if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs))
{
$photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
{
dol_delete_file($dirthumb.$photo_vignette);
}
// If it exists, remove thumb.
$regs = array();
if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs))
{
$photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
{
dol_delete_file($dirthumb.$photo_vignette);
}
$photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
{
dol_delete_file($dirthumb.$photo_vignette);
}
}
$photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
{
dol_delete_file($dirthumb.$photo_vignette);
}
}
if ($ret) {
setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
} else {
setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
}
} elseif ($linkid) { // delete of external link
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$link = new Link($db);
$link->fetch($linkid);
$res = $link->delete($user);
if ($ret) {
setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
} else {
setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
}
} elseif ($linkid) { // delete of external link
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$link = new Link($db);
$link->fetch($linkid);
$res = $link->delete($user);
$langs->load('link');
if ($res > 0) {
setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
} else {
if (count($link->errors)) {
setEventMessages('', $link->errors, 'errors');
} else {
setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
}
}
}
$langs->load('link');
if ($res > 0) {
setEventMessages($langs->trans("LinkRemoved", $link->label), null, 'mesgs');
} else {
if (count($link->errors)) {
setEventMessages('', $link->errors, 'errors');
} else {
setEventMessages($langs->trans("ErrorFailedToDeleteLink", $link->label), null, 'errors');
}
}
}
if (is_object($object) && $object->id > 0) {
if ($backtopage) {
header('Location: '.$backtopage);
exit;
} else {
$tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
header('Location: '.$tmpurl);
exit;
}
}
if (is_object($object) && $object->id > 0) {
if ($backtopage) {
header('Location: '.$backtopage);
exit;
} else {
$tmpurl = $_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : '');
header('Location: '.$tmpurl);
exit;
}
}
} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
{
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$langs->load('link');
$link = new Link($db);
$f = $link->fetch(GETPOST('linkid', 'int'));
if ($f)
{
$link->url = GETPOST('link', 'alpha');
if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://')
{
$link->url = 'http://'.$link->url;
}
$link->label = GETPOST('label', 'alphanohtml');
$res = $link->update($user);
if (!$res)
{
setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
}
} else {
//error fetching
}
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$langs->load('link');
$link = new Link($db);
$f = $link->fetch(GETPOST('linkid', 'int'));
if ($f)
{
$link->url = GETPOST('link', 'alpha');
if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://')
{
$link->url = 'http://'.$link->url;
}
$link->label = GETPOST('label', 'alphanohtml');
$res = $link->update($user);
if (!$res)
{
setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
}
} else {
//error fetching
}
} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))
{
// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
@ -183,97 +183,97 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes')
// this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
$filenameto = dol_string_nohtmltag($filenameto);
if ($filenamefrom != $filenameto)
{
// Security:
// Disallow file with some extensions. We rename them.
// Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
{
// $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
$publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
if (!preg_match('/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash .= '/';
if ($filenamefrom != $filenameto)
{
// Security:
// Disallow file with some extensions. We rename them.
// Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
{
// $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
$publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
if (!preg_match('/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash .= '/';
if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
$filenameto .= '.noexe';
}
}
if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory
$filenameto .= '.noexe';
}
}
if ($filenamefrom && $filenameto)
{
$srcpath = $upload_dir.'/'.$filenamefrom;
$destpath = $upload_dir.'/'.$filenameto;
if ($filenamefrom && $filenameto)
{
$srcpath = $upload_dir.'/'.$filenamefrom;
$destpath = $upload_dir.'/'.$filenameto;
$reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
$parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
$reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
$reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
$parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
$reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
if (empty($reshook))
{
if (preg_match('/^\./', $filenameto)) {
$langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
} elseif (!file_exists($destpath)) {
$result = dol_move($srcpath, $destpath);
if ($result)
{
// Define if we have to generate thumbs or not
$generatethumbs = 1;
// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
// but when we rename from a tab "Documents", we must regenerate thumbs
if (GETPOST('modulepart') == 'medias') $generatethumbs = 0;
if (empty($reshook))
{
if (preg_match('/^\./', $filenameto)) {
$langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors');
} elseif (!file_exists($destpath)) {
$result = dol_move($srcpath, $destpath);
if ($result)
{
// Define if we have to generate thumbs or not
$generatethumbs = 1;
// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
// but when we rename from a tab "Documents", we must regenerate thumbs
if (GETPOST('modulepart') == 'medias') $generatethumbs = 0;
if ($generatethumbs)
{
if ($object->id)
{
$object->addThumbs($destpath);
}
if ($generatethumbs)
{
if ($object->id)
{
$object->addThumbs($destpath);
}
// TODO Add revert function of addThumbs to remove thumbs with old name
//$object->delThumbs($srcpath);
}
// TODO Add revert function of addThumbs to remove thumbs with old name
//$object->delThumbs($srcpath);
}
setEventMessages($langs->trans("FileRenamed"), null);
} else {
$langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
}
} else {
$langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
}
}
}
}
}
setEventMessages($langs->trans("FileRenamed"), null);
} else {
$langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
}
} else {
$langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now.
setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
}
}
}
}
}
// Update properties in ECM table
if (GETPOST('ecmfileid', 'int') > 0)
{
$shareenabled = GETPOST('shareenabled', 'alpha');
// Update properties in ECM table
if (GETPOST('ecmfileid', 'int') > 0)
{
$shareenabled = GETPOST('shareenabled', 'alpha');
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
$ecmfile = new EcmFiles($db);
$result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
if ($result > 0)
{
if ($shareenabled)
{
if (empty($ecmfile->share))
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$ecmfile->share = getRandomPassword(true);
}
} else {
$ecmfile->share = '';
}
$result = $ecmfile->update($user);
if ($result < 0)
{
setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
}
}
}
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
$ecmfile = new EcmFiles($db);
$result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
if ($result > 0)
{
if ($shareenabled)
{
if (empty($ecmfile->share))
{
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
$ecmfile->share = getRandomPassword(true);
}
} else {
$ecmfile->share = '';
}
$result = $ecmfile->update($user);
if ($result < 0)
{
setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
}
}
}
}

View File

@ -102,7 +102,7 @@ class box_accountancy_last_manual_entries extends ModeleBoxes
$objp = $this->db->fetch_object($result);
$date = $this->db->jdate($objp->date_movement);
$journal = $objp->code_journal;
$label = $objp->label_operation;
$label = $objp->label_operation;
$amount = $objp->amount;
$bookkeepingstatic->id = $objp->id;

View File

@ -32,20 +32,20 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php';
*/
class box_actions extends ModeleBoxes
{
public $boxcode = "lastactions";
public $boximg = "object_action";
public $boxlabel = "BoxLastActions";
public $depends = array("agenda");
public $boxcode = "lastactions";
public $boximg = "object_action";
public $boxlabel = "BoxLastActions";
public $depends = array("agenda");
/**
* @var DoliDB Database handler.
*/
public $db;
* @var DoliDB Database handler.
*/
public $db;
public $enabled = 1;
public $enabled = 1;
public $info_box_head = array();
public $info_box_contents = array();
public $info_box_head = array();
public $info_box_contents = array();
/**
@ -56,20 +56,20 @@ class box_actions extends ModeleBoxes
*/
public function __construct($db, $param)
{
global $conf, $user;
global $conf, $user;
$this->db = $db;
$this->db = $db;
$this->enabled = $conf->agenda->enabled;
$this->enabled = $conf->agenda->enabled;
$this->hidden = !($user->rights->agenda->myactions->read);
$this->hidden = !($user->rights->agenda->myactions->read);
}
/**
* Load data for box to show them later
*
* @param int $max Maximum number of records to load
* @return void
* Load data for box to show them later
*
* @param int $max Maximum number of records to load
* @return void
*/
public function loadBox($max = 5)
{
@ -105,84 +105,84 @@ class box_actions extends ModeleBoxes
dol_syslog(get_class($this)."::loadBox", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result) {
if ($result) {
$now = dol_now();
$delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
$num = $this->db->num_rows($result);
$line = 0;
while ($line < $num) {
while ($line < $num) {
$late = '';
$objp = $this->db->fetch_object($result);
$datelimite = $this->db->jdate($objp->dp);
$actionstatic->id = $objp->id;
$actionstatic->label = $objp->label;
$actionstatic->type_label = $objp->type_label;
$actionstatic->code = $objp->code;
$societestatic->id = $objp->socid;
$societestatic->name = $objp->name;
$societestatic->code_client = $objp->code_client;
$actionstatic->id = $objp->id;
$actionstatic->label = $objp->label;
$actionstatic->type_label = $objp->type_label;
$actionstatic->code = $objp->code;
$societestatic->id = $objp->socid;
$societestatic->name = $objp->name;
$societestatic->code_client = $objp->code_client;
if ($objp->percentage >= 0 && $objp->percentage < 100 && $datelimite < ($now - $delay_warning))
$late = img_warning($langs->trans("Late"));
if ($objp->percentage >= 0 && $objp->percentage < 100 && $datelimite < ($now - $delay_warning))
$late = img_warning($langs->trans("Late"));
//($langs->transnoentities("Action".$objp->code)!=("Action".$objp->code) ? $langs->transnoentities("Action".$objp->code) : $objp->label)
$label = empty($objp->label) ? $objp->type_label : $objp->label;
$this->info_box_contents[$line][0] = array(
'td' => '',
'text' => $actionstatic->getNomUrl(1),
'text2'=> $late,
'asis' => 1
);
$this->info_box_contents[$line][0] = array(
'td' => '',
'text' => $actionstatic->getNomUrl(1),
'text2'=> $late,
'asis' => 1
);
$this->info_box_contents[$line][1] = array(
'td' => '',
'text' => ($societestatic->id > 0 ? $societestatic->getNomUrl(1) : ''),
'asis' => 1
);
$this->info_box_contents[$line][1] = array(
'td' => '',
'text' => ($societestatic->id > 0 ? $societestatic->getNomUrl(1) : ''),
'asis' => 1
);
$this->info_box_contents[$line][2] = array(
'td' => 'class="nowrap left"',
'text' => dol_print_date($datelimite, "dayhour"),
'asis' => 1
);
$this->info_box_contents[$line][2] = array(
'td' => 'class="nowrap left"',
'text' => dol_print_date($datelimite, "dayhour"),
'asis' => 1
);
$this->info_box_contents[$line][3] = array(
'td' => 'class="right"',
'text' => ($objp->percentage >= 0 ? $objp->percentage.'%' : ''),
'asis' => 1
);
$this->info_box_contents[$line][3] = array(
'td' => 'class="right"',
'text' => ($objp->percentage >= 0 ? $objp->percentage.'%' : ''),
'asis' => 1
);
$this->info_box_contents[$line][4] = array(
'td' => 'class="right" width="18"',
'text' => $actionstatic->LibStatut($objp->percentage, 3),
'asis' => 1
);
$this->info_box_contents[$line][4] = array(
'td' => 'class="right" width="18"',
'text' => $actionstatic->LibStatut($objp->percentage, 3),
'asis' => 1
);
$line++;
}
$line++;
}
if ($num == 0)
$this->info_box_contents[$line][0] = array(
'td' => 'class="center opacitymedium"',
'text'=>$langs->trans("NoActionsToDo")
);
if ($num == 0)
$this->info_box_contents[$line][0] = array(
'td' => 'class="center opacitymedium"',
'text'=>$langs->trans("NoActionsToDo")
);
$this->db->free($result);
} else {
$this->info_box_contents[0][0] = array(
'td' => '',
'maxlength'=>500,
'text' => ($this->db->error().' sql='.$sql)
);
}
} else {
$this->info_box_contents[0][0] = array(
'td' => 'class="nohover opacitymedium left"',
'text' => $langs->trans("ReadPermissionNotAllowed")
);
$this->db->free($result);
} else {
$this->info_box_contents[0][0] = array(
'td' => '',
'maxlength'=>500,
'text' => ($this->db->error().' sql='.$sql)
);
}
} else {
$this->info_box_contents[0][0] = array(
'td' => 'class="nohover opacitymedium left"',
'text' => $langs->trans("ReadPermissionNotAllowed")
);
}
}
@ -194,13 +194,13 @@ class box_actions extends ModeleBoxes
* @param int $nooutput No print, only return string
* @return string
*/
public function showBox($head = null, $contents = null, $nooutput = 0)
{
public function showBox($head = null, $contents = null, $nooutput = 0)
{
global $langs, $conf;
$out = parent::showBox($this->info_box_head, $this->info_box_contents, 1);
if (!empty($conf->global->SHOW_DIALOG_HOMEPAGE))
{
if (!empty($conf->global->SHOW_DIALOG_HOMEPAGE))
{
$actioncejour = false;
$contents = $this->info_box_contents;
$nblines = count($contents);

View File

@ -80,93 +80,93 @@ class box_task extends ModeleBoxes
$this->max = $max;
include_once DOL_DOCUMENT_ROOT."/projet/class/task.class.php";
include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
require_once DOL_DOCUMENT_ROOT."/core/lib/project.lib.php";
$projectstatic = new Project($this->db);
require_once DOL_DOCUMENT_ROOT."/core/lib/project.lib.php";
$projectstatic = new Project($this->db);
$taskstatic = new Task($this->db);
$form = new Form($this->db);
$cookie_name = 'DOLUSERCOOKIE_boxfilter_task';
$boxcontent = '';
$socid = $user->socid;
$cookie_name = 'DOLUSERCOOKIE_boxfilter_task';
$boxcontent = '';
$socid = $user->socid;
$textHead = $langs->trans("CurentlyOpenedTasks");
$textHead = $langs->trans("CurentlyOpenedTasks");
$filterValue = 'all';
if (in_array(GETPOST($cookie_name), array('all', 'im_project_contact', 'im_task_contact'))) {
$filterValue = GETPOST($cookie_name);
} elseif (!empty($_COOKIE[$cookie_name])) {
$filterValue = preg_replace('/[^a-z_]/', '', $_COOKIE[$cookie_name]); // Clean cookie from evil data
}
$filterValue = 'all';
if (in_array(GETPOST($cookie_name), array('all', 'im_project_contact', 'im_task_contact'))) {
$filterValue = GETPOST($cookie_name);
} elseif (!empty($_COOKIE[$cookie_name])) {
$filterValue = preg_replace('/[^a-z_]/', '', $_COOKIE[$cookie_name]); // Clean cookie from evil data
}
if ($filterValue == 'im_task_contact') {
$textHead .= ' : '.$langs->trans("WhichIamLinkedTo");
} elseif ($filterValue == 'im_project_contact') {
$textHead .= ' : '.$langs->trans("WhichIamLinkedToProject");
}
if ($filterValue == 'im_task_contact') {
$textHead .= ' : '.$langs->trans("WhichIamLinkedTo");
} elseif ($filterValue == 'im_project_contact') {
$textHead .= ' : '.$langs->trans("WhichIamLinkedToProject");
}
$this->info_box_head = array(
'text' => $textHead,
'limit'=> dol_strlen($textHead),
'sublink'=>'',
'subtext'=>$langs->trans("Filter"),
'subpicto'=>'filter.png',
'subclass'=>'linkobject boxfilter',
'target'=>'none' // Set '' to get target="_blank"
);
'text' => $textHead,
'limit'=> dol_strlen($textHead),
'sublink'=>'',
'subtext'=>$langs->trans("Filter"),
'subpicto'=>'filter.png',
'subclass'=>'linkobject boxfilter',
'target'=>'none' // Set '' to get target="_blank"
);
// list the summary of the orders
if ($user->rights->projet->lire) {
$boxcontent .= '<div id="ancor-idfilter'.$this->boxcode.'" style="display: block; position: absolute; margin-top: -100px"></div>'."\n";
$boxcontent .= '<div id="idfilter'.$this->boxcode.'" class="center" >'."\n";
$boxcontent .= '<form class="flat " method="POST" action="'.$_SERVER["PHP_SELF"].'#ancor-idfilter'.$this->boxcode.'">'."\n";
$boxcontent .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
$selectArray = array('all' => $langs->trans("NoFilter"), 'im_task_contact' => $langs->trans("WhichIamLinkedTo"), 'im_project_contact' => $langs->trans("WhichIamLinkedToProject"));
$boxcontent .= $form->selectArray($cookie_name, $selectArray, $filterValue);
$boxcontent .= '<button type="submit" class="button buttongen">'.$langs->trans("Refresh").'</button>';
$boxcontent .= '</form>'."\n";
$boxcontent .= '</div>'."\n";
if (!empty($conf->use_javascript_ajax)) {
$boxcontent .= '<script type="text/javascript" language="javascript">
$boxcontent .= '<div id="ancor-idfilter'.$this->boxcode.'" style="display: block; position: absolute; margin-top: -100px"></div>'."\n";
$boxcontent .= '<div id="idfilter'.$this->boxcode.'" class="center" >'."\n";
$boxcontent .= '<form class="flat " method="POST" action="'.$_SERVER["PHP_SELF"].'#ancor-idfilter'.$this->boxcode.'">'."\n";
$boxcontent .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
$selectArray = array('all' => $langs->trans("NoFilter"), 'im_task_contact' => $langs->trans("WhichIamLinkedTo"), 'im_project_contact' => $langs->trans("WhichIamLinkedToProject"));
$boxcontent .= $form->selectArray($cookie_name, $selectArray, $filterValue);
$boxcontent .= '<button type="submit" class="button buttongen">'.$langs->trans("Refresh").'</button>';
$boxcontent .= '</form>'."\n";
$boxcontent .= '</div>'."\n";
if (!empty($conf->use_javascript_ajax)) {
$boxcontent .= '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
jQuery("#idsubimg'.$this->boxcode.'").click(function() {
jQuery(".showiffilter'.$this->boxcode.'").toggle();
});
});
</script>';
// set cookie by js
$boxcontent .= '<script>date = new Date(); date.setTime(date.getTime()+(30*86400000)); document.cookie = "'.$cookie_name.'='.$filterValue.'; expires= " + date.toGMTString() + "; path=/ "; </script>';
}
$this->info_box_contents[0][] = array(
'tr'=>'class="nohover showiffilter'.$this->boxcode.' hideobject"',
'td' => 'class="nohover"',
'textnoformat' => $boxcontent,
);
// set cookie by js
$boxcontent .= '<script>date = new Date(); date.setTime(date.getTime()+(30*86400000)); document.cookie = "'.$cookie_name.'='.$filterValue.'; expires= " + date.toGMTString() + "; path=/ "; </script>';
}
$this->info_box_contents[0][] = array(
'tr'=>'class="nohover showiffilter'.$this->boxcode.' hideobject"',
'td' => 'class="nohover"',
'textnoformat' => $boxcontent,
);
// Get list of project id allowed to user (in a string list separated by coma)
$projectsListId = '';
if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
// Get list of project id allowed to user (in a string list separated by coma)
$projectsListId = '';
if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
$sql = "SELECT pt.rowid, pt.ref, pt.fk_projet, pt.fk_task_parent, pt.datec, pt.dateo, pt.datee, pt.datev, pt.label, pt.description, pt.duration_effective, pt.planned_workload, pt.progress";
$sql = "SELECT pt.rowid, pt.ref, pt.fk_projet, pt.fk_task_parent, pt.datec, pt.dateo, pt.datee, pt.datev, pt.label, pt.description, pt.duration_effective, pt.planned_workload, pt.progress";
$sql .= ", p.rowid project_id, p.ref project_ref, p.title project_title";
$sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt";
$sql .= " JOIN ".MAIN_DB_PREFIX."projet as p ON (pt.fk_projet = p.rowid)";
if ($filterValue === 'im_task_contact') {
$sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = ".((int) $user->id).")";
$sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )";
} elseif ($filterValue === 'im_project_contact') {
$sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = ".((int) $user->id).")";
$sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )";
}
if ($filterValue === 'im_task_contact') {
$sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = ".((int) $user->id).")";
$sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )";
} elseif ($filterValue === 'im_project_contact') {
$sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = ".((int) $user->id).")";
$sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )";
}
$sql .= " WHERE ";
$sql .= " pt.entity = ".$conf->entity;
$sql .= " AND p.fk_statut = ".Project::STATUS_VALIDATED;
$sql .= " AND (pt.progress < 100 OR pt.progress IS NULL ) "; // 100% is done and not displayed
$sql .= " AND p.usage_task = 1 ";
if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users
$sql .= " AND p.usage_task = 1 ";
if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users
$sql .= " ORDER BY pt.datee ASC, pt.dateo ASC";
$sql .= $this->db->plimit($max, 0);

View File

@ -31,8 +31,8 @@ include_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php";
*/
class box_validated_projects extends ModeleBoxes
{
public $boxcode="validated_project";
public $boximg="object_projectpub";
public $boxcode = "validated_project";
public $boximg = "object_projectpub";
public $boxlabel;
//var $depends = array("projet");
@ -65,7 +65,7 @@ class box_validated_projects extends ModeleBoxes
$this->db = $db;
$this->boxlabel = "ProjectsWithTask";
$this->hidden = ! ($user->rights->projet->lire);
$this->hidden = !($user->rights->projet->lire);
if ($conf->global->MAIN_FEATURES_LEVEL < 2) $this->enabled = 0;
}
@ -80,11 +80,11 @@ class box_validated_projects extends ModeleBoxes
{
global $conf, $user, $langs;
$this->max=$max;
$this->max = $max;
$totalMnt = 0;
$totalnb = 0;
$totalnbTask=0;
$totalnbTask = 0;
$textHead = $langs->trans("ProjectTasksWithoutTimeSpent");
$this->info_box_head = array('text' => $textHead, 'limit'=> dol_strlen($textHead));
@ -94,27 +94,27 @@ class box_validated_projects extends ModeleBoxes
include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$projectstatic = new Project($this->db);
$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.
// Get list of project id allowed to user (in a string list separated by coma)
$projectsListId='';
if (! $user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
$projectsListId = '';
if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid);
// I tried to solve sql error and performance problem, rewriting sql request but it is not clear what we want.
// Count of tasks without time spent for tasks we are assigned too or
// Count of tasks without time spent for all tasks of projects we are allowed to read (what it does) ?
$sql = "SELECT p.rowid, p.ref, p.fk_soc, p.dateo as startdate,";
$sql.= " COUNT(DISTINCT t.rowid) as tasknumber";
$sql.= " FROM ".MAIN_DB_PREFIX."projet AS p";
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."projet_task AS t ON p.rowid = t.fk_projet";
$sql .= " COUNT(DISTINCT t.rowid) as tasknumber";
$sql .= " FROM ".MAIN_DB_PREFIX."projet AS p";
$sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet_task AS t ON p.rowid = t.fk_projet";
// TODO Replace -1, -2, -3 with ID used for type of contat project_task into llx_c_type_contact. Once done, we can switch widget as stable.
$sql.= " INNER JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = t.rowid AND fk_c_type_contact IN (-1, -2, -3)";
$sql.= " WHERE p.fk_statut = 1"; // Only open projects
$sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = t.rowid AND fk_c_type_contact IN (-1, -2, -3)";
$sql .= " WHERE p.fk_statut = 1"; // Only open projects
if ($projectsListId) $sql .= ' AND p.rowid IN ('.$this->db->sanitize($projectsListId).')'; // Only project we ara allowed
$sql.= " AND t.rowid NOT IN (SELECT fk_task FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_user =".$user->id.")";
$sql.= " GROUP BY p.rowid, p.ref, p.fk_soc, p.dateo";
$sql.= " ORDER BY p.dateo ASC";
$sql .= " AND t.rowid NOT IN (SELECT fk_task FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_user =".$user->id.")";
$sql .= " GROUP BY p.rowid, p.ref, p.fk_soc, p.dateo";
$sql .= " ORDER BY p.dateo ASC";
$result = $this->db->query($sql);
if ($result) {
@ -138,7 +138,7 @@ class box_validated_projects extends ModeleBoxes
);
$i++;
while ($i < min($num+1, $max+1)) {
while ($i < min($num + 1, $max + 1)) {
$objp = $this->db->fetch_object($result);
$projectstatic->id = $objp->rowid;
@ -183,7 +183,7 @@ class box_validated_projects extends ModeleBoxes
);
$i++;
}
}else {
} else {
dol_print_error($this->db);
}
}

View File

@ -458,7 +458,7 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box
{
// Define disabledbyname and disabledbymodule
$disabledbyname = 0;
$disabledbymodule = 0; // TODO Set to 2 if module is not enabled
$disabledbymodule = 0; // TODO Set to 2 if module is not enabled
$module = '';
// Check if widget file is disabled by name

View File

@ -1288,7 +1288,7 @@ abstract class CommonDocGenerator
if (!empty($fields))
{
// Sort extrafields by rank
uasort($fields, function ($a, $b) {
uasort($fields, function($a, $b) {
return ($a->rank > $b->rank) ? 1 : -1;
});

View File

@ -51,12 +51,12 @@ class CProductNature // extends CommonObject
/**
* @var string element
*/
public $element='cproductnbature';
public $element = 'cproductnbature';
/**
* @var string table element
*/
public $table_element='c_product_nature';
public $table_element = 'c_product_nature';
/**
* @var int ID
@ -108,7 +108,7 @@ class CProductNature // extends CommonObject
$sql .= "label,";
$sql .= "active";
$sql .= ") VALUES (";
$sql .= " ".(!isset($this->id) ? 'NULL' : ((int) $this->id)) .",";
$sql .= " ".(!isset($this->id) ? 'NULL' : ((int) $this->id)).",";
$sql .= " ".(!isset($this->code) ? 'NULL' : ((int) $this->code)).",";
$sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape(trim($this->label))."'").",";
$sql .= " ".(!isset($this->active) ? 'NULL' : ((int) $this->active)).",";
@ -151,7 +151,7 @@ class CProductNature // extends CommonObject
$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
$sql_where = array();
if ($id) $sql_where[] = " t.rowid = ".$id;
if ($code>=0) $sql_where[] = " t.code = ". ((int) $code);
if ($code >= 0) $sql_where[] = " t.code = ".((int) $code);
if (count($sql_where) > 0) {
$sql .= ' WHERE '.implode(' AND ', $sql_where);
}

View File

@ -167,9 +167,9 @@ class Cstate // extends CommonObject
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->code_departement = $obj->code_departement; //deprecated
$this->code_departement = $obj->code_departement; //deprecated
$this->code = $obj->code_departement;
$this->nom = $obj->nom; //deprecated
$this->nom = $obj->nom; //deprecated
$this->name = $obj->nom;
$this->active = $obj->active;
}

View File

@ -88,7 +88,7 @@ class DolEditor
// Define some properties
if (in_array($this->tool, array('textarea', 'ckeditor', 'ace')))
{
if ($this->tool == 'ckeditor' && ! dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML.
if ($this->tool == 'ckeditor' && !dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML.
$this->content = dol_nl2br($content);
}
else {

View File

@ -881,13 +881,13 @@ class DolGraph
if ($i > $firstlot) $this->stringtoshow .= ', '."\n";
$color = sprintf("%02x%02x%02x", $this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
$this->stringtoshow .= '{ ';
if (! isset($this->type[$i]) || $this->type[$i] == 'bars') {
if (!isset($this->type[$i]) || $this->type[$i] == 'bars') {
if ($nblot == 3) {
if ($i == $firstlot) $align = 'right';
elseif ($i == $firstlot + 1) $align = 'center';
else $align = 'left';
$this->stringtoshow .= 'bars: { lineWidth: 1, show: true, align: "'.$align.'", barWidth: 0.45 }, ';
} else $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
} else $this->stringtoshow .= 'bars: { lineWidth: 1, show: true, align: "'.($i == $firstlot ? 'center' : 'left').'", barWidth: 0.5 }, ';
}
if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow .= 'lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
$this->stringtoshow .= 'color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';

View File

@ -868,7 +868,7 @@ class dolReceiptPrinter extends Printer
public function initPrinter($printerid)
{
global $conf;
if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector"){
if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") {
$this->connector = new DummyPrintConnector();
$this->printer = new Printer($this->connector, $this->profile);
return;

View File

@ -3577,16 +3577,16 @@ class Form
// phpcs:enable
global $langs;
$num=count($this->cache_transport_mode);
if ($num > 0) return $num; // Cache already loaded
$num = count($this->cache_transport_mode);
if ($num > 0) return $num; // Cache already loaded
dol_syslog(__METHOD__, LOG_DEBUG);
$this->cache_transport_mode = array();
$sql = "SELECT rowid, code, label, active";
$sql.= " FROM ".MAIN_DB_PREFIX."c_transport_mode";
$sql.= " WHERE entity IN (".getEntity('c_transport_mode').")";
$sql .= " FROM ".MAIN_DB_PREFIX."c_transport_mode";
$sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
//if ($active >= 0) $sql.= " AND active = ".$active;
$resql = $this->db->query($sql);
@ -3599,10 +3599,10 @@ class Form
$obj = $this->db->fetch_object($resql);
// If traduction exist, we use it else we take the default label
$label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
$label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
$this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
$this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
$this->cache_transport_mode[$obj->rowid]['label']= $label;
$this->cache_transport_mode[$obj->rowid]['label'] = $label;
$this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
$i++;
}
@ -3632,13 +3632,13 @@ class Form
*/
public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
{
global $langs,$user;
global $langs, $user;
dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
$this->load_cache_transport_mode();
print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
if ($empty) print '<option value="">&nbsp;</option>';
foreach ($this->cache_transport_mode as $id => $arraytypes)
{
@ -3656,15 +3656,15 @@ class Form
if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
elseif ($selected == $id) print ' selected';
print '>';
if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'], $maxlength):$arraytypes['label']);
elseif ($format == 1) $value=$arraytypes['code'];
elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'], $maxlength):$arraytypes['label']);
elseif ($format == 3) $value=$arraytypes['code'];
print $value?$value:'&nbsp;';
if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
elseif ($format == 1) $value = $arraytypes['code'];
elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
elseif ($format == 3) $value = $arraytypes['code'];
print $value ? $value : '&nbsp;';
print '</option>';
}
print '</select>';
if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
/**

View File

@ -204,7 +204,7 @@ class FormMargin
if (!empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON)) // TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better
{
print $langs->trans('ShowMarginInfos').' : ';
$hidemargininfos = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW']); // Clean cookie
$hidemargininfos = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW']); // Clean cookie
print '<span id="showMarginInfos" class="linkobject '.(!empty($hidemargininfos) ? '' : 'hideobject').'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</span>';
print '<span id="hideMarginInfos" class="linkobject '.(!empty($hidemargininfos) ? 'hideobject' : '').'">'.img_picto($langs->trans("Enabled"), 'switch_on').'</span>';

View File

@ -121,7 +121,7 @@ class Menu
foreach ($this->liste as $val)
{
//if (dol_eval($val['enabled'], 1)) $nb++;
if (!empty($val['enabled'])) $nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval()
if (!empty($val['enabled'])) $nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval()
}
return $nb;
}

View File

@ -392,17 +392,17 @@ class SMTPs
$socket_context = stream_context_create($this->_options); // An array of options for stream_context_create()
set_error_handler([$this, 'errorHandler']);
$this->socket = @stream_socket_client(
preg_replace('@tls://@i', '', $this->getHost()) . // Host to 'hit', IP or domain
':' . $this->getPort(), // which Port number to use
$this->errno, // actual system level error
$this->errstr, // and any text that goes with the error
$this->_smtpTimeout, // timeout for reading/writing data over the socket
preg_replace('@tls://@i', '', $this->getHost()).// Host to 'hit', IP or domain
':'.$this->getPort(), // which Port number to use
$this->errno, // actual system level error
$this->errstr, // and any text that goes with the error
$this->_smtpTimeout, // timeout for reading/writing data over the socket
STREAM_CLIENT_CONNECT,
$socket_context // Options for connection
);
} else {
$this->socket = @fsockopen(
preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain
preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain
$this->getPort(), // which Port number to use
$this->errno, // actual system level error
$this->errstr, // and any text that goes with the error
@ -590,7 +590,7 @@ class SMTPs
$host = preg_replace('@ssl://@i', '', $host); // Remove prefix
$host = preg_replace('@tls://@i', '', $host); // Remove prefix
if ($usetls && ! empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) $host = 'tls://'.$host;
if ($usetls && !empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) $host = 'tls://'.$host;
$hosth = $host;

View File

@ -483,7 +483,7 @@ if (!empty($search_measures) && !empty($search_xaxis))
$tmpval = preg_replace('/\-average$/', '', $val);
$sql .= 'AVG('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', ';
} elseif (preg_match('/\-min$/', $val)) {
$tmpval = preg_replace('/\-min$/', '', $val);
$tmpval = preg_replace('/\-min$/', '', $val);
$sql .= 'MIN('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', ';
} elseif (preg_match('/\-max$/', $val)) {
$tmpval = preg_replace('/\-max$/', '', $val);

View File

@ -131,246 +131,246 @@ function versiondolibarrarray()
*/
function run_sql($sqlfile, $silent = 1, $entity = '', $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0)
{
global $db, $conf, $langs, $user;
global $db, $conf, $langs, $user;
dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG);
dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG);
if (!is_numeric($linelengthlimit))
{
dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR);
return -1;
}
if (!is_numeric($linelengthlimit))
{
dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR);
return -1;
}
$ok = 0;
$error = 0;
$i = 0;
$buffer = '';
$arraysql = array();
$ok = 0;
$error = 0;
$i = 0;
$buffer = '';
$arraysql = array();
// Get version of database
$versionarray = $db->getVersionArray();
// Get version of database
$versionarray = $db->getVersionArray();
$fp = fopen($sqlfile, "r");
if ($fp)
{
while (!feof($fp))
{
// Warning fgets with second parameter that is null or 0 hang.
if ($linelengthlimit > 0) $buf = fgets($fp, $linelengthlimit);
else $buf = fgets($fp);
$fp = fopen($sqlfile, "r");
if ($fp)
{
while (!feof($fp))
{
// Warning fgets with second parameter that is null or 0 hang.
if ($linelengthlimit > 0) $buf = fgets($fp, $linelengthlimit);
else $buf = fgets($fp);
// Test if request must be ran only for particular database or version (if yes, we must remove the -- comment)
$reg = array();
if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg))
{
$qualified = 1;
// Test if request must be ran only for particular database or version (if yes, we must remove the -- comment)
$reg = array();
if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg))
{
$qualified = 1;
// restrict on database type
if (!empty($reg[1]))
{
if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) $qualified = 0;
}
// restrict on database type
if (!empty($reg[1]))
{
if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) $qualified = 0;
}
// restrict on version
if ($qualified)
{
if (!empty($reg[2]))
{
if (is_numeric($reg[2])) // This is a version
{
$versionrequest = explode('.', $reg[2]);
//print var_dump($versionrequest);
//print var_dump($versionarray);
if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0)
{
$qualified = 0;
}
} else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE
{
$dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation));
//var_dump($reg[2]);
//var_dump($dbcollation);
if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) $qualified = 0;
//var_dump($qualified);
}
}
}
// restrict on version
if ($qualified)
{
if (!empty($reg[2]))
{
if (is_numeric($reg[2])) // This is a version
{
$versionrequest = explode('.', $reg[2]);
//print var_dump($versionrequest);
//print var_dump($versionarray);
if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0)
{
$qualified = 0;
}
} else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE
{
$dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation));
//var_dump($reg[2]);
//var_dump($dbcollation);
if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) $qualified = 0;
//var_dump($qualified);
}
}
}
if ($qualified)
{
// Version qualified, delete SQL comments
$buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf);
//print "Ligne $i qualifi?e par version: ".$buf.'<br>';
}
}
if ($qualified)
{
// Version qualified, delete SQL comments
$buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf);
//print "Ligne $i qualifi?e par version: ".$buf.'<br>';
}
}
// Add line buf to buffer if not a comment
if ($nocommentremoval || !preg_match('/^\s*--/', $buf))
{
if (empty($nocommentremoval)) $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer
$buffer .= trim($buf);
}
// Add line buf to buffer if not a comment
if ($nocommentremoval || !preg_match('/^\s*--/', $buf))
{
if (empty($nocommentremoval)) $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer
$buffer .= trim($buf);
}
//print $buf.'<br>';exit;
//print $buf.'<br>';exit;
if (preg_match('/;/', $buffer)) // If string contains ';', it's end of a request string, we save it in arraysql.
{
// Found new request
if ($buffer) $arraysql[$i] = $buffer;
$i++;
$buffer = '';
}
}
if (preg_match('/;/', $buffer)) // If string contains ';', it's end of a request string, we save it in arraysql.
{
// Found new request
if ($buffer) $arraysql[$i] = $buffer;
$i++;
$buffer = '';
}
}
if ($buffer) $arraysql[$i] = $buffer;
fclose($fp);
} else {
dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR);
}
if ($buffer) $arraysql[$i] = $buffer;
fclose($fp);
} else {
dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR);
}
// Loop on each request to see if there is a __+MAX_table__ key
$listofmaxrowid = array(); // This is a cache table
foreach ($arraysql as $i => $sql)
{
$newsql = $sql;
// Loop on each request to see if there is a __+MAX_table__ key
$listofmaxrowid = array(); // This is a cache table
foreach ($arraysql as $i => $sql)
{
$newsql = $sql;
// Replace __+MAX_table__ with max of table
while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg))
{
$table = $reg[1];
if (!isset($listofmaxrowid[$table]))
{
//var_dump($db);
$sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table);
$resql = $db->query($sqlgetrowid);
if ($resql)
{
$obj = $db->fetch_object($resql);
$listofmaxrowid[$table] = $obj->max;
if (empty($listofmaxrowid[$table])) $listofmaxrowid[$table] = 0;
} else {
if (!$silent) print '<tr><td class="tdtop" colspan="2">';
if (!$silent) print '<div class="error">'.$langs->trans("Failed to get max rowid for ".$table)."</div></td>";
if (!$silent) print '</tr>';
$error++;
break;
}
}
// Replace __+MAX_llx_table__ with +999
$from = '__+MAX_'.$table.'__';
$to = '+'.$listofmaxrowid[$table];
$newsql = str_replace($from, $to, $newsql);
dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG);
// Replace __+MAX_table__ with max of table
while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg))
{
$table = $reg[1];
if (!isset($listofmaxrowid[$table]))
{
//var_dump($db);
$sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table);
$resql = $db->query($sqlgetrowid);
if ($resql)
{
$obj = $db->fetch_object($resql);
$listofmaxrowid[$table] = $obj->max;
if (empty($listofmaxrowid[$table])) $listofmaxrowid[$table] = 0;
} else {
if (!$silent) print '<tr><td class="tdtop" colspan="2">';
if (!$silent) print '<div class="error">'.$langs->trans("Failed to get max rowid for ".$table)."</div></td>";
if (!$silent) print '</tr>';
$error++;
break;
}
}
// Replace __+MAX_llx_table__ with +999
$from = '__+MAX_'.$table.'__';
$to = '+'.$listofmaxrowid[$table];
$newsql = str_replace($from, $to, $newsql);
dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG);
$arraysql[$i] = $newsql;
}
$arraysql[$i] = $newsql;
}
if ($offsetforchartofaccount > 0)
{
// Replace lines
// 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE', 'CAPIT', '1234', 1400, '...', 1);'
// with
// 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', '1234', 1400 + 200100000, '...', 1);'
// Note: string with 1234 instead of '1234' is also supported
$newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.$offsetforchartofaccount.', \2, \3 + '.$offsetforchartofaccount, $newsql);
$newsql = preg_replace('/([,\s])0 \+ '.$offsetforchartofaccount.'/ims', '\1 0', $newsql);
//var_dump($newsql);
$arraysql[$i] = $newsql;
}
}
if ($offsetforchartofaccount > 0)
{
// Replace lines
// 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE', 'CAPIT', '1234', 1400, '...', 1);'
// with
// 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', '1234', 1400 + 200100000, '...', 1);'
// Note: string with 1234 instead of '1234' is also supported
$newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.$offsetforchartofaccount.', \2, \3 + '.$offsetforchartofaccount, $newsql);
$newsql = preg_replace('/([,\s])0 \+ '.$offsetforchartofaccount.'/ims', '\1 0', $newsql);
//var_dump($newsql);
$arraysql[$i] = $newsql;
}
}
// Loop on each request to execute request
$cursorinsert = 0;
$listofinsertedrowid = array();
foreach ($arraysql as $i => $sql)
{
if ($sql)
{
// Replace the prefix tables
if (MAIN_DB_PREFIX != 'llx_')
{
$sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql);
}
// Loop on each request to execute request
$cursorinsert = 0;
$listofinsertedrowid = array();
foreach ($arraysql as $i => $sql)
{
if ($sql)
{
// Replace the prefix tables
if (MAIN_DB_PREFIX != 'llx_')
{
$sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql);
}
if (!empty($handler)) $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql);
if (!empty($handler)) $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql);
$newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql);
$newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql);
// Add log of request
if (!$silent) print '<tr class="trforrunsql"><td class="tdtop opacitymedium">'.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'</td></tr>\n";
dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG);
// Add log of request
if (!$silent) print '<tr class="trforrunsql"><td class="tdtop opacitymedium">'.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'</td></tr>\n";
dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG);
$sqlmodified = 0;
// Replace for encrypt data
if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg))
{
$num = count($reg[0]);
// Replace for encrypt data
if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg))
{
$num = count($reg[0]);
for ($j = 0; $j < $num; $j++)
{
$from = $reg[0][$j];
$to = $db->encrypt($reg[1][$j], 1);
$newsql = str_replace($from, $to, $newsql);
}
$sqlmodified++;
}
for ($j = 0; $j < $num; $j++)
{
$from = $reg[0][$j];
$to = $db->encrypt($reg[1][$j], 1);
$newsql = str_replace($from, $to, $newsql);
}
$sqlmodified++;
}
// Replace for decrypt data
if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg))
{
$num = count($reg[0]);
// Replace for decrypt data
if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg))
{
$num = count($reg[0]);
for ($j = 0; $j < $num; $j++)
{
$from = $reg[0][$j];
$to = $db->decrypt($reg[1][$j]);
$newsql = str_replace($from, $to, $newsql);
}
$sqlmodified++;
}
for ($j = 0; $j < $num; $j++)
{
$from = $reg[0][$j];
$to = $db->decrypt($reg[1][$j]);
$newsql = str_replace($from, $to, $newsql);
}
$sqlmodified++;
}
// Replace __x__ with rowid of insert nb x
while (preg_match('/__([0-9]+)__/', $newsql, $reg))
{
$cursor = $reg[1];
if (empty($listofinsertedrowid[$cursor]))
{
if (!$silent) print '<tr><td class="tdtop" colspan="2">';
if (!$silent) print '<div class="error">'.$langs->trans("FileIsNotCorrect")."</div></td>";
if (!$silent) print '</tr>';
$error++;
break;
}
$from = '__'.$cursor.'__';
$to = $listofinsertedrowid[$cursor];
$newsql = str_replace($from, $to, $newsql);
$sqlmodified++;
}
// Replace __x__ with rowid of insert nb x
while (preg_match('/__([0-9]+)__/', $newsql, $reg))
{
$cursor = $reg[1];
if (empty($listofinsertedrowid[$cursor]))
{
if (!$silent) print '<tr><td class="tdtop" colspan="2">';
if (!$silent) print '<div class="error">'.$langs->trans("FileIsNotCorrect")."</div></td>";
if (!$silent) print '</tr>';
$error++;
break;
}
$from = '__'.$cursor.'__';
$to = $listofinsertedrowid[$cursor];
$newsql = str_replace($from, $to, $newsql);
$sqlmodified++;
}
if ($sqlmodified) dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG);
if ($sqlmodified) dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG);
$result = $db->query($newsql, $usesavepoint);
if ($result)
{
if (!$silent) print '<!-- Result = OK -->'."\n";
$result = $db->query($newsql, $usesavepoint);
if ($result)
{
if (!$silent) print '<!-- Result = OK -->'."\n";
if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg))
{
$cursorinsert++;
if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg))
{
$cursorinsert++;
// It's an insert
$table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]);
$insertedrowid = $db->last_insert_id($table);
$listofinsertedrowid[$cursorinsert] = $insertedrowid;
dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG);
}
// print '<td class="right">OK</td>';
} else {
$errno = $db->errno();
if (!$silent) print '<!-- Result = '.$errno.' -->'."\n";
// It's an insert
$table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]);
$insertedrowid = $db->last_insert_id($table);
$listofinsertedrowid[$cursorinsert] = $insertedrowid;
dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG);
}
// print '<td class="right">OK</td>';
} else {
$errno = $db->errno();
if (!$silent) print '<!-- Result = '.$errno.' -->'."\n";
// Define list of errors we accept (array $okerrors)
$okerrors = array( // By default
$okerrors = array( // By default
'DB_ERROR_TABLE_ALREADY_EXISTS',
'DB_ERROR_COLUMN_ALREADY_EXISTS',
'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
@ -383,32 +383,32 @@ function run_sql($sqlfile, $silent = 1, $entity = '', $usesavepoint = 1, $handle
'DB_ERROR_CANNOT_CREATE', // Qd contrainte deja existante
'DB_ERROR_CANT_DROP_PRIMARY_KEY',
'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
'DB_ERROR_22P02'
'DB_ERROR_22P02'
);
if ($okerror == 'none') $okerrors = array();
if ($okerror == 'none') $okerrors = array();
// Is it an error we accept
// Is it an error we accept
if (!in_array($errno, $okerrors))
{
if (!$silent) print '<tr><td class="tdtop" colspan="2">';
if (!$silent) print '<div class="error">'.$langs->trans("Error")." ".$db->errno().": ".$newsql."<br>".$db->error()."</div></td>";
if (!$silent) print '</tr>'."\n";
dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."<br>".$db->error(), LOG_ERR);
$error++;
if (!$silent) print '<tr><td class="tdtop" colspan="2">';
if (!$silent) print '<div class="error">'.$langs->trans("Error")." ".$db->errno().": ".$newsql."<br>".$db->error()."</div></td>";
if (!$silent) print '</tr>'."\n";
dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."<br>".$db->error(), LOG_ERR);
$error++;
}
}
}
if (!$silent) print '</tr>'."\n";
}
}
if (!$silent) print '</tr>'."\n";
}
}
if ($error == 0)
{
if (!$silent) {
print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
print '<td class="right">'.$langs->trans("OK");
//if (! empty($conf->use_javascript_ajax)) {
print '<script type="text/javascript" language="javascript">
if ($error == 0)
{
if (!$silent) {
print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
print '<td class="right">'.$langs->trans("OK");
//if (! empty($conf->use_javascript_ajax)) {
print '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
function init_trrunsql()
{
@ -421,21 +421,21 @@ function run_sql($sqlfile, $silent = 1, $entity = '', $usesavepoint = 1, $handle
});
});
</script>';
print ' - <a class="trforrunsqlshowhide" href="#">'.$langs->trans("ShowHideDetails").'</a>';
//}
print '</td></tr>'."\n";
}
$ok = 1;
} else {
if (!$silent) {
print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
print '<td class="right"><font class="error">'.$langs->trans("KO").'</font>';
print '</td></tr>'."\n";
}
$ok = 0;
}
print ' - <a class="trforrunsqlshowhide" href="#">'.$langs->trans("ShowHideDetails").'</a>';
//}
print '</td></tr>'."\n";
}
$ok = 1;
} else {
if (!$silent) {
print '<tr><td>'.$langs->trans("ProcessMigrateScript").'</td>';
print '<td class="right"><font class="error">'.$langs->trans("KO").'</font>';
print '</td></tr>'."\n";
}
$ok = 0;
}
return $ok;
return $ok;
}

View File

@ -59,7 +59,7 @@ function contact_prepare_head(Contact $object)
$tab++;
// Related items
if (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))
if (!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))
{
$head[$tab][0] = DOL_URL_ROOT.'/contact/consumption.php?id='.$object->id;
$head[$tab][1] = $langs->trans("Referers");

View File

@ -45,8 +45,8 @@ function facturefourn_prepare_head($object)
if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
{
$nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id;
$nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id;
$head[$h][1] = $langs->trans('ContactsAddresses');
if ($nbContact > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbContact.'</span>';
$head[$h][2] = 'contact';
@ -75,29 +75,29 @@ function facturefourn_prepare_head($object)
$h++;
}
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice');
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice');
if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
{
$nbNote = 0;
if (!empty($object->note_private)) $nbNote++;
if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
{
$nbNote = 0;
if (!empty($object->note_private)) $nbNote++;
if (!empty($object->note_public)) $nbNote++;
$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id;
$head[$h][1] = $langs->trans('Notes');
$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id;
$head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>';
$head[$h][2] = 'note';
$h++;
}
$head[$h][2] = 'note';
$h++;
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object->ref;
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
$nbLinks = Link::count($db, $object->element, $object->id);
$nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id;
$head[$h][1] = $langs->trans('Documents');
if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';

View File

@ -1129,7 +1129,7 @@ function dol_strtoupper($string, $encoding = "UTF-8")
function dol_ucfirst($string, $encoding = "UTF-8")
{
if (function_exists('mb_substr')) {
return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding) . mb_substr($string, 1, null, $encoding);
return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
} else {
return ucfirst($string);
}

View File

@ -1440,7 +1440,7 @@ function print_left_eldy_menu($db, $menu_array_before, $menu_array_after, &$tabM
}
// Intracomm report
if (! empty($conf->intracommreport->enabled))
if (!empty($conf->intracommreport->enabled))
{
$newmenu->add("/intracommreport/list.php?leftmenu=intracommreport", $langs->trans("MenuIntracommReport"), 0, $user->rights->intracommreport->read, '', $mainmenu, 'intracommreport', 1);
if ($usemenuhider || empty($leftmenu) || preg_match('/intracommreport/', $leftmenu)) {

View File

@ -422,8 +422,8 @@ class pdf_storm extends ModelePDFDeliveryOrder
$pdf->SetTextColor(0, 0, 0);
// Define size of image if we need it
$imglinesize=array();
if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
$imglinesize = array();
if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
$pdf->setTopMargin($tab_top_newpage);

View File

@ -52,7 +52,7 @@ class modIntracommreport extends DolibarrModules
// Possible values for version are: 'development', 'experimental', 'dolibarr' or 'dolibarr_deprecated' or version
$this->version = 'development';
$this->const_name = 'MAIN_MODULE_' . strtoupper($this->name);
$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
$this->picto = 'intracommreport';
// Data directories to create when module is enabled
@ -86,12 +86,12 @@ class modIntracommreport extends DolibarrModules
$this->boxes = array();
// Dictionaries
if (! isset($conf->intracommreport->enabled))
if (!isset($conf->intracommreport->enabled))
{
$conf->intracommreport=new stdClass();
$conf->intracommreport->enabled=0;
$conf->intracommreport = new stdClass();
$conf->intracommreport->enabled = 0;
}
$this->dictionaries=array();
$this->dictionaries = array();
// Permissions
$this->rights = array();

View File

@ -257,7 +257,7 @@ if (empty($backtourl))
elseif (in_array($modulepart, array('mrp'))) $backtourl = DOL_URL_ROOT."/mrp/mo_document.php?id=".$id.'&file='.urldecode($file);
elseif (in_array($modulepart, array('medias'))) {
$section_dir = dirname($file);
if (! preg_match('/\/$/', $section_dir)) $section_dir.='/';
if (!preg_match('/\/$/', $section_dir)) $section_dir .= '/';
$backtourl = DOL_URL_ROOT."/website/index.php?action=file_manager&website=".$website.'&section_dir='.urlencode($section_dir);
}
// Generic case that should work for everybody else

View File

@ -82,7 +82,7 @@ $tmpDir = $conf->dav->multidir_output[$entity]; // We need root dir, not a dir t
// Authentication callback function
$authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function ($username, $password) {
$authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function($username, $password) {
global $user;
global $conf;
global $dolibarr_main_authentication, $dolibarr_auto_user;

View File

@ -4,7 +4,7 @@
* Simple autoloader, so we don't need Composer just for this.
*/
spl_autoload_register(function ($class) {
spl_autoload_register(function($class) {
if (preg_match('/^DebugBar/', $class)) {
$file = DOL_DOCUMENT_ROOT.'/includes/maximebf/debugbar/src/'.str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php';
//var_dump($class.' - '.file_exists($file).' - '.$file);

View File

@ -304,62 +304,62 @@ class Donations extends DolibarrApi
$result = $this->don->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already validated');
throw new RestException(304, 'Error nothing done. May be object is already validated');
}
if ($result < 0) {
throw new RestException(500, 'Error when validating Order: '.$this->don->error);
throw new RestException(500, 'Error when validating Order: '.$this->don->error);
}
$result = $this->don->fetch($id);
if (!$result) {
throw new RestException(404, 'Order not found');
}
$result = $this->don->fetch($id);
if (!$result) {
throw new RestException(404, 'Order not found');
}
if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->don->fetchObjectLinked();
$this->don->fetchObjectLinked();
return $this->_cleanObjectDatas($this->don);
}
return $this->_cleanObjectDatas($this->don);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->note);
unset($object->address);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->note);
unset($object->address);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$don = array();
foreach (Orders::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, $field." field missing");
$don[$field] = $data[$field];
}
return $don;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$don = array();
foreach (Orders::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, $field." field missing");
$don[$field] = $data[$field];
}
return $don;
}
}

View File

@ -606,60 +606,60 @@ class Shipments extends DolibarrApi
}
*/
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->thirdparty); // id already returned
unset($object->thirdparty); // id already returned
unset($object->note);
unset($object->address);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->note);
unset($object->address);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
if (!empty($object->lines) && is_array($object->lines))
{
foreach ($object->lines as $line)
{
unset($line->tva_tx);
unset($line->vat_src_code);
unset($line->total_ht);
unset($line->total_ttc);
unset($line->total_tva);
unset($line->total_localtax1);
unset($line->total_localtax2);
unset($line->remise_percent);
}
}
if (!empty($object->lines) && is_array($object->lines))
{
foreach ($object->lines as $line)
{
unset($line->tva_tx);
unset($line->vat_src_code);
unset($line->total_ht);
unset($line->total_ttc);
unset($line->total_tva);
unset($line->total_localtax1);
unset($line->total_localtax2);
unset($line->remise_percent);
}
}
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$shipment = array();
foreach (Shipments::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$shipment[$field] = $data[$field];
}
return $shipment;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$shipment = array();
foreach (Shipments::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$shipment[$field] = $data[$field];
}
return $shipment;
}
}

View File

@ -30,171 +30,171 @@
class ExpenseReports extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'fk_user_author'
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'fk_user_author'
);
/**
* @var ExpenseReport $expensereport {@type ExpenseReport}
*/
public $expensereport;
/**
* @var ExpenseReport $expensereport {@type ExpenseReport}
*/
public $expensereport;
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->expensereport = new ExpenseReport($this->db);
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->expensereport = new ExpenseReport($this->db);
}
/**
* Get properties of a Expense Report object
*
* Return an array with Expense Report informations
*
* @param int $id ID of Expense Report
* @return array|mixed Data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->expensereport->lire) {
throw new RestException(401);
}
/**
* Get properties of a Expense Report object
*
* Return an array with Expense Report informations
*
* @param int $id ID of Expense Report
* @return array|mixed Data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->expensereport->lire) {
throw new RestException(401);
}
$result = $this->expensereport->fetch($id);
if (!$result) {
throw new RestException(404, 'Expense report not found');
}
$result = $this->expensereport->fetch($id);
if (!$result) {
throw new RestException(404, 'Expense report not found');
}
if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->expensereport->fetchObjectLinked();
return $this->_cleanObjectDatas($this->expensereport);
}
$this->expensereport->fetchObjectLinked();
return $this->_cleanObjectDatas($this->expensereport);
}
/**
* List Expense Reports
*
* Get a list of Expense Reports
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $user_ids User ids filter field. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i}
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of Expense Report objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '')
{
global $db, $conf;
/**
* List Expense Reports
*
* Get a list of Expense Reports
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $user_ids User ids filter field. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i}
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of Expense Report objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
// case of external user, $societe param is ignored and replaced by user's socid
//$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe;
// case of external user, $societe param is ignored and replaced by user's socid
//$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe;
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t";
$sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')';
if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")";
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t";
$sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')';
if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")";
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
$result = $this->db->query($sql);
if ($result)
{
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
if ($result)
{
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0;
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$expensereport_static = new ExpenseReport($this->db);
if ($expensereport_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($expensereport_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No Expense Report found');
}
return $obj_ret;
}
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$expensereport_static = new ExpenseReport($this->db);
if ($expensereport_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($expensereport_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No Expense Report found');
}
return $obj_ret;
}
/**
* Create Expense Report object
*
* @param array $request_data Request data
* @return int ID of Expense Report
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->expensereport->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validate($request_data);
/**
* Create Expense Report object
*
* @param array $request_data Request data
* @return int ID of Expense Report
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->expensereport->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach ($request_data as $field => $value) {
$this->expensereport->$field = $value;
}
/*if (isset($request_data["lines"])) {
foreach ($request_data as $field => $value) {
$this->expensereport->$field = $value;
}
/*if (isset($request_data["lines"])) {
$lines = array();
foreach ($request_data["lines"] as $line) {
array_push($lines, (object) $line);
}
$this->expensereport->lines = $lines;
}*/
if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors));
}
if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors));
}
return $this->expensereport->id;
}
return $this->expensereport->id;
}
/**
* Get lines of an Expense Report
*
* @param int $id Id of Expense Report
*
* @url GET {id}/lines
*
* @return int
*/
/*
/**
* Get lines of an Expense Report
*
* @param int $id Id of Expense Report
*
* @url GET {id}/lines
*
* @return int
*/
/*
public function getLines($id)
{
if(! DolibarrApiAccess::$user->rights->expensereport->lire) {
@ -490,75 +490,75 @@ class ExpenseReports extends DolibarrApi
);
}*/
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->fk_statut);
unset($object->statut);
unset($object->user);
unset($object->thirdparty);
unset($object->fk_statut);
unset($object->statut);
unset($object->user);
unset($object->thirdparty);
unset($object->cond_reglement);
unset($object->shipping_method_id);
unset($object->cond_reglement);
unset($object->shipping_method_id);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->code_paiement);
unset($object->code_statut);
unset($object->fk_c_paiement);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->code_paiement);
unset($object->code_statut);
unset($object->fk_c_paiement);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->mode_reglement_id);
unset($object->cond_reglement_id);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->cond_reglement_id);
unset($object->contact);
unset($object->contact_id);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->cond_reglement_id);
unset($object->contact);
unset($object->contact_id);
unset($object->state);
unset($object->state_id);
unset($object->state_code);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->state);
unset($object->state_id);
unset($object->state_code);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->note); // We already use note_public and note_pricate
unset($object->note); // We already use note_public and note_pricate
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$expensereport = array();
foreach (ExpenseReports::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$expensereport[$field] = $data[$field];
}
return $expensereport;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$expensereport = array();
foreach (ExpenseReports::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$expensereport[$field] = $data[$field];
}
return $expensereport;
}
}

View File

@ -239,218 +239,218 @@ class Interventions extends DolibarrApi
}
*/
/**
* Add a line to given intervention
*
* @param int $id Id of intervention to update
* @param array $request_data Request data
*
* @url POST {id}/lines
*
* @return int
*/
public function postLine($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validateLine($request_data);
/**
* Add a line to given intervention
*
* @param int $id Id of intervention to update
* @param array $request_data Request data
*
* @url POST {id}/lines
*
* @return int
*/
public function postLine($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validateLine($request_data);
foreach ($request_data as $field => $value) {
$this->fichinter->$field = $value;
}
foreach ($request_data as $field => $value) {
$this->fichinter->$field = $value;
}
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$updateRes = $this->fichinter->addLine(
DolibarrApiAccess::$user,
$id,
$this->fichinter->description,
$this->fichinter->date,
$this->fichinter->duree
);
$updateRes = $this->fichinter->addLine(
DolibarrApiAccess::$user,
$id,
$this->fichinter->description,
$this->fichinter->date,
$this->fichinter->duree
);
if ($updateRes > 0) {
return $updateRes;
} else {
throw new RestException(400, $this->fichinter->error);
}
}
if ($updateRes > 0) {
return $updateRes;
} else {
throw new RestException(400, $this->fichinter->error);
}
}
/**
* Delete order
*
* @param int $id Order ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) {
throw new RestException(401);
}
$result = $this->fichinter->fetch($id);
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
/**
* Delete order
*
* @param int $id Order ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) {
throw new RestException(401);
}
$result = $this->fichinter->fetch($id);
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$this->fichinter->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error);
}
if (!$this->fichinter->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Intervention deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Intervention deleted'
)
);
}
/**
* Validate an intervention
*
* If you get a bad value for param notrigger check, provide this in body
* {
* "notrigger": 0
* }
*
* @param int $id Intervention ID
* @param int $notrigger 1=Does not execute triggers, 0= execute triggers
*
* @url POST {id}/validate
*
* @return array
*/
public function validate($id, $notrigger = 0)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
throw new RestException(401, "Insuffisant rights");
}
$result = $this->fichinter->fetch($id);
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
/**
* Validate an intervention
*
* If you get a bad value for param notrigger check, provide this in body
* {
* "notrigger": 0
* }
*
* @param int $id Intervention ID
* @param int $notrigger 1=Does not execute triggers, 0= execute triggers
*
* @url POST {id}/validate
*
* @return array
*/
public function validate($id, $notrigger = 0)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
throw new RestException(401, "Insuffisant rights");
}
$result = $this->fichinter->fetch($id);
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger);
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already validated');
}
if ($result < 0) {
throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error);
}
$result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger);
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already validated');
}
if ($result < 0) {
throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error);
}
$this->fichinter->fetchObjectLinked();
$this->fichinter->fetchObjectLinked();
return $this->_cleanObjectDatas($this->fichinter);
}
return $this->_cleanObjectDatas($this->fichinter);
}
/**
* Close an intervention
*
* @param int $id Intervention ID
*
* @url POST {id}/close
*
* @return array
*/
public function closeFichinter($id)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->creer)
{
throw new RestException(401, "Insuffisant rights");
}
$result = $this->fichinter->fetch($id);
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
/**
* Close an intervention
*
* @param int $id Intervention ID
*
* @url POST {id}/close
*
* @return array
*/
public function closeFichinter($id)
{
if (!DolibarrApiAccess::$user->rights->ficheinter->creer)
{
throw new RestException(401, "Insuffisant rights");
}
$result = $this->fichinter->fetch($id);
if (!$result) {
throw new RestException(404, 'Intervention not found');
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$result = $this->fichinter->setStatut(3);
$result = $this->fichinter->setStatut(3);
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already closed');
}
if ($result < 0) {
throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error);
}
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already closed');
}
if ($result < 0) {
throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error);
}
$this->fichinter->fetchObjectLinked();
$this->fichinter->fetchObjectLinked();
return $this->_cleanObjectDatas($this->fichinter);
}
return $this->_cleanObjectDatas($this->fichinter);
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$fichinter = array();
foreach (Interventions::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$fichinter[$field] = $data[$field];
}
return $fichinter;
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$fichinter = array();
foreach (Interventions::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$fichinter[$field] = $data[$field];
}
return $fichinter;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->statuts_short);
unset($object->statuts_logo);
unset($object->statuts);
unset($object->statuts_short);
unset($object->statuts_logo);
unset($object->statuts);
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validateLine($data)
{
$fichinter = array();
foreach (Interventions::$FIELDSLINE as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$fichinter[$field] = $data[$field];
}
return $fichinter;
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validateLine($data)
{
$fichinter = array();
foreach (Interventions::$FIELDSLINE as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$fichinter[$field] = $data[$field];
}
return $fichinter;
}
}

View File

@ -677,8 +677,8 @@ class SupplierInvoices extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -339,8 +339,8 @@ class SupplierOrders extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -626,13 +626,13 @@ class ProductFournisseur extends Product
$prodfourn->fourn_remise_percent = $record["remise_percent"];
$prodfourn->fourn_remise = $record["remise"];
$prodfourn->fourn_unitprice = $record["unitprice"];
$prodfourn->fourn_charges = $record["charges"]; // deprecated
$prodfourn->fourn_charges = $record["charges"]; // deprecated
$prodfourn->fourn_tva_tx = $record["tva_tx"];
$prodfourn->fourn_id = $record["fourn_id"];
$prodfourn->fourn_id = $record["fourn_id"];
$prodfourn->fourn_name = $record["supplier_name"];
$prodfourn->fk_availability = $record["fk_availability"];
$prodfourn->delivery_time_days = $record["delivery_time_days"];
$prodfourn->id = $prodid;
$prodfourn->delivery_time_days = $record["delivery_time_days"];
$prodfourn->id = $prodid;
$prodfourn->fourn_tva_npr = $record["info_bits"];
$prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
$prodfourn->supplier_reputation = $record["supplier_reputation"];

View File

@ -317,39 +317,39 @@ if (empty($reshook))
// payments conditions
if ($action == 'setconditions' && $usercancreate)
{
$object->fetch($id);
$object->cond_reglement_code = 0; // To clean property
$object->cond_reglement_id = 0; // To clean property
$object->fetch($id);
$object->cond_reglement_code = 0; // To clean property
$object->cond_reglement_id = 0; // To clean property
$error = 0;
$error = 0;
$db->begin();
$db->begin();
if (!$error) {
$result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
if ($result < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
}
if (!$error) {
$result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
if ($result < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
}
if (!$error) {
$old_date_echeance = $object->date_echeance;
$new_date_echeance = $object->calculate_date_lim_reglement();
if ($new_date_echeance > $old_date_echeance) $object->date_echeance = $new_date_echeance;
if ($object->date_echeance < $object->date) $object->date_echeance = $object->date;
$result = $object->update($user);
if ($result < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
}
if (!$error) {
$old_date_echeance = $object->date_echeance;
$new_date_echeance = $object->calculate_date_lim_reglement();
if ($new_date_echeance > $old_date_echeance) $object->date_echeance = $new_date_echeance;
if ($object->date_echeance < $object->date) $object->date_echeance = $object->date;
$result = $object->update($user);
if ($result < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
}
if ($error) {
$db->rollback();
} else {
$db->commit();
}
if ($error) {
$db->rollback();
} else {
$db->commit();
}
}
// Set incoterm
@ -379,11 +379,11 @@ if (empty($reshook))
$result = $object->setBankAccount(GETPOST('fk_account', 'int'));
}
// transport mode
if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer)
{
$result = $object->setTransportMode(GETPOST('transport_mode_id', 'int'));
}
// transport mode
if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer)
{
$result = $object->setTransportMode(GETPOST('transport_mode_id', 'int'));
}
// Set label
elseif ($action == 'setlabel' && $usercancreate)
@ -2096,14 +2096,14 @@ if ($action == 'create')
print '</td></tr>';
}
// Intracomm report
if (!empty($conf->intracommreport->enabled))
{
$langs->loadLangs(array("intracommreport"));
print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>';
$form->selectModeTransport(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id');
print '</td></tr>';
}
// Intracomm report
if (!empty($conf->intracommreport->enabled))
{
$langs->loadLangs(array("intracommreport"));
print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>';
$form->selectModeTransport(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id');
print '</td></tr>';
}
// Public note
print '<tr><td>'.$langs->trans('NotePublic').'</td>';

View File

@ -2115,8 +2115,8 @@ class Holiday extends CommonObject
if (empty($user->rights->expensereport->read_all))
{
$userchildids = $user->getAllChildIds(1);
$sql.= " AND (h.fk_user IN (".join(',', $userchildids).")";
$sql.= " OR h.fk_validator IN (".join(',', $userchildids)."))";
$sql .= " AND (h.fk_user IN (".join(',', $userchildids).")";
$sql .= " OR h.fk_validator IN (".join(',', $userchildids)."))";
}
$resql = $this->db->query($sql);

View File

@ -104,106 +104,106 @@ $actiondone = 0;
// Action to launch the migrate script
if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09')))
{
$actiondone = 1;
$actiondone = 1;
print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '.$langs->trans("DatabaseMigration").'</h3>';
print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '.$langs->trans("DatabaseMigration").'</h3>';
print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
$error = 0;
print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
$error = 0;
// If password is encoded, we decode it
if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
{
require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
if (preg_match('/crypted:/i', $dolibarr_main_db_pass))
{
$dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
$dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
$dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted
} else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
}
// If password is encoded, we decode it
if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
{
require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
if (preg_match('/crypted:/i', $dolibarr_main_db_pass))
{
$dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
$dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
$dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted
} else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
}
// $conf is already instancied inside inc.php
$conf->db->type = $dolibarr_main_db_type;
$conf->db->host = $dolibarr_main_db_host;
$conf->db->port = $dolibarr_main_db_port;
$conf->db->name = $dolibarr_main_db_name;
$conf->db->user = $dolibarr_main_db_user;
$conf->db->pass = $dolibarr_main_db_pass;
// $conf is already instancied inside inc.php
$conf->db->type = $dolibarr_main_db_type;
$conf->db->host = $dolibarr_main_db_host;
$conf->db->port = $dolibarr_main_db_port;
$conf->db->name = $dolibarr_main_db_name;
$conf->db->user = $dolibarr_main_db_user;
$conf->db->pass = $dolibarr_main_db_pass;
// Load type and crypt key
if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0;
$conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = '';
$conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
// Load type and crypt key
if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0;
$conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = '';
$conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
$db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port);
$db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port);
// Create the global $hookmanager object
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($db);
// Create the global $hookmanager object
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($db);
if ($db->connected)
{
print '<tr><td class="nowrap">';
print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.'</td><td class="right">'.$langs->trans("OK").'</td></tr>'."\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerConnection").": $dolibarr_main_db_host ".$langs->transnoentities("OK"));
$ok = 1;
} else {
print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right">'.$langs->transnoentities("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
$ok = 0;
}
if ($db->connected)
{
print '<tr><td class="nowrap">';
print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.'</td><td class="right">'.$langs->trans("OK").'</td></tr>'."\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerConnection").": $dolibarr_main_db_host ".$langs->transnoentities("OK"));
$ok = 1;
} else {
print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right">'.$langs->transnoentities("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
$ok = 0;
}
if ($ok)
{
if ($db->database_selected)
{
print '<tr><td class="nowrap">';
print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.'</td><td class="right">'.$langs->trans("OK")."</td></tr>\n";
dolibarr_install_syslog("upgrade: Database connection successful: ".$dolibarr_main_db_name);
$ok = 1;
} else {
print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right">'.$langs->trans("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
$ok = 0;
}
}
if ($ok)
{
if ($db->database_selected)
{
print '<tr><td class="nowrap">';
print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.'</td><td class="right">'.$langs->trans("OK")."</td></tr>\n";
dolibarr_install_syslog("upgrade: Database connection successful: ".$dolibarr_main_db_name);
$ok = 1;
} else {
print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right">'.$langs->trans("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
$ok = 0;
}
}
// Affiche version
if ($ok)
{
$version = $db->getVersion();
$versionarray = $db->getVersionArray();
print '<tr><td>'.$langs->trans("ServerVersion").'</td>';
print '<td class="right">'.$version.'</td></tr>';
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerVersion").": ".$version);
if ($db->type == 'mysqli' && function_exists('mysqli_get_charset'))
{
$tmparray = $db->db->get_charset();
print '<tr><td>'.$langs->trans("ClientCharset").'</td>';
print '<td class="right">'.$tmparray->charset.'</td></tr>';
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCharset").": ".$tmparray->charset);
print '<tr><td>'.$langs->trans("ClientSortingCharset").'</td>';
print '<td class="right">'.$tmparray->collation.'</td></tr>';
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCollation").": ".$tmparray->collation);
}
// Affiche version
if ($ok)
{
$version = $db->getVersion();
$versionarray = $db->getVersionArray();
print '<tr><td>'.$langs->trans("ServerVersion").'</td>';
print '<td class="right">'.$version.'</td></tr>';
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerVersion").": ".$version);
if ($db->type == 'mysqli' && function_exists('mysqli_get_charset'))
{
$tmparray = $db->db->get_charset();
print '<tr><td>'.$langs->trans("ClientCharset").'</td>';
print '<td class="right">'.$tmparray->charset.'</td></tr>';
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCharset").": ".$tmparray->charset);
print '<tr><td>'.$langs->trans("ClientSortingCharset").'</td>';
print '<td class="right">'.$tmparray->collation.'</td></tr>';
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCollation").": ".$tmparray->collation);
}
// Test database version requirement
$versionmindb = explode('.', $db::VERSIONMIN);
//print join('.',$versionarray).' - '.join('.',$versionmindb);
if (count($versionmindb) && count($versionarray)
&& versioncompare($versionarray, $versionmindb) < 0)
{
// Warning: database version too low.
print "<tr><td>".$langs->trans("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))."</td><td class=\"right\">".$langs->trans("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb)));
$ok = 0;
}
// Test database version requirement
$versionmindb = explode('.', $db::VERSIONMIN);
//print join('.',$versionarray).' - '.join('.',$versionmindb);
if (count($versionmindb) && count($versionarray)
&& versioncompare($versionarray, $versionmindb) < 0)
{
// Warning: database version too low.
print "<tr><td>".$langs->trans("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))."</td><td class=\"right\">".$langs->trans("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb)));
$ok = 0;
}
// Test database version is not forbidden for migration
if (empty($ignoredbversion))
{
// Test database version is not forbidden for migration
if (empty($ignoredbversion))
{
$dbversion_disallowed = array(
array('type'=>'mysql', 'version'=>array(5, 5, 40)),
array('type'=>'mysqli', 'version'=>array(5, 5, 40)) //,
@ -217,196 +217,196 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ
}
foreach ($dbversion_disallowed as $dbversion_totest)
{
//print $db->type.' - '.join('.',$versionarray).' - '.versioncompare($dbversion_totest['version'],$versionarray)."<br>\n";
if ($dbversion_totest['type'] == $db->type
&& (versioncompare($dbversion_totest['version'], $versionarray) == 0 || versioncompare($dbversion_totest['version'], $versionarray) <= -4 || versioncompare($dbversion_totest['version'], $versionarray) >= 4)
)
{
// Warning: database version too low.
print '<tr><td><div class="warning">'.$langs->trans("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)."</div></td><td class=\"right\">".$langs->trans("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion));
$ok = 0;
break;
}
//print $db->type.' - '.join('.',$versionarray).' - '.versioncompare($dbversion_totest['version'],$versionarray)."<br>\n";
if ($dbversion_totest['type'] == $db->type
&& (versioncompare($dbversion_totest['version'], $versionarray) == 0 || versioncompare($dbversion_totest['version'], $versionarray) <= -4 || versioncompare($dbversion_totest['version'], $versionarray) >= 4)
)
{
// Warning: database version too low.
print '<tr><td><div class="warning">'.$langs->trans("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)."</div></td><td class=\"right\">".$langs->trans("Error")."</td></tr>\n";
dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion));
$ok = 0;
break;
}
}
}
}
}
}
// Force l'affichage de la progression
if ($ok)
{
print '<tr><td colspan="2">'.$langs->trans("PleaseBePatient").'</td></tr>';
flush();
}
// Force l'affichage de la progression
if ($ok)
{
print '<tr><td colspan="2">'.$langs->trans("PleaseBePatient").'</td></tr>';
flush();
}
/*
* Remove deprecated indexes and constraints for Mysql
*/
if ($ok && preg_match('/mysql/', $db->type))
{
$versioncommande = array(4, 0, 0);
if (count($versioncommande) && count($versionarray)
&& versioncompare($versioncommande, $versionarray) <= 0) // Si mysql >= 4.0
{
dolibarr_install_syslog("Clean database from bad named constraints");
if ($ok && preg_match('/mysql/', $db->type))
{
$versioncommande = array(4, 0, 0);
if (count($versioncommande) && count($versionarray)
&& versioncompare($versioncommande, $versionarray) <= 0) // Si mysql >= 4.0
{
dolibarr_install_syslog("Clean database from bad named constraints");
// Suppression vieilles contraintes sans noms et en doubles
// Les contraintes indesirables ont un nom qui commence par 0_ ou se termine par ibfk_999
$listtables = array(
MAIN_DB_PREFIX.'adherent_options',
MAIN_DB_PREFIX.'bank_class',
MAIN_DB_PREFIX.'c_ecotaxe',
MAIN_DB_PREFIX.'c_methode_commande_fournisseur', // table renamed
MAIN_DB_PREFIX.'c_input_method'
);
// Suppression vieilles contraintes sans noms et en doubles
// Les contraintes indesirables ont un nom qui commence par 0_ ou se termine par ibfk_999
$listtables = array(
MAIN_DB_PREFIX.'adherent_options',
MAIN_DB_PREFIX.'bank_class',
MAIN_DB_PREFIX.'c_ecotaxe',
MAIN_DB_PREFIX.'c_methode_commande_fournisseur', // table renamed
MAIN_DB_PREFIX.'c_input_method'
);
$listtables = $db->DDLListTables($conf->db->name, '');
foreach ($listtables as $val)
{
// Database prefix filter
if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val))
{
//print "x".$val."<br>";
$sql = "SHOW CREATE TABLE ".$val;
$resql = $db->query($sql);
if ($resql)
{
$values = $db->fetch_array($resql);
$i = 0;
$createsql = $values[1];
while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100)
{
$sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1];
$resqldrop = $db->query($sqldrop);
if ($resqldrop)
{
print '<tr><td colspan="2">'.$sqldrop.";</td></tr>\n";
}
$createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql);
$i++;
}
$db->free($resql);
} else {
if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE')
{
print '<tr><td colspan="2"><span class="error">'.$sql.' : '.$db->lasterror()."</font></td></tr>\n";
}
}
}
}
}
}
$listtables = $db->DDLListTables($conf->db->name, '');
foreach ($listtables as $val)
{
// Database prefix filter
if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val))
{
//print "x".$val."<br>";
$sql = "SHOW CREATE TABLE ".$val;
$resql = $db->query($sql);
if ($resql)
{
$values = $db->fetch_array($resql);
$i = 0;
$createsql = $values[1];
while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100)
{
$sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1];
$resqldrop = $db->query($sqldrop);
if ($resqldrop)
{
print '<tr><td colspan="2">'.$sqldrop.";</td></tr>\n";
}
$createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql);
$i++;
}
$db->free($resql);
} else {
if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE')
{
print '<tr><td colspan="2"><span class="error">'.$sql.' : '.$db->lasterror()."</font></td></tr>\n";
}
}
}
}
}
}
/*
/*
* Load sql files
*/
if ($ok)
{
$dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver
if ($ok)
{
$dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver
if (!empty($dirmodule)) $dir = dol_buildpath('/'.$dirmodule.'/sql/', 0);
dolibarr_install_syslog("Scan sql files for migration files in ".$dir);
// Clean last part to exclude minor version x.y.z -> x.y
$newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.0', $versionfrom);
$newversionto = preg_replace('/(\.[0-9]+)$/i', '.0', $versionto);
$newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.0', $versionfrom);
$newversionto = preg_replace('/(\.[0-9]+)$/i', '.0', $versionto);
$filelist = array();
$i = 0;
$ok = 0;
$from = '^'.$newversionfrom;
$to = $newversionto.'\.sql$';
$filelist = array();
$i = 0;
$ok = 0;
$from = '^'.$newversionfrom;
$to = $newversionto.'\.sql$';
// Get files list
$filesindir = array();
$handle = opendir($dir);
if (is_resource($handle))
{
while (($file = readdir($handle)) !== false)
{
if (preg_match('/\.sql$/i', $file)) $filesindir[] = $file;
}
sort($filesindir);
} else {
print '<div class="error">'.$langs->trans("ErrorCanNotReadDir", $dir).'</div>';
}
// Get files list
$filesindir = array();
$handle = opendir($dir);
if (is_resource($handle))
{
while (($file = readdir($handle)) !== false)
{
if (preg_match('/\.sql$/i', $file)) $filesindir[] = $file;
}
sort($filesindir);
} else {
print '<div class="error">'.$langs->trans("ErrorCanNotReadDir", $dir).'</div>';
}
// Define which file to run
foreach ($filesindir as $file)
{
if (preg_match('/'.$from.'/i', $file))
{
$filelist[] = $file;
} elseif (preg_match('/'.$to.'/i', $file)) // First test may be false if we migrate from x.y.* to x.y.*
{
$filelist[] = $file;
}
}
// Define which file to run
foreach ($filesindir as $file)
{
if (preg_match('/'.$from.'/i', $file))
{
$filelist[] = $file;
} elseif (preg_match('/'.$to.'/i', $file)) // First test may be false if we migrate from x.y.* to x.y.*
{
$filelist[] = $file;
}
}
if (count($filelist) == 0)
{
print '<div class="error">'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'</div>';
} else {
if (count($filelist) == 0)
{
print '<div class="error">'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'</div>';
} else {
$listoffileprocessed = array(); // Protection to avoid to process twice the same file
// Loop on each migrate files
foreach ($filelist as $file)
{
if (in_array($dir.$file, $listoffileprocessed)) continue;
// Loop on each migrate files
foreach ($filelist as $file)
{
if (in_array($dir.$file, $listoffileprocessed)) continue;
print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>';
print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").'</td><td class="right">'.$file.'</td></tr>'."\n";
print '<tr><td colspan="2"><hr style="border-color: #ccc; border-top-style: none;"></td></tr>';
print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").'</td><td class="right">'.$file.'</td></tr>'."\n";
// Run sql script
$ok = run_sql($dir.$file, 0, '', 1);
$listoffileprocessed[$dir.$file] = $dir.$file;
// Run sql script
$ok = run_sql($dir.$file, 0, '', 1);
$listoffileprocessed[$dir.$file] = $dir.$file;
// Scan if there is migration scripts that depends of Dolibarr version
// for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql")
$modulesfile = array();
foreach ($conf->file->dol_document_root as $type => $dirroot)
{
$handlemodule = @opendir($dirroot); // $dirroot may be '..'
if (is_resource($handlemodule))
{
while (($filemodule = readdir($handlemodule)) !== false)
{
if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) // We exclude filemodule that contains . (are not directories) and are not directories.
{
//print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file;
if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file))
{
$modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file;
}
}
}
closedir($handlemodule);
}
}
// Scan if there is migration scripts that depends of Dolibarr version
// for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql")
$modulesfile = array();
foreach ($conf->file->dol_document_root as $type => $dirroot)
{
$handlemodule = @opendir($dirroot); // $dirroot may be '..'
if (is_resource($handlemodule))
{
while (($filemodule = readdir($handlemodule)) !== false)
{
if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) // We exclude filemodule that contains . (are not directories) and are not directories.
{
//print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file;
if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file))
{
$modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file;
}
}
}
closedir($handlemodule);
}
}
foreach ($modulesfile as $modulefilelong => $modulefileshort)
{
if (in_array($modulefilelong, $listoffileprocessed)) continue;
foreach ($modulesfile as $modulefilelong => $modulefileshort)
{
if (in_array($modulefilelong, $listoffileprocessed)) continue;
print '<tr><td colspan="2"><hr></td></tr>';
print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").' (external modules)</td><td class="right">'.$modulefileshort.'</td></tr>'."\n";
print '<tr><td colspan="2"><hr></td></tr>';
print '<tr><td class="nowrap">'.$langs->trans("ChoosedMigrateScript").' (external modules)</td><td class="right">'.$modulefileshort.'</td></tr>'."\n";
// Run sql script
$okmodule = run_sql($modulefilelong, 0, '', 1); // Note: Result of migration of external module should not decide if we continue migration of Dolibarr or not.
$listoffileprocessed[$modulefilelong] = $modulefilelong;
}
}
// Run sql script
$okmodule = run_sql($modulefilelong, 0, '', 1); // Note: Result of migration of external module should not decide if we continue migration of Dolibarr or not.
$listoffileprocessed[$modulefilelong] = $modulefilelong;
}
}
}
}
}
print '</table>';
print '</table>';
if ($db->connected) $db->close();
if ($db->connected) $db->close();
}
if (empty($actiondone))
{
print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
}
$ret = 0;

View File

@ -28,31 +28,31 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/intracommreport.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
// Load translation files required by the page
$langs->loadLangs(array("admin","intracommreport"));
$langs->loadLangs(array("admin", "intracommreport"));
if (! $user->admin) accessforbidden();
if (!$user->admin) accessforbidden();
$action = GETPOST('action', 'aZ09');
// Parameters INTRACOMMREPORT_* and others
$list_DEB = array (
$list_DEB = array(
'INTRACOMMREPORT_NUM_AGREMENT',
);
$list_DES = array (
$list_DES = array(
'INTRACOMMREPORT_NUM_DECLARATION',
);
if ($action == 'update') {
$error = 0;
if (! $error)
if (!$error)
{
foreach ($list_DEB as $constname)
{
$constvalue = GETPOST($constname, 'alpha');
if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
$error++;
}
}
@ -61,7 +61,7 @@ if ($action == 'update') {
{
$constvalue = GETPOST($constname, 'alpha');
if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
$error++;
}
}
@ -77,7 +77,7 @@ if ($action == 'update') {
}
}
if (! $error) {
if (!$error) {
setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
}
}
@ -119,7 +119,7 @@ foreach ($list_DEB as $key)
print '<td>'.$label.'</td>';
// Value
print '<td class="left">';
print '<input type="text" class="maxwidth100" id="' . $key . '" name="' . $key . '" value="' . $conf->global->$key . '">';
print '<input type="text" class="maxwidth100" id="'.$key.'" name="'.$key.'" value="'.$conf->global->$key.'">';
print '</td>';
print '</tr>';
@ -185,7 +185,7 @@ foreach ($list_DES as $key)
print '<td>'.$label.'</td>';
// Value
print '<td class="left">';
print '<input type="text" class="maxwidth100" id="' . $key . '" name="' . $key . '" value="' . $conf->global->$key . '">';
print '<input type="text" class="maxwidth100" id="'.$key.'" name="'.$key.'" value="'.$conf->global->$key.'">';
print '</td>';
print '</tr>';

View File

@ -45,10 +45,10 @@ $backtopage = GETPOST('backtopage', 'alpha');
if ($user->rights->intracommreport->delete && $action == 'confirm_delete' && $confirm == 'yes')
{
$result=$object->delete($id, $user);
$result = $object->delete($id, $user);
if ($result > 0)
{
if (! empty($backtopage))
if (!empty($backtopage))
{
header("Location: ".$backtopage);
exit;
@ -59,12 +59,12 @@ if ($user->rights->intracommreport->delete && $action == 'confirm_delete' && $co
}
}
else {
$errmesg=$object->error;
$errmesg = $object->error;
}
}
if ($action == 'add' && $user->rights->intracommreport->write) {
$object->label = trim($label);
$object->label = trim($label);
$object->type = trim($type);
$object->type_declaration = (int) $statut;
$object->subscription = (int) $subscription;
@ -90,9 +90,9 @@ if ($action == 'add' && $user->rights->intracommreport->write) {
}
}
if (! $error)
if (!$error)
{
$id=$object->create($user);
$id = $object->create($user);
if ($id > 0)
{
header("Location: ".$_SERVER["PHP_SELF"]);
@ -134,7 +134,7 @@ if ($action == 'create')
$declaration["deb"] = $langs->trans("DEB");
$declaration["des"] = $langs->trans("DES");
print '<tr><td class="fieldrequired">'.$langs->trans("Declaration")."</td><td>\n";
print $form->selectarray("declaration", $declaration, GETPOST('declaration', 'alpha')?GETPOST('declaration', 'alpha'):$object->declaration, 0);
print $form->selectarray("declaration", $declaration, GETPOST('declaration', 'alpha') ?GETPOST('declaration', 'alpha') : $object->declaration, 0);
print "</td>\n";
// Analysis period
@ -152,7 +152,7 @@ if ($action == 'create')
$typeOfDeclaration["introduction"] = $langs->trans("Introduction");
$typeOfDeclaration["expedition"] = $langs->trans("Expedition");
print '<tr><td class="fieldrequired">'.$langs->trans("TypeOfDeclaration")."</td><td>\n";
print $form->selectarray("type_declaration", $typeOfDeclaration, GETPOST('type_declaration', 'alpha')?GETPOST('type_declaration', 'alpha'):$object->type_declaration, 0);
print $form->selectarray("type_declaration", $typeOfDeclaration, GETPOST('type_declaration', 'alpha') ?GETPOST('type_declaration', 'alpha') : $object->type_declaration, 0);
print "</td>\n";
print '</table>';
@ -160,7 +160,7 @@ if ($action == 'create')
print dol_get_fiche_end();
print '<div class="center"><input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">';
print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
print '</div>';
print '</form>';
@ -195,11 +195,11 @@ if ($id > 0 && $action != 'edit') {
'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])
);
}
print $form->formconfirm("card.php?rowid=" . $id, $langs->trans("DeleteReport"),
print $form->formconfirm("card.php?rowid=".$id, $langs->trans("DeleteReport"),
$langs->trans("ConfirmDeleteReport"), "confirm_delete", $formquestion, 'no', 1);
}
$linkback = '<a href="' . DOL_URL_ROOT . '/intracommreport/list.php?restore_lastsearch_values=1">' . $langs->trans("BackToList") . '</a>';
$linkback = '<a href="'.DOL_URL_ROOT.'/intracommreport/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
dol_banner_tab($object, 'rowid', $linkback);
@ -210,14 +210,14 @@ if ($id > 0 && $action != 'edit') {
print '<table class="border tableforfield centpercent">';
// Type
print '<tr><td class="titlefield">' . $langs->trans("Type") . '</td><td class="valeur">' . $object->declaration . "</td></tr>\n";
print '<tr><td class="titlefield">'.$langs->trans("Type").'</td><td class="valeur">'.$object->declaration."</td></tr>\n";
// Analysis Period
print '<tr><td>' . $langs->trans("AnalysisPeriod") . '</td><td class="valeur">' . $object->period . '</td>';
print '<tr><td>'.$langs->trans("AnalysisPeriod").'</td><td class="valeur">'.$object->period.'</td>';
print '</tr>';
// Type of Declaration
print '<tr><td>' . $langs->trans("TypeOfDeclaration") . '</td><td class="valeur">' . $object->type_declaration . '</td>';
print '<tr><td>'.$langs->trans("TypeOfDeclaration").'</td><td class="valeur">'.$object->type_declaration.'</td>';
print '</tr>';
print "</table>\n";

View File

@ -32,17 +32,17 @@ class IntracommReport extends CommonObject
/**
* @var string ID to identify managed object
*/
public $element='intracommreport';
public $element = 'intracommreport';
/**
* @var string Name of table without prefix where object is stored
*/
public $table_element='intracommreport';
public $table_element = 'intracommreport';
/**
* @var int Field with ID of parent key if this field has a parent
*/
public $fk_element='fk_intracommreport';
public $fk_element = 'fk_intracommreport';
/**
* @var string declaration number
@ -422,7 +422,7 @@ class IntracommReport extends CommonObject
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fname));
header('Content-Length: '.filesize($fname));
readfile($fname);
exit;
}

View File

@ -102,13 +102,13 @@ $fieldstosearchall = array(
"i.note"=>"Note",
);
$isInEEC=isInEEC($mysoc);
$isInEEC = isInEEC($mysoc);
// Definition of fields for lists
$arrayfields=array(
$arrayfields = array(
'i.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1),
'i.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
'i.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->produit->enabled) && ! empty($conf->service->enabled))),
'i.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(!empty($conf->produit->enabled) && !empty($conf->service->enabled))),
);
/*
// Extra fields
@ -145,19 +145,19 @@ if (empty($reshook))
// Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
{
$sall="";
$search_ref="";
$search_label="";
$sall = "";
$search_ref = "";
$search_label = "";
//$search_type=''; // There is 2 types of list: a list of product and a list of services. No list with both. So when we clear search criteria, we must keep the filter on type.
$show_childproducts = '';
$search_array_options=array();
$search_array_options = array();
}
// Mass actions
$objectclass='Product';
if ((string) $search_type == '1') { $objectlabel='Services'; }
if ((string) $search_type == '0') { $objectlabel='Products'; }
$objectclass = 'Product';
if ((string) $search_type == '1') { $objectlabel = 'Services'; }
if ((string) $search_type == '0') { $objectlabel = 'Products'; }
$permtoread = $user->rights->produit->lire;
$permtodelete = $user->rights->produit->supprimer;
@ -181,22 +181,22 @@ if (! empty($extrafields->attributes[$object->table_element]['label'])) {
}
*/
// Add fields from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql.= ' FROM '.MAIN_DB_PREFIX.'intracommreport as i';
$sql .= ' FROM '.MAIN_DB_PREFIX.'intracommreport as i';
// if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."intracommreport_extrafields as ef on (i.rowid = ef.fk_object)";
$sql.= ' WHERE i.entity IN ('.getEntity('intracommreport').')';
$sql .= ' WHERE i.entity IN ('.getEntity('intracommreport').')';
if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall);
// if the type is not 1, we show all products (type = 0,2,3)
if (dol_strlen($search_type) && $search_type != '-1')
{
if ($search_type == 1) $sql.= " AND i.type = 1";
else $sql.= " AND i.type = 0";
if ($search_type == 1) $sql .= " AND i.type = 1";
else $sql .= " AND i.type = 0";
}
/*
@ -253,40 +253,40 @@ if ($resql)
{
$num = $db->num_rows($resql);
$arrayofselected=is_array($toselect)?$toselect:array();
$arrayofselected = is_array($toselect) ? $toselect : array();
$helpurl='EN:Module_IntracommReport|FR:Module_ProDouane';
$helpurl = 'EN:Module_IntracommReport|FR:Module_ProDouane';
llxHeader('', $title, $helpurl, '');
// Displays product removal confirmation
if (GETPOST('delreport')) {
if (GETPOST('delreport')) {
setEventMessages($langs->trans("IntracommReportDeleted", GETPOST('delreport')), null, 'mesgs');
}
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
if ($sall) $param.="&sall=".urlencode($sall);
if ($search_ref) $param="&search_ref=".urlencode($search_ref);
if ($search_label) $param.="&search_label=".urlencode($search_label);
$param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
if ($sall) $param .= "&sall=".urlencode($sall);
if ($search_ref) $param = "&search_ref=".urlencode($search_ref);
if ($search_label) $param .= "&search_label=".urlencode($search_label);
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
// List of mass actions available
$arrayofmassactions = array(
$arrayofmassactions = array(
'generate_doc'=>$langs->trans("ReGeneratePDF"),
//'builddoc'=>$langs->trans("PDFMerge"),
//'presend'=>$langs->trans("SendByMail"),
);
if ($user->rights->intracommreport->delete) $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);
if ($user->rights->intracommreport->delete) $arrayofmassactions['predelete'] = "<span class='fa fa-trash paddingrightonly'></span>".$langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
$newcardbutton='';
$newcardbutton = '';
if ($user->rights->intracommreport->write)
{
$newcardbutton.= dolGetButtonTitle($langs->trans("NewDeclaration"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/intracommreport/card.php?action=create&amp;type='.$type);
$newcardbutton .= dolGetButtonTitle($langs->trans("NewDeclaration"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/intracommreport/card.php?action=create&amp;type='.$type);
}
print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" name="formulaire">';
@ -302,22 +302,22 @@ if ($resql)
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, $newcardbutton, '', $limit);
$topicmail="Information";
$modelmail="product";
$objecttmp=new IntracommReport($db);
$trackid='prod'.$object->id;
$topicmail = "Information";
$modelmail = "product";
$objecttmp = new IntracommReport($db);
$trackid = 'prod'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall)
{
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>';
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
}
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter.=$hookmanager->resPrint;
else $moreforfilter=$hookmanager->resPrint;
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
else $moreforfilter = $hookmanager->resPrint;
if ($moreforfilter)
{
@ -326,22 +326,22 @@ if ($resql)
print '</div>';
}
$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
// Lines with input filters
print '<tr class="liste_titre_filter">';
if (! empty($arrayfields['i.ref']['checked']))
if (!empty($arrayfields['i.ref']['checked']))
{
print '<td class="liste_titre left">';
print '<input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'">';
print '</td>';
}
if (! empty($arrayfields['i.label']['checked']))
if (!empty($arrayfields['i.label']['checked']))
{
print '<td class="liste_titre left">';
print '<input class="flat" type="text" name="search_label" size="12" value="'.dol_escape_htmltag($search_label).'">';
@ -357,10 +357,10 @@ if ($resql)
print '</select></td>';
}
if (! empty($arrayfields['i.fk_product_type']['checked']))
if (!empty($arrayfields['i.fk_product_type']['checked']))
{
print '<td class="liste_titre left">';
$array=array('-1'=>'&nbsp;', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service'));
$array = array('-1'=>'&nbsp;', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service'));
print $form->selectarray('search_type', $array, $search_type);
print '</td>';
}
@ -370,36 +370,36 @@ if ($resql)
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
*/
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
$parameters = array('arrayfields'=>$arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Date creation
if (! empty($arrayfields['i.datec']['checked']))
if (!empty($arrayfields['i.datec']['checked']))
{
print '<td class="liste_titre">';
print '</td>';
}
// Date modification
if (! empty($arrayfields['i.tms']['checked']))
if (!empty($arrayfields['i.tms']['checked']))
{
print '<td class="liste_titre">';
print '</td>';
}
print '<td class="liste_titre center maxwidthsearch">';
$searchpicto=$form->showFilterButtons();
$searchpicto = $form->showFilterButtons();
print $searchpicto;
print '</td>';
print '</tr>';
print '<tr class="liste_titre">';
if (! empty($arrayfields['i.ref']['checked'])) {
if (!empty($arrayfields['i.ref']['checked'])) {
print_liste_field_titre($arrayfields['i.ref']['label'], $_SERVER["PHP_SELF"], "i.ref", "", $param, "", $sortfield, $sortorder);
}
if (! empty($arrayfields['i.label']['checked'])) {
if (!empty($arrayfields['i.label']['checked'])) {
print_liste_field_titre($arrayfields['i.label']['label'], $_SERVER["PHP_SELF"], "i.label", "", $param, "", $sortfield, $sortorder);
}
if (! empty($arrayfields['i.fk_product_type']['checked'])) {
if (!empty($arrayfields['i.fk_product_type']['checked'])) {
print_liste_field_titre($arrayfields['i.fk_product_type']['label'], $_SERVER["PHP_SELF"], "i.fk_product_type", "", $param, "", $sortfield, $sortorder);
}
@ -408,13 +408,13 @@ if ($resql)
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
*/
// Hook fields
$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder);
$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (! empty($arrayfields['i.datec']['checked'])) {
if (!empty($arrayfields['i.datec']['checked'])) {
print_liste_field_titre($arrayfields['i.datec']['label'], $_SERVER["PHP_SELF"], "i.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
if (! empty($arrayfields['i.tms']['checked'])) {
if (!empty($arrayfields['i.tms']['checked'])) {
print_liste_field_titre($arrayfields['i.tms']['label'], $_SERVER["PHP_SELF"], "i.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
}
@ -425,7 +425,7 @@ if ($resql)
$intracommreport_static = new IntracommReport($db);
$i = 0;
$totalarray=array();
$totalarray = array();
while ($i < min($num, $limit))
{
$obj = $db->fetch_object($resql);
@ -443,35 +443,35 @@ if ($resql)
print '<tr class="oddeven">';
// Ref
if (! empty($arrayfields['i.ref']['checked']))
if (!empty($arrayfields['i.ref']['checked']))
{
print '<td class="tdoverflowmax200">';
print $intracommreport_static->getNomUrl(1);
print "</td>\n";
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
}
// Label
if (! empty($arrayfields['i.label']['checked']))
if (!empty($arrayfields['i.label']['checked']))
{
print '<td class="tdoverflowmax200">'.dol_trunc($obj->label, 80).'</td>';
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
}
// Type
if (! empty($arrayfields['i.fk_product_type']['checked']))
if (!empty($arrayfields['i.fk_product_type']['checked']))
{
print '<td>'.$obj->fk_product_type.'</td>';
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
}
// Action
print '<td class="nowrap center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected=0;
if (in_array($obj->rowid, $arrayofselected)) $selected=1;
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
$selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
}
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
print "</tr>\n";
$i++;

View File

@ -203,28 +203,28 @@ class LoanSchedule extends CommonObject
{
global $langs;
$sql = "SELECT";
$sql.= " t.rowid,";
$sql.= " t.fk_loan,";
$sql.= " t.datec,";
$sql.= " t.tms,";
$sql.= " t.datep,";
$sql.= " t.amount_capital,";
$sql.= " t.amount_insurance,";
$sql.= " t.amount_interest,";
$sql.= " t.fk_typepayment,";
$sql.= " t.num_payment,";
$sql.= " t.note_private,";
$sql.= " t.note_public,";
$sql.= " t.fk_bank,";
$sql.= " t.fk_payment_loan,";
$sql.= " t.fk_user_creat,";
$sql.= " t.fk_user_modif,";
$sql.= " pt.code as type_code, pt.libelle as type_label,";
$sql.= ' b.fk_account';
$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id";
$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid';
$sql.= " WHERE t.rowid = ".$id;
$sql .= " t.rowid,";
$sql .= " t.fk_loan,";
$sql .= " t.datec,";
$sql .= " t.tms,";
$sql .= " t.datep,";
$sql .= " t.amount_capital,";
$sql .= " t.amount_insurance,";
$sql .= " t.amount_interest,";
$sql .= " t.fk_typepayment,";
$sql .= " t.num_payment,";
$sql .= " t.note_private,";
$sql .= " t.note_public,";
$sql .= " t.fk_bank,";
$sql .= " t.fk_payment_loan,";
$sql .= " t.fk_user_creat,";
$sql .= " t.fk_user_modif,";
$sql .= " pt.code as type_code, pt.libelle as type_label,";
$sql .= ' b.fk_account';
$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id";
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid';
$sql .= " WHERE t.rowid = ".$id;
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$resql = $this->db->query($sql);

View File

@ -125,7 +125,7 @@ if ($action == 'add_payment')
if (!empty($line)) $pay_amount_interest = $line->amount_interest;
else $pay_amount_interest = price2num(GETPOST('amount_interest'));
$remaindertopay = price2num(GETPOST('remaindertopay'));
$amount = $pay_amount_capital + $pay_amount_insurance + $pay_amount_interest;
$amount = $pay_amount_capital + $pay_amount_insurance + $pay_amount_interest;
// This term is allready paid
if (!empty($line) && !empty($line->fk_bank))
@ -184,7 +184,7 @@ if ($action == 'add_payment')
}
// Update loan schedule with payment value
if (! $error && !empty($line))
if (!$error && !empty($line))
{
// If payment values are modified, recalculate schedule
if (($line->amount_capital <> $pay_amount_capital) || ($line->amount_insurance <> $pay_amount_insurance) || ($line->amount_interest <> $pay_amount_interest))
@ -195,14 +195,14 @@ if ($action == 'add_payment')
// Update fk_bank for current line
if ($k == $echance)
{
$ls->lines[$k-1]->fk_bank = $payment->fk_bank;
$ls->lines[$k-1]->fk_payment_loan = $payment->id;
$ls->lines[$k - 1]->fk_bank = $payment->fk_bank;
$ls->lines[$k - 1]->fk_payment_loan = $payment->id;
}
$ls->lines[$k-1]->amount_capital = $v['mens'] - $v['interet'];
$ls->lines[$k-1]->amount_interest = $v['interet'];
$ls->lines[$k-1]->tms = dol_now();
$ls->lines[$k-1]->fk_user_modif = $user->id;
$result = $ls->lines[$k-1]->update($user, 0);
$ls->lines[$k - 1]->amount_capital = $v['mens'] - $v['interet'];
$ls->lines[$k - 1]->amount_interest = $v['interet'];
$ls->lines[$k - 1]->tms = dol_now();
$ls->lines[$k - 1]->fk_user_modif = $user->id;
$result = $ls->lines[$k - 1]->update($user, 0);
if ($result < 1)
{
setEventMessages(null, $ls->errors, 'errors');
@ -300,7 +300,7 @@ if ($action == 'create')
print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Date").'</td><td colspan="2">';
if (empty($datepaid))
if (empty($ts_temppaid)) $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:dol_now();
if (empty($ts_temppaid)) $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : dol_now();
else $datepayment = $ts_temppaid;
else $datepayment = $datepaid;
print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1);
@ -367,7 +367,7 @@ if ($action == 'create')
print '<td class="right">';
if ($sumpaid < $loan->capital)
{
print $langs->trans("LoanCapital") .': <input type="text" size="8" name="amount_capital" value="'.(GETPOSTISSET('amount_capital')?GETPOST('amount_capital'):$amount_capital).'">';
print $langs->trans("LoanCapital").': <input type="text" size="8" name="amount_capital" value="'.(GETPOSTISSET('amount_capital') ?GETPOST('amount_capital') : $amount_capital).'">';
}
else {
print '-';

View File

@ -114,7 +114,7 @@ if ($action == 'updateecheancier' && empty($pay_without_schedule)) {
break;
}
$echeances->lines[$i-1] = $new_echeance;
$echeances->lines[$i - 1] = $new_echeance;
$i++;
}
if ($result > 0) $db->commit();

View File

@ -61,7 +61,7 @@ $enddatemonth = GETPOST('enddatemonth', 'int');
$enddateyear = GETPOST('enddateyear', 'int');
if (!empty($startdatemonth))
$startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear);
$startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear);
if (!empty($enddatemonth))
$enddate = dol_mktime(23, 59, 59, $enddatemonth, $enddateday, $enddateyear);

View File

@ -76,190 +76,190 @@ llxHeader('', $title, $help_url);
if ($socid > 0)
{
$object = new Societe($db);
$object->fetch($socid);
$object = new Societe($db);
$object->fetch($socid);
/*
/*
* Affichage onglets
*/
$head = societe_prepare_head($object);
$head = societe_prepare_head($object);
print dol_get_fiche_head($head, 'margin', $langs->trans("ThirdParty"), -1, 'company');
print dol_get_fiche_head($head, 'margin', $langs->trans("ThirdParty"), -1, 'company');
$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
print '<div class="fichecenter">';
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">';
if ($object->client)
{
print '<tr><td class="titlefield">';
print $langs->trans('CustomerCode').'</td><td colspan="3">';
print $object->code_client;
if ($object->check_codeclient() <> 0) print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
print '</td></tr>';
}
if ($object->client)
{
print '<tr><td class="titlefield">';
print $langs->trans('CustomerCode').'</td><td colspan="3">';
print $object->code_client;
if ($object->check_codeclient() <> 0) print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
print '</td></tr>';
}
if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire))
{
print '<tr><td class="titlefield">';
print $langs->trans('SupplierCode').'</td><td colspan="3">';
print $object->code_fournisseur;
if ($object->check_codefournisseur() <> 0) print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
print '</td></tr>';
}
if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire))
{
print '<tr><td class="titlefield">';
print $langs->trans('SupplierCode').'</td><td colspan="3">';
print $object->code_fournisseur;
if ($object->check_codefournisseur() <> 0) print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
print '</td></tr>';
}
// Total Margin
print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="3">';
print '<span id="totalMargin"></span>'; // set by jquery (see below)
print '</td></tr>';
// Total Margin
print '<tr><td class="titlefield">'.$langs->trans("TotalMargin").'</td><td colspan="3">';
print '<span id="totalMargin"></span>'; // set by jquery (see below)
print '</td></tr>';
// Margin Rate
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="3">';
print '<span id="marginRate"></span>'; // set by jquery (see below)
print '</td></tr>';
}
// Margin Rate
if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="3">';
print '<span id="marginRate"></span>'; // set by jquery (see below)
print '</td></tr>';
}
// Mark Rate
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="3">';
print '<span id="markRate"></span>'; // set by jquery (see below)
print '</td></tr>';
}
// Mark Rate
if (!empty($conf->global->DISPLAY_MARK_RATES)) {
print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="3">';
print '<span id="markRate"></span>'; // set by jquery (see below)
print '</td></tr>';
}
print "</table>";
print "</table>";
print '</div>';
print '<div style="clear:both"></div>';
print '</div>';
print '<div style="clear:both"></div>';
print dol_get_fiche_end();
print dol_get_fiche_end();
print '<br>';
print '<br>';
$sql = "SELECT distinct s.nom, s.rowid as socid, s.code_client,";
$sql .= " f.rowid as facid, f.ref, f.total as total_ht,";
$sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
$sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
$sql .= " sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // always positive
$sql .= " sum(abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100))) as marge"; // always positive
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."facture as f";
$sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
$sql .= " WHERE f.fk_soc = s.rowid";
$sql .= " AND f.fk_statut > 0";
$sql .= " AND f.entity IN (".getEntity('invoice').")";
$sql .= " AND d.fk_facture = f.rowid";
$sql .= " AND f.fk_soc = $socid";
$sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0";
$sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type";
$sql .= $db->order($sortfield, $sortorder);
// TODO: calculate total to display then restore pagination
//$sql.= $db->plimit($conf->liste_limit +1, $offset);
$sql = "SELECT distinct s.nom, s.rowid as socid, s.code_client,";
$sql .= " f.rowid as facid, f.ref, f.total as total_ht,";
$sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,";
$sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive
$sql .= " sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // always positive
$sql .= " sum(abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100))) as marge"; // always positive
$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql .= ", ".MAIN_DB_PREFIX."facture as f";
$sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
$sql .= " WHERE f.fk_soc = s.rowid";
$sql .= " AND f.fk_statut > 0";
$sql .= " AND f.entity IN (".getEntity('invoice').")";
$sql .= " AND d.fk_facture = f.rowid";
$sql .= " AND f.fk_soc = $socid";
$sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0";
$sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type";
$sql .= $db->order($sortfield, $sortorder);
// TODO: calculate total to display then restore pagination
//$sql.= $db->plimit($conf->liste_limit +1, $offset);
dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG);
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG);
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;socid=".$object->id, $sortfield, $sortorder, '', $num, $num, '');
print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;socid=".$object->id, $sortfield, $sortorder, '', $num, $num, '');
$i = 0;
print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
print "<table class=\"noborder\" width=\"100%\">";
$i = 0;
print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
print "<table class=\"noborder\" width=\"100%\">";
print '<tr class="liste_titre">';
print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder);
print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'center ');
print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARGIN_RATES))
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARK_RATES))
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print "</tr>\n";
print '<tr class="liste_titre">';
print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder);
print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'center ');
print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARGIN_RATES))
print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
if (!empty($conf->global->DISPLAY_MARK_RATES))
print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&amp;socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right ');
print "</tr>\n";
$cumul_achat = 0;
$cumul_vente = 0;
$cumul_achat = 0;
$cumul_vente = 0;
if ($num > 0)
{
while ($i < $num /*&& $i < $conf->liste_limit*/)
{
$objp = $db->fetch_object($result);
if ($num > 0)
{
while ($i < $num /*&& $i < $conf->liste_limit*/)
{
$objp = $db->fetch_object($result);
$marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
$markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
$marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : '';
$markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : '';
$sign = '';
if ($objp->type == Facture::TYPE_CREDIT_NOTE) {
$sign = '-';
}
$sign = '';
if ($objp->type == Facture::TYPE_CREDIT_NOTE) {
$sign = '-';
}
print '<tr class="oddeven">';
print '<td>';
$invoicestatic->id = $objp->facid;
$invoicestatic->ref = $objp->ref;
print $invoicestatic->getNomUrl(1);
print "</td>\n";
print "<td class=\"center\">";
print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
print "<td class=\"right\">".price(price2num($objp->selling_price, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."</td>\n";
print "<td class=\"right\">".$sign.price(price2num($objp->marge, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES))
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES))
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
print "</tr>\n";
$i++;
$cumul_vente += $objp->selling_price;
$cumul_achat += ($objp->type == 2 ? -1 : 1) * $objp->buying_price;
}
}
print '<tr class="oddeven">';
print '<td>';
$invoicestatic->id = $objp->facid;
$invoicestatic->ref = $objp->ref;
print $invoicestatic->getNomUrl(1);
print "</td>\n";
print "<td class=\"center\">";
print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
print "<td class=\"right\">".price(price2num($objp->selling_price, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."</td>\n";
print "<td class=\"right\">".$sign.price(price2num($objp->marge, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES))
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES))
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
print '<td class="right">'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'</td>';
print "</tr>\n";
$i++;
$cumul_vente += $objp->selling_price;
$cumul_achat += ($objp->type == 2 ? -1 : 1) * $objp->buying_price;
}
}
// affichage totaux marges
// affichage totaux marges
$totalMargin = $cumul_vente - $cumul_achat;
if ($totalMargin < 0)
{
$marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
$markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
} else {
$marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
$markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
}
$totalMargin = $cumul_vente - $cumul_achat;
if ($totalMargin < 0)
{
$marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : '';
$markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : '';
} else {
$marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
$markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
}
// Total
print '<tr class="liste_total">';
print '<td colspan=2>'.$langs->trans('TotalMargin')."</td>";
print "<td class=\"right\">".price(price2num($cumul_vente, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($cumul_achat, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($totalMargin, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES))
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES))
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
print '<td class="right">&nbsp;</td>';
print "</tr>\n";
} else {
dol_print_error($db);
}
print "</table>";
print '</div>';
// Total
print '<tr class="liste_total">';
print '<td colspan=2>'.$langs->trans('TotalMargin')."</td>";
print "<td class=\"right\">".price(price2num($cumul_vente, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($cumul_achat, 'MT'))."</td>\n";
print "<td class=\"right\">".price(price2num($totalMargin, 'MT'))."</td>\n";
if (!empty($conf->global->DISPLAY_MARGIN_RATES))
print "<td class=\"right\">".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."</td>\n";
if (!empty($conf->global->DISPLAY_MARK_RATES))
print "<td class=\"right\">".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."</td>\n";
print '<td class="right">&nbsp;</td>';
print "</tr>\n";
} else {
dol_print_error($db);
}
print "</table>";
print '</div>';
print '<br>';
$db->free($result);
print '<br>';
$db->free($result);
} else {
dol_print_error('', 'Parameter socid not defined');
}

View File

@ -290,8 +290,8 @@ class MyModuleApi extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -270,8 +270,8 @@ class Mos extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -103,7 +103,7 @@ class Mo extends CommonObject
'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'css'=>'maxwidth300'),
'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>51, 'notnull'=>-1, 'index'=>1,),
'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'enabled'=>1, 'visible'=>1, 'position'=>52, 'css'=>'maxwidth300'),
'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,),
'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,),
'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'notnull'=>-1,),
'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,),
'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>-1,),

View File

@ -96,7 +96,7 @@ if ($conf->use_javascript_ajax)
print '<div class="div-table-responsive-no-min">';
print '<table class="noborder nohover centpercent">';
print '<tr class="liste_titre"><th colspan="2">' . $langs->trans("Statistics") . ' - ' . $langs->trans("ManufacturingOrder") . '</th></tr>' . "\n";
print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("ManufacturingOrder").'</th></tr>'."\n";
$listofstatus = array(0, 1, 2, 3, 9);
foreach ($listofstatus as $status)
{

View File

@ -43,38 +43,38 @@ $action = GETPOST('action', 'alpha');
$massaction = GETPOST('massaction', 'alpha');
$show_files = GETPOST('show_files', 'int');
$confirm = GETPOST('confirm', 'alpha');
$toselect = GETPOST('toselect', 'array');
$id_rate_selected = GETPOST('id_rate', 'int');
$sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
$search_date_sync = GETPOST('search_date_sync', 'alpha');
$toselect = GETPOST('toselect', 'array');
$id_rate_selected = GETPOST('id_rate', 'int');
$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
$search_date_sync = GETPOST('search_date_sync', 'alpha');
$search_rate = GETPOST('search_rate', 'alpha');
$search_code = GETPOST('search_code', 'alpha');
$multicurrency_code = GETPOST('multicurrency_code', 'alpha');
$dateinput = dol_mktime(0, 0, 0, GETPOST('dateinputmonth', 'int'), GETPOST('dateinputday', 'int'), GETPOST('dateinputyear', 'int'));
$rateinput = price2num(GETPOST('rateinput', 'alpha'));
$optioncss = GETPOST('optioncss', 'alpha');
$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int') : $conf->liste_limit;
$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
$page = (GETPOST("page", 'int')?GETPOST("page", 'int'):0);
$page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0);
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortfield) $sortfield="cr.date_sync";
if (! $sortorder) $sortorder="ASC";
if (!$sortfield) $sortfield = "cr.date_sync";
if (!$sortorder) $sortorder = "ASC";
// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
$object=new CurrencyRate($db);
$object = new CurrencyRate($db);
$extrafields = new ExtraFields($db);
$form=new Form($db);
$form = new Form($db);
$hookmanager->initHooks(array('EditorRatelist', 'globallist'));
if (empty($action)) $action='list';
if (empty($action)) $action = 'list';
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
@ -84,7 +84,7 @@ $fieldstosearchall = array(
);
// Definition of fields for lists
$arrayfields=array(
$arrayfields = array(
'cr.date_sync'=>array('label'=>'Date', 'checked'=>1),
'cr.rate'=>array('label'=>'Rate', 'checked'=>1),
'm.code'=>array('label'=>'Code', 'checked'=>1),
@ -99,7 +99,7 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
/*
* Actions
*/
if ($action == "create"){
if ($action == "create") {
if (!empty($rateinput)) {
$currencyRate_static = new CurrencyRate($db);
$currency_static = new MultiCurrency($db);
@ -122,34 +122,34 @@ if ($action == "create"){
}
}
if ($action == 'update'){
if ($action == 'update') {
$currencyRate = new CurrencyRate($db);
$result = $currencyRate->fetch($id_rate_selected);
if ( $result > 0){
$currency_static = new MultiCurrency($db);
if ($result > 0) {
$currency_static = new MultiCurrency($db);
$fk_currency = $currency_static->getIdFromCode($db, $multicurrency_code);
$currencyRate->date_sync = $dateinput;
$currencyRate->fk_multicurrency = $fk_currency;
$currencyRate->rate = $rateinput;
$res = $currencyRate->update();
if ($res){
if ($res) {
setEventMessages($langs->trans('successUpdateRate'), null);
}else {
} else {
setEventMessages($currencyRate->error, $currencyRate->errors, "errors");
}
}else {
} else {
setEventMessages($langs->trans('Error'), null, "warnings");
}
}
if ($action == "deleteRate"){
if ($action == "deleteRate") {
$current_rate = new CurrencyRate($db);
$current_rate->fetch(intval($id_rate_selected));
if ($current_rate){
if ($current_rate) {
$current_currency = new MultiCurrency($db);
$current_currency->fetch($current_rate->fk_multicurrency);
if ($current_currency){
if ($current_currency) {
$delayedhtmlcontent = $form->formconfirm(
$_SERVER["PHP_SELF"].'?id_rate='.$id_rate_selected,
$langs->trans('DeleteLineRate'),
@ -159,36 +159,36 @@ if ($action == "deleteRate"){
0,
1
);
}else {
} else {
dol_syslog("Multicurrency::fetch", LOG_WARNING);
}
}else {
} else {
setEventMessage($langs->trans('NoCurrencyRateSelected'), "warnings");
}
}
if ($action == "confirm_delete"){
if ($action == "confirm_delete") {
$current_rate = new CurrencyRate($db);
$current_rate->fetch(intval($id_rate_selected));
if ($current_rate){
$result = $current_rate->delete();
if ($result){
if ($current_rate) {
$result = $current_rate->delete();
if ($result) {
setEventMessages($langs->trans('successRateDelete'), null);
}else {
} else {
setEventMessages($current_rate->error, $current_rate->errors, 'errors');
}
}else {
} else {
setEventMessages($langs->trans('NoCurrencyRateSelected'), null, "warnings");
dol_syslog($langs->trans('NoCurrencyRateSelected'), LOG_WARNING);
}
}
if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; }
if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
$parameters=array();
$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
@ -198,15 +198,15 @@ if (empty($reshook))
// Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
{
$sall="";
$search_date_sync="";
$search_rate="";
$search_code="";
$search_array_options=array();
$sall = "";
$search_date_sync = "";
$search_rate = "";
$search_code = "";
$search_array_options = array();
}
// Mass actions
$objectclass="CurrencyRate";
$objectclass = "CurrencyRate";
$uploaddir = $conf->multicurrency->multidir_output; // define only because core/actions_massactions.inc.php want it
$permtoread = $user->admin;
$permtodelete = $user->admin;
@ -217,9 +217,9 @@ if (empty($reshook))
* View
*/
$htmlother=new FormOther($db);
$htmlother = new FormOther($db);
$title=$langs->trans("CurrencyRate");
$title = $langs->trans("CurrencyRate");
$page_name = "ListCurrencyRate";
llxHeader('', $title, $helpurl, '');
@ -233,30 +233,30 @@ print dol_get_fiche_head($head, 'ratelist', $langs->trans("ModuleSetup"), -1, "m
// ACTION
if ($action!= "updateRate" && $action!= "deleteRate" ) {
if ($action != "updateRate" && $action != "deleteRate") {
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("FormCreateRate").'</td>'."\n";
print '</tr></table>';
$form = new Form($db);
print '<form action="' . $_SERVER["PHP_SELF"] . '" method="post" name="formulaire">';
print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" name="formulaire">';
print '<table><tr>';
print ' <td>' . $langs->trans('Date') . '</td>';
print ' <td>'.$langs->trans('Date').'</td>';
print ' <td>';
print $form->selectDate($dateinput, 'dateinput');
print '</td>';
print '<td> ' . $langs->trans('Currency') . '</td>';
print '<td>' . $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code', 'alpha') : $multicurrency_code), 'multicurrency_code', 0, " code != '".$conf->currency."'", true) . '</td>';
print '<td> '.$langs->trans('Currency').'</td>';
print '<td>'.$form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code', 'alpha') : $multicurrency_code), 'multicurrency_code', 0, " code != '".$conf->currency."'", true).'</td>';
print ' <td>' . $langs->trans('Rate') . '</td>';
print ' <td><input type="number" min ="0" step="any" class="minwidth200" name="rateinput" value="' . dol_escape_htmltag($rateinput) . '"></td>';
print ' <td>'.$langs->trans('Rate').'</td>';
print ' <td><input type="number" min ="0" step="any" class="minwidth200" name="rateinput" value="'.dol_escape_htmltag($rateinput).'"></td>';
print '<td>';
print '<input type="hidden" name="action" value="create">';
print '<input type="submit" class="butAction" name="btnCreateCurrencyRate" value="' . $langs->trans('CreateRate') . '">';
print '<input type="submit" class="butAction" name="btnCreateCurrencyRate" value="'.$langs->trans('CreateRate').'">';
print '</td>';
print '</tr></table>';
@ -265,49 +265,49 @@ if ($action!= "updateRate" && $action!= "deleteRate" ) {
print '<br>';
}
if ($action == "updateRate"){
if ($action == "updateRate") {
$current_rate = new CurrencyRate($db);
$current_rate->fetch(intval($id_rate_selected));
if ($current_rate) {
$curr = new MultiCurrency($db);
$resultcurrentCurrency = $curr->fetch($current_rate->fk_multicurrency);
$resultcurrentCurrency = $curr->fetch($current_rate->fk_multicurrency);
if ($resultcurrentCurrency){
if ($resultcurrentCurrency) {
$currency_code = $curr->code;
}else {
} else {
$currency_code = '';
}
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("FormUpdateRate") . '</td>' . "\n";
print '<td>'.$langs->trans("FormUpdateRate").'</td>'."\n";
print '</tr></table>';
$form = new Form($db);
print '<form action="' . $_SERVER["PHP_SELF"] . '" method="post" name="formtoupdaterate">';
print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" name="formtoupdaterate">';
print '<table><tr>';
print ' <td>' . $langs->trans('Date') . '</td>';
print ' <td>'.$langs->trans('Date').'</td>';
print '<td>';
print $form->selectDate($current_rate->date_sync, 'dateinput');
print '</td>';
print '<td> ' . $langs->trans('Currency') . '</td>';
print '<td>' . $form->selectMultiCurrency($currency_code, 'multicurrency_code', 0, " code != '".$conf->currency."'", true) . '</td>';
print '<td> '.$langs->trans('Currency').'</td>';
print '<td>'.$form->selectMultiCurrency($currency_code, 'multicurrency_code', 0, " code != '".$conf->currency."'", true).'</td>';
print '<td>' . $langs->trans('Rate') . '</td>';
print '<td><input class="minwidth200" name="rateinput" value="' . dol_escape_htmltag($current_rate->rate) . '" type="text"></td>';
print '<td>'.$langs->trans('Rate').'</td>';
print '<td><input class="minwidth200" name="rateinput" value="'.dol_escape_htmltag($current_rate->rate).'" type="text"></td>';
print '<td>';
print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id_rate" value="'.$current_rate->id.'">';
print '<input type="submit" class="butAction" name="btnupdateCurrencyRate" value="' . $langs->trans('UpdateRate') . '">';
print '<a href="'.$_SERVER["PHP_SELF"].'" class="butAction">' .$langs->trans('CancelUpdate') . '</a>';
print '<input type="submit" class="butAction" name="btnupdateCurrencyRate" value="'.$langs->trans('UpdateRate').'">';
print '<a href="'.$_SERVER["PHP_SELF"].'" class="butAction">'.$langs->trans('CancelUpdate').'</a>';
print '</td>';
print '</tr></table>';
print '</form>';
}else {
} else {
dol_syslog("currency_rate:list:update", LOG_WARNING);
}
}
@ -315,29 +315,29 @@ if ($action == "updateRate"){
$sql = 'SELECT cr.rowid, cr.date_sync, cr.rate, cr.entity, m.code, m.name ';
// Add fields from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql.= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr ';
$sql .=" INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid";
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql .= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr ';
$sql .= " INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid";
if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall);
if ($search_date_sync) $sql .= natural_search('cr.date_sync', $search_date_sync);
if ($search_rate) $sql .= natural_search('cr.rate', $search_rate);
if ($search_code) $sql .= natural_search('m.code', $search_code);
$sql.= " WHERE m.code <> '".$db->escape($conf->currency)."'";
$sql .= " WHERE m.code <> '".$db->escape($conf->currency)."'";
// Add where from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql.= " GROUP BY cr.rowid, cr.date_sync, cr.rate, m.code, cr.entity, m.code, m.name";
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql .= " GROUP BY cr.rowid, cr.date_sync, cr.rate, m.code, cr.entity, m.code, m.name";
// Add fields from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql.= $db->order($sortfield, $sortorder);
$sql .= $db->order($sortfield, $sortorder);
$nbtotalofrecords = '';
@ -345,41 +345,41 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
if ($result){
if ($result) {
$nbtotalofrecords = $db->num_rows($result);
if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
{
$page = 0;
$offset = 0;
}
}else {
} else {
setEventMessage($langs->trans('No_record_on_multicurrency_rate'), 'warnings');
}
}
$sql.= $db->plimit($limit + 1, $offset);
$sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$arrayofselected=is_array($toselect)?$toselect:array();
$arrayofselected = is_array($toselect) ? $toselect : array();
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
if ($sall) $param.="&sall=".urlencode($sall);
$param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
if ($sall) $param .= "&sall=".urlencode($sall);
if ($search_date_sync) $param="&search_date_sync=".urlencode($search_date_sync);
if ($search_rate) $param="&search_rate=".urlencode($search_rate);
if ($search_code != '') $param.="&search_code=".urlencode($search_code);
if ($search_date_sync) $param = "&search_date_sync=".urlencode($search_date_sync);
if ($search_rate) $param = "&search_rate=".urlencode($search_rate);
if ($search_code != '') $param .= "&search_code=".urlencode($search_code);
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
if ($user->admin) $arrayofmassactions['predelete']=$langs->trans("Delete");
if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
if ($user->admin) $arrayofmassactions['predelete'] = $langs->trans("Delete");
if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
@ -397,18 +397,18 @@ if ($resql)
if ($sall)
{
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>';
foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
}
// Filter on categories
$moreforfilter='';
$moreforfilter = '';
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter.=$hookmanager->resPrint;
else $moreforfilter=$hookmanager->resPrint;
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
else $moreforfilter = $hookmanager->resPrint;
if ($moreforfilter)
{
@ -417,32 +417,32 @@ if ($resql)
print '</div>';
}
$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
// Lines with input filters
print '<tr class="liste_titre_filter">';
// date
if (! empty($arrayfields['cr.date_sync']['checked']))
if (!empty($arrayfields['cr.date_sync']['checked']))
{
print '<td class="liste_titre" align="left">';
print '<input class="flat" type="text" name="search_date_sync" size="8" value="'.dol_escape_htmltag($search_date_sync).'">';
print '</td>';
}
// code
if (! empty($arrayfields['m.code']['checked']))
if (!empty($arrayfields['m.code']['checked']))
{
print '<td class="liste_titre" align="left">';
print '<input class="flat" type="text" name="search_code" size="12" value="'.dol_escape_htmltag($search_code).'">';
print '</td>';
}
// rate
if (! empty($arrayfields['cr.rate']['checked']))
if (!empty($arrayfields['cr.rate']['checked']))
{
print '<td class="liste_titre" align="left">';
print '<input class="flat" type="text" name="search_rate" size="8" value="'.dol_escape_htmltag($search_rate).'">';
@ -450,32 +450,32 @@ if ($resql)
}
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
$parameters = array('arrayfields'=>$arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '<td class="liste_titre" align="middle">';
$searchpicto=$form->showFilterButtons();
$searchpicto = $form->showFilterButtons();
print $searchpicto;
print '</td>';
print '</tr>';
print '<tr class="liste_titre">';
if (! empty($arrayfields['cr.date_sync']['checked'])) print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder);
if (! empty($arrayfields['m.code']['checked'])) print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder);
if (! empty($arrayfields['cr.rate']['checked'])) print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['cr.date_sync']['checked'])) print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['m.code']['checked'])) print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder);
if (!empty($arrayfields['cr.rate']['checked'])) print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder);
// Hook fields
$parameters=array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
print "</tr>\n";
$i = 0;
$totalarray=array();
$totalarray = array();
while ($i < min($num, $limit))
{
$obj = $db->fetch_object($resql);
@ -483,50 +483,50 @@ if ($resql)
print '<tr class="oddeven">';
// date_sync
if (! empty($arrayfields['cr.date_sync']['checked']))
if (!empty($arrayfields['cr.date_sync']['checked']))
{
print '<td class="tdoverflowmax200">';
print $obj->date_sync;
print "</td>\n";
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
}
// code
if (! empty($arrayfields['m.code']['checked']))
if (!empty($arrayfields['m.code']['checked']))
{
print '<td class="tdoverflowmax200">';
print $obj->code ." ". $obj->name;
print $obj->code." ".$obj->name;
print "</td>\n";
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
}
// rate
if (! empty($arrayfields['cr.rate']['checked']))
if (!empty($arrayfields['cr.rate']['checked']))
{
print '<td class="tdoverflowmax200">';
print $obj->rate;
print "</td>\n";
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
}
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
$reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj);
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action
print '<td class="nowrap" align="center">';
if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
{
$selected=0;
if (in_array($obj->rowid, $arrayofselected)) $selected=1;
print '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=updateRate&amp;id_rate='.$obj->rowid.'" class="like-link " style="margin-right:15px;important">' . img_picto('edit', 'edit') . '</a>';
print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteRate&amp;id_rate='.$obj->rowid.'" class="like-link" style="margin-right:45px;important">' . img_picto('delete', 'delete') . '</a>';
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
$selected = 0;
if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
print '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=updateRate&amp;id_rate='.$obj->rowid.'" class="like-link " style="margin-right:15px;important">'.img_picto('edit', 'edit').'</a>';
print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteRate&amp;id_rate='.$obj->rowid.'" class="like-link" style="margin-right:45px;important">'.img_picto('delete', 'delete').'</a>';
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
}
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (!$i) $totalarray['nbfield']++;
print "</tr>\n";
$i++;

View File

@ -141,7 +141,7 @@ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
$price_options[$i] = $langs->trans('SellingPrice').' '.$i;
}
$genPriceOptions = function ($level) use ($price_options) {
$genPriceOptions = function($level) use ($price_options) {
$return = array();

File diff suppressed because it is too large Load Diff

View File

@ -1040,16 +1040,16 @@ SCRIPT;
// Unit price in currency
if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) {
print '<td class="right">';
print price($productfourn->fourn_multicurrency_unitprice);
print '</td>'; }
print '<td class="right">';
print price($productfourn->fourn_multicurrency_unitprice);
print '</td>'; }
// Currency
if ($conf->multicurrency->enabled) {
print '<td class="right">';
print $productfourn->fourn_multicurrency_code ? currency_name($productfourn->fourn_multicurrency_code) : '';
print '</td>';
}
if ($conf->multicurrency->enabled) {
print '<td class="right">';
print $productfourn->fourn_multicurrency_code ? currency_name($productfourn->fourn_multicurrency_code) : '';
print '</td>';
}
// Discount
print '<td class="right">';

View File

@ -405,19 +405,19 @@ if ($resql)
print price2num($product->stock_theorique, 'MS');
print '</td>';
}
// Units
if (!empty($conf->global->PRODUCT_USE_UNITS)) {
print '<td class="left">'.$objp->unit_short.'</td>';
}
// Units
if (!empty($conf->global->PRODUCT_USE_UNITS)) {
print '<td class="left">'.$objp->unit_short.'</td>';
}
print '<td class="right"><a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?idproduct='.$product->id.'">'.$langs->trans("Movements").'</a></td>';
print '<td class="right nowrap">'.$product->LibStatut($objp->statut, 5, 0).'</td>';
print '<td class="right nowrap">'.$product->LibStatut($objp->tobuy, 5, 1).'</td>';
print '<td class="right nowrap">'.$product->LibStatut($objp->tobuy, 5, 1).'</td>';
// Fields from hook
$parameters = array('obj'=>$objp);
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '<td></td>';
print "</tr>\n";
print "</tr>\n";
$i++;
}

View File

@ -272,79 +272,79 @@ class StockMovements extends DolibarrApi
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param MouvementStock $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param MouvementStock $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// Remove useless data
unset($object->civility_id);
unset($object->firstname);
unset($object->lastname);
unset($object->name);
unset($object->location_incoterms);
unset($object->label_incoterms);
unset($object->fk_incoterms);
unset($object->lines);
unset($object->total_ht);
unset($object->total_ttc);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->note);
unset($object->note_private);
unset($object->note_public);
unset($object->shipping_method_id);
unset($object->fk_account);
unset($object->model_pdf);
unset($object->fk_delivery_address);
unset($object->cond_reglement);
unset($object->cond_reglement_id);
unset($object->mode_reglement_id);
unset($object->barcode_type_coder);
unset($object->barcode_type_label);
unset($object->barcode_type_code);
unset($object->barcode_type);
unset($object->country_code);
unset($object->country_id);
unset($object->country);
unset($object->thirdparty);
unset($object->contact);
unset($object->contact_id);
unset($object->user);
unset($object->fk_project);
unset($object->project);
unset($object->canvas);
// Remove useless data
unset($object->civility_id);
unset($object->firstname);
unset($object->lastname);
unset($object->name);
unset($object->location_incoterms);
unset($object->label_incoterms);
unset($object->fk_incoterms);
unset($object->lines);
unset($object->total_ht);
unset($object->total_ttc);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->note);
unset($object->note_private);
unset($object->note_public);
unset($object->shipping_method_id);
unset($object->fk_account);
unset($object->model_pdf);
unset($object->fk_delivery_address);
unset($object->cond_reglement);
unset($object->cond_reglement_id);
unset($object->mode_reglement_id);
unset($object->barcode_type_coder);
unset($object->barcode_type_label);
unset($object->barcode_type_code);
unset($object->barcode_type);
unset($object->country_code);
unset($object->country_id);
unset($object->country);
unset($object->thirdparty);
unset($object->contact);
unset($object->contact_id);
unset($object->user);
unset($object->fk_project);
unset($object->project);
unset($object->canvas);
//unset($object->eatby); Filled correctly in read mode
//unset($object->sellby); Filled correctly in read mode
//unset($object->eatby); Filled correctly in read mode
//unset($object->sellby); Filled correctly in read mode
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$stockmovement = array();
foreach (self::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$stockmovement[$field] = $data[$field];
}
return $stockmovement;
}
/**
* Validate fields before create or update object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$stockmovement = array();
foreach (self::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$stockmovement[$field] = $data[$field];
}
return $stockmovement;
}
}

View File

@ -28,264 +28,264 @@
*/
class Warehouses extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'label',
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'label',
);
/**
* @var Entrepot $warehouse {@type Entrepot}
*/
public $warehouse;
/**
* @var Entrepot $warehouse {@type Entrepot}
*/
public $warehouse;
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->warehouse = new Entrepot($this->db);
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->warehouse = new Entrepot($this->db);
}
/**
* Get properties of a warehouse object
*
* Return an array with warehouse informations
*
* @param int $id ID of warehouse
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->stock->lire) {
throw new RestException(401);
}
/**
* Get properties of a warehouse object
*
* Return an array with warehouse informations
*
* @param int $id ID of warehouse
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->stock->lire) {
throw new RestException(401);
}
$result = $this->warehouse->fetch($id);
if (!$result) {
throw new RestException(404, 'warehouse not found');
}
$result = $this->warehouse->fetch($id);
if (!$result) {
throw new RestException(404, 'warehouse not found');
}
if (!DolibarrApi::_checkAccessToResource('warehouse', $this->warehouse->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('warehouse', $this->warehouse->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->warehouse);
}
return $this->_cleanObjectDatas($this->warehouse);
}
/**
* List warehouses
*
* Get a list of warehouses
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
/**
* List warehouses
*
* Get a list of warehouses
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param int $category Use this param to filter list by category
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'WH-%') and (t.date_creation:<:'20160101')"
* @return array Array of warehouse objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '')
{
global $db, $conf;
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'WH-%') and (t.date_creation:<:'20160101')"
* @return array Array of warehouse objects
*
* @throws RestException
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->stock->lire) {
throw new RestException(401);
}
if (!DolibarrApiAccess::$user->rights->stock->lire) {
throw new RestException(401);
}
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as t";
if ($category > 0) {
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c";
}
$sql .= ' WHERE t.entity IN ('.getEntity('stock').')';
// Select warehouses of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category);
}
$sql .= ' WHERE t.entity IN ('.getEntity('stock').')';
// Select warehouses of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category);
$sql .= " AND c.fk_warehouse = t.rowid ";
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
if ($result)
{
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$warehouse_static = new Entrepot($this->db);
if ($warehouse_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($warehouse_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve warehouse list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No warehouse found');
}
return $obj_ret;
}
$result = $this->db->query($sql);
if ($result)
{
$i = 0;
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$warehouse_static = new Entrepot($this->db);
if ($warehouse_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($warehouse_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve warehouse list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No warehouse found');
}
return $obj_ret;
}
/**
* Create warehouse object
*
* @param array $request_data Request data
* @return int ID of warehouse
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->stock->creer) {
throw new RestException(401);
}
/**
* Create warehouse object
*
* @param array $request_data Request data
* @return int ID of warehouse
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->stock->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
// Check mandatory fields
$result = $this->_validate($request_data);
foreach ($request_data as $field => $value) {
$this->warehouse->$field = $value;
}
if ($this->warehouse->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating warehouse", array_merge(array($this->warehouse->error), $this->warehouse->errors));
}
return $this->warehouse->id;
}
foreach ($request_data as $field => $value) {
$this->warehouse->$field = $value;
}
if ($this->warehouse->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating warehouse", array_merge(array($this->warehouse->error), $this->warehouse->errors));
}
return $this->warehouse->id;
}
/**
* Update warehouse
*
* @param int $id Id of warehouse to update
* @param array $request_data Datas
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->stock->creer) {
throw new RestException(401);
}
/**
* Update warehouse
*
* @param int $id Id of warehouse to update
* @param array $request_data Datas
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->stock->creer) {
throw new RestException(401);
}
$result = $this->warehouse->fetch($id);
if (!$result) {
throw new RestException(404, 'warehouse not found');
}
$result = $this->warehouse->fetch($id);
if (!$result) {
throw new RestException(404, 'warehouse not found');
}
if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->warehouse->$field = $value;
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->warehouse->$field = $value;
}
if ($this->warehouse->update($id, DolibarrApiAccess::$user))
return $this->get($id);
if ($this->warehouse->update($id, DolibarrApiAccess::$user))
return $this->get($id);
return false;
}
return false;
}
/**
* Delete warehouse
*
* @param int $id Warehouse ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->stock->supprimer) {
throw new RestException(401);
}
$result = $this->warehouse->fetch($id);
if (!$result) {
throw new RestException(404, 'warehouse not found');
}
/**
* Delete warehouse
*
* @param int $id Warehouse ID
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->stock->supprimer) {
throw new RestException(401);
}
$result = $this->warehouse->fetch($id);
if (!$result) {
throw new RestException(404, 'warehouse not found');
}
if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$this->warehouse->delete(DolibarrApiAccess::$user)) {
throw new RestException(401, 'error when delete warehouse');
}
if (!$this->warehouse->delete(DolibarrApiAccess::$user)) {
throw new RestException(401, 'error when delete warehouse');
}
return array(
'success' => array(
'code' => 200,
'message' => 'Warehouse deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Warehouse deleted'
)
);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Entrepot $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Entrepot $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// Remove the subscriptions because they are handled as a subresource.
//unset($object->subscriptions);
// Remove the subscriptions because they are handled as a subresource.
//unset($object->subscriptions);
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$warehouse = array();
foreach (Warehouses::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$warehouse[$field] = $data[$field];
}
return $warehouse;
}
/**
* Validate fields before create or update object
*
* @param array|null $data Data to validate
* @return array
*
* @throws RestException
*/
private function _validate($data)
{
$warehouse = array();
foreach (Warehouses::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$warehouse[$field] = $data[$field];
}
return $warehouse;
}
}

View File

@ -309,24 +309,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
$shownav = 1;
if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0;
$shownav = 1;
if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0;
dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch');
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent">'."\n";
print '<table class="border centpercent">'."\n";
// Product
print '<tr><td class="titlefield">'.$langs->trans("Product").'</td><td>';
$producttmp = new Product($db);
$producttmp->fetch($object->fk_product);
print $producttmp->getNomUrl(1, 'stock')." - ".$producttmp->label;
print '</td></tr>';
print '<tr><td class="titlefield">'.$langs->trans("Product").'</td><td>';
$producttmp = new Product($db);
$producttmp->fetch($object->fk_product);
print $producttmp->getNomUrl(1, 'stock')." - ".$producttmp->label;
print '</td></tr>';
// Eat by
// Eat by
if (empty($conf->global->PRODUCT_DISABLE_EATBY)) {
print '<tr><td>';
print $form->editfieldkey($langs->trans('EatByDate'), 'eatby', $object->eatby, $object, $user->rights->stock->creer, 'datepicker');

View File

@ -30,284 +30,284 @@
class Projects extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'ref',
'title'
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'ref',
'title'
);
/**
* @var Project $project {@type Project}
*/
public $project;
/**
* @var Project $project {@type Project}
*/
public $project;
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->project = new Project($this->db);
$this->task = new Task($this->db);
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->project = new Project($this->db);
$this->task = new Task($this->db);
}
/**
* Get properties of a project object
*
* Return an array with project informations
*
* @param int $id ID of project
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->projet->lire) {
throw new RestException(401);
}
/**
* Get properties of a project object
*
* Return an array with project informations
*
* @param int $id ID of project
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->projet->lire) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->project->fetchObjectLinked();
return $this->_cleanObjectDatas($this->project);
}
$this->project->fetchObjectLinked();
return $this->_cleanObjectDatas($this->project);
}
/**
* List projects
*
* Get a list of projects
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $thirdparty_ids Thirdparty ids to filter projects of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
/**
* List projects
*
* Get a list of projects
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $thirdparty_ids Thirdparty ids to filter projects of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
* @param int $category Use this param to filter list by category
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of project objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '')
{
global $db, $conf;
* @return array Array of project objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT t.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
if ($category > 0) {
$sql = "SELECT t.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_project as c";
}
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('project').')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
// Select projects of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_project = t.rowid ";
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= ' WHERE t.entity IN ('.getEntity('project').')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
// Select projects of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_project = t.rowid ";
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
dol_syslog("API Rest request");
$result = $this->db->query($sql);
dol_syslog("API Rest request");
$result = $this->db->query($sql);
if ($result)
{
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
if ($result)
{
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0;
while ($i < $min) {
$obj = $this->db->fetch_object($result);
$project_static = new Project($this->db);
if ($project_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($project_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve project list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No project found');
}
return $obj_ret;
}
while ($i < $min) {
$obj = $this->db->fetch_object($result);
$project_static = new Project($this->db);
if ($project_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($project_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve project list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No project found');
}
return $obj_ret;
}
/**
* Create project object
*
* @param array $request_data Request data
* @return int ID of project
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->projet->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validate($request_data);
/**
* Create project object
*
* @param array $request_data Request data
* @return int ID of project
*/
public function post($request_data = null)
{
if (!DolibarrApiAccess::$user->rights->projet->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach ($request_data as $field => $value) {
$this->project->$field = $value;
}
/*if (isset($request_data["lines"])) {
foreach ($request_data as $field => $value) {
$this->project->$field = $value;
}
/*if (isset($request_data["lines"])) {
$lines = array();
foreach ($request_data["lines"] as $line) {
array_push($lines, (object) $line);
}
$this->project->lines = $lines;
}*/
if ($this->project->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
}
if ($this->project->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
}
return $this->project->id;
}
return $this->project->id;
}
/**
* Get tasks of a project.
* See also API /tasks
*
* @param int $id Id of project
* @param int $includetimespent 0=Return only list of tasks. 1=Include a summary of time spent, 2=Include details of time spent lines (2 is no implemented yet)
* @return int
*
* @url GET {id}/tasks
*/
public function getLines($id, $includetimespent = 0)
{
if (!DolibarrApiAccess::$user->rights->projet->lire) {
throw new RestException(401);
}
/**
* Get tasks of a project.
* See also API /tasks
*
* @param int $id Id of project
* @param int $includetimespent 0=Return only list of tasks. 1=Include a summary of time spent, 2=Include details of time spent lines (2 is no implemented yet)
* @return int
*
* @url GET {id}/tasks
*/
public function getLines($id, $includetimespent = 0)
{
if (!DolibarrApiAccess::$user->rights->projet->lire) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->project->getLinesArray(DolibarrApiAccess::$user);
$result = array();
foreach ($this->project->lines as $line) // $line is a task
{
if ($includetimespent == 1)
{
$timespent = $line->getSummaryOfTimeSpent(0);
}
if ($includetimespent == 1)
{
// TODO
// Add class for timespent records and loop and fill $line->lines with records of timespent
}
array_push($result, $this->_cleanObjectDatas($line));
}
return $result;
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->project->getLinesArray(DolibarrApiAccess::$user);
$result = array();
foreach ($this->project->lines as $line) // $line is a task
{
if ($includetimespent == 1)
{
$timespent = $line->getSummaryOfTimeSpent(0);
}
if ($includetimespent == 1)
{
// TODO
// Add class for timespent records and loop and fill $line->lines with records of timespent
}
array_push($result, $this->_cleanObjectDatas($line));
}
return $result;
}
/**
* Get roles a user is assigned to a project with
*
* @param int $id Id of project
* @param int $userid Id of user (0 = connected user)
*
* @url GET {id}/roles
*
* @return int
*/
public function getRoles($id, $userid = 0)
{
global $db;
/**
* Get roles a user is assigned to a project with
*
* @param int $id Id of project
* @param int $userid Id of user (0 = connected user)
*
* @url GET {id}/roles
*
* @return int
*/
public function getRoles($id, $userid = 0)
{
global $db;
if (!DolibarrApiAccess::$user->rights->projet->lire) {
throw new RestException(401);
}
if (!DolibarrApiAccess::$user->rights->projet->lire) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
$taskstatic = new Task($this->db);
$userp = DolibarrApiAccess::$user;
if ($userid > 0)
{
$userp = new User($this->db);
$userp->fetch($userid);
}
$this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, 0, $id, 0);
$result = array();
foreach ($this->project->roles as $line) {
array_push($result, $this->_cleanObjectDatas($line));
}
return $result;
}
require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
$taskstatic = new Task($this->db);
$userp = DolibarrApiAccess::$user;
if ($userid > 0)
{
$userp = new User($this->db);
$userp->fetch($userid);
}
$this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, 0, $id, 0);
$result = array();
foreach ($this->project->roles as $line) {
array_push($result, $this->_cleanObjectDatas($line));
}
return $result;
}
/**
* Add a task to given project
*
* @param int $id Id of project to update
* @param array $request_data Projectline data
*
* @url POST {id}/tasks
*
* @return int
*/
/*
/**
* Add a task to given project
*
* @param int $id Id of project to update
* @param array $request_data Projectline data
*
* @url POST {id}/tasks
*
* @return int
*/
/*
public function postLine($id, $request_data = null)
{
if(! DolibarrApiAccess::$user->rights->projet->creer) {
@ -420,194 +420,194 @@ class Projects extends DolibarrApi
/**
* Update project general fields (won't touch lines of project)
*
* @param int $id Id of project to update
* @param array $request_data Datas
*
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->projet->creer) {
throw new RestException(401);
}
/**
* Update project general fields (won't touch lines of project)
*
* @param int $id Id of project to update
* @param array $request_data Datas
*
* @return int
*/
public function put($id, $request_data = null)
{
if (!DolibarrApiAccess::$user->rights->projet->creer) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if ($result <= 0) {
throw new RestException(404, 'Project not found');
}
$result = $this->project->fetch($id);
if ($result <= 0) {
throw new RestException(404, 'Project not found');
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->project->$field = $value;
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value) {
if ($field == 'id') continue;
$this->project->$field = $value;
}
if ($this->project->update(DolibarrApiAccess::$user) >= 0)
{
return $this->get($id);
} else {
throw new RestException(500, $this->project->error);
}
}
if ($this->project->update(DolibarrApiAccess::$user) >= 0)
{
return $this->get($id);
} else {
throw new RestException(500, $this->project->error);
}
}
/**
* Delete project
*
* @param int $id Project ID
*
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->projet->supprimer) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
/**
* Delete project
*
* @param int $id Project ID
*
* @return array
*/
public function delete($id)
{
if (!DolibarrApiAccess::$user->rights->projet->supprimer) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!$this->project->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete project : '.$this->project->error);
}
if (!$this->project->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete project : '.$this->project->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Project deleted'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Project deleted'
)
);
}
/**
* Validate a project.
* You can test this API with the following input message
* { "notrigger": 0 }
*
* @param int $id Project ID
* @param int $notrigger 1=Does not execute triggers, 0= execute triggers
*
* @url POST {id}/validate
*
* @return array
* FIXME An error 403 is returned if the request has an empty body.
* Error message: "Forbidden: Content type `text/plain` is not supported."
* Workaround: send this in the body
* {
* "notrigger": 0
* }
*/
public function validate($id, $notrigger = 0)
{
if (!DolibarrApiAccess::$user->rights->projet->creer) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
/**
* Validate a project.
* You can test this API with the following input message
* { "notrigger": 0 }
*
* @param int $id Project ID
* @param int $notrigger 1=Does not execute triggers, 0= execute triggers
*
* @url POST {id}/validate
*
* @return array
* FIXME An error 403 is returned if the request has an empty body.
* Error message: "Forbidden: Content type `text/plain` is not supported."
* Workaround: send this in the body
* {
* "notrigger": 0
* }
*/
public function validate($id, $notrigger = 0)
{
if (!DolibarrApiAccess::$user->rights->projet->creer) {
throw new RestException(401);
}
$result = $this->project->fetch($id);
if (!$result) {
throw new RestException(404, 'Project not found');
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger);
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already validated');
}
if ($result < 0) {
throw new RestException(500, 'Error when validating Project: '.$this->project->error);
}
$result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger);
if ($result == 0) {
throw new RestException(304, 'Error nothing done. May be object is already validated');
}
if ($result < 0) {
throw new RestException(500, 'Error when validating Project: '.$this->project->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Project validated'
)
);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Project validated'
)
);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->datec);
unset($object->datem);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->fk_account);
unset($object->note);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->mode_reglement_id);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->datec);
unset($object->datem);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);
unset($object->cond_reglement_id);
unset($object->cond_reglement);
unset($object->fk_delivery_address);
unset($object->shipping_method_id);
unset($object->fk_account);
unset($object->note);
unset($object->fk_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->mode_reglement_id);
unset($object->country);
unset($object->country_id);
unset($object->country_code);
unset($object->weekWorkLoad);
unset($object->weekWorkLoad);
unset($object->weekWorkLoad);
unset($object->weekWorkLoad);
//unset($object->lines); // for task we use timespent_lines, but for project we use lines
//unset($object->lines); // for task we use timespent_lines, but for project we use lines
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->comments);
unset($object->comments);
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$object = array();
foreach (self::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$object[$field] = $data[$field];
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$object = array();
foreach (self::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$object[$field] = $data[$field];
}
return $object;
}
// TODO
// getSummaryOfTimeSpent
// TODO
// getSummaryOfTimeSpent
}

View File

@ -550,8 +550,8 @@ class Tasks extends DolibarrApi
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{

View File

@ -1159,325 +1159,325 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
}
}
dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error');
dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error');
print '<form enctype="multipart/form-data" action="'.$_SERVER["PHP_SELF"].'" method="post" name="formsoc" autocomplete="off">'; // Chrome ignor autocomplete
print '<form enctype="multipart/form-data" action="'.$_SERVER["PHP_SELF"].'" method="post" name="formsoc" autocomplete="off">'; // Chrome ignor autocomplete
print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="private" value='.$object->particulier.'>';
print '<input type="hidden" name="type" value='.GETPOST("type", 'alpha').'>';
print '<input type="hidden" name="LastName" value="'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName').'">';
print '<input type="hidden" name="ThirdPartyName" value="'.$langs->trans('ThirdPartyName').'">';
if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print '<input type="hidden" name="code_auto" value="1">';
print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="private" value='.$object->particulier.'>';
print '<input type="hidden" name="type" value='.GETPOST("type", 'alpha').'>';
print '<input type="hidden" name="LastName" value="'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName').'">';
print '<input type="hidden" name="ThirdPartyName" value="'.$langs->trans('ThirdPartyName').'">';
if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print '<input type="hidden" name="code_auto" value="1">';
print dol_get_fiche_head(null, 'card', '', 0, '');
print dol_get_fiche_head(null, 'card', '', 0, '');
print '<table class="border centpercent">';
print '<table class="border centpercent">';
// Name, firstname
print '<tr class="tr-field-thirdparty-name"><td class="titlefieldcreate tdtop">';
if ($object->particulier || $private)
{
print '<span id="TypeName" class="fieldrequired">'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName', 'name').'</span>';
} else {
// Name, firstname
print '<tr class="tr-field-thirdparty-name"><td class="titlefieldcreate tdtop">';
if ($object->particulier || $private)
{
print '<span id="TypeName" class="fieldrequired">'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName', 'name').'</span>';
} else {
print '<span id="TypeName" class="fieldrequired">'.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0).'</span>';
}
print '</td><td'.(empty($conf->global->SOCIETE_USEPREFIX) ? ' colspan="3"' : '').'>';
print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus">';
print $form->widgetForTranslation("name", $object, $permissiontoadd, 'string', 'alpahnohtml', 'minwidth300');
print '</td>';
if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field
{
print '<td>'.$langs->trans('Prefix').'</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="'.dol_escape_htmltag($object->prefix_comm).'"></td>';
}
print '</tr>';
}
print '</td><td'.(empty($conf->global->SOCIETE_USEPREFIX) ? ' colspan="3"' : '').'>';
print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus">';
print $form->widgetForTranslation("name", $object, $permissiontoadd, 'string', 'alpahnohtml', 'minwidth300');
print '</td>';
if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field
{
print '<td>'.$langs->trans('Prefix').'</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="'.dol_escape_htmltag($object->prefix_comm).'"></td>';
}
print '</tr>';
// If javascript on, we show option individual
if ($conf->use_javascript_ajax)
{
if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION))
{
// Firstname
print '<tr class="individualline"><td>'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'</td>';
print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="firstname" id="firstname" value="'.dol_escape_htmltag($object->firstname).'"></td>';
print '</tr>';
// If javascript on, we show option individual
if ($conf->use_javascript_ajax)
{
if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION))
{
// Firstname
print '<tr class="individualline"><td>'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'</td>';
print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="firstname" id="firstname" value="'.dol_escape_htmltag($object->firstname).'"></td>';
print '</tr>';
// Title
print '<tr class="individualline"><td>'.$form->editfieldkey('UserTitle', 'civility_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
print $formcompany->select_civility($object->civility_id, 'civility_id', 'maxwidth100').'</td>';
print '</tr>';
}
}
// Title
print '<tr class="individualline"><td>'.$form->editfieldkey('UserTitle', 'civility_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
print $formcompany->select_civility($object->civility_id, 'civility_id', 'maxwidth100').'</td>';
print '</tr>';
}
}
// Alias names (commercial, trademark or alias names)
print '<tr id="name_alias"><td><label for="name_alias_input">'.$langs->trans('AliasNames').'</label></td>';
print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.dol_escape_htmltag($object->name_alias).'"></td></tr>';
// Alias names (commercial, trademark or alias names)
print '<tr id="name_alias"><td><label for="name_alias_input">'.$langs->trans('AliasNames').'</label></td>';
print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.dol_escape_htmltag($object->name_alias).'"></td></tr>';
// Prospect/Customer
print '<tr><td class="titlefieldcreate">'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).'</td>';
print '<td class="maxwidthonsmartphone">';
$selected = (GETPOSTISSET('client') ?GETPOST('client', 'int') : $object->client);
print $formcompany->selectProspectCustomerType($selected);
print '</td>';
// Prospect/Customer
print '<tr><td class="titlefieldcreate">'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).'</td>';
print '<td class="maxwidthonsmartphone">';
$selected = (GETPOSTISSET('client') ?GETPOST('client', 'int') : $object->client);
print $formcompany->selectProspectCustomerType($selected);
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).'</td><td>';
print '<table class="nobordernopadding"><tr><td>';
print '<td>'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).'</td><td>';
print '<table class="nobordernopadding"><tr><td>';
$tmpcode = $object->code_client;
if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0);
print '<input type="text" name="customer_code" id="customer_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
print '</td><td>';
$s = $modCodeClient->getToolTip($langs, $object, 0);
print $form->textwithpicto('', $s, 1);
print '</td></tr></table>';
print '</td></tr>';
if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0);
print '<input type="text" name="customer_code" id="customer_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
print '</td><td>';
$s = $modCodeClient->getToolTip($langs, $object, 0);
print $form->textwithpicto('', $s, 1);
print '</td></tr></table>';
print '</td></tr>';
if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire))
|| (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire)))
{
// Supplier
print '<tr>';
print '<td>'.$form->editfieldkey('Vendor', 'fournisseur', '', $object, 0, 'string', '', 1).'</td><td>';
$default = -1;
if (!empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) $default = 1;
print $form->selectyesno("fournisseur", (GETPOST('fournisseur', 'int') != '' ? GETPOST('fournisseur', 'int') : (GETPOST("type", 'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type", 'alpha') == '' ? 1 : 0));
print '</td>';
if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire))
|| (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire)))
{
// Supplier
print '<tr>';
print '<td>'.$form->editfieldkey('Vendor', 'fournisseur', '', $object, 0, 'string', '', 1).'</td><td>';
$default = -1;
if (!empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) $default = 1;
print $form->selectyesno("fournisseur", (GETPOST('fournisseur', 'int') != '' ? GETPOST('fournisseur', 'int') : (GETPOST("type", 'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type", 'alpha') == '' ? 1 : 0));
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>';
if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire))
{
print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);
}
print '</td><td>';
if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire))
{
print '<table class="nobordernopadding"><tr><td>';
$tmpcode = $object->code_fournisseur;
if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1);
print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
print '</td><td>';
$s = $modCodeFournisseur->getToolTip($langs, $object, 1);
print $form->textwithpicto('', $s, 1);
print '</td></tr></table>';
}
print '</td></tr>';
}
print '<td>';
if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire))
{
print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);
}
print '</td><td>';
if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire))
{
print '<table class="nobordernopadding"><tr><td>';
$tmpcode = $object->code_fournisseur;
if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1);
print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
print '</td><td>';
$s = $modCodeFournisseur->getToolTip($langs, $object, 1);
print $form->textwithpicto('', $s, 1);
print '</td></tr></table>';
}
print '</td></tr>';
}
// Status
print '<tr><td>'.$form->editfieldkey('Status', 'status', '', $object, 0).'</td><td colspan="3">';
print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1);
print '</td></tr>';
// Status
print '<tr><td>'.$form->editfieldkey('Status', 'status', '', $object, 0).'</td><td colspan="3">';
print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1);
print '</td></tr>';
// Barcode
if (!empty($conf->barcode->enabled))
{
print '<tr><td>'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>';
print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">';
print '</td></tr>';
}
// Barcode
if (!empty($conf->barcode->enabled))
{
print '<tr><td>'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>';
print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.dol_escape_htmltag($object->barcode).'">';
print '</td></tr>';
}
// Address
print '<tr><td class="tdtop">';
print $form->editfieldkey('Address', 'address', '', $object, 0);
print '</td>';
print '<td colspan="3">';
print '<textarea name="address" id="address" class="quatrevingtpercent" rows="'.ROWS_2.'" wrap="soft">';
print dol_escape_htmltag($object->address);
print '</textarea>';
print $form->widgetForTranslation("address", $object, $permissiontoadd, 'textarea', 'alphanohtml', 'quatrevingtpercent');
print '</td></tr>';
// Address
print '<tr><td class="tdtop">';
print $form->editfieldkey('Address', 'address', '', $object, 0);
print '</td>';
print '<td colspan="3">';
print '<textarea name="address" id="address" class="quatrevingtpercent" rows="'.ROWS_2.'" wrap="soft">';
print dol_escape_htmltag($object->address);
print '</textarea>';
print $form->widgetForTranslation("address", $object, $permissiontoadd, 'textarea', 'alphanohtml', 'quatrevingtpercent');
print '</td></tr>';
// Zip / Town
print '<tr><td>'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).'</td><td>';
print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent');
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td class="tdtop">'.$form->editfieldkey('Town', 'town', '', $object, 0).'</td><td>';
print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent');
print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent');
print '</td></tr>';
// Zip / Town
print '<tr><td>'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).'</td><td>';
print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent');
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td class="tdtop">'.$form->editfieldkey('Town', 'town', '', $object, 0).'</td><td>';
print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent');
print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent');
print '</td></tr>';
// Country
print '<tr><td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
print img_picto('', 'globe-americas', 'class="paddingrightonly"');
print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
print '</td></tr>';
// Country
print '<tr><td>'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
print img_picto('', 'globe-americas', 'class="paddingrightonly"');
print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
print '</td></tr>';
// State
if (empty($conf->global->SOCIETE_DISABLE_STATE))
{
if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
{
print '<tr><td>'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
} else {
print '<tr><td>'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
}
// State
if (empty($conf->global->SOCIETE_DISABLE_STATE))
{
if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
{
print '<tr><td>'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
} else {
print '<tr><td>'.$form->editfieldkey('State', 'state_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
}
if ($object->country_id) print $formcompany->select_state($object->state_id, $object->country_code);
else print $countrynotdefined;
print '</td></tr>';
}
if ($object->country_id) print $formcompany->select_state($object->state_id, $object->country_code);
else print $countrynotdefined;
print '</td></tr>';
}
// Phone / Fax
print '<tr><td>'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'</td>';
print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning').' <input type="text" name="phone" id="phone" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('phone') ?GETPOST('phone', 'alpha') : $object->phone).'"></td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'</td>';
print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning_fax').' <input type="text" name="fax" id="fax" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('fax') ?GETPOST('fax', 'alpha') : $object->fax).'"></td></tr>';
// Phone / Fax
print '<tr><td>'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'</td>';
print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning').' <input type="text" name="phone" id="phone" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('phone') ?GETPOST('phone', 'alpha') : $object->phone).'"></td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'</td>';
print '<td'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning_fax').' <input type="text" name="fax" id="fax" class="maxwidth200 widthcentpercentminusx" value="'.(GETPOSTISSET('fax') ?GETPOST('fax', 'alpha') : $object->fax).'"></td></tr>';
// Email / Web
print '<tr><td>'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', $conf->global->SOCIETE_EMAIL_MANDATORY).'</td>';
print '<td colspan="3">'.img_picto('', 'object_email').' <input type="text" class="widthcentpercentminusx" name="email" id="email" value="'.$object->email.'"></td></tr>';
print '<tr><td>'.$form->editfieldkey('Web', 'url', '', $object, 0).'</td>';
print '<td colspan="3">'.img_picto('', 'globe').' <input type="text" class="widthcentpercentminusx" name="url" id="url" value="'.$object->url.'"></td></tr>';
// Email / Web
print '<tr><td>'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', $conf->global->SOCIETE_EMAIL_MANDATORY).'</td>';
print '<td colspan="3">'.img_picto('', 'object_email').' <input type="text" class="widthcentpercentminusx" name="email" id="email" value="'.$object->email.'"></td></tr>';
print '<tr><td>'.$form->editfieldkey('Web', 'url', '', $object, 0).'</td>';
print '<td colspan="3">'.img_picto('', 'globe').' <input type="text" class="widthcentpercentminusx" name="url" id="url" value="'.$object->url.'"></td></tr>';
if (!empty($conf->socialnetworks->enabled)) {
foreach ($socialnetworks as $key => $value) {
if ($value['active']) {
print '<tr>';
print '<td><label for="'.$value['label'].'">'.$form->editfieldkey($value['label'], $key, '', $object, 0).'</label></td>';
print '<td colspan="3">';
print '<input type="text" name="'.$key.'" id="'.$key.'" class="minwidth100" maxlength="80" value="'.dol_escape_htmltag(GETPOSTISSET($key) ?GETPOST($key, 'alphanohtml') : $object->socialnetworks[$key]).'">';
print '</td>';
print '</tr>';
} elseif (!empty($object->socialnetworks[$key])) {
print '<input type="hidden" name="'.$key.'" value="'.$object->socialnetworks[$key].'">';
}
}
}
if (!empty($conf->socialnetworks->enabled)) {
foreach ($socialnetworks as $key => $value) {
if ($value['active']) {
print '<tr>';
print '<td><label for="'.$value['label'].'">'.$form->editfieldkey($value['label'], $key, '', $object, 0).'</label></td>';
print '<td colspan="3">';
print '<input type="text" name="'.$key.'" id="'.$key.'" class="minwidth100" maxlength="80" value="'.dol_escape_htmltag(GETPOSTISSET($key) ?GETPOST($key, 'alphanohtml') : $object->socialnetworks[$key]).'">';
print '</td>';
print '</tr>';
} elseif (!empty($object->socialnetworks[$key])) {
print '<input type="hidden" name="'.$key.'" value="'.$object->socialnetworks[$key].'">';
}
}
}
// Prof ids
$i = 1; $j = 0; $NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2);
while ($i <= 6)
{
$idprof = $langs->transcountry('ProfId'.$i, $object->country_code);
if ($idprof != '-')
{
$key = 'idprof'.$i;
// Prof ids
$i = 1; $j = 0; $NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2);
while ($i <= 6)
{
$idprof = $langs->transcountry('ProfId'.$i, $object->country_code);
if ($idprof != '-')
{
$key = 'idprof'.$i;
if (($j % $NBCOLS) == 0) print '<tr>';
if (($j % $NBCOLS) == 0) print '<tr>';
$idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY';
print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', (empty($conf->global->$idprof_mandatory) ? 0 : 1)).'</td><td>';
$idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY';
print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', (empty($conf->global->$idprof_mandatory) ? 0 : 1)).'</td><td>';
print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code);
print '</td>';
if (($j % $NBCOLS) == ($NBCOLS - 1)) print '</tr>';
$j++;
}
$i++;
}
if ($NBCOLS > 1 && ($j % 2 == 1)) print '<td colspan="2"></td></tr>';
print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code);
print '</td>';
if (($j % $NBCOLS) == ($NBCOLS - 1)) print '</tr>';
$j++;
}
$i++;
}
if ($NBCOLS > 1 && ($j % 2 == 1)) print '<td colspan="2"></td></tr>';
// Vat is used
print '<tr><td>'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).'</td>';
print '<td>';
print $form->selectyesno('assujtva_value', GETPOSTISSET('assujtva_value') ?GETPOST('assujtva_value', 'int') : 1, 1); // Assujeti par defaut en creation
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td class="nowrap">'.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).'</td>';
print '<td class="nowrap">';
$s = '<input type="text" class="flat maxwidthonsmartphone" name="tva_intra" id="intra_vat" maxlength="20" value="'.$object->tva_intra.'">';
// Vat is used
print '<tr><td>'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).'</td>';
print '<td>';
print $form->selectyesno('assujtva_value', GETPOSTISSET('assujtva_value') ?GETPOST('assujtva_value', 'int') : 1, 1); // Assujeti par defaut en creation
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td class="nowrap">'.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).'</td>';
print '<td class="nowrap">';
$s = '<input type="text" class="flat maxwidthonsmartphone" name="tva_intra" id="intra_vat" maxlength="20" value="'.$object->tva_intra.'">';
if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object))
{
$s .= ' ';
if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object))
{
$s .= ' ';
if (!empty($conf->use_javascript_ajax))
{
$widthpopup = 600;
if (!empty($conf->dol_use_jmobile)) $widthpopup = 350;
$heightpopup = 400;
print "\n";
print '<script language="JavaScript" type="text/javascript">';
print "function CheckVAT(a) {\n";
print "newpopup('".DOL_URL_ROOT."/societe/checkvat/checkVatPopup.php?vatNumber='+a, '".dol_escape_js($langs->trans("VATIntraCheckableOnEUSite"))."', ".$widthpopup.", ".$heightpopup.");\n";
print "}\n";
print '</script>';
print "\n";
$s .= '<a href="#" class="hideonsmartphone" onclick="javascript: CheckVAT(document.formsoc.tva_intra.value);">'.$langs->trans("VATIntraCheck").'</a>';
$s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1);
} else {
$s .= '<a href="'.$langs->transcountry("VATIntraCheckURL", $object->country_id).'" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').'</a>';
}
}
print $s;
print '</td>';
print '</tr>';
if (!empty($conf->use_javascript_ajax))
{
$widthpopup = 600;
if (!empty($conf->dol_use_jmobile)) $widthpopup = 350;
$heightpopup = 400;
print "\n";
print '<script language="JavaScript" type="text/javascript">';
print "function CheckVAT(a) {\n";
print "newpopup('".DOL_URL_ROOT."/societe/checkvat/checkVatPopup.php?vatNumber='+a, '".dol_escape_js($langs->trans("VATIntraCheckableOnEUSite"))."', ".$widthpopup.", ".$heightpopup.");\n";
print "}\n";
print '</script>';
print "\n";
$s .= '<a href="#" class="hideonsmartphone" onclick="javascript: CheckVAT(document.formsoc.tva_intra.value);">'.$langs->trans("VATIntraCheck").'</a>';
$s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1);
} else {
$s .= '<a href="'.$langs->transcountry("VATIntraCheckURL", $object->country_id).'" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').'</a>';
}
}
print $s;
print '</td>';
print '</tr>';
// Local Taxes
//TODO: Place into a function to control showing by country or study better option
if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1")
{
print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>';
print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1);
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>';
print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1);
print '</td></tr>';
} elseif ($mysoc->localtax1_assuj == "1")
{
print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td colspan="3">';
print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1);
print '</td></tr>';
} elseif ($mysoc->localtax2_assuj == "1")
{
print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td colspan="3">';
print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1);
print '</td></tr>';
}
// Local Taxes
//TODO: Place into a function to control showing by country or study better option
if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1")
{
print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>';
print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1);
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>';
print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1);
print '</td></tr>';
} elseif ($mysoc->localtax1_assuj == "1")
{
print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td colspan="3">';
print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1);
print '</td></tr>';
} elseif ($mysoc->localtax2_assuj == "1")
{
print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td colspan="3">';
print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1);
print '</td></tr>';
}
// Type - Workforce/Staff
print '<tr><td>'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'."\n";
$sortparam = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label.
print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 0, 0, 0, '', 0, 0, 0, $sortparam);
if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>';
print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id);
if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
print '</td></tr>';
// Type - Workforce/Staff
print '<tr><td>'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>'."\n";
$sortparam = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label.
print $form->selectarray("typent_id", $formcompany->typent_array(0), $object->typent_id, 0, 0, 0, '', 0, 0, 0, $sortparam);
if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
print '</td>';
if ($conf->browser->layout == 'phone') print '</tr><tr>';
print '<td>'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'</td><td class="maxwidthonsmartphone"'.($conf->browser->layout == 'phone' ? ' colspan="3"' : '').'>';
print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id);
if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
print '</td></tr>';
// Legal Form
print '<tr><td>'.$form->editfieldkey('JuridicalStatus', 'forme_juridique_code', '', $object, 0).'</td>';
print '<td colspan="3" class="maxwidthonsmartphone">';
if ($object->country_id)
{
print $formcompany->select_juridicalstatus($object->forme_juridique_code, $object->country_code, '', 'forme_juridique_code');
} else {
print $countrynotdefined;
}
print '</td></tr>';
// Legal Form
print '<tr><td>'.$form->editfieldkey('JuridicalStatus', 'forme_juridique_code', '', $object, 0).'</td>';
print '<td colspan="3" class="maxwidthonsmartphone">';
if ($object->country_id)
{
print $formcompany->select_juridicalstatus($object->forme_juridique_code, $object->country_code, '', 'forme_juridique_code');
} else {
print $countrynotdefined;
}
print '</td></tr>';
// Capital
print '<tr><td>'.$form->editfieldkey('Capital', 'capital', '', $object, 0).'</td>';
print '<td colspan="3"><input type="text" name="capital" id="capital" class="maxwidth100" value="'.$object->capital.'"> ';
print '<span class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</span></td></tr>';
// Capital
print '<tr><td>'.$form->editfieldkey('Capital', 'capital', '', $object, 0).'</td>';
print '<td colspan="3"><input type="text" name="capital" id="capital" class="maxwidth100" value="'.$object->capital.'"> ';
print '<span class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</span></td></tr>';
if (!empty($conf->global->MAIN_MULTILANGS))
{
print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'."\n";
print $formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone');
print '</td>';
print '</tr>';
}
if (!empty($conf->global->MAIN_MULTILANGS))
{
print '<tr><td>'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">'."\n";
print $formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone');
print '</td>';
print '</tr>';
}
// Incoterms
if (!empty($conf->incoterm->enabled))
{
print '<tr>';
print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>';
print '<td colspan="3" class="maxwidthonsmartphone">';
print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''));
print '<td colspan="3" class="maxwidthonsmartphone">';
print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''));
print '</td></tr>';
}

View File

@ -431,131 +431,131 @@ class Contacts extends DolibarrApi
}
return $result;
}
}
/**
* Add a category to a contact
*
* @url POST {id}/categories/{category_id}
*
* @param int $id Id of contact
* @param int $category_id Id of category
*
* @return mixed
*
* @throws RestException 401 Insufficient rights
* @throws RestException 404 Category or contact not found
*/
public function addCategory($id, $category_id)
{
if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
throw new RestException(401, 'Insufficient rights');
}
/**
* Add a category to a contact
*
* @url POST {id}/categories/{category_id}
*
* @param int $id Id of contact
* @param int $category_id Id of category
*
* @return mixed
*
* @throws RestException 401 Insufficient rights
* @throws RestException 404 Category or contact not found
*/
public function addCategory($id, $category_id)
{
if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
throw new RestException(401, 'Insufficient rights');
}
$result = $this->contact->fetch($id);
if (!$result) {
throw new RestException(404, 'Contact not found');
}
$category = new Categorie($this->db);
$result = $category->fetch($category_id);
if (!$result) {
throw new RestException(404, 'category not found');
}
$result = $this->contact->fetch($id);
if (!$result) {
throw new RestException(404, 'Contact not found');
}
$category = new Categorie($this->db);
$result = $category->fetch($category_id);
if (!$result) {
throw new RestException(404, 'category not found');
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$category->add_type($this->contact, 'contact');
$category->add_type($this->contact, 'contact');
return $this->_cleanObjectDatas($this->contact);
}
return $this->_cleanObjectDatas($this->contact);
}
/**
* Remove the link between a category and a contact
*
* @url DELETE {id}/categories/{category_id}
*
* @param int $id Id of contact
* @param int $category_id Id of category
* @return mixed
*
* @throws RestException 401 Insufficient rights
* @throws RestException 404 Category or contact not found
*/
public function deleteCategory($id, $category_id)
{
if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
throw new RestException(401, 'Insufficient rights');
}
/**
* Remove the link between a category and a contact
*
* @url DELETE {id}/categories/{category_id}
*
* @param int $id Id of contact
* @param int $category_id Id of category
* @return mixed
*
* @throws RestException 401 Insufficient rights
* @throws RestException 404 Category or contact not found
*/
public function deleteCategory($id, $category_id)
{
if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
throw new RestException(401, 'Insufficient rights');
}
$result = $this->contact->fetch($id);
if (!$result) {
throw new RestException(404, 'Contact not found');
}
$category = new Categorie($this->db);
$result = $category->fetch($category_id);
if (!$result) {
throw new RestException(404, 'category not found');
}
$result = $this->contact->fetch($id);
if (!$result) {
throw new RestException(404, 'Contact not found');
}
$category = new Categorie($this->db);
$result = $category->fetch($category_id);
if (!$result) {
throw new RestException(404, 'category not found');
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$category->del_type($this->contact, 'contact');
$category->del_type($this->contact, 'contact');
return $this->_cleanObjectDatas($this->contact);
}
return $this->_cleanObjectDatas($this->contact);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->total_ht);
unset($object->total_tva);
unset($object->total_localtax1);
unset($object->total_localtax2);
unset($object->total_ttc);
unset($object->note);
unset($object->lines);
unset($object->thirdparty);
unset($object->note);
unset($object->lines);
unset($object->thirdparty);
return $object;
}
return $object;
}
/**
* Validate fields before create or update object
*
* @param array|null $data Data to validate
* @return array
* @throws RestException
*/
private function _validate($data)
{
$contact = array();
foreach (Contacts::$FIELDS as $field) {
if (!isset($data[$field])) {
throw new RestException(400, "$field field missing");
}
$contact[$field] = $data[$field];
}
/**
* Validate fields before create or update object
*
* @param array|null $data Data to validate
* @return array
* @throws RestException
*/
private function _validate($data)
{
$contact = array();
foreach (Contacts::$FIELDS as $field) {
if (!isset($data[$field])) {
throw new RestException(400, "$field field missing");
}
$contact[$field] = $data[$field];
}
return $contact;
}
return $contact;
}
}

View File

@ -1303,10 +1303,10 @@ class Societe extends CommonObject
$sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
$sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
$sql .= ",transport_mode = ".(! empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
$sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
$sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
$sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
$sql .= ",transport_mode_supplier = ".(! empty($this->transport_mode_supplier_id)? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
$sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
$sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
$sql .= ",client = ".(!empty($this->client) ? $this->client : 0);

View File

@ -30,185 +30,185 @@ require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class
class Supplierproposals extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'socid'
);
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'socid'
);
/**
* @var SupplierProposal $supplier_proposal {@type SupplierProposal}
*/
public $supplier_proposal;
/**
* @var SupplierProposal $supplier_proposal {@type SupplierProposal}
*/
public $supplier_proposal;
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->supplier_proposal = new SupplierProposal($this->db);
}
/**
* Constructor
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->supplier_proposal = new SupplierProposal($this->db);
}
/**
* Get properties of a supplier proposal (price request) object
*
* Return an array with supplier proposal informations
*
* @param int $id ID of supplier proposal
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->supplier_proposal->lire) {
throw new RestException(401);
}
/**
* Get properties of a supplier proposal (price request) object
*
* Return an array with supplier proposal informations
*
* @param int $id ID of supplier proposal
* @return array|mixed data without useless information
*
* @throws RestException
*/
public function get($id)
{
if (!DolibarrApiAccess::$user->rights->supplier_proposal->lire) {
throw new RestException(401);
}
$result = $this->supplier_proposal->fetch($id);
if (!$result) {
throw new RestException(404, 'Supplier Proposal not found');
}
$result = $this->supplier_proposal->fetch($id);
if (!$result) {
throw new RestException(404, 'Supplier Proposal not found');
}
if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->propal->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->propal->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->supplier_proposal->fetchObjectLinked();
return $this->_cleanObjectDatas($this->supplier_proposal);
}
$this->supplier_proposal->fetchObjectLinked();
return $this->_cleanObjectDatas($this->supplier_proposal);
}
/**
* List supplier proposals
*
* Get a list of supplier proposals
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $thirdparty_ids Thirdparty ids to filter supplier proposals (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
* @return array Array of order objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
{
global $db, $conf;
/**
* List supplier proposals
*
* Get a list of supplier proposals
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $thirdparty_ids Thirdparty ids to filter supplier proposals (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
* @return array Array of order objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT t.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as t";
$sql = "SELECT t.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal 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('propal').')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
// Add sql filters
if ($sqlfilters)
{
if (!DolibarrApi::_checkFilters($sqlfilters))
{
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql .= $this->db->plimit($limit + 1, $offset);
}
$sql .= $this->db->plimit($limit + 1, $offset);
}
$result = $this->db->query($sql);
$result = $this->db->query($sql);
if ($result)
{
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0;
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$propal_static = new SupplierProposal($this->db);
if ($propal_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($propal_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No supplier proposal found');
}
return $obj_ret;
}
if ($result)
{
$num = $this->db->num_rows($result);
$min = min($num, ($limit <= 0 ? $num : $limit));
$i = 0;
while ($i < $min)
{
$obj = $this->db->fetch_object($result);
$propal_static = new SupplierProposal($this->db);
if ($propal_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($propal_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No supplier proposal found');
}
return $obj_ret;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$propal = array();
foreach (SupplierProposals::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$propal[$field] = $data[$field];
}
return $propal;
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
private function _validate($data)
{
$propal = array();
foreach (SupplierProposals::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$propal[$field] = $data[$field];
}
return $propal;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param Object $object Object to clean
* @return Object Object with cleaned properties
*/
protected function _cleanObjectDatas($object)
{
// phpcs:enable
$object = parent::_cleanObjectDatas($object);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->address);
unset($object->datec);
unset($object->datev);
unset($object->name);
unset($object->lastname);
unset($object->firstname);
unset($object->civility_id);
unset($object->address);
unset($object->datec);
unset($object->datev);
return $object;
}
return $object;
}
}

View File

@ -77,13 +77,13 @@ if ($action == 'getProducts') {
$result = $thirdparty->fetch('', '', '', $term);
if ($result && $thirdparty->id > 0) {
$rows = array();
$rows[] = array(
'rowid' => $thirdparty->id,
'name' => $thirdparty->name,
'barcode' => $thirdparty->barcode,
'object' => 'thirdparty'
);
$rows = array();
$rows[] = array(
'rowid' => $thirdparty->id,
'name' => $thirdparty->name,
'barcode' => $thirdparty->barcode,
'object' => 'thirdparty'
);
echo json_encode($rows);
exit;
}

File diff suppressed because it is too large Load Diff

View File

@ -159,7 +159,7 @@ class Diff
* @param string $start the starting index
* @return array array of diff
*/
private static function generatePartialDiff($table, $sequence1, $sequence2, $start)
private static function generatePartialDiff($table, $sequence1, $sequence2, $start)
{
// initialise the diff
$diff = array();

View File

@ -77,7 +77,7 @@ if ($action == 'validatenewpassword' && $username && $passwordhash)
{
// Clear session
unset($_SESSION['dol_login']);
$_SESSION['dol_loginmesg'] = $langs->trans('NewPasswordValidated'); // Save message for the session page
$_SESSION['dol_loginmesg'] = $langs->trans('NewPasswordValidated'); // Save message for the session page
$newpassword = $edituser->setPassword($user, $edituser->pass_temp, 0);
dol_syslog("passwordforgotten.php new password for user->id=".$edituser->id." validated in database");
@ -112,7 +112,7 @@ if ($action == 'buildnewpassword' && $username)
if ($result <= 0 && $edituser->error == 'USERNOTFOUND')
{
$message = '<div class="warning paddingtopbottom'.(empty($conf->global->MAIN_LOGIN_BACKGROUND) ? '' : ' backgroundsemitransparent').'">';
if (! $isanemail) {
if (!$isanemail) {
$message .= $langs->trans("IfLoginExistPasswordRequestSent");
} else {
$message .= $langs->trans("IfEmailExistPasswordRequestSent");
@ -134,7 +134,7 @@ if ($action == 'buildnewpassword' && $username)
if ($edituser->send_password($user, $newpassword, 1) > 0)
{
$message = '<div class="warning paddingtopbottom'.(empty($conf->global->MAIN_LOGIN_BACKGROUND) ? '' : ' backgroundsemitransparent').'">';
if (! $isanemail) {
if (!$isanemail) {
$message .= $langs->trans("IfLoginExistPasswordRequestSent");
} else {
$message .= $langs->trans("IfEmailExistPasswordRequestSent");

View File

@ -571,7 +571,7 @@ function createInvoice($authentication, $invoice)
$res = $soc->fetch($new_invoice->socid);
if ($res > 0) {
$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'];

View File

@ -245,23 +245,23 @@ class Website extends CommonObject
}
}
// Uncomment this and change MYOBJECT to your own tag if you
// want this action to call a trigger.
// if (!$notrigger) {
// Uncomment this and change MYOBJECT to your own tag if you
// want this action to call a trigger.
// if (!$notrigger) {
// // Call triggers
// $result = $this->call_trigger('MYOBJECT_CREATE',$user);
// if ($result < 0) $error++;
// // End call triggers
// }
}
// // Call triggers
// $result = $this->call_trigger('MYOBJECT_CREATE',$user);
// if ($result < 0) $error++;
// // End call triggers
// }
}
if (!$error) {
$stringtodolibarrfile = "# Some properties for Dolibarr web site CMS\n";
$stringtodolibarrfile .= "param=value\n";
//print $conf->website->dir_output.'/'.$this->ref.'/.dolibarr';exit;
file_put_contents($conf->website->dir_output.'/'.$this->ref.'/.dolibarr', $stringtodolibarrfile);
}
if (!$error) {
$stringtodolibarrfile = "# Some properties for Dolibarr web site CMS\n";
$stringtodolibarrfile .= "param=value\n";
//print $conf->website->dir_output.'/'.$this->ref.'/.dolibarr';exit;
file_put_contents($conf->website->dir_output.'/'.$this->ref.'/.dolibarr', $stringtodolibarrfile);
}
// Commit or rollback
if ($error) {

View File

@ -178,34 +178,34 @@ if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) {
dol_syslog("cron_run_jobs.php we work on another entity conf than ".$conf->entity." so we reload mysoc, langs, user and conf", LOG_DEBUG);
echo " -> we change entity so we reload mysoc, langs, user and conf";
$conf->entity = (empty($line->entity) ? 1 : $line->entity);
$conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
$mysoc->setMysoc($conf);
$conf->entity = (empty($line->entity) ? 1 : $line->entity);
$conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
$mysoc->setMysoc($conf);
// Force recheck that user is ok for the entity to process and reload permission for entity
if ($conf->entity != $user->entity && $user->entity != 0)
{
$result = $user->fetch('', $userlogin, '', 0, $conf->entity);
if ($result < 0)
{
echo "\nUser Error: ".$user->error."\n";
dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
exit(-1);
} else {
if ($result == 0)
{
echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n";
dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
exit(-1);
}
}
$user->getrights();
}
// Force recheck that user is ok for the entity to process and reload permission for entity
if ($conf->entity != $user->entity && $user->entity != 0)
{
$result = $user->fetch('', $userlogin, '', 0, $conf->entity);
if ($result < 0)
{
echo "\nUser Error: ".$user->error."\n";
dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
exit(-1);
} else {
if ($result == 0)
{
echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n";
dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
exit(-1);
}
}
$user->getrights();
}
// Reload langs
$langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
if (!empty($user->conf->MAIN_LANG_DEFAULT)) $langcode = $user->conf->MAIN_LANG_DEFAULT;
if ($langs->getDefaultLang() != $langcode) $langs->setDefaultLang($langcode);
// Reload langs
$langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
if (!empty($user->conf->MAIN_LANG_DEFAULT)) $langcode = $user->conf->MAIN_LANG_DEFAULT;
if ($langs->getDefaultLang() != $langcode) $langs->setDefaultLang($langcode);
}
//If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database