From 5d0ac98c34b285274df0741981400f9ac9c63f6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Thu, 29 Oct 2020 00:34:41 +0100 Subject: [PATCH] work on zapier --- dev/examples/zapier/authentication.js | 2 +- dev/examples/zapier/creates/thirdparty.js | 6 +- dev/examples/zapier/index.js | 4 +- dev/examples/zapier/package.json | 4 +- dev/examples/zapier/searches/thirdparty.js | 15 +- dev/examples/zapier/triggers/action.js | 12 +- dev/examples/zapier/triggers/order.js | 8 +- dev/examples/zapier/triggers/thirdparty.js | 8 +- dev/examples/zapier/triggers/user.js | 176 +++ ...face_99_modZapier_ZapierTriggers.class.php | 804 ++++++------- htdocs/user/class/api_users.class.php | 625 +++++----- htdocs/user/class/user.class.php | 1004 +++++++++-------- 12 files changed, 1452 insertions(+), 1216 deletions(-) create mode 100644 dev/examples/zapier/triggers/user.js diff --git a/dev/examples/zapier/authentication.js b/dev/examples/zapier/authentication.js index 1c95c76f9c2..3e595bddd6d 100644 --- a/dev/examples/zapier/authentication.js +++ b/dev/examples/zapier/authentication.js @@ -48,7 +48,7 @@ module.exports = { fields: [ { key: 'url', - label: 'Url of service', + label: 'Url of service without ending-slash', required: true, type: 'string' }, diff --git a/dev/examples/zapier/creates/thirdparty.js b/dev/examples/zapier/creates/thirdparty.js index 82cc39f8fab..3e20fd10e41 100644 --- a/dev/examples/zapier/creates/thirdparty.js +++ b/dev/examples/zapier/creates/thirdparty.js @@ -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'} ] diff --git a/dev/examples/zapier/index.js b/dev/examples/zapier/index.js index fc452a196e6..0a46f7c38d0 100644 --- a/dev/examples/zapier/index.js +++ b/dev/examples/zapier/index.js @@ -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! diff --git a/dev/examples/zapier/package.json b/dev/examples/zapier/package.json index be13c719c97..5b5827b22b2 100644 --- a/dev/examples/zapier/package.json +++ b/dev/examples/zapier/package.json @@ -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", diff --git a/dev/examples/zapier/searches/thirdparty.js b/dev/examples/zapier/searches/thirdparty.js index c71c2965789..8f72b9270e5 100644 --- a/dev/examples/zapier/searches/thirdparty.js +++ b/dev/examples/zapier/searches/thirdparty.js @@ -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' + } ] } }; diff --git a/dev/examples/zapier/triggers/action.js b/dev/examples/zapier/triggers/action.js index d387d88ec1f..8d55abc6ee0 100644 --- a/dev/examples/zapier/triggers/action.js +++ b/dev/examples/zapier/triggers/action.js @@ -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'} ] } diff --git a/dev/examples/zapier/triggers/order.js b/dev/examples/zapier/triggers/order.js index 6262d734edc..c423583028c 100644 --- a/dev/examples/zapier/triggers/order.js +++ b/dev/examples/zapier/triggers/order.js @@ -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'} ] diff --git a/dev/examples/zapier/triggers/thirdparty.js b/dev/examples/zapier/triggers/thirdparty.js index 4b13e23ff1c..dfad664d98c 100644 --- a/dev/examples/zapier/triggers/thirdparty.js +++ b/dev/examples/zapier/triggers/thirdparty.js @@ -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'}, diff --git a/dev/examples/zapier/triggers/user.js b/dev/examples/zapier/triggers/user.js new file mode 100644 index 00000000000..53afc5cf324 --- /dev/null +++ b/dev/examples/zapier/triggers/user.js @@ -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'} + ] + } +}; diff --git a/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php b/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php index 95595863cb3..a0210fcd9d0 100644 --- a/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php +++ b/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php @@ -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; } diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php index 5245ff0b961..4260a1b0791 100644 --- a/htdocs/user/class/api_users.class.php +++ b/htdocs/user/class/api_users.class.php @@ -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; + } } diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index 87f36cab15a..ee18a60104c 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -284,29 +284,26 @@ class User extends CommonObject $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON u.fk_country = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON u.fk_state = d.rowid"; - if ($entity < 0) - { - if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty($user->entity))) - { + if ($entity < 0) { + if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty($user->entity))) { $sql .= " WHERE u.entity IN (0,".$conf->entity.")"; } else { $sql .= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database } } else // The fetch was forced on an entity { - if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database - else $sql .= " WHERE u.entity IN (0, ".(($entity != '' && $entity >= 0) ? $entity : $conf->entity).")"; // search in entity provided in parameter + } else { + $sql .= " WHERE u.entity IN (0, ".(($entity != '' && $entity >= 0) ? $entity : $conf->entity).")"; // search in entity provided in parameter + } } - if ($sid) // permet une recherche du user par son SID ActiveDirectory ou Samba - { + if ($sid) { // permet une recherche du user par son SID ActiveDirectory ou Samba $sql .= " AND (u.ldap_sid = '".$this->db->escape($sid)."' OR u.login = '".$this->db->escape($login)."') LIMIT 1"; - } elseif ($login) - { + } elseif ($login) { $sql .= " AND u.login = '".$this->db->escape($login)."'"; - } elseif ($email) - { + } elseif ($email) { $sql .= " AND u.email = '".$this->db->escape($email)."'"; } else { $sql .= " AND u.rowid = ".$id; @@ -314,11 +311,9 @@ class User extends CommonObject $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->ref = $obj->rowid; @@ -399,7 +394,9 @@ class User extends CommonObject // Protection when module multicompany was set, admin was set to first entity and then, the module was disabled, // in such case, this admin user must be admin for ALL entities. - if (empty($conf->multicompany->enabled) && $this->admin && $this->entity == 1) $this->entity = 0; + if (empty($conf->multicompany->enabled) && $this->admin && $this->entity == 1) { + $this->entity = 0; + } // Retrieve all extrafield // fetch optionals attributes and labels @@ -419,23 +416,22 @@ class User extends CommonObject } // To get back the global configuration unique to the user - if ($loadpersonalconf) - { + if ($loadpersonalconf) { // Load user->conf for user $sql = "SELECT param, value FROM ".MAIN_DB_PREFIX."user_param"; $sql .= " WHERE fk_user = ".$this->id; $sql .= " AND entity = ".$conf->entity; //dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $p = (!empty($obj->param) ? $obj->param : ''); - if (!empty($p)) $this->conf->$p = $obj->value; + if (!empty($p)) { + $this->conf->$p = $obj->value; + } $i++; } $this->db->free($resql); @@ -446,8 +442,7 @@ class User extends CommonObject $result = $this->loadDefaultValues(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -471,20 +466,16 @@ class User extends CommonObject $sql .= " WHERE entity IN (".($this->entity > 0 ? $this->entity.", " : "").$conf->entity.")"; // Entity of user (if defined) + current entity $sql .= " AND user_id IN (0".($this->id > 0 ? ", ".$this->id : "").")"; // User 0 (all) + me (if defined) $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - if (!empty($obj->page) && !empty($obj->type) && !empty($obj->param)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + if (!empty($obj->page) && !empty($obj->type) && !empty($obj->param)) { // $obj->page is relative URL with or without params // $obj->type can be 'filters', 'sortorder', 'createform', ... // $obj->param is key or param $pagewithoutquerystring = $obj->page; $pagequeries = ''; $reg = array(); - if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) // There is query param - { + if (preg_match('/^([^\?]+)\?(.*)$/', $pagewithoutquerystring, $reg)) { // There is query param $pagewithoutquerystring = $reg[1]; $pagequeries = $reg[2]; } @@ -494,10 +485,8 @@ class User extends CommonObject } // Sort by key, so _noquery_ is last if (!empty($this->default_values)) { - foreach ($this->default_values as $a => $b) - { - foreach ($b as $c => $d) - { + foreach ($this->default_values as $a => $b) { + foreach ($b as $c => $d) { krsort($this->default_values[$a][$c]); } } @@ -534,8 +523,7 @@ class User extends CommonObject $this->db->begin(); - if (!empty($rid)) - { + if (!empty($rid)) { // Si on a demande ajout d'un droit en particulier, on recupere // les caracteristiques (module, perms et subperms) de ce droit. $sql = "SELECT module, perms, subperms"; @@ -557,27 +545,29 @@ class User extends CommonObject // Where pour la liste des droits a ajouter $whereforadd = "id=".$this->db->escape($rid); // Ajout des droits induits - if (!empty($subperms)) $whereforadd .= " OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))"; - elseif (!empty($perms)) $whereforadd .= " OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)"; + if (!empty($subperms)) { + $whereforadd .= " OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))"; + } elseif (!empty($perms)) { + $whereforadd .= " OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)"; + } } else { // On a pas demande un droit en particulier mais une liste de droits // sur la base d'un nom de module de de perms // Where pour la liste des droits a ajouter - if (!empty($allmodule)) - { - if ($allmodule == 'allmodules') - { + if (!empty($allmodule)) { + if ($allmodule == 'allmodules') { $whereforadd = 'allmodules'; } else { $whereforadd = "module='".$this->db->escape($allmodule)."'"; - if (!empty($allperms)) $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + if (!empty($allperms)) { + $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + } } } } // Ajout des droits trouves grace au critere whereforadd - if (!empty($whereforadd)) - { + if (!empty($whereforadd)) { //print "$module-$perms-$subperms"; $sql = "SELECT id"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def"; @@ -587,19 +577,21 @@ class User extends CommonObject } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $nid = $obj->id; $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id." AND fk_id=".$nid." AND entity = ".$entity; - if (!$this->db->query($sql)) $error++; + if (!$this->db->query($sql)) { + $error++; + } $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (entity, fk_user, fk_id) VALUES (".$entity.", ".$this->id.", ".$nid.")"; - if (!$this->db->query($sql)) $error++; + if (!$this->db->query($sql)) { + $error++; + } $i++; } @@ -609,14 +601,15 @@ class User extends CommonObject } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { $langs->load("other"); $this->context = array('audit'=>$langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : '')); // Call trigger $result = $this->call_trigger('USER_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -673,26 +666,29 @@ class User extends CommonObject // Where pour la liste des droits a supprimer $wherefordel = "id=".$this->db->escape($rid); // Suppression des droits induits - if ($subperms == 'lire' || $subperms == 'read') $wherefordel .= " OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)"; - if ($perms == 'lire' || $perms == 'read') $wherefordel .= " OR (module='$module')"; + if ($subperms == 'lire' || $subperms == 'read') { + $wherefordel .= " OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)"; + } + if ($perms == 'lire' || $perms == 'read') { + $wherefordel .= " OR (module='$module')"; + } } else { // On a demande suppression d'un droit sur la base d'un nom de module ou perms // Where pour la liste des droits a supprimer - if (!empty($allmodule)) - { - if ($allmodule == 'allmodules') - { + if (!empty($allmodule)) { + if ($allmodule == 'allmodules') { $wherefordel = 'allmodules'; } else { $wherefordel = "module='".$this->db->escape($allmodule)."'"; - if (!empty($allperms)) $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + if (!empty($allperms)) { + $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + } } } } // Suppression des droits selon critere defini dans wherefordel - if (!empty($wherefordel)) - { + if (!empty($wherefordel)) { //print "$module-$perms-$subperms"; $sql = "SELECT id"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def"; @@ -702,8 +698,7 @@ class User extends CommonObject } // avoid admin can remove his own important rights - if ($this->admin == 1) - { + if ($this->admin == 1) { $sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights $sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights $sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights @@ -711,19 +706,19 @@ class User extends CommonObject } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $nid = $obj->id; $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights"; $sql .= " WHERE fk_user = ".$this->id." AND fk_id=".$nid; $sql .= " AND entity = ".$entity; - if (!$this->db->query($sql)) $error++; + if (!$this->db->query($sql)) { + $error++; + } $i++; } @@ -733,14 +728,15 @@ class User extends CommonObject } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { $langs->load("other"); $this->context = array('audit'=>$langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : '')); // Call trigger $result = $this->call_trigger('USER_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -782,16 +778,13 @@ class User extends CommonObject { global $conf; - if (empty($forcereload)) - { - if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) - { + if (empty($forcereload)) { + if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) { // Rights for this module are already loaded, so we leave return; } - if (!empty($this->all_permissions_are_loaded)) - { + if (!empty($this->all_permissions_are_loaded)) { // We already loaded all rights for this user, so we leave return; } @@ -804,42 +797,48 @@ class User extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur"; $sql .= ", ".MAIN_DB_PREFIX."rights_def as r"; $sql .= " WHERE r.id = ur.fk_id"; - if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) - { + if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) { $sql .= " AND r.entity IN (0,".(!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "").$conf->entity.")"; } else { $sql .= " AND ur.entity = ".$conf->entity; } $sql .= " AND ur.fk_user= ".$this->id; $sql .= " AND r.perms IS NOT NULL"; - if ($moduletag) $sql .= " AND r.module = '".$this->db->escape($moduletag)."'"; + if ($moduletag) { + $sql .= " AND r.module = '".$this->db->escape($moduletag)."'"; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $module = $obj->module; $perms = $obj->perms; $subperms = $obj->subperms; - if ($perms) - { - if (!isset($this->rights) || !is_object($this->rights)) $this->rights = new stdClass(); // For avoid error - if ($module) - { - if (!isset($this->rights->$module) || !is_object($this->rights->$module)) $this->rights->$module = new stdClass(); - if ($subperms) - { - if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass(); - if (empty($this->rights->$module->$perms->$subperms)) $this->nb_rights++; + if ($perms) { + if (!isset($this->rights) || !is_object($this->rights)) { + $this->rights = new stdClass(); // For avoid error + } + if ($module) { + if (!isset($this->rights->$module) || !is_object($this->rights->$module)) { + $this->rights->$module = new stdClass(); + } + if ($subperms) { + if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) { + $this->rights->$module->$perms = new stdClass(); + } + if (empty($this->rights->$module->$perms->$subperms)) { + $this->nb_rights++; + } $this->rights->$module->$perms->$subperms = 1; } else { - if (empty($this->rights->$module->$perms)) $this->nb_rights++; + if (empty($this->rights->$module->$perms)) { + $this->nb_rights++; + } $this->rights->$module->$perms = 1; } } @@ -855,8 +854,7 @@ class User extends CommonObject $sql .= " ".MAIN_DB_PREFIX."usergroup_user as gu,"; $sql .= " ".MAIN_DB_PREFIX."rights_def as r"; $sql .= " WHERE r.id = gr.fk_id"; - if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) - { + if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) { if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= " AND gu.entity IN (0,".$conf->entity.")"; } else { @@ -870,34 +868,44 @@ class User extends CommonObject $sql .= " AND gr.fk_usergroup = gu.fk_usergroup"; $sql .= " AND gu.fk_user = ".$this->id; $sql .= " AND r.perms IS NOT NULL"; - if ($moduletag) $sql .= " AND r.module = '".$this->db->escape($moduletag)."'"; + if ($moduletag) { + $sql .= " AND r.module = '".$this->db->escape($moduletag)."'"; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $module = $obj->module; $perms = $obj->perms; $subperms = $obj->subperms; - if ($perms) - { - if (!isset($this->rights) || !is_object($this->rights)) $this->rights = new stdClass(); // For avoid error - if (!isset($this->rights->$module) || !is_object($this->rights->$module)) $this->rights->$module = new stdClass(); - if ($subperms) - { - if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass(); - if (empty($this->rights->$module->$perms->$subperms)) $this->nb_rights++; + if ($perms) { + if (!isset($this->rights) || !is_object($this->rights)) { + $this->rights = new stdClass(); // For avoid error + } + if (!isset($this->rights->$module) || !is_object($this->rights->$module)) { + $this->rights->$module = new stdClass(); + } + if ($subperms) { + if (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) { + $this->rights->$module->$perms = new stdClass(); + } + if (empty($this->rights->$module->$perms->$subperms)) { + $this->nb_rights++; + } $this->rights->$module->$perms->$subperms = 1; } else { - if (empty($this->rights->$module->$perms)) $this->nb_rights++; + if (empty($this->rights->$module->$perms)) { + $this->nb_rights++; + } // if we have already define a subperm like this $this->rights->$module->level1->level2 with llx_user_rights, we don't want override level1 because the level2 can be not define on user group - if (!is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = 1; + if (!is_object($this->rights->$module->$perms)) { + $this->rights->$module->$perms = 1; + } } } $i++; @@ -906,11 +914,14 @@ class User extends CommonObject } // For backward compatibility - if (isset($this->rights->propale) && !isset($this->rights->propal)) $this->rights->propal = $this->rights->propale; - if (isset($this->rights->propal) && !isset($this->rights->propale)) $this->rights->propale = $this->rights->propal; + if (isset($this->rights->propale) && !isset($this->rights->propal)) { + $this->rights->propal = $this->rights->propale; + } + if (isset($this->rights->propal) && !isset($this->rights->propale)) { + $this->rights->propale = $this->rights->propal; + } - if (!$moduletag) - { + if (!$moduletag) { // Si module etait non defini, alors on a tout charge, on peut donc considerer // que les droits sont en cache (car tous charges) pour cet instance de user $this->all_permissions_are_loaded = 1; @@ -933,8 +944,11 @@ class User extends CommonObject $error = 0; // Check parameters - if ($this->statut == $status) return 0; - else $this->statut = $status; + if ($this->statut == $status) { + return 0; + } else { + $this->statut = $status; + } $this->db->begin(); @@ -945,16 +959,16 @@ class User extends CommonObject $result = $this->db->query($sql); dol_syslog(get_class($this)."::setstatus", LOG_DEBUG); - if ($result) - { + if ($result) { // Call trigger $result = $this->call_trigger('USER_ENABLEDISABLE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if ($error) - { + if ($error) { $this->db->rollback(); return -$error; } else { @@ -1033,68 +1047,57 @@ class User extends CommonObject // Remove rights $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id; - if (!$error && !$this->db->query($sql)) - { + if (!$error && !$this->db->query($sql)) { $error++; $this->error = $this->db->lasterror(); } // Remove group $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user WHERE fk_user = ".$this->id; - if (!$error && !$this->db->query($sql)) - { + if (!$error && !$this->db->query($sql)) { $error++; $this->error = $this->db->lasterror(); } // Remove params $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param WHERE fk_user = ".$this->id; - if (!$error && !$this->db->query($sql)) - { + if (!$error && !$this->db->query($sql)) { $error++; $this->error = $this->db->lasterror(); } // If contact, remove link - if ($this->contact_id > 0) - { + if ($this->contact_id > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET fk_user_creat = null WHERE rowid = ".$this->contact_id; - if (!$error && !$this->db->query($sql)) - { + if (!$error && !$this->db->query($sql)) { $error++; $this->error = $this->db->lasterror(); } } // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } // Remove user - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if (!$this->db->query($sql)) - { - $error++; - $this->error = $this->db->lasterror(); - } + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + if (!$this->db->query($sql)) { + $error++; + $this->error = $this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('USER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $error++; $this->db->rollback(); return -1; @@ -1123,24 +1126,30 @@ class User extends CommonObject // Clean parameters - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = dol_ucwords(dol_strtolower($this->lastname)); - if (!empty($conf->global->MAIN_ALL_TO_UPPER)) $this->lastname = dol_strtoupper($this->lastname); - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = dol_ucwords(dol_strtolower($this->firstname)); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) { + $this->lastname = dol_ucwords(dol_strtolower($this->lastname)); + } + if (!empty($conf->global->MAIN_ALL_TO_UPPER)) { + $this->lastname = dol_strtoupper($this->lastname); + } + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) { + $this->firstname = dol_ucwords(dol_strtolower($this->firstname)); + } $this->login = trim($this->login); - if (!isset($this->entity)) $this->entity = $conf->entity; // If not defined, we use default value + if (!isset($this->entity)) { + $this->entity = $conf->entity; // If not defined, we use default value + } dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object($user) ? $user->id : ''), LOG_DEBUG); // Check parameters - if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) - { + if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) { $langs->load("errors"); $this->error = $langs->trans("ErrorBadEMail", $this->email); return -1; } - if (empty($this->login)) - { + if (empty($this->login)) { $langs->load("errors"); $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login")); return -1; @@ -1157,13 +1166,11 @@ class User extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $this->db->free($resql); - if ($num) - { + if ($num) { $this->error = 'ErrorLoginAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); @@ -1174,20 +1181,17 @@ class User extends CommonObject $result = $this->db->query($sql); dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."user"); // Set default rights - if ($this->set_default_rights() < 0) - { + if ($this->set_default_rights() < 0) { $this->error = 'ErrorFailedToSetDefaultRightOfUser'; $this->db->rollback(); return -5; } - if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) - { + if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $langs->load("stocks"); $entrepot = new Entrepot($this->db); @@ -1203,22 +1207,21 @@ class User extends CommonObject // Update minor fields $result = $this->update($user, 1, 1); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -4; } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('USER_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1274,29 +1277,33 @@ class User extends CommonObject $this->country_id = $contact->country_id; $this->employee = 0; - if (empty($login)) $login = strtolower(substr($contact->firstname, 0, 4)).strtolower(substr($contact->lastname, 0, 4)); + if (empty($login)) { + $login = strtolower(substr($contact->firstname, 0, 4)).strtolower(substr($contact->lastname, 0, 4)); + } $this->login = $login; $this->db->begin(); // Create user and set $this->id. Trigger is disabled because executed later. $result = $this->create($user, 1); - if ($result > 0) - { + if ($result > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql .= " SET fk_socpeople=".$contact->id; - if ($contact->socid) $sql .= ", fk_soc=".$contact->socid; + if ($contact->socid) { + $sql .= ", fk_soc=".$contact->socid; + } $sql .= " WHERE rowid=".$this->id; $resql = $this->db->query($sql); dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG); - if ($resql) - { + if ($resql) { $this->context['createfromcontact'] = 'createfromcontact'; // Call trigger $result = $this->call_trigger('USER_CREATE', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers $this->db->commit(); @@ -1347,40 +1354,40 @@ class User extends CommonObject $this->pass = $member->pass; $this->pass_crypted = $member->pass_indatabase_crypted; - if (empty($login)) $login = strtolower(substr($member->firstname, 0, 4)).strtolower(substr($member->lastname, 0, 4)); + if (empty($login)) { + $login = strtolower(substr($member->firstname, 0, 4)).strtolower(substr($member->lastname, 0, 4)); + } $this->login = $login; $this->db->begin(); // Create and set $this->id $result = $this->create($user); - if ($result > 0) - { + if ($result > 0) { if (!empty($this->pass)) { // If a clear password was received (this situation should not happen anymore now), we use it to save it into database $newpass = $this->setPassword($user, $this->pass); - if (is_numeric($newpass) && $newpass < 0) $result = -2; + if (is_numeric($newpass) && $newpass < 0) { + $result = -2; + } } elseif (!empty($this->pass_crypted)) { // If a crypted password is already known, we save it directly into database because the previous create did not save it. $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql .= " SET pass_crypted = '".$this->db->escape($this->pass_crypted)."'"; $sql .= " WHERE rowid=".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $result = -1; } } - if ($result > 0 && $member->fk_soc) // If member is linked to a thirdparty - { + if ($result > 0 && $member->fk_soc) { // If member is linked to a thirdparty $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql .= " SET fk_soc=".$member->fk_soc; $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return $this->id; } else { @@ -1392,8 +1399,7 @@ class User extends CommonObject } } - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->id; } else { @@ -1419,13 +1425,11 @@ class User extends CommonObject $sql .= " AND entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; $rd = array(); - while ($i < $num) - { + while ($i < $num) { $row = $this->db->fetch_row($resql); $rd[$i] = $row[0]; $i++; @@ -1433,14 +1437,15 @@ class User extends CommonObject $this->db->free($resql); } $i = 0; - while ($i < $num) - { + while ($i < $num) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]"; $result = $this->db->query($sql); $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])"; $result = $this->db->query($sql); - if (!$result) return -1; + if (!$result) { + return -1; + } $i++; } @@ -1468,9 +1473,15 @@ class User extends CommonObject // Clean parameters - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = dol_ucwords(dol_strtolower($this->lastname)); - if (!empty($conf->global->MAIN_ALL_TO_UPPER)) $this->lastname = dol_strtoupper($this->lastname); - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = dol_ucwords(dol_strtolower($this->firstname)); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) { + $this->lastname = dol_ucwords(dol_strtolower($this->lastname)); + } + if (!empty($conf->global->MAIN_ALL_TO_UPPER)) { + $this->lastname = dol_strtoupper($this->lastname); + } + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) { + $this->firstname = dol_ucwords(dol_strtolower($this->firstname)); + } $this->lastname = trim($this->lastname); $this->firstname = trim($this->firstname); @@ -1510,14 +1521,12 @@ class User extends CommonObject $this->fk_warehouse = trim(empty($this->fk_warehouse) ? '' : $this->fk_warehouse); // Check parameters - if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) - { + if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) { $langs->load("errors"); $this->error = $langs->trans("ErrorBadEMail", $this->email); return -1; } - if (empty($this->login)) - { + if (empty($this->login)) { $langs->load("errors"); $this->error = $langs->trans("ErrorFieldRequired", 'Login'); return -1; @@ -1534,7 +1543,9 @@ class User extends CommonObject $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape($this->api_key)."'" : "null"); $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth)."'" : 'null'); - if (!empty($user->admin)) $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user + if (!empty($user->admin)) { + $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user + } $sql .= ", address = '".$this->db->escape($this->address)."'"; $sql .= ", zip = '".$this->db->escape($this->zip)."'"; $sql .= ", town = '".$this->db->escape($this->town)."'"; @@ -1562,10 +1573,18 @@ class User extends CommonObject $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".$this->db->escape($this->fk_user)."'" : "null"); $sql .= ", fk_user_expense_validator = ".($this->fk_user_expense_validator > 0 ? "'".$this->db->escape($this->fk_user_expense_validator)."'" : "null"); $sql .= ", fk_user_holiday_validator = ".($this->fk_user_holiday_validator > 0 ? "'".$this->db->escape($this->fk_user_holiday_validator)."'" : "null"); - if (isset($this->thm) || $this->thm != '') $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null"); - if (isset($this->tjm) || $this->tjm != '') $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null"); - if (isset($this->salary) || $this->salary != '') $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null"); - if (isset($this->salaryextra) || $this->salaryextra != '') $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null"); + if (isset($this->thm) || $this->thm != '') { + $sql .= ", thm= ".($this->thm != '' ? "'".$this->db->escape($this->thm)."'" : "null"); + } + if (isset($this->tjm) || $this->tjm != '') { + $sql .= ", tjm= ".($this->tjm != '' ? "'".$this->db->escape($this->tjm)."'" : "null"); + } + if (isset($this->salary) || $this->salary != '') { + $sql .= ", salary= ".($this->salary != '' ? "'".$this->db->escape($this->salary)."'" : "null"); + } + if (isset($this->salaryextra) || $this->salaryextra != '') { + $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".$this->db->escape($this->salaryextra)."'" : "null"); + } $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".$this->db->escape($this->weeklyhours)."'" : "null"); $sql .= ", entity = '".$this->db->escape($this->entity)."'"; $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null'); @@ -1576,39 +1595,39 @@ class User extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $nbrowsaffected += $this->db->affected_rows($resql); // Update password - if (!empty($this->pass)) - { - if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) - { + if (!empty($this->pass)) { + if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) { // Si mot de passe saisi et different de celui en base $result = $this->setPassword($user, $this->pass, 0, $notrigger, $nosyncmemberpass); - if (!$nbrowsaffected) $nbrowsaffected++; + if (!$nbrowsaffected) { + $nbrowsaffected++; + } } } // If user is linked to a member, remove old link to this member - if ($this->fk_member > 0) - { + if ($this->fk_member > 0) { dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG); $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL where fk_member = ".$this->fk_member; $resql = $this->db->query($sql); - if (!$resql) { $this->error = $this->db->error(); $this->db->rollback(); return -5; } + if (!$resql) { + $this->error = $this->db->error(); $this->db->rollback(); return -5; + } } // Set link to user dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG); $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member =".($this->fk_member > 0 ? $this->fk_member : 'null')." where rowid = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) { $this->error = $this->db->error(); $this->db->rollback(); return -5; } + if (!$resql) { + $this->error = $this->db->error(); $this->db->rollback(); return -5; + } - if ($nbrowsaffected) // If something has changed in data - { - if ($this->fk_member > 0 && !$nosyncmember) - { + if ($nbrowsaffected) { // If something has changed in data + if ($this->fk_member > 0 && !$nosyncmember) { dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG); require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; @@ -1618,8 +1637,7 @@ class User extends CommonObject $adh = new Adherent($this->db); $result = $adh->fetch($this->fk_member); - if ($result > 0) - { + if ($result > 0) { $adh->firstname = $this->firstname; $adh->lastname = $this->lastname; $adh->login = $this->login; @@ -1647,23 +1665,20 @@ class User extends CommonObject $adh->user_login = $this->login; $result = $adh->update($user, 0, 1, 0); - if ($result < 0) - { + if ($result < 0) { $this->error = $adh->error; $this->errors = $adh->errors; dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR); $error++; } - } elseif ($result < 0) - { + } elseif ($result < 0) { $this->error = $adh->error; $this->errors = $adh->errors; $error++; } } - if ($this->contact_id > 0 && !$nosynccontact) - { + if ($this->contact_id > 0 && !$nosynccontact) { dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG); require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; @@ -1672,8 +1687,7 @@ class User extends CommonObject $tmpobj = new Contact($this->db); $result = $tmpobj->fetch($this->contact_id); - if ($result >= 0) - { + if ($result >= 0) { $tmpobj->firstname = $this->firstname; $tmpobj->lastname = $this->lastname; $tmpobj->login = $this->login; @@ -1702,8 +1716,7 @@ class User extends CommonObject $tmpobj->user_login = $this->login; $result = $tmpobj->update($tmpobj->id, $user, 0, 'update', 1); - if ($result < 0) - { + if ($result < 0) { $this->error = $tmpobj->error; $this->errors = $tmpobj->errors; dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR); @@ -1720,25 +1733,23 @@ class User extends CommonObject $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('USER_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $nbrowsaffected; } else { @@ -1773,8 +1784,7 @@ class User extends CommonObject dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->datepreviouslogin = $this->datelastlogin; $this->datelastlogin = $now; return 1; @@ -1805,8 +1815,7 @@ class User extends CommonObject dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG); // If new password not provided, we generate one - if (!$password) - { + if (!$password) { $password = getRandomPassword(false); } @@ -1814,17 +1823,17 @@ class User extends CommonObject $password_crypted = dol_hash($password); // Mise a jour - if (!$changelater) - { - if (!is_object($this->oldcopy)) $this->oldcopy = clone $this; + if (!$changelater) { + if (!is_object($this->oldcopy)) { + $this->oldcopy = clone $this; + } $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."user"; $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."',"; $sql .= " pass_temp = null"; - if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) - { + if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { $sql .= ", pass = null"; } else { $sql .= ", pass = '".$this->db->escape($password)."'"; @@ -1833,16 +1842,13 @@ class User extends CommonObject dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->affected_rows($result)) - { + if ($result) { + if ($this->db->affected_rows($result)) { $this->pass = $password; $this->pass_indatabase = $password; $this->pass_indatabase_crypted = $password_crypted; - if ($this->fk_member && !$nosyncmember) - { + if ($this->fk_member && !$nosyncmember) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; // This user is linked with a member, so we also update members informations @@ -1850,11 +1856,9 @@ class User extends CommonObject $adh = new Adherent($this->db); $result = $adh->fetch($this->fk_member); - if ($result >= 0) - { + if ($result >= 0) { $result = $adh->setPassword($user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent - if ($result < 0) - { + if ($result < 0) { $this->error = $adh->error; dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR); $error++; @@ -1867,11 +1871,12 @@ class User extends CommonObject dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('USER_NEW_PASSWORD', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } @@ -1895,8 +1900,7 @@ class User extends CommonObject dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log $result = $this->db->query($sql); - if ($result) - { + if ($result) { return $password; } else { dol_print_error($this->db); @@ -1931,8 +1935,7 @@ class User extends CommonObject $outputlangs = new Translate("", $conf); if (isset($this->conf->MAIN_LANG_DEFAULT) - && $this->conf->MAIN_LANG_DEFAULT != 'auto') - { // If user has defined its own language (rare because in most cases, auto is used) + && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used) $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT); } @@ -1946,7 +1949,9 @@ class User extends CommonObject $outputlangs->loadLangs(array("main", "errors", "users", "other")); $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $appli = $conf->global->MAIN_APPLICATION_TITLE; + } $subject = $outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli); @@ -1954,8 +1959,7 @@ class User extends CommonObject $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - if (!$changelater) - { + if (!$changelater) { $url = $urlwithroot.'/'; $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n"; $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n"; @@ -2002,8 +2006,7 @@ class User extends CommonObject $trackid ); - if ($mailfile->sendfile()) - { + if ($mailfile->sendfile()) { return 1; } else { $langs->trans("errors"); @@ -2037,10 +2040,8 @@ class User extends CommonObject $sql .= " WHERE u.fk_user = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->clicktodial_url = $obj->url; @@ -2086,8 +2087,7 @@ class User extends CommonObject dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->db->commit(); return 1; } else { @@ -2127,21 +2127,20 @@ class User extends CommonObject $sql .= " VALUES (".$entity.",".$this->id.",".$group.")"; $result = $this->db->query($sql); - if ($result) - { - if (!$error && !$notrigger) - { + if ($result) { + if (!$error && !$notrigger) { $this->newgroupid = $group; // deprecated. Remove this. $this->context = array('audit'=>$langs->trans("UserSetInGroup"), 'newgroupid'=>$group); // Call trigger $result = $this->call_trigger('USER_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2180,21 +2179,20 @@ class User extends CommonObject $sql .= " AND entity = ".$entity; $result = $this->db->query($sql); - if ($result) - { - if (!$error && !$notrigger) - { + if ($result) { + if (!$error && !$notrigger) { $this->oldgroupid = $group; // deprecated. Remove this. $this->context = array('audit'=>$langs->trans("UserRemovedFromGroup"), 'oldgroupid'=>$group); // Call trigger $result = $this->call_trigger('USER_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2250,14 +2248,17 @@ class User extends CommonObject global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - if (!$user->rights->user->user->lire && $user->id != $this->id) $option = 'nolink'; + if (!$user->rights->user->user->lire && $user->id != $this->id) { + $option = 'nolink'; + } - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg = 0; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) { + $withpictoimg = 0; + } $result = ''; $label = ''; - if (!empty($this->photo)) - { + if (!empty($this->photo)) { $label .= '
'; $label .= Form::showphoto('userphoto', $this, 0, 60, 0, 'photowithmargin photologintooltip', 'small', 0, 1); // Force height to 60 so we total height of tooltip can be calculated and collision can be managed $label .= '
'; @@ -2267,29 +2268,38 @@ class User extends CommonObject $label .= '
'; $label .= img_picto('', $this->picto).' '.$langs->trans("User").'
'; $label .= ''.$langs->trans('Name').': '.$this->getFullName($langs, ''); - if (!empty($this->login)) $label .= '
'.$langs->trans('Login').': '.$this->login; - if (!empty($this->job)) $label .= '
'.$langs->trans("Job").': '.$this->job; + if (!empty($this->login)) { + $label .= '
'.$langs->trans('Login').': '.$this->login; + } + if (!empty($this->job)) { + $label .= '
'.$langs->trans("Job").': '.$this->job; + } $label .= '
'.$langs->trans("Email").': '.$this->email; - if (!empty($this->phone)) $label .= '
'.$langs->trans("Phone").': '.$this->phone; - if (!empty($this->admin)) + if (!empty($this->phone)) { + $label .= '
'.$langs->trans("Phone").': '.$this->phone; + } + if (!empty($this->admin)) { $label .= '
'.$langs->trans("Administrator").': '.yn($this->admin); - if (!empty($this->socid)) // Add thirdparty for external users - { + } + if (!empty($this->socid)) { // Add thirdparty for external users $thirdpartystatic = new Societe($db); $thirdpartystatic->fetch($this->socid); - if (empty($hidethirdpartylogo)) $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company + if (empty($hidethirdpartylogo)) { + $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company + } $company = ' ('.$langs->trans("Company").': '.$thirdpartystatic->name.')'; } $type = ($this->socid ? $langs->trans("External").$company : $langs->trans("Internal")); $label .= '
'.$langs->trans("Type").': '.$type; $label .= '
'.$langs->trans("Status").': '.$this->getLibStatut(4); $label .= '
'; - if ($infologin > 0) - { + if ($infologin > 0) { $label .= '
'; $label .= '
'.$langs->trans("Session").''; $label .= '
'.$langs->trans("IPAddress").': '.$_SERVER["REMOTE_ADDR"]; - if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) $label .= '
'.$langs->trans("ConnectedOnMultiCompany").': '.$conf->entity.' (user entity '.$this->entity.')'; + if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) { + $label .= '
'.$langs->trans("ConnectedOnMultiCompany").': '.$conf->entity.' (user entity '.$this->entity.')'; + } $label .= '
'.$langs->trans("AuthenticationMode").': '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'); $label .= '
'.$langs->trans("ConnectedSince").': '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser'); $label .= '
'.$langs->trans("PreviousConnexion").': '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser'); @@ -2300,28 +2310,37 @@ class User extends CommonObject $label .= '
'.$langs->trans("Browser").': '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')'; $label .= '
'.$langs->trans("Layout").': '.$conf->browser->layout; $label .= '
'.$langs->trans("Screen").': '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; - if ($conf->browser->layout == 'phone') $label .= '
'.$langs->trans("Phone").': '.$langs->trans("Yes"); - if (!empty($_SESSION["disablemodules"])) $label .= '
'.$langs->trans("DisabledModules").':
'.join(', ', explode(',', $_SESSION["disablemodules"])); + if ($conf->browser->layout == 'phone') { + $label .= '
'.$langs->trans("Phone").': '.$langs->trans("Yes"); + } + if (!empty($_SESSION["disablemodules"])) { + $label .= '
'.$langs->trans("DisabledModules").':
'.join(', ', explode(',', $_SESSION["disablemodules"])); + } + } + if ($infologin < 0) { + $label = ''; } - if ($infologin < 0) $label = ''; $url = DOL_URL_ROOT.'/user/card.php?id='.$this->id; - if ($option == 'leave') $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id; + if ($option == 'leave') { + $url = DOL_URL_ROOT.'/holiday/list.php?id='.$this->id; + } - if ($option != 'nolink') - { + if ($option != 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkstart = 'global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $langs->load("users"); $label = $langs->trans("ShowUser"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; @@ -2342,22 +2361,33 @@ class User extends CommonObject //if ($withpictoimg == -1) $result.='
'; $result .= (($option == 'nolink') ? '' : $linkstart); - if ($withpictoimg) - { - $paddafterimage = ''; - if (abs($withpictoimg) == 1) $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"'; + if ($withpictoimg) { + $paddafterimage = ''; + if (abs($withpictoimg) == 1) { + $paddafterimage = 'style="margin-'.($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right').': 3px;"'; + } // Only picto - if ($withpictoimg > 0) $picto = ''.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).''; + if ($withpictoimg > 0) { + $picto = ''.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1).''; + } // Picto must be a photo - else $picto = ''.Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1).''; + else { + $picto = ''.Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1).''; + } $result .= $picto; } - if ($withpictoimg > -2 && $withpictoimg != 2) - { - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= ''; - if ($mode == 'login') $result .= dol_trunc($this->login, $maxlen); - else $result .= $this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen); - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= ''; + if ($withpictoimg > -2 && $withpictoimg != 2) { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $result .= ''; + } + if ($mode == 'login') { + $result .= dol_trunc($this->login, $maxlen); + } else { + $result .= $this->getFullName($langs, '', ($mode == 'firstelselast' ? 3 : ($mode == 'firstname' ? 2 : -1)), $maxlen); + } + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $result .= ''; + } } $result .= (($option == 'nolink') ? '' : $linkend); //if ($withpictoimg == -1) $result.='
'; @@ -2368,8 +2398,11 @@ class User extends CommonObject $hookmanager->initHooks(array('userdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -2391,22 +2424,24 @@ class User extends CommonObject $linkend = '
'; //Check user's rights to see an other user - if ((!$user->rights->user->user->lire && $this->id != $user->id)) $option = 'nolink'; + if ((!$user->rights->user->user->lire && $this->id != $user->id)) { + $option = 'nolink'; + } - if ($option == 'xxx') - { + if ($option == 'xxx') { $linkstart = ''; $linkend = ''; } - if ($option == 'nolink') - { + if ($option == 'nolink') { $linkstart = ''; $linkend = ''; } $result .= $linkstart; - if ($withpicto) $result .= img_object($langs->trans("ShowUser"), 'user', 'class="paddingright"'); + if ($withpicto) { + $result .= img_object($langs->trans("ShowUser"), 'user', 'class="paddingright"'); + } $result .= $this->login; $result .= $linkend; return $result; @@ -2436,8 +2471,7 @@ class User extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Enabled'); @@ -2447,7 +2481,9 @@ class User extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_ENABLED) $statusType = 'status4'; + if ($status == self::STATUS_ENABLED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -2469,9 +2505,13 @@ class User extends CommonObject // phpcs:enable global $conf; $dn = ''; - if ($mode == 0) $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".$conf->global->LDAP_USER_DN; - elseif ($mode == 1) $dn = $conf->global->LDAP_USER_DN; - elseif ($mode == 2) $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS]; + if ($mode == 0) { + $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".$conf->global->LDAP_USER_DN; + } elseif ($mode == 1) { + $dn = $conf->global->LDAP_USER_DN; + } elseif ($mode == 2) { + $dn = $conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS]; + } return $dn; } @@ -2514,63 +2554,77 @@ class User extends CommonObject ); // Champs - foreach ($ldapkey as $constname => $varname) - { - if (!empty($this->$varname) && !empty($conf->global->$constname)) - { + foreach ($ldapkey as $constname => $varname) { + if (!empty($this->$varname) && !empty($conf->global->$constname)) { $info[$conf->global->$constname] = $this->$varname; // Check if it is the LDAP key and if its value has been changed - if (!empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) - { - if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified = true; // For check if LDAP key has been modified + if (!empty($conf->global->LDAP_KEY_USERS) && $conf->global->LDAP_KEY_USERS == $conf->global->$constname) { + if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) { + $keymodified = true; // For check if LDAP key has been modified + } } } } - if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address; - if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip; - if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) $info[$conf->global->LDAP_FIELD_TOWN] = $this->town; - if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2); - if ($this->socid > 0) - { + if ($this->address && !empty($conf->global->LDAP_FIELD_ADDRESS)) { + $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address; + } + if ($this->zip && !empty($conf->global->LDAP_FIELD_ZIP)) { + $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip; + } + if ($this->town && !empty($conf->global->LDAP_FIELD_TOWN)) { + $info[$conf->global->LDAP_FIELD_TOWN] = $this->town; + } + if ($this->note_public && !empty($conf->global->LDAP_FIELD_DESCRIPTION)) { + $info[$conf->global->LDAP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_public, 2); + } + if ($this->socid > 0) { $soc = new Societe($this->db); $soc->fetch($this->socid); $info[$conf->global->LDAP_FIELD_COMPANY] = $soc->name; - if ($soc->client == 1) $info["businessCategory"] = "Customers"; - if ($soc->client == 2) $info["businessCategory"] = "Prospects"; - if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers"; + if ($soc->client == 1) { + $info["businessCategory"] = "Customers"; + } + if ($soc->client == 2) { + $info["businessCategory"] = "Prospects"; + } + if ($soc->fournisseur == 1) { + $info["businessCategory"] = "Suppliers"; + } } // When password is modified - if (!empty($this->pass)) - { - if (!empty($conf->global->LDAP_FIELD_PASSWORD)) $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte - if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) + if (!empty($this->pass)) { + if (!empty($conf->global->LDAP_FIELD_PASSWORD)) { + $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte + } + if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) { + $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) + } } // Set LDAP password if possible - elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password - { - if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) - { + elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password + if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { // Just for the default MD5 ! - if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) - { + if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) { if ($this->pass_indatabase_crypted && !empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) { $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase_crypted, 5); // Create OpenLDAP MD5 password from Dolibarr MD5 password } } } // Use $this->pass_indatabase value if exists - elseif (!empty($this->pass_indatabase)) - { - if (!empty($conf->global->LDAP_FIELD_PASSWORD)) $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte - if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + elseif (!empty($this->pass_indatabase)) { + if (!empty($conf->global->LDAP_FIELD_PASSWORD)) { + $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte + } + if (!empty($conf->global->LDAP_FIELD_PASSWORD_CRYPTED)) { + $info[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + } } } - if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') - { + if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') { $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware $info['uidnumber'] = $this->id; @@ -2583,18 +2637,23 @@ class User extends CommonObject $info["phpgwContactCatId"] = 0; $info["phpgwContactAccess"] = "public"; - if (dol_strlen($this->egroupware_id) == 0) - { + if (dol_strlen($this->egroupware_id) == 0) { $this->egroupware_id = 1; } $info["phpgwContactOwner"] = $this->egroupware_id; - if ($this->email) $info["rfc822Mailbox"] = $this->email; - if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile; + if ($this->email) { + $info["rfc822Mailbox"] = $this->email; + } + if ($this->phone_mobile) { + $info["phpgwCellTelephoneNumber"] = $this->phone_mobile; + } } - if (!empty($conf->global->LDAP_FIELD_USERID))$info[$conf->global->LDAP_FIELD_USERID] = $this->id; + if (!empty($conf->global->LDAP_FIELD_USERID)) { + $info[$conf->global->LDAP_FIELD_USERID] = $this->id; + } if (!empty($info[$conf->global->LDAP_FIELD_GROUPID])) { $usergroup = new UserGroup($this->db); $groupslist = $usergroup->listGroupsForUser($this->id); @@ -2606,7 +2665,9 @@ class User extends CommonObject } } } - if (!empty($this->firstname) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORY) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX)) $info[$conf->global->LDAP_FIELD_HOMEDIRECTORY] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->firstname"; + if (!empty($this->firstname) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORY) && !empty($conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX)) { + $info[$conf->global->LDAP_FIELD_HOMEDIRECTORY] = "{$conf->global->LDAP_FIELD_HOMEDIRECTORYPREFIX}/$this->firstname"; + } return $info; } @@ -2617,7 +2678,7 @@ class User extends CommonObject * Used to build previews or test instances. * id must be 0 if object instance is a specimen. * - * @return void + * @return int */ public function initAsSpecimen() { @@ -2660,6 +2721,7 @@ class User extends CommonObject $this->statut = 1; $this->entity = 1; + return 1; } /** @@ -2676,10 +2738,8 @@ class User extends CommonObject $sql .= " WHERE u.rowid = ".$id; $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -2710,8 +2770,7 @@ class User extends CommonObject $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $nb = $obj->nb; @@ -2737,19 +2796,23 @@ class User extends CommonObject $sql = "SELECT count(rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."user"; - if ($option == 'superadmin') - { + if ($option == 'superadmin') { $sql .= " WHERE entity = 0"; - if ($admin >= 0) $sql .= " AND admin = ".$admin; + if ($admin >= 0) { + $sql .= " AND admin = ".$admin; + } } else { $sql .= " WHERE entity IN (".getEntity('user', 0).")"; - if ($limitTo == 'active') $sql .= " AND statut = 1"; - if ($admin >= 0) $sql .= " AND admin = ".$admin; + if ($limitTo == 'active') { + $sql .= " AND statut = 1"; + } + if ($admin >= 0) { + $sql .= " AND admin = ".$admin; + } } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $nb = $obj->nb; @@ -2816,11 +2879,9 @@ class User extends CommonObject dol_syslog(get_class($this)."::get_children sql=".$sql, LOG_DEBUG); $res = $this->db->query($sql); - if ($res) - { + if ($res) { $users = array(); - while ($rec = $this->db->fetch_array($res)) - { + while ($rec = $this->db->fetch_array($res)) { $user = new User($this->db); $user->fetch($rec['rowid']); $users[] = $user; @@ -2852,10 +2913,8 @@ class User extends CommonObject dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->parentof[$obj->id_son] = $obj->id_parent; } return 1; @@ -2904,15 +2963,15 @@ class User extends CommonObject } else { $sql .= " WHERE u.entity IN (".getEntity('user').")"; } - if ($filter) $sql .= " AND ".$filter; + if ($filter) { + $sql .= " AND ".$filter; + } dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $this->users[$obj->rowid]['rowid'] = $obj->rowid; $this->users[$obj->rowid]['id'] = $obj->rowid; $this->users[$obj->rowid]['fk_user'] = $obj->fk_user; @@ -2935,29 +2994,24 @@ class User extends CommonObject // We add the fullpath property to each elements of first level (no parent exists) dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG); - foreach ($this->users as $key => $val) - { + foreach ($this->users as $key => $val) { $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent) - if ($result < 0) - { + if ($result < 0) { $this->error = 'ErrorLoopInHierarchy'; return -1; } } // Exclude leaf including $deleteafterid from tree - if ($deleteafterid) - { + if ($deleteafterid) { //print "Look to discard user ".$deleteafterid."\n"; $keyfilter1 = '^'.$deleteafterid.'$'; $keyfilter2 = '_'.$deleteafterid.'$'; $keyfilter3 = '^'.$deleteafterid.'_'; $keyfilter4 = '_'.$deleteafterid.'_'; - foreach ($this->users as $key => $val) - { + foreach ($this->users as $key => $val) { if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath']) - || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) - { + || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) { unset($this->users[$key]); } } @@ -2983,8 +3037,7 @@ class User extends CommonObject { $childids = array(); - if (isset($this->cache_childids[$this->id])) - { + if (isset($this->cache_childids[$this->id])) { $childids = $this->cache_childids[$this->id]; } else { // Init this->users @@ -2993,15 +3046,18 @@ class User extends CommonObject $idtoscan = $this->id; dol_syslog("Build childid for id = ".$idtoscan); - foreach ($this->users as $id => $val) - { + foreach ($this->users as $id => $val) { //var_dump($val['fullpath']); - if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) $childids[$val['id']] = $val['id']; + if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) { + $childids[$val['id']] = $val['id']; + } } } $this->cache_childids[$this->id] = $childids; - if ($addcurrentuser) $childids[$this->id] = $this->id; + if ($addcurrentuser) { + $childids[$this->id] = $this->id; + } return $childids; } @@ -3020,8 +3076,7 @@ class User extends CommonObject // phpcs:enable //dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG); - if (!empty($this->users[$id_user]['fullpath'])) - { + if (!empty($this->users[$id_user]['fullpath'])) { // Already defined dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING); return 0; @@ -3033,10 +3088,8 @@ class User extends CommonObject $i = 0; $cursor_user = $id_user; $useridfound = array($id_user); - while (!empty($this->parentof[$cursor_user])) - { - if (in_array($this->parentof[$cursor_user], $useridfound)) - { + while (!empty($this->parentof[$cursor_user])) { + if (in_array($this->parentof[$cursor_user], $useridfound)) { dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING); return -1; // Should not happen. Protection against looping hierarchy } @@ -3089,10 +3142,8 @@ class User extends CommonObject $sql .= " AND u.entity IN (".getEntity('user').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["users"] = $obj->nb; } $this->db->free($resql); @@ -3122,10 +3173,8 @@ class User extends CommonObject $langs->load("user"); // Positionne le modele sur le nom du modele a utiliser - if (!dol_strlen($modele)) - { - if (!empty($conf->global->USER_ADDON_PDF)) - { + if (!dol_strlen($modele)) { + if (!empty($conf->global->USER_ADDON_PDF)) { $modele = $conf->global->USER_ADDON_PDF; } else { $modele = 'bluesky'; @@ -3150,23 +3199,26 @@ class User extends CommonObject // phpcs:enable $user_property = ''; - if (empty($rowid)) return ''; + if (empty($rowid)) { + return ''; + } $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname"; $sql .= " FROM ".MAIN_DB_PREFIX."user"; $sql .= " WHERE rowid = ".((int) $rowid); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $nump = $this->db->num_rows($resql); - if ($nump) - { + if ($nump) { $obj = $this->db->fetch_object($resql); - if ($mode == 'email') $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">"; - elseif ($mode == 'mobile') $user_property = $obj->user_mobile; + if ($mode == 'email') { + $user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">"; + } elseif ($mode == 'mobile') { + $user_property = $obj->user_mobile; + } } return $user_property; } else { @@ -3193,10 +3245,8 @@ class User extends CommonObject $sql = "SELECT t.rowid"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t '; - if ($entityfilter) - { - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { + if ($entityfilter) { + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { $sql .= " WHERE t.entity IS NOT NULL"; // Show all users } else { @@ -3231,19 +3281,18 @@ class User extends CommonObject $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; } $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) $sql .= $this->db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $this->db->plimit($limit + 1, $offset); + } dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->users = array(); $num = $this->db->num_rows($resql); - if ($num) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($num) { + while ($obj = $this->db->fetch_object($resql)) { $line = new self($this->db); $result = $line->fetch($obj->rowid); if ($result > 0 && !empty($line->id)) { @@ -3280,8 +3329,7 @@ class User extends CommonObject */ public function findUserIdByEmail($email) { - if ($this->findUserIdByEmailCache[$email]) - { + if ($this->findUserIdByEmailCache[$email]) { return $this->findUserIdByEmailCache[$email]; } @@ -3292,25 +3340,21 @@ class User extends CommonObject $sql = 'SELECT rowid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'user'; - if (!empty($conf->global->AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR)) - { + if (!empty($conf->global->AGENDA_DISABLE_EXACT_USER_EMAIL_COMPARE_FOR_EXTERNAL_CALENDAR)) { $sql .= ' WHERE email LIKE "%'.$email.'%"'; - } - else { + } else { $sql .= ' WHERE email = "'.$email.'"'; } $sql .= ' LIMIT 1'; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { return -1; } $obj = $this->db->fetch_object($resql); - if (!$obj) - { + if (!$obj) { return -1; }