work on zapier

This commit is contained in:
Frédéric FRANCE 2020-10-29 00:34:41 +01:00
parent cb0f1bc6d4
commit 5d0ac98c34
No known key found for this signature in database
GPG Key ID: 06809324E4B2ABC1
12 changed files with 1452 additions and 1216 deletions

View File

@ -48,7 +48,7 @@ module.exports = {
fields: [
{
key: 'url',
label: 'Url of service',
label: 'Url of service without ending-slash',
required: true,
type: 'string'
},

View File

@ -72,7 +72,7 @@ module.exports = {
},
outputFields: [
{key: 'id', label: 'ID'},
{key: 'id', type: "integer", label: 'ID'},
{key: 'name', label: 'Name'},
{key: 'name_alias', label: 'Name alias'},
{key: 'address', label: 'Address'},
@ -81,8 +81,8 @@ module.exports = {
{key: 'phone', label: 'Phone'},
{key: 'fax', label: 'Fax'},
{key: 'email', label: 'Email'},
{key: 'client', label: 'Customer/Prospect 0/1/2/3'},
{key: 'fournisseur', label: 'Supplier 0/1'},
{key: 'client', type: "integer", label: 'Customer/Prospect 0/1/2/3'},
{key: 'fournisseur', type: "integer", label: 'Supplier 0/1'},
{key: 'code_client', label: 'Customer code'},
{key: 'code_fournisseur', label: 'Supplier code'}
]

View File

@ -1,5 +1,6 @@
/*jshint esversion: 6 */
const triggerThirdparty = require('./triggers/thirdparty');
const triggerUser = require('./triggers/user');
const triggerOrder = require('./triggers/order');
const triggerAction = require('./triggers/action');
@ -54,8 +55,9 @@ const App = {
// If you want your trigger to show up, you better include it here!
triggers: {
[triggerThirdparty.key]: triggerThirdparty,
[triggerUser.key]: triggerUser,
[triggerOrder.key]: triggerOrder,
[triggerAction.key]: triggerAction
[triggerAction.key]: triggerAction,
},
// If you want your searches to show up, you better include it here!

View File

@ -1,6 +1,6 @@
{
"name": "dolibarr",
"version": "1.0.0",
"version": "1.13.0",
"description": "An app for connecting Dolibarr to the Zapier platform.",
"repository": "Dolibarr/dolibarr",
"homepage": "https://www.dolibarr.org/",
@ -15,7 +15,7 @@
"npm": ">=5.6.0"
},
"dependencies": {
"zapier-platform-core": "8.0.1"
"zapier-platform-core": "10.1.1"
},
"devDependencies": {
"mocha": "^5.2.0",

View File

@ -54,13 +54,20 @@ module.exports = {
// outputFields: () => { return []; }
// Alternatively, a static field definition should be provided, to specify labels for the fields
outputFields: [
{key: 'id', label: 'ID'},
{key: 'createdAt', label: 'Created At'},
{
key: 'id',
type: "integer",
label: 'ID'
},
{key: 'createdAt', type: "integer", label: 'Created At'},
{key: 'name', label: 'Name'},
{key: 'firstname', label: 'Firstname'},
{key: 'directions', label: 'Directions'},
{key: 'authorId', label: 'Author ID'},
{key: 'style', label: 'Style'}
{key: 'authorId', type: "integer", label: 'Author ID'},
{
key: 'style',
label: 'Style'
}
]
}
};

View File

@ -100,7 +100,7 @@ module.exports = {
noun: 'Action',
display: {
label: 'New Agenda',
description: 'Trigger when a new agenda with action is done in Dolibarr.'
description: 'Triggers when a new agenda with action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
@ -145,11 +145,15 @@ module.exports = {
// outputFields: () => { return []; }
// Alternatively, a static field definition should be provided, to specify labels for the fields
outputFields: [
{key: 'id', label: 'ID'},
{key: 'createdAt', label: 'Created At'},
{
key: 'id',
type: "integer",
label: 'ID'
},
{key: 'createdAt', type: "integer", label: 'Created At'},
{key: 'name', label: 'Name'},
{key: 'usertodo__name', label: 'UserToDo Name'},
{key: 'authorId', label: 'Author ID'},
{key: 'authorId', type: "integer", label: 'Author ID'},
{key: 'action', label: 'Action'}
]
}

View File

@ -90,7 +90,7 @@ module.exports = {
noun: 'Order',
display: {
label: 'New Order',
description: 'Trigger when a new order with action is done in Dolibarr.'
description: 'Triggers when a new order with action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
@ -136,11 +136,11 @@ module.exports = {
// outputFields: () => { return []; }
// Alternatively, a static field definition should be provided, to specify labels for the fields
outputFields: [
{key: 'id', label: 'ID'},
{key: 'createdAt', label: 'Created At'},
{key: 'id', type: "integer", label: 'ID'},
{key: 'createdAt', type: "integer", label: 'Created At'},
{key: 'name', label: 'Name'},
{key: 'directions', label: 'Directions'},
{key: 'authorId', label: 'Author ID'},
{key: 'authorId', type: "integer", label: 'Author ID'},
{key: 'module', label: 'Module'},
{key: 'action', label: 'Action'}
]

View File

@ -112,7 +112,7 @@ module.exports = {
noun: 'Thirdparty',
display: {
label: 'New Thirdparty',
description: 'Trigger when a new thirdpaty action is done in Dolibarr.'
description: 'Triggers when a new thirdpaty action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
@ -159,12 +159,12 @@ module.exports = {
// outputFields: () => { return []; }
// Alternatively, a static field definition should be provided, to specify labels for the fields
outputFields: [
{key: 'id', label: 'ID'},
{key: 'id', type: "integer", label: 'ID'},
{key: 'createdAt', label: 'Created At'},
{key: 'name', label: 'Name'},
{key: 'name_alias', label: 'Name alias'},
{key: 'firstname', label: 'Firstame'},
{key: 'authorId', label: 'Author ID'},
{key: 'firstname', label: 'Firstname'},
{key: 'authorId', type: "integer", label: 'Author ID'},
{key: 'action', label: 'Action'},
{key: 'client', label: 'Customer/Prospect 0/1/2/3'},
{key: 'fournisseur', label: 'Supplier 0/1'},

View File

@ -0,0 +1,176 @@
const subscribeHook = (z, bundle) => {
// `z.console.log()` is similar to `console.log()`.
z.console.log('suscribing hook!');
// bundle.targetUrl has the Hook URL this app should call when an action is created.
const data = {
url: bundle.targetUrl,
event: bundle.event,
module: 'user',
action: bundle.inputData.action
};
const url = bundle.authData.url + '/api/index.php/zapierapi/hook';
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: url,
method: 'POST',
body: JSON.stringify(data)
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const unsubscribeHook = (z, bundle) => {
// bundle.subscribeData contains the parsed response JSON from the subscribe
// request made initially.
z.console.log('unsuscribing hook!');
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: bundle.authData.url + '/api/index.php/zapierapi/hook/' + bundle.subscribeData.id,
method: 'DELETE',
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const getUser = (z, bundle) => {
// bundle.cleanedRequest will include the parsed JSON object (if it's not a
// test poll) and also a .querystring property with the URL's query string.
const user = {
id: bundle.cleanedRequest.id,
lastname: bundle.cleanedRequest.lastname,
firstname: bundle.cleanedRequest.firstname,
address: bundle.cleanedRequest.address,
zip: bundle.cleanedRequest.zip,
town: bundle.cleanedRequest.town,
email: bundle.cleanedRequest.email,
login: bundle.cleanedRequest.login,
authorId: bundle.cleanedRequest.authorId,
createdAt: bundle.cleanedRequest.createdAt,
action: bundle.cleanedRequest.action
};
return [user];
};
const getFallbackRealUser = (z, bundle) => {
// For the test poll, you should get some real data, to aid the setup process.
const module = bundle.inputData.module;
const options = {
url: bundle.authData.url + '/api/index.php/users/0',
};
return z.request(options).then((response) => [JSON.parse(response.content)]);
};
// const getModulesChoices = (z/*, bundle*/) => {
// // For the test poll, you should get some real data, to aid the setup process.
// const options = {
// url: bundle.authData.url + '/api/index.php/zapierapi/getmoduleschoices',
// };
// return z.request(options).then((response) => JSON.parse(response.content));
// };
// const getModulesChoices = () => {
// return {
// orders: "Order",
// invoices: "Invoice",
// thirdparties: "Thirdparty",
// users: "User",
// contacts: "Contacts"
// };
// };
// const getActionsChoices = (z, bundle) => {
// // For the test poll, you should get some real data, to aid the setup process.
// const module = bundle.inputData.module;
// const options = {
// url: url: bundle.authData.url + '/api/index.php/zapierapi/getactionschoices/thirparty`,
// };
// return z.request(options).then((response) => JSON.parse(response.content));
// };
// We recommend writing your triggers separate like this and rolling them
// into the App definition at the end.
module.exports = {
key: 'user',
// You'll want to provide some helpful display labels and descriptions
// for users. Zapier will put them into the UX.
noun: 'User',
display: {
label: 'New User',
description: 'Triggers when a new user action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
operation: {
// `inputFields` can define the fields a user could provide,
// we'll pass them in as `bundle.inputData` later.
inputFields: [
{
key: 'action',
type: 'string',
helpText: 'Which action of user this should trigger on.',
choices: {
create: "Create",
modify: "Modify",
validate: "Validate",
}
}
],
type: 'hook',
performSubscribe: subscribeHook,
performUnsubscribe: unsubscribeHook,
perform: getUser,
performList: getFallbackRealUser,
// In cases where Zapier needs to show an example record to the user, but we are unable to get a live example
// from the API, Zapier will fallback to this hard-coded sample. It should reflect the data structure of
// returned records, and have obviously dummy values that we can show to any user.
sample: {
id: 1,
createdAt: 1472069465,
lastname: 'DOE',
firstname: 'John',
email: 'john@doe.com',
address: 'Park Avenue',
zip: '12345',
town: 'NEW-YORK',
login: 'doe.john',
authorId: 1,
action: 'create'
},
// If the resource can have fields that are custom on a per-user basis, define a function to fetch the custom
// field definitions. The result will be used to augment the sample.
// outputFields: () => { return []; }
// Alternatively, a static field definition should be provided, to specify labels for the fields
outputFields: [
{key: 'id', type: "integer", label: 'ID'},
{key: 'createdAt', type: "integer", label: 'Created At'},
{key: 'lastname', label: 'Lastname'},
{key: 'firstname', label: 'Firstname'},
{key: 'email', label: 'Email'},
{key: 'address', label: 'Address'},
{key: 'zip', label: 'Zip'},
{key: 'town', label: 'Town'},
{key: 'login', label: 'Login'},
{key: 'authorId', type: "integer", label: 'Author ID'},
{key: 'action', label: 'Action'}
]
}
};

View File

@ -39,308 +39,330 @@ require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php';
*/
class InterfaceZapierTriggers extends DolibarrTriggers
{
/**
* 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;
$this->name = preg_replace('/^Interface/i', '', get_class($this));
$this->family = "technic";
$this->description = "Zapier triggers.";
// 'development', 'experimental', 'dolibarr' or version
$this->version = self::VERSION_DEVELOPMENT;
$this->picto = 'zapier';
}
$this->name = preg_replace('/^Interface/i', '', get_class($this));
$this->family = "technic";
$this->description = "Zapier triggers.";
// 'development', 'experimental', 'dolibarr' or version
$this->version = self::VERSION_DEVELOPMENT;
$this->picto = 'zapier';
}
/**
* Function called when a Dolibarrr business event is done.
* All functions "runTrigger" are triggered if file
* is inside directory core/triggers
*
* @param string $action Event action code
* @param CommonObject $object Object
* @param User $user Object user
* @param Translate $langs Object langs
* @param Conf $conf Object conf
* @return int <0 if KO, 0 if no triggered ran, >0 if OK
*/
public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
{
if (empty($conf->zapier->enabled)) {
// Module not active, we do nothing
return 0;
}
$logtriggeraction = false;
$sql = '';
if ($action != '') {
$actions = explode('_', $action);
$sql = 'SELECT rowid, url FROM '.MAIN_DB_PREFIX.'zapier_hook';
$sql .= ' WHERE module="'.$this->db->escape(strtolower($actions[0])).'" AND action="'.$this->db->escape(strtolower($actions[1])).'"';
//setEventMessages($sql, null);
}
/**
* Function called when a Dolibarrr business event is done.
* All functions "runTrigger" are triggered if file
* is inside directory core/triggers
*
* @param string $action Event action code
* @param CommonObject $object Object
* @param User $user Object user
* @param Translate $langs Object langs
* @param Conf $conf Object conf
* @return int <0 if KO, 0 if no triggered ran, >0 if OK
*/
public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
{
if (empty($conf->zapier->enabled)) {
// Module not active, we do nothing
return 0;
}
$logtriggeraction = false;
$sql = '';
if ($action != '') {
$actions = explode('_', $action);
$sql = 'SELECT rowid, url FROM '.MAIN_DB_PREFIX.'zapier_hook';
$sql .= ' WHERE module="'.$this->db->escape(strtolower($actions[0])).'" AND action="'.$this->db->escape(strtolower($actions[1])).'"';
//setEventMessages($sql, null);
}
switch ($action) {
// Users
//case 'USER_CREATE':
//case 'USER_MODIFY':
//case 'USER_NEW_PASSWORD':
//case 'USER_ENABLEDISABLE':
//case 'USER_DELETE':
//case 'USER_SETINGROUP':
//case 'USER_REMOVEFROMGROUP':
// case 'USER_LOGIN':
// case 'USER_LOGIN_FAILED':
// case 'USER_LOGOUT':
// Warning: To increase performances, this action is triggered only if constant MAIN_ACTIVATE_UPDATESESSIONTRIGGER is set to 1.
// // case 'USER_UPDATE_SESSION':
switch ($action) {
// Users
case 'USER_CREATE':
$resql = $this->db->query($sql);
// TODO voir comment regrouper les webhooks en un post
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
//setEventMessages($obj['url'], null);
}
$logtriggeraction = true;
break;
case 'USER_MODIFY':
$resql = $this->db->query($sql);
// TODO voir comment regrouper les webhooks en un post
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
//setEventMessages($obj['url'], null);
}
$logtriggeraction = true;
break;
//case 'USER_NEW_PASSWORD':
//case 'USER_ENABLEDISABLE':
//case 'USER_DELETE':
//case 'USER_SETINGROUP':
//case 'USER_REMOVEFROMGROUP':
// case 'USER_LOGIN':
// case 'USER_LOGIN_FAILED':
// case 'USER_LOGOUT':
// Warning: To increase performances, this action is triggered only if constant MAIN_ACTIVATE_UPDATESESSIONTRIGGER is set to 1.
// // case 'USER_UPDATE_SESSION':
// Actions
case 'ACTION_MODIFY':
//$logtriggeraction = true;
break;
case 'ACTION_CREATE':
$resql = $this->db->query($sql);
// TODO voir comment regrouper les webhooks en un post
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$cleaned = cleanAgendaEventsDatas($cleaned);
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
//setEventMessages($obj['url'], null);
}
$logtriggeraction = true;
break;
case 'ACTION_DELETE':
//$logtriggeraction = true;
break;
// Actions
case 'ACTION_MODIFY':
//$logtriggeraction = true;
break;
case 'ACTION_CREATE':
$resql = $this->db->query($sql);
// TODO voir comment regrouper les webhooks en un post
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$cleaned = cleanAgendaEventsDatas($cleaned);
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
//setEventMessages($obj['url'], null);
}
$logtriggeraction = true;
break;
case 'ACTION_DELETE':
//$logtriggeraction = true;
break;
// Groups
//case 'USERGROUP_CREATE':
//case 'USERGROUP_MODIFY':
//case 'USERGROUP_DELETE':
// Groups
//case 'USERGROUP_CREATE':
//case 'USERGROUP_MODIFY':
//case 'USERGROUP_DELETE':
// Companies
case 'COMPANY_CREATE':
$resql = $this->db->query($sql);
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'COMPANY_MODIFY':
$resql = $this->db->query($sql);
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'COMPANY_DELETE':
//$logtriggeraction = true;
break;
// Companies
case 'COMPANY_CREATE':
$resql = $this->db->query($sql);
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'COMPANY_MODIFY':
$resql = $this->db->query($sql);
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'COMPANY_DELETE':
//$logtriggeraction = true;
break;
// Contacts
case 'CONTACT_CREATE':
case 'CONTACT_MODIFY':
case 'CONTACT_DELETE':
case 'CONTACT_ENABLEDISABLE':
break;
// Products
// case 'PRODUCT_CREATE':
// case 'PRODUCT_MODIFY':
// case 'PRODUCT_DELETE':
// case 'PRODUCT_PRICE_MODIFY':
// case 'PRODUCT_SET_MULTILANGS':
// case 'PRODUCT_DEL_MULTILANGS':
// Contacts
case 'CONTACT_CREATE':
case 'CONTACT_MODIFY':
case 'CONTACT_DELETE':
case 'CONTACT_ENABLEDISABLE':
break;
// Products
// case 'PRODUCT_CREATE':
// case 'PRODUCT_MODIFY':
// case 'PRODUCT_DELETE':
// case 'PRODUCT_PRICE_MODIFY':
// case 'PRODUCT_SET_MULTILANGS':
// case 'PRODUCT_DEL_MULTILANGS':
//Stock mouvement
// case 'STOCK_MOVEMENT':
//Stock mouvement
// case 'STOCK_MOVEMENT':
//MYECMDIR
// case 'MYECMDIR_DELETE':
// case 'MYECMDIR_CREATE':
// case 'MYECMDIR_MODIFY':
//MYECMDIR
// case 'MYECMDIR_DELETE':
// case 'MYECMDIR_CREATE':
// case 'MYECMDIR_MODIFY':
// Customer orders
case 'ORDER_CREATE':
$resql = $this->db->query($sql);
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'ORDER_CLONE':
break;
case 'ORDER_VALIDATE':
break;
case 'ORDER_DELETE':
case 'ORDER_CANCEL':
case 'ORDER_SENTBYMAIL':
case 'ORDER_CLASSIFY_BILLED':
case 'ORDER_SETDRAFT':
case 'LINEORDER_INSERT':
case 'LINEORDER_UPDATE':
case 'LINEORDER_DELETE':
break;
// Supplier orders
// case 'ORDER_SUPPLIER_CREATE':
// case 'ORDER_SUPPLIER_CLONE':
// case 'ORDER_SUPPLIER_VALIDATE':
// case 'ORDER_SUPPLIER_DELETE':
// case 'ORDER_SUPPLIER_APPROVE':
// case 'ORDER_SUPPLIER_REFUSE':
// case 'ORDER_SUPPLIER_CANCEL':
// case 'ORDER_SUPPLIER_SENTBYMAIL':
// case 'ORDER_SUPPLIER_DISPATCH':
// case 'LINEORDER_SUPPLIER_DISPATCH':
// case 'LINEORDER_SUPPLIER_CREATE':
// case 'LINEORDER_SUPPLIER_UPDATE':
// Customer orders
case 'ORDER_CREATE':
$resql = $this->db->query($sql);
while ($resql && $obj = $this->db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'ORDER_CLONE':
break;
case 'ORDER_VALIDATE':
break;
case 'ORDER_DELETE':
case 'ORDER_CANCEL':
case 'ORDER_SENTBYMAIL':
case 'ORDER_CLASSIFY_BILLED':
case 'ORDER_SETDRAFT':
case 'LINEORDER_INSERT':
case 'LINEORDER_UPDATE':
case 'LINEORDER_DELETE':
break;
// Supplier orders
// case 'ORDER_SUPPLIER_CREATE':
// case 'ORDER_SUPPLIER_CLONE':
// case 'ORDER_SUPPLIER_VALIDATE':
// case 'ORDER_SUPPLIER_DELETE':
// case 'ORDER_SUPPLIER_APPROVE':
// case 'ORDER_SUPPLIER_REFUSE':
// case 'ORDER_SUPPLIER_CANCEL':
// case 'ORDER_SUPPLIER_SENTBYMAIL':
// case 'ORDER_SUPPLIER_DISPATCH':
// case 'LINEORDER_SUPPLIER_DISPATCH':
// case 'LINEORDER_SUPPLIER_CREATE':
// case 'LINEORDER_SUPPLIER_UPDATE':
// Proposals
// case 'PROPAL_CREATE':
// case 'PROPAL_CLONE':
// case 'PROPAL_MODIFY':
// case 'PROPAL_VALIDATE':
// case 'PROPAL_SENTBYMAIL':
// case 'PROPAL_CLOSE_SIGNED':
// case 'PROPAL_CLOSE_REFUSED':
// case 'PROPAL_DELETE':
// case 'LINEPROPAL_INSERT':
// case 'LINEPROPAL_UPDATE':
// case 'LINEPROPAL_DELETE':
// Proposals
// case 'PROPAL_CREATE':
// case 'PROPAL_CLONE':
// case 'PROPAL_MODIFY':
// case 'PROPAL_VALIDATE':
// case 'PROPAL_SENTBYMAIL':
// case 'PROPAL_CLOSE_SIGNED':
// case 'PROPAL_CLOSE_REFUSED':
// case 'PROPAL_DELETE':
// case 'LINEPROPAL_INSERT':
// case 'LINEPROPAL_UPDATE':
// case 'LINEPROPAL_DELETE':
// SupplierProposal
// case 'SUPPLIER_PROPOSAL_CREATE':
// case 'SUPPLIER_PROPOSAL_CLONE':
// case 'SUPPLIER_PROPOSAL_MODIFY':
// case 'SUPPLIER_PROPOSAL_VALIDATE':
// case 'SUPPLIER_PROPOSAL_SENTBYMAIL':
// case 'SUPPLIER_PROPOSAL_CLOSE_SIGNED':
// case 'SUPPLIER_PROPOSAL_CLOSE_REFUSED':
// case 'SUPPLIER_PROPOSAL_DELETE':
// case 'LINESUPPLIER_PROPOSAL_INSERT':
// case 'LINESUPPLIER_PROPOSAL_UPDATE':
// case 'LINESUPPLIER_PROPOSAL_DELETE':
// SupplierProposal
// case 'SUPPLIER_PROPOSAL_CREATE':
// case 'SUPPLIER_PROPOSAL_CLONE':
// case 'SUPPLIER_PROPOSAL_MODIFY':
// case 'SUPPLIER_PROPOSAL_VALIDATE':
// case 'SUPPLIER_PROPOSAL_SENTBYMAIL':
// case 'SUPPLIER_PROPOSAL_CLOSE_SIGNED':
// case 'SUPPLIER_PROPOSAL_CLOSE_REFUSED':
// case 'SUPPLIER_PROPOSAL_DELETE':
// case 'LINESUPPLIER_PROPOSAL_INSERT':
// case 'LINESUPPLIER_PROPOSAL_UPDATE':
// case 'LINESUPPLIER_PROPOSAL_DELETE':
// Contracts
// case 'CONTRACT_CREATE':
// case 'CONTRACT_ACTIVATE':
// case 'CONTRACT_CANCEL':
// case 'CONTRACT_CLOSE':
// case 'CONTRACT_DELETE':
// case 'LINECONTRACT_INSERT':
// case 'LINECONTRACT_UPDATE':
// case 'LINECONTRACT_DELETE':
// Contracts
// case 'CONTRACT_CREATE':
// case 'CONTRACT_ACTIVATE':
// case 'CONTRACT_CANCEL':
// case 'CONTRACT_CLOSE':
// case 'CONTRACT_DELETE':
// case 'LINECONTRACT_INSERT':
// case 'LINECONTRACT_UPDATE':
// case 'LINECONTRACT_DELETE':
// Bills
// case 'BILL_CREATE':
// case 'BILL_CLONE':
// case 'BILL_MODIFY':
// case 'BILL_VALIDATE':
// case 'BILL_UNVALIDATE':
// case 'BILL_SENTBYMAIL':
// case 'BILL_CANCEL':
// case 'BILL_DELETE':
// case 'BILL_PAYED':
// case 'LINEBILL_INSERT':
// case 'LINEBILL_UPDATE':
// case 'LINEBILL_DELETE':
// Bills
// case 'BILL_CREATE':
// case 'BILL_CLONE':
// case 'BILL_MODIFY':
// case 'BILL_VALIDATE':
// case 'BILL_UNVALIDATE':
// case 'BILL_SENTBYMAIL':
// case 'BILL_CANCEL':
// case 'BILL_DELETE':
// case 'BILL_PAYED':
// case 'LINEBILL_INSERT':
// case 'LINEBILL_UPDATE':
// case 'LINEBILL_DELETE':
//Supplier Bill
// case 'BILL_SUPPLIER_CREATE':
// case 'BILL_SUPPLIER_UPDATE':
// case 'BILL_SUPPLIER_DELETE':
// case 'BILL_SUPPLIER_PAYED':
// case 'BILL_SUPPLIER_UNPAYED':
// case 'BILL_SUPPLIER_VALIDATE':
// case 'BILL_SUPPLIER_UNVALIDATE':
// case 'LINEBILL_SUPPLIER_CREATE':
// case 'LINEBILL_SUPPLIER_UPDATE':
// case 'LINEBILL_SUPPLIER_DELETE':
//Supplier Bill
// case 'BILL_SUPPLIER_CREATE':
// case 'BILL_SUPPLIER_UPDATE':
// case 'BILL_SUPPLIER_DELETE':
// case 'BILL_SUPPLIER_PAYED':
// case 'BILL_SUPPLIER_UNPAYED':
// case 'BILL_SUPPLIER_VALIDATE':
// case 'BILL_SUPPLIER_UNVALIDATE':
// case 'LINEBILL_SUPPLIER_CREATE':
// case 'LINEBILL_SUPPLIER_UPDATE':
// case 'LINEBILL_SUPPLIER_DELETE':
// Payments
// case 'PAYMENT_CUSTOMER_CREATE':
// case 'PAYMENT_SUPPLIER_CREATE':
// case 'PAYMENT_ADD_TO_BANK':
// case 'PAYMENT_DELETE':
// Payments
// case 'PAYMENT_CUSTOMER_CREATE':
// case 'PAYMENT_SUPPLIER_CREATE':
// case 'PAYMENT_ADD_TO_BANK':
// case 'PAYMENT_DELETE':
// Online
// case 'PAYMENT_PAYBOX_OK':
// case 'PAYMENT_PAYPAL_OK':
// case 'PAYMENT_STRIPE_OK':
// Online
// case 'PAYMENT_PAYBOX_OK':
// case 'PAYMENT_PAYPAL_OK':
// case 'PAYMENT_STRIPE_OK':
// Donation
// case 'DON_CREATE':
// case 'DON_UPDATE':
// case 'DON_DELETE':
// Donation
// case 'DON_CREATE':
// case 'DON_UPDATE':
// case 'DON_DELETE':
// Interventions
// case 'FICHINTER_CREATE':
// case 'FICHINTER_MODIFY':
// case 'FICHINTER_VALIDATE':
// case 'FICHINTER_DELETE':
// case 'LINEFICHINTER_CREATE':
// case 'LINEFICHINTER_UPDATE':
// case 'LINEFICHINTER_DELETE':
// Interventions
// case 'FICHINTER_CREATE':
// case 'FICHINTER_MODIFY':
// case 'FICHINTER_VALIDATE':
// case 'FICHINTER_DELETE':
// case 'LINEFICHINTER_CREATE':
// case 'LINEFICHINTER_UPDATE':
// case 'LINEFICHINTER_DELETE':
// Members
// case 'MEMBER_CREATE':
// case 'MEMBER_VALIDATE':
// case 'MEMBER_SUBSCRIPTION':
// case 'MEMBER_MODIFY':
// case 'MEMBER_NEW_PASSWORD':
// case 'MEMBER_RESILIATE':
// case 'MEMBER_DELETE':
// Members
// case 'MEMBER_CREATE':
// case 'MEMBER_VALIDATE':
// case 'MEMBER_SUBSCRIPTION':
// case 'MEMBER_MODIFY':
// case 'MEMBER_NEW_PASSWORD':
// case 'MEMBER_RESILIATE':
// case 'MEMBER_DELETE':
// Categories
// case 'CATEGORY_CREATE':
// case 'CATEGORY_MODIFY':
// case 'CATEGORY_DELETE':
// case 'CATEGORY_SET_MULTILANGS':
// Categories
// case 'CATEGORY_CREATE':
// case 'CATEGORY_MODIFY':
// case 'CATEGORY_DELETE':
// case 'CATEGORY_SET_MULTILANGS':
// Projects
// case 'PROJECT_CREATE':
// case 'PROJECT_MODIFY':
// case 'PROJECT_DELETE':
// Projects
// case 'PROJECT_CREATE':
// case 'PROJECT_MODIFY':
// case 'PROJECT_DELETE':
// Project tasks
// case 'TASK_CREATE':
// case 'TASK_MODIFY':
// case 'TASK_DELETE':
// Project tasks
// case 'TASK_CREATE':
// case 'TASK_MODIFY':
// case 'TASK_DELETE':
// Task time spent
// case 'TASK_TIMESPENT_CREATE':
// case 'TASK_TIMESPENT_MODIFY':
// case 'TASK_TIMESPENT_DELETE':
// Task time spent
// case 'TASK_TIMESPENT_CREATE':
// case 'TASK_TIMESPENT_MODIFY':
// case 'TASK_TIMESPENT_DELETE':
// Shipping
// case 'SHIPPING_CREATE':
// case 'SHIPPING_MODIFY':
// case 'SHIPPING_VALIDATE':
// case 'SHIPPING_SENTBYMAIL':
// case 'SHIPPING_BILLED':
// case 'SHIPPING_CLOSED':
// case 'SHIPPING_REOPEN':
// case 'SHIPPING_DELETE':
}
if ($logtriggeraction) {
dol_syslog("Trigger '".$this->name."' for action '.$action.' launched by ".__FILE__." id=".$object->id);
}
return 0;
}
// Shipping
// case 'SHIPPING_CREATE':
// case 'SHIPPING_MODIFY':
// case 'SHIPPING_VALIDATE':
// case 'SHIPPING_SENTBYMAIL':
// case 'SHIPPING_BILLED':
// case 'SHIPPING_CLOSED':
// case 'SHIPPING_REOPEN':
// case 'SHIPPING_DELETE':
}
if ($logtriggeraction) {
dol_syslog("Trigger '".$this->name."' for action '.$action.' launched by ".__FILE__." id=".$object->id);
}
return 0;
}
}
/**
* Post webhook in zapier with object data
@ -351,18 +373,18 @@ class InterfaceZapierTriggers extends DolibarrTriggers
*/
function zapierPostWebhook($url, $json)
{
$headers = array('Accept: application/json', 'Content-Type: application/json');
// TODO supprimer le webhook en cas de mauvaise réponse
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
curl_close($ch);
$headers = array('Accept: application/json', 'Content-Type: application/json');
// TODO supprimer le webhook en cas de mauvaise réponse
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
curl_close($ch);
}
/**
@ -373,81 +395,81 @@ function zapierPostWebhook($url, $json)
*/
function cleanObjectDatas($toclean)
{
// Remove $db object property for object
unset($toclean->db);
// Remove $db object property for object
unset($toclean->db);
// Remove linkedObjects. We should already have linkedObjectsIds that avoid huge responses
unset($toclean->linkedObjects);
// Remove linkedObjects. We should already have linkedObjectsIds that avoid huge responses
unset($toclean->linkedObjects);
unset($toclean->lines); // should be ->lines
unset($toclean->lines); // should be ->lines
unset($toclean->fields);
unset($toclean->fields);
unset($toclean->oldline);
unset($toclean->oldline);
unset($toclean->error);
unset($toclean->errors);
unset($toclean->error);
unset($toclean->errors);
unset($toclean->ref_previous);
unset($toclean->ref_next);
unset($toclean->ref_int);
unset($toclean->ref_previous);
unset($toclean->ref_next);
unset($toclean->ref_int);
unset($toclean->projet); // Should be fk_project
unset($toclean->project); // Should be fk_project
unset($toclean->author); // Should be fk_user_author
unset($toclean->timespent_old_duration);
unset($toclean->timespent_id);
unset($toclean->timespent_duration);
unset($toclean->timespent_date);
unset($toclean->timespent_datehour);
unset($toclean->timespent_withhour);
unset($toclean->timespent_fk_user);
unset($toclean->timespent_note);
unset($toclean->projet); // Should be fk_project
unset($toclean->project); // Should be fk_project
unset($toclean->author); // Should be fk_user_author
unset($toclean->timespent_old_duration);
unset($toclean->timespent_id);
unset($toclean->timespent_duration);
unset($toclean->timespent_date);
unset($toclean->timespent_datehour);
unset($toclean->timespent_withhour);
unset($toclean->timespent_fk_user);
unset($toclean->timespent_note);
unset($toclean->statuts);
unset($toclean->statuts_short);
unset($toclean->statuts_logo);
unset($toclean->statuts_long);
unset($toclean->statuts);
unset($toclean->statuts_short);
unset($toclean->statuts_logo);
unset($toclean->statuts_long);
unset($toclean->element);
unset($toclean->fk_element);
unset($toclean->table_element);
unset($toclean->table_element_line);
unset($toclean->picto);
unset($toclean->element);
unset($toclean->fk_element);
unset($toclean->table_element);
unset($toclean->table_element_line);
unset($toclean->picto);
unset($toclean->skip_update_total);
unset($toclean->context);
unset($toclean->skip_update_total);
unset($toclean->context);
// Remove the $oldcopy property because it is not supported by the JSON
// encoder. The following error is generated when trying to serialize
// it: "Error encoding/decoding JSON: Type is not supported"
// Note: Event if this property was correctly handled by the JSON
// encoder, it should be ignored because keeping it would let the API
// have a very strange behavior: calling PUT and then GET on the same
// resource would give different results:
// PUT /objects/{id} -> returns object with oldcopy = previous version of the object
// GET /objects/{id} -> returns object with oldcopy empty
unset($toclean->oldcopy);
// Remove the $oldcopy property because it is not supported by the JSON
// encoder. The following error is generated when trying to serialize
// it: "Error encoding/decoding JSON: Type is not supported"
// Note: Event if this property was correctly handled by the JSON
// encoder, it should be ignored because keeping it would let the API
// have a very strange behavior: calling PUT and then GET on the same
// resource would give different results:
// PUT /objects/{id} -> returns object with oldcopy = previous version of the object
// GET /objects/{id} -> returns object with oldcopy empty
unset($toclean->oldcopy);
// If object has lines, remove $db property
if (isset($toclean->lines) && count($toclean->lines) > 0) {
$nboflines = count($toclean->lines);
for ($i = 0; $i < $nboflines; $i++) {
cleanObjectDatas($toclean->lines[$i]);
}
}
// If object has lines, remove $db property
if (isset($toclean->lines) && count($toclean->lines) > 0) {
$nboflines = count($toclean->lines);
for ($i = 0; $i < $nboflines; $i++) {
cleanObjectDatas($toclean->lines[$i]);
}
}
// If object has linked objects, remove $db property
/*
if(isset($toclean->linkedObjects) && count($toclean->linkedObjects) > 0) {
foreach($toclean->linkedObjects as $type_object => $linked_object) {
foreach($linked_object as $toclean2clean) {
$this->cleanObjectDatas($toclean2clean);
}
}
}*/
// If object has linked objects, remove $db property
/*
if(isset($toclean->linkedObjects) && count($toclean->linkedObjects) > 0) {
foreach($toclean->linkedObjects as $type_object => $linked_object) {
foreach($linked_object as $toclean2clean) {
$this->cleanObjectDatas($toclean2clean);
}
}
}*/
return $toclean;
return $toclean;
}
/**
@ -458,46 +480,46 @@ function cleanObjectDatas($toclean)
*/
function cleanAgendaEventsDatas($toclean)
{
unset($toclean->usermod);
unset($toclean->libelle);
//unset($toclean->array_options);
unset($toclean->context);
unset($toclean->canvas);
unset($toclean->contact);
unset($toclean->contact_id);
unset($toclean->thirdparty);
unset($toclean->user);
unset($toclean->origin);
unset($toclean->origin_id);
unset($toclean->ref_ext);
unset($toclean->statut);
unset($toclean->country);
unset($toclean->country_id);
unset($toclean->country_code);
unset($toclean->barcode_type);
unset($toclean->barcode_type_code);
unset($toclean->barcode_type_label);
unset($toclean->barcode_type_coder);
unset($toclean->mode_reglement_id);
unset($toclean->cond_reglement_id);
unset($toclean->cond_reglement);
unset($toclean->fk_delivery_address);
unset($toclean->shipping_method_id);
unset($toclean->fk_account);
unset($toclean->total_ht);
unset($toclean->total_tva);
unset($toclean->total_localtax1);
unset($toclean->total_localtax2);
unset($toclean->total_ttc);
unset($toclean->fk_incoterms);
unset($toclean->libelle_incoterms);
unset($toclean->location_incoterms);
unset($toclean->name);
unset($toclean->lastname);
unset($toclean->firstname);
unset($toclean->civility_id);
unset($toclean->contact);
unset($toclean->societe);
unset($toclean->usermod);
unset($toclean->libelle);
//unset($toclean->array_options);
unset($toclean->context);
unset($toclean->canvas);
unset($toclean->contact);
unset($toclean->contact_id);
unset($toclean->thirdparty);
unset($toclean->user);
unset($toclean->origin);
unset($toclean->origin_id);
unset($toclean->ref_ext);
unset($toclean->statut);
unset($toclean->country);
unset($toclean->country_id);
unset($toclean->country_code);
unset($toclean->barcode_type);
unset($toclean->barcode_type_code);
unset($toclean->barcode_type_label);
unset($toclean->barcode_type_coder);
unset($toclean->mode_reglement_id);
unset($toclean->cond_reglement_id);
unset($toclean->cond_reglement);
unset($toclean->fk_delivery_address);
unset($toclean->shipping_method_id);
unset($toclean->fk_account);
unset($toclean->total_ht);
unset($toclean->total_tva);
unset($toclean->total_localtax1);
unset($toclean->total_localtax2);
unset($toclean->total_ttc);
unset($toclean->fk_incoterms);
unset($toclean->libelle_incoterms);
unset($toclean->location_incoterms);
unset($toclean->name);
unset($toclean->lastname);
unset($toclean->firstname);
unset($toclean->civility_id);
unset($toclean->contact);
unset($toclean->societe);
return $toclean;
return $toclean;
}

View File

@ -45,8 +45,8 @@ class Users extends DolibarrApi
/**
* Constructor
*/
public function __construct()
{
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->useraccount = new User($this->db);
@ -63,82 +63,79 @@ class Users extends DolibarrApi
* @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 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')"
* @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 User objects
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $category = 0, $sqlfilters = '')
{
global $db, $conf;
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $category = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->user->user->lire) {
throw new RestException(401, "You are not allowed to read list of users");
}
throw new RestException(401, "You are not allowed to read list of users");
}
// 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."user as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_user as c";
}
$sql .= ' WHERE t.entity IN ('.getEntity('user').')';
if ($user_ids) $sql .= " AND t.rowid IN (".$user_ids.")";
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."user as t";
if ($category > 0) {
$sql .= ", ".MAIN_DB_PREFIX."categorie_user as c";
}
$sql .= ' WHERE t.entity IN ('.getEntity('user').')';
if ($user_ids) {
$sql .= " AND t.rowid IN (".$user_ids.")";
}
// Select products of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category);
// Select products of given category
if ($category > 0) {
$sql .= " AND c.fk_categorie = ".$this->db->escape($category);
$sql .= " AND c.fk_user = 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);
$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);
$user_static = new User($this->db);
if ($user_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($user_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve User list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No User 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);
$user_static = new User($this->db);
if ($user_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($user_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve User list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No User found');
}
return $obj_ret;
}
/**
@ -151,20 +148,21 @@ class Users extends DolibarrApi
* @throws RestException 401 Insufficient rights
* @throws RestException 404 User or group not found
*/
public function get($id, $includepermissions = 0)
{
public function get($id, $includepermissions = 0)
{
//if (!DolibarrApiAccess::$user->rights->user->user->lire) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
if ($id == 0) {
$result = $this->useraccount->initAsSpecimen();
} else {
$result = $this->useraccount->fetch($id);
}
if (!$result) {
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
if ($id > 0 && !DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
@ -187,20 +185,18 @@ class Users extends DolibarrApi
* @throws RestException 401 Insufficient rights
* @throws RestException 404 User or group not found
*/
public function getByLogin($login, $includepermissions = 0)
{
public function getByLogin($login, $includepermissions = 0)
{
//if (!DolibarrApiAccess::$user->rights->user->user->lire) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch('', $login);
if (!$result)
{
if (!$result) {
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
@ -223,20 +219,18 @@ class Users extends DolibarrApi
* @throws RestException 401 Insufficient rights
* @throws RestException 404 User or group not found
*/
public function getByEmail($email, $includepermissions = 0)
{
public function getByEmail($email, $includepermissions = 0)
{
//if (!DolibarrApiAccess::$user->rights->user->user->lire) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch('', '', '', 0, -1, $email);
if (!$result)
{
if (!$result) {
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
@ -247,39 +241,39 @@ class Users extends DolibarrApi
return $this->_cleanObjectDatas($this->useraccount);
}
/**
* Get properties of user connected
*
* @url GET /info
*
* @return array|mixed Data without useless information
*
* @throws RestException 401 Insufficient rights
* @throws RestException 404 User or group not found
*/
public function getInfo()
{
$apiUser = DolibarrApiAccess::$user;
/**
* Get properties of user connected
*
* @url GET /info
*
* @return array|mixed Data without useless information
*
* @throws RestException 401 Insufficient rights
* @throws RestException 404 User or group not found
*/
public function getInfo()
{
$apiUser = DolibarrApiAccess::$user;
$result = $this->useraccount->fetch($apiUser->id);
if (!$result) {
throw new RestException(404, 'User not found');
}
$result = $this->useraccount->fetch($apiUser->id);
if (!$result) {
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$usergroup = new UserGroup($this->db);
$userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
if (!is_array($userGroupList)) {
throw new RestException(404, 'User group not found');
}
$usergroup = new UserGroup($this->db);
$userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
if (!is_array($userGroupList)) {
throw new RestException(404, 'User group not found');
}
$this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
$this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
return $this->_cleanObjectDatas($this->useraccount);
}
return $this->_cleanObjectDatas($this->useraccount);
}
/**
* Create user account
@ -287,30 +281,29 @@ class Users extends DolibarrApi
* @param array $request_data New user data
* @return int
*/
public function post($request_data = null)
{
// check user authorization
//if(! DolibarrApiAccess::$user->rights->user->creer) {
// throw new RestException(401, "User creation not allowed");
//}
// check mandatory fields
/*if (!isset($request_data["login"]))
throw new RestException(400, "login field missing");
if (!isset($request_data["password"]))
throw new RestException(400, "password field missing");
if (!isset($request_data["lastname"]))
throw new RestException(400, "lastname field missing");*/
//assign field values
foreach ($request_data as $field => $value)
{
$this->useraccount->$field = $value;
}
public function post($request_data = null)
{
// check user authorization
//if(! DolibarrApiAccess::$user->rights->user->creer) {
// throw new RestException(401, "User creation not allowed");
//}
// check mandatory fields
/*if (!isset($request_data["login"]))
throw new RestException(400, "login field missing");
if (!isset($request_data["password"]))
throw new RestException(400, "password field missing");
if (!isset($request_data["lastname"]))
throw new RestException(400, "lastname field missing");*/
//assign field values
foreach ($request_data as $field => $value) {
$this->useraccount->$field = $value;
}
if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
}
return $this->useraccount->id;
}
if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
}
return $this->useraccount->id;
}
/**
@ -319,50 +312,48 @@ class Users extends DolibarrApi
* @param int $id Id of account to update
* @param array $request_data Datas
* @return array
*
* @throws RestException
*
* @throws RestException
*/
public function put($id, $request_data = null)
{
public function put($id, $request_data = null)
{
//if (!DolibarrApiAccess::$user->rights->user->user->creer) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
if (!$result) {
throw new RestException(404, 'Account not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value)
{
if ($field == 'id') continue;
foreach ($request_data as $field => $value) {
if ($field == 'id') {
continue;
}
// The status must be updated using setstatus() because it
// is not handled by the update() method.
if ($field == 'statut') {
$result = $this->useraccount->setstatus($value);
if ($result < 0) {
throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
}
} else {
$this->useraccount->$field = $value;
$this->useraccount->$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 zezo.
if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0)
{
if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0) {
return $this->get($id);
} else {
throw new RestException(500, $this->useraccount->error);
}
}
}
/**
@ -372,7 +363,7 @@ class Users extends DolibarrApi
* @return array Array of group objects
*
* @throws RestException 403 Not allowed
* @throws RestException 404 Not found
* @throws RestException 404 Not found
*
* @url GET {id}/groups
*/
@ -400,18 +391,18 @@ class Users extends DolibarrApi
}
/**
/**
* Add a user into a group
*
* @param int $id User ID
* @param int $group Group ID
* @param int $entity Entity ID (valid only for superadmin in multicompany transverse mode)
* @return int 1 if success
*
*
* @url GET {id}/setGroup/{group}
*/
public function setGroup($id, $group, $entity = 1)
{
public function setGroup($id, $group, $entity = 1)
{
global $conf;
@ -419,18 +410,15 @@ class Users extends DolibarrApi
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
if (!$result) {
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity))
{
if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity)) {
$entity = (!empty($entity) ? $entity : $conf->entity);
} else {
// When using API, action is done on entity of logged user because a user of entity X with permission to create user should not be able to
@ -439,8 +427,7 @@ class Users extends DolibarrApi
}
$result = $this->useraccount->SetInGroup($group, $entity);
if (!($result > 0))
{
if (!($result > 0)) {
throw new RestException(500, $this->useraccount->error);
}
@ -462,68 +449,65 @@ class Users extends DolibarrApi
* @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 User objects
*/
public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = 0, $sqlfilters = '')
{
global $db, $conf;
public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$obj_ret = array();
if (!DolibarrApiAccess::$user->rights->user->group_advance->read) {
throw new RestException(401, "You are not allowed to read list of groups");
}
throw new RestException(401, "You are not allowed to read list of groups");
}
// 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."usergroup as t";
$sql .= ' WHERE t.entity IN ('.getEntity('user').')';
if ($group_ids) $sql .= " AND t.rowid IN (".$group_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).")";
}
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."usergroup as t";
$sql .= ' WHERE t.entity IN ('.getEntity('user').')';
if ($group_ids) {
$sql .= " AND t.rowid IN (".$group_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).")";
}
$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);
$group_static = new UserGroup($this->db);
if ($group_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($group_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No Group 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);
$group_static = new UserGroup($this->db);
if ($group_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($group_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
}
if (!count($obj_ret)) {
throw new RestException(404, 'No Group found');
}
return $obj_ret;
}
/**
@ -537,23 +521,22 @@ class Users extends DolibarrApi
* @param int $load_members Load members list or not {@min 0} {@max 1}
* @return array Array of User objects
*/
public function infoGroups($group, $load_members = 0)
{
global $db, $conf;
public function infoGroups($group, $load_members = 0)
{
global $db, $conf;
if (!DolibarrApiAccess::$user->rights->user->group_advance->read) {
throw new RestException(401, "You are not allowed to read groups");
}
throw new RestException(401, "You are not allowed to read groups");
}
$group_static = new UserGroup($this->db);
$result = $group_static->fetch($group, '', $load_members);
$group_static = new UserGroup($this->db);
$result = $group_static->fetch($group, '', $load_members);
if (!$result)
{
if (!$result) {
throw new RestException(404, 'Group not found');
}
return $this->_cleanObjectDatas($group_static);
return $this->_cleanObjectDatas($group_static);
}
/**
@ -562,22 +545,20 @@ class Users extends DolibarrApi
* @param int $id Account ID
* @return array
*/
public function delete($id)
{
public function delete($id)
{
//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
if (!$result) {
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->useraccount->oldcopy = clone $this->useraccount;
$this->useraccount->oldcopy = clone $this->useraccount;
return $this->useraccount->delete(DolibarrApiAccess::$user);
}
@ -593,122 +574,122 @@ class Users extends DolibarrApi
// phpcs:enable
global $conf;
$object = parent::_cleanObjectDatas($object);
$object = parent::_cleanObjectDatas($object);
unset($object->default_values);
unset($object->lastsearch_values);
unset($object->lastsearch_values_tmp);
unset($object->default_values);
unset($object->lastsearch_values);
unset($object->lastsearch_values_tmp);
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->label_incoterms);
unset($object->location_incoterms);
unset($object->label_incoterms);
unset($object->location_incoterms);
unset($object->fk_delivery_address);
unset($object->fk_incoterms);
unset($object->all_permissions_are_loaded);
unset($object->shipping_method_id);
unset($object->nb_rights);
unset($object->search_sid);
unset($object->ldap_sid);
unset($object->clicktodial_loaded);
unset($object->fk_delivery_address);
unset($object->fk_incoterms);
unset($object->all_permissions_are_loaded);
unset($object->shipping_method_id);
unset($object->nb_rights);
unset($object->search_sid);
unset($object->ldap_sid);
unset($object->clicktodial_loaded);
// List of properties never returned by API, whatever are permissions
unset($object->pass);
unset($object->pass_indatabase);
unset($object->pass_indatabase_crypted);
unset($object->pass_temp);
unset($object->api_key);
unset($object->clicktodial_password);
unset($object->openid);
// List of properties never returned by API, whatever are permissions
unset($object->pass);
unset($object->pass_indatabase);
unset($object->pass_indatabase_crypted);
unset($object->pass_temp);
unset($object->api_key);
unset($object->clicktodial_password);
unset($object->openid);
unset($object->lines);
unset($object->model_pdf);
unset($object->skype);
unset($object->twitter);
unset($object->facebook);
unset($object->linkedin);
unset($object->lines);
unset($object->model_pdf);
unset($object->skype);
unset($object->twitter);
unset($object->facebook);
unset($object->linkedin);
$canreadsalary = ((!empty($conf->salaries->enabled) && !empty(DolibarrApiAccess::$user->rights->salaries->read))
|| (!empty($conf->hrm->enabled) && !empty(DolibarrApiAccess::$user->rights->hrm->employee->read)));
$canreadsalary = ((!empty($conf->salaries->enabled) && !empty(DolibarrApiAccess::$user->rights->salaries->read))
|| (!empty($conf->hrm->enabled) && !empty(DolibarrApiAccess::$user->rights->hrm->employee->read)));
if (!$canreadsalary)
{
if (!$canreadsalary) {
unset($object->salary);
unset($object->salaryextra);
unset($object->thm);
unset($object->tjm);
}
return $object;
return $object;
}
/**
* Clean sensible user group list datas
*
* @param array $objectList Array of object to clean
* @return array Array of cleaned object properties
*/
private function _cleanUserGroupListDatas($objectList)
{
$cleanObjectList = array();
/**
* Clean sensible user group list datas
*
* @param array $objectList Array of object to clean
* @return array Array of cleaned object properties
*/
private function _cleanUserGroupListDatas($objectList)
{
$cleanObjectList = array();
foreach ($objectList as $object) {
$cleanObject = parent::_cleanObjectDatas($object);
foreach ($objectList as $object) {
$cleanObject = parent::_cleanObjectDatas($object);
unset($cleanObject->default_values);
unset($cleanObject->lastsearch_values);
unset($cleanObject->lastsearch_values_tmp);
unset($cleanObject->default_values);
unset($cleanObject->lastsearch_values);
unset($cleanObject->lastsearch_values_tmp);
unset($cleanObject->total_ht);
unset($cleanObject->total_tva);
unset($cleanObject->total_localtax1);
unset($cleanObject->total_localtax2);
unset($cleanObject->total_ttc);
unset($cleanObject->total_ht);
unset($cleanObject->total_tva);
unset($cleanObject->total_localtax1);
unset($cleanObject->total_localtax2);
unset($cleanObject->total_ttc);
unset($cleanObject->libelle_incoterms);
unset($cleanObject->location_incoterms);
unset($cleanObject->libelle_incoterms);
unset($cleanObject->location_incoterms);
unset($cleanObject->fk_delivery_address);
unset($cleanObject->fk_incoterms);
unset($cleanObject->all_permissions_are_loaded);
unset($cleanObject->shipping_method_id);
unset($cleanObject->nb_rights);
unset($cleanObject->search_sid);
unset($cleanObject->ldap_sid);
unset($cleanObject->clicktodial_loaded);
unset($cleanObject->fk_delivery_address);
unset($cleanObject->fk_incoterms);
unset($cleanObject->all_permissions_are_loaded);
unset($cleanObject->shipping_method_id);
unset($cleanObject->nb_rights);
unset($cleanObject->search_sid);
unset($cleanObject->ldap_sid);
unset($cleanObject->clicktodial_loaded);
unset($cleanObject->datec);
unset($cleanObject->datem);
unset($cleanObject->members);
unset($cleanObject->note);
unset($cleanObject->note_private);
unset($cleanObject->datec);
unset($cleanObject->datem);
unset($cleanObject->members);
unset($cleanObject->note);
unset($cleanObject->note_private);
$cleanObjectList[] = $cleanObject;
}
$cleanObjectList[] = $cleanObject;
}
return $cleanObjectList;
}
return $cleanObjectList;
}
/**
* Validate fields before create or update object
*
*
* @param array|null $data Data to validate
* @return array
* @throws RestException
*/
private function _validate($data)
{
$account = array();
foreach (Users::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$account[$field] = $data[$field];
}
return $account;
}
*/
private function _validate($data)
{
$account = array();
foreach (Users::$FIELDS as $field) {
if (!isset($data[$field])) {
throw new RestException(400, "$field field missing");
}
$account[$field] = $data[$field];
}
return $account;
}
}

File diff suppressed because it is too large Load Diff