diff --git a/dev/examples/zapier/README.md b/dev/examples/zapier/README.md index 6408c55c221..453a5224993 100644 --- a/dev/examples/zapier/README.md +++ b/dev/examples/zapier/README.md @@ -1,10 +1,19 @@ # HOW TO BUILD -## DEVELOPPER ACCOUNT + +## ENABLE MODULE ZAPIER ON DOLIBARR + +This should also enable the module API (required for authentication by Zapier service and to execute action in Dolibarr by Zapier). + +Create the Dolibarr login that will be used by Zapier to call APIs. Give the login the permissions on the action you plan to automate. + + +## CREATE A ZAPIER DEVELOPPER ACCOUNT At first, you need to have a Zapier developper acoount, create it here [Zapier Platform](https://developer.zapier.com/) -## BUILD INTEGRATION + +## INSTALL ZAPIER COMMAND LINE TOOLS WITH LINK TO ZAPIER ONLINE ACCOUNT ### Install Node.js @@ -17,7 +26,7 @@ After installation, confirm that Node.js is ready to use: Next let's install the Zapier CLI tools. The CLI will allow you to build your app, deploy it to the Zapier platform, do local testing, manage users and testers, view remote logs, collaborate with your team, and more: - `cd dev/exemples/zapier` + `cd dev/examples/zapier` `npm install -g zapier-platform-cli` to install the CLI globally @@ -27,13 +36,15 @@ Next let's install the Zapier CLI tools. The CLI will allow you to build your ap Let's configure authentication between your dev environment and the Zapier platform. You'll use the email address and password you use to log in to the Zapier application. - `zapier --version` + `zapier login` This command will set up a .zapierrc file in your home directory. ### Install the Project -In zapier exemple directory, run: +In zapier example directory, run: + + `cd dev/examples/zapier` `npm install` @@ -41,8 +52,17 @@ In zapier exemple directory, run: Let's deploy it! When you're ready to try your code out on the Zapier platform use the push command. Only you will be able to see the app until you invite testers. + `zapier register` (the first time, choose name for example "Dolibarr") + `zapier push` -### More info +After a push, the Application, with the name you defined during the register step, is available when creating a Zap. You will find original tutorial here : [https://zapier.com/developer/start/introduction](https://zapier.com/developer/start/introduction) + + +### Create a Zap + +Create a ZAP that use the application you registered. +For authentication, you must enter the login / pass of account used by Zapier to call APIs. + diff --git a/dev/examples/zapier/authentication.js b/dev/examples/zapier/authentication.js index 1c95c76f9c2..fceedd4ab5f 100644 --- a/dev/examples/zapier/authentication.js +++ b/dev/examples/zapier/authentication.js @@ -1,6 +1,6 @@ /*jshint esversion: 6 */ -const testAuth = (z , bundle) => { - const url = bundle.authData.url+'/api/index.php/login'; +const test = (z , bundle) => { + const url = bundle.authData.url+'/api/index.php/status'; // Normally you want to make a request to an endpoint that is either specifically designed to test auth, or one that // every user will have access to, such as an account or profile endpoint like /me. // In this example, we'll hit httpbin, which validates the Authorization Header against the arguments passed in the URL path @@ -11,67 +11,92 @@ const testAuth = (z , bundle) => { // This method can return any truthy value to indicate the credentials are valid. // Raise an error to show return promise.then((response) => { - if (response.status === 401) { - throw new Error('The Session Key you supplied is invalid'); + if (response.status === 400) { + throw new Error('400 -The Session Key you supplied is invalid'); + } + if (response.status === 403) { + throw new Error('403 -The Session Key you supplied is invalid'); } return response; }); }; -const getSessionKey = (z, bundle) => { +// To include the session key header on all outbound requests, simply define a function here. +// It runs runs before each request is sent out, allowing you to make tweaks to the request in a centralized spot +const includeSessionKeyHeader = (request, z, bundle) => { + if (bundle.authData.sessionKey) { + request.headers = request.headers || {}; + request.headers['DOLAPIKEY'] = bundle.authData.sessionKey; + } + return request; +}; + +// If we get a response and it is a 401, we can raise a special error telling Zapier to retry this after another exchange. +const sessionRefreshIf401 = (response, z, bundle) => { + if (bundle.authData.sessionKey) { + if (response.status === 401) { + throw new z.errors.RefreshAuthError('Session apikey needs refreshing.'); + } + } + return response; +}; + +const getSessionKey = async (z, bundle) => { const url = bundle.authData.url + '/api/index.php/login'; - const promise = z.request({ - method: 'POST', + const response = await z.request({ url: url, + method: 'POST', body: { login: bundle.authData.login, password: bundle.authData.password, - } + }, }); - return promise.then((response) => { - if (response.status === 401) { - throw new Error('The login/password you supplied is invalid'); - } - const json = JSON.parse(response.content); - return { - sessionKey: json.success.token || 'secret' - }; - }); + // if (response.status === 401) { + // throw new Error('The login/password you supplied is invalid'); + // } + const json = JSON.parse(response.content); + return { + sessionKey: json.success.token || '', + }; }; module.exports = { - type: 'session', - // Define any auth fields your app requires here. The user will be prompted to enter this info when - // they connect their account. - fields: [ - { - key: 'url', - label: 'Url of service', - required: true, - type: 'string' + config: { + type: 'session', + sessionConfig: { + perform: getSessionKey }, - { - key: 'login', - label: 'Login', - required: true, - type: 'string' - }, - { - key: 'password', - label: 'Password', - required: true, - type: 'password' - } - ], - // The test method allows Zapier to verify that the credentials a user provides are valid. We'll execute this - // method whenever a user connects their account for the first time. - test: testAuth, - // The method that will exchange the fields provided by the user for session credentials. - sessionConfig: { - perform: getSessionKey + // Define any auth fields your app requires here. The user will be prompted to enter this info when + // they connect their account. + fields: [ + { + key: 'url', + label: 'Url of service without trailing-slash', + required: true, + type: 'string' + }, + { + key: 'login', + label: 'Login', + required: true, + type: 'string' + }, + { + key: 'password', + label: 'Password', + required: true, + type: 'password' + } + ], + // The test method allows Zapier to verify that the credentials a user provides are valid. We'll execute this + // method whenever a user connects their account for the first time. + test, + // The method that will exchange the fields provided by the user for session credentials. + // assuming "login" is a key returned from the test + connectionLabel: '{{login}}' }, - // assuming "login" is a key returned from the test - connectionLabel: '{{login}}' + befores: [includeSessionKeyHeader], + afters: [sessionRefreshIf401], }; 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..d1897673b39 100644 --- a/dev/examples/zapier/index.js +++ b/dev/examples/zapier/index.js @@ -1,33 +1,39 @@ /*jshint esversion: 6 */ -const triggerThirdparty = require('./triggers/thirdparty'); -const triggerOrder = require('./triggers/order'); const triggerAction = require('./triggers/action'); +const triggerOrder = require('./triggers/order'); +const triggerThirdparty = require('./triggers/thirdparty'); +const triggerTicket = require('./triggers/ticket'); +const triggerUser = require('./triggers/user'); const searchThirdparty = require('./searches/thirdparty'); const createThirdparty = require('./creates/thirdparty'); -const authentication = require('./authentication'); +const { + config: authentication, + befores = [], + afters = [], +} = require('./authentication'); // To include the session key header on all outbound requests, simply define a function here. // It runs runs before each request is sent out, allowing you to make tweaks to the request in a centralized spot -const includeSessionKeyHeader = (request, z, bundle) => { - if (bundle.authData.sessionKey) { - request.headers = request.headers || {}; - request.headers['DOLAPIKEY'] = bundle.authData.sessionKey; - } - return request; -}; +// const includeSessionKeyHeader = (request, z, bundle) => { +// if (bundle.authData.sessionKey) { +// request.headers = request.headers || {}; +// request.headers['DOLAPIKEY'] = bundle.authData.sessionKey; +// } +// return request; +// }; // If we get a response and it is a 401, we can raise a special error telling Zapier to retry this after another exchange. -const sessionRefreshIf401 = (response, z, bundle) => { - if (bundle.authData.sessionKey) { - if (response.status === 401) { - throw new z.errors.RefreshAuthError('Session apikey needs refreshing.'); - } - } - return response; -}; +// const sessionRefreshIf401 = (response, z, bundle) => { +// if (bundle.authData.sessionKey) { +// if (response.status === 401) { +// throw new z.errors.RefreshAuthError('Session apikey needs refreshing.'); +// } +// } +// return response; +// }; // We can roll up all our behaviors in an App. const App = { @@ -40,11 +46,11 @@ const App = { // beforeRequest & afterResponse are optional hooks into the provided HTTP client beforeRequest: [ - includeSessionKeyHeader + ...befores ], afterResponse: [ - sessionRefreshIf401 + ...afters ], // If you want to define optional resources to simplify creation of triggers, searches, creates - do that here! @@ -53,9 +59,11 @@ const App = { // If you want your trigger to show up, you better include it here! triggers: { - [triggerThirdparty.key]: triggerThirdparty, + [triggerAction.key]: triggerAction, [triggerOrder.key]: triggerOrder, - [triggerAction.key]: triggerAction + [triggerThirdparty.key]: triggerThirdparty, + [triggerTicket.key]: triggerTicket, + [triggerUser.key]: triggerUser, }, // 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..0e152473869 100644 --- a/dev/examples/zapier/triggers/action.js +++ b/dev/examples/zapier/triggers/action.js @@ -10,14 +10,14 @@ const subscribeHook = (z, bundle) => { action: bundle.inputData.action }; - const url = bundle.authData.url + '/api/index.php/zapierapi/hook'; + 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) + body: data, }; // You may return a promise or a normal data structure from any perform method. @@ -32,7 +32,7 @@ const unsubscribeHook = (z, bundle) => { // 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, + url: bundle.authData.url + '/api/index.php/zapierapi/hook/' + bundle.subscribeData.id, method: 'DELETE', }; @@ -74,7 +74,7 @@ const getFallbackRealAction = (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/agendaevents/0', + url: bundle.authData.url + '/api/index.php/agendaevents/0', }; return z.request(options).then((response) => [JSON.parse(response.content)]); @@ -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. @@ -111,6 +111,7 @@ module.exports = { inputFields: [ { key: 'action', + required: true, type: 'string', helpText: 'Which action of agenda this should trigger on.', choices: { @@ -145,12 +146,33 @@ 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: 'name', label: 'Name'}, - {key: 'usertodo__name', label: 'UserToDo Name'}, - {key: 'authorId', label: 'Author ID'}, - {key: 'action', label: 'Action'} + { + 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', + 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..061ce218d10 100644 --- a/dev/examples/zapier/triggers/order.js +++ b/dev/examples/zapier/triggers/order.js @@ -17,7 +17,7 @@ const subscribeHook = (z, bundle) => { const options = { url: url, method: 'POST', - body: JSON.stringify(data) + body: data, }; // You may return a promise or a normal data structure from any perform method. @@ -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. @@ -101,6 +101,7 @@ module.exports = { inputFields: [ { key: 'action', + required: true, type: 'string', helpText: 'Which action of order this should trigger on.', choices: { @@ -136,11 +137,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..4656f836e74 100644 --- a/dev/examples/zapier/triggers/thirdparty.js +++ b/dev/examples/zapier/triggers/thirdparty.js @@ -17,7 +17,7 @@ const subscribeHook = (z, bundle) => { const options = { url: url, method: 'POST', - body: JSON.stringify(data) + body: data, }; // You may return a promise or a normal data structure from any perform method. @@ -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. @@ -123,6 +123,7 @@ module.exports = { inputFields: [ { key: 'action', + required: true, type: 'string', helpText: 'Which action of thirdparty this should trigger on.', choices: { @@ -159,12 +160,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/ticket.js b/dev/examples/zapier/triggers/ticket.js new file mode 100644 index 00000000000..c642099bd55 --- /dev/null +++ b/dev/examples/zapier/triggers/ticket.js @@ -0,0 +1,237 @@ +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: 'ticket', + 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: 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 getTicket = (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 ticket = { + id: bundle.cleanedRequest.id, + track_id: bundle.cleanedRequest.track_id, + subject: bundle.cleanedRequest.subject, + message: bundle.cleanedRequest.message, + lastname: bundle.cleanedRequest.lastname, + firstname: bundle.cleanedRequest.firstname, + address: bundle.cleanedRequest.address, + zip: bundle.cleanedRequest.zip, + town: bundle.cleanedRequest.town, + email_from: bundle.cleanedRequest.email_from, + login: bundle.cleanedRequest.login, + authorId: bundle.cleanedRequest.authorId, + createdAt: bundle.cleanedRequest.createdAt, + action: bundle.cleanedRequest.action + }; + + return [ticket]; +}; + +const getFallbackRealTicket = (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/tickets/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", +// tickets: "Ticket", +// 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: 'ticket', + + // You'll want to provide some helpful display labels and descriptions + // for tickets. Zapier will put them into the UX. + noun: 'Ticket', + display: { + label: 'New Ticket', + description: 'Triggers when a new ticket action is done in Dolibarr.' + }, + + // `operation` is where the business logic goes. + operation: { + + // `inputFields` can define the fields a ticket could provide, + // we'll pass them in as `bundle.inputData` later. + inputFields: [ + { + key: 'action', + type: 'string', + required: true, + helpText: 'Which action of ticket this should trigger on.', + choices: { + create: "Create", + modify: "Modify", + validate: "Validate", + } + } + ], + + type: 'hook', + + performSubscribe: subscribeHook, + performUnsubscribe: unsubscribeHook, + + perform: getTicket, + performList: getFallbackRealTicket, + + // 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, + track_id: 'Xaz123er', + subject: 'Subject', + message: 'Message', + createdAt: 1472069465, + lastname: 'DOE', + firstname: 'John', + email: 'john@doe.com', + address: 'Park Avenue', + zip: '12345', + town: 'NEW-YORK', + email_from: 'doe.john@example;com', + 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: 'track_id', + type: "string", + label: 'TrackID' + }, + { + key: 'subject', + type: "string", + label: 'Subject' + }, + { + key: 'message', + type: "string", + label: 'Message' + }, + { + 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: 'email_from', + type: 'string', + label: 'Email from' + }, + { + key: 'authorId', + type: "integer", + label: 'Author ID' + }, + { + key: 'action', + type: 'string', + label: 'Action' + } + ] + } +}; diff --git a/dev/examples/zapier/triggers/user.js b/dev/examples/zapier/triggers/user.js new file mode 100644 index 00000000000..92209bb8651 --- /dev/null +++ b/dev/examples/zapier/triggers/user.js @@ -0,0 +1,177 @@ +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: 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', + required: true, + 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/accountancy/admin/subaccount.php b/htdocs/accountancy/admin/subaccount.php index 4b44bd35149..20fe5b86355 100644 --- a/htdocs/accountancy/admin/subaccount.php +++ b/htdocs/accountancy/admin/subaccount.php @@ -105,7 +105,7 @@ $title = $langs->trans('ChartOfIndividualAccountsOfSubsidiaryLedger'); llxHeader('', $title); // Customer -$sql = "SELECT sa.rowid, sa.nom as label, sa.code_compta as subaccount, '0' as type, sa.entity"; +$sql = "SELECT sa.rowid, sa.nom as label, sa.code_compta as subaccount, '1' as type, sa.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."societe sa"; $sql .= " WHERE sa.entity IN (".getEntity('societe').")"; $sql .= " AND sa.code_compta <> ''"; @@ -148,7 +148,7 @@ if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db // Supplier $sql .= " UNION "; -$sql .= " SELECT sa.rowid, sa.nom as label, sa.code_compta_fournisseur as subaccount, '1' as type, sa.entity FROM ".MAIN_DB_PREFIX."societe sa"; +$sql .= " SELECT sa.rowid, sa.nom as label, sa.code_compta_fournisseur as subaccount, '2' as type, sa.entity FROM ".MAIN_DB_PREFIX."societe sa"; $sql .= " WHERE sa.entity IN (".getEntity('societe').")"; $sql .= " AND sa.code_compta_fournisseur <> ''"; //print $sql; @@ -190,7 +190,7 @@ if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db // User $sql .= " UNION "; -$sql .= " SELECT u.rowid, u.lastname as label, u.accountancy_code as subaccount, '2' as type, u.entity FROM ".MAIN_DB_PREFIX."user u"; +$sql .= " SELECT u.rowid, u.lastname as label, u.accountancy_code as subaccount, '3' as type, u.entity FROM ".MAIN_DB_PREFIX."user u"; $sql .= " WHERE u.entity IN (".getEntity('user').")"; $sql .= " AND u.accountancy_code <> ''"; //print $sql; @@ -287,7 +287,7 @@ if ($resql) print ''; if (!empty($arrayfields['subaccount']['checked'])) print ''; if (!empty($arrayfields['label']['checked'])) print ''; - if (!empty($arrayfields['type']['checked'])) print ''.$form->selectarray('search_type', array('0'=>$langs->trans('Customer'), '1'=>$langs->trans('Supplier'), '2'=>$langs->trans('Employee')), $search_type, 1).''; + if (!empty($arrayfields['type']['checked'])) print ''.$form->selectarray('search_type', array('1'=>$langs->trans('Customer'), '2'=>$langs->trans('Supplier'), '3'=>$langs->trans('Employee')), $search_type, 1).''; if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['reconcilable']['checked'])) print ' '; } print ''; $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); @@ -335,17 +335,17 @@ if ($resql) print ''; $s = ''; // Customer - if ($obj->type == 0) + if ($obj->type == 1) { $s .= ''.$langs->trans("Customer").''; } // Supplier - elseif ($obj->type == 1) + elseif ($obj->type == 2) { $s .= ''.$langs->trans("Supplier").''; } // User - elseif ($obj->type == 2) + elseif ($obj->type == 3) { $s .= ''.$langs->trans("Employee").''; } @@ -378,17 +378,17 @@ if ($resql) print ''; $e = ''; // Customer - if ($obj->type == 0) + if ($obj->type == 1) { $e .= ''.img_edit().''; } // Supplier - elseif ($obj->type == 1) + elseif ($obj->type == 2) { $e .= ''.img_edit().''; } // User - elseif ($obj->type == 2) + elseif ($obj->type == 3) { $e .= ''.img_edit().''; } diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index a06d2f25d8c..eb2743258d7 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -357,12 +357,6 @@ if ($result) { print ''.$langs->trans("DescVentilTodoCustomer").'

'; - /*$topicmail="Information"; - $modelmail="project"; - $objecttmp=new Project($db); - $trackid='prj'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';*/ - if ($msg) print $msg.'
'; $moreforfilter = ''; diff --git a/htdocs/accountancy/expensereport/list.php b/htdocs/accountancy/expensereport/list.php index 2ee3044895a..500c11d3cce 100644 --- a/htdocs/accountancy/expensereport/list.php +++ b/htdocs/accountancy/expensereport/list.php @@ -285,12 +285,6 @@ if ($result) { print ''.$langs->trans("DescVentilTodoExpenseReport").'

'; - /*$topicmail="Information"; - $modelmail="project"; - $objecttmp=new Project($db); - $trackid='prj'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';*/ - if ($msg) print $msg.'
'; $moreforfilter = ''; diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php index 96b36fa8fa3..cbdecd2e85e 100644 --- a/htdocs/accountancy/supplier/list.php +++ b/htdocs/accountancy/supplier/list.php @@ -358,12 +358,6 @@ if ($result) { print ''.$langs->trans("DescVentilTodoCustomer").'

'; - /*$topicmail="Information"; - $modelmail="project"; - $objecttmp=new Project($db); - $trackid='prj'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';*/ - if ($msg) print $msg.'
'; $moreforfilter = ''; diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index a8cb095a889..009c73cf318 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -2306,14 +2306,16 @@ class Adherent 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() { global $user, $langs; + $now = dol_now(); // Initialise parametres $this->id = 0; + $this->entity = 1; $this->specimen = 1; $this->civility_id = 0; $this->lastname = 'DOLIBARR'; @@ -2330,24 +2332,30 @@ class Adherent extends CommonObject $this->country = 'France'; $this->morphy = 'mor'; $this->email = 'specimen@specimen.com'; - $this->socialnetworks = array('skype' => 'skypepseudo', 'twitter' => 'twitterpseudo', 'facebook' => 'facebookpseudo', 'linkedin' => 'linkedinpseudo'); + $this->socialnetworks = array( + 'skype' => 'skypepseudo', + 'twitter' => 'twitterpseudo', + 'facebook' => 'facebookpseudo', + 'linkedin' => 'linkedinpseudo', + ); $this->phone = '0999999999'; $this->phone_perso = '0999999998'; $this->phone_mobile = '0999999997'; - $this->note_private = 'No comment'; - $this->birth = time(); + $this->note_public = 'This is a public note'; + $this->note_private = 'This is a private note'; + $this->birth = $now; $this->photo = ''; $this->public = 1; $this->statut = 0; - $this->datefin = time(); - $this->datevalid = time(); + $this->datefin = $now; + $this->datevalid = $now; $this->typeid = 1; // Id type adherent $this->type = 'Type adherent'; // Libelle type adherent $this->need_subscription = 0; - $this->first_subscription_date = time(); + $this->first_subscription_date = $now; $this->first_subscription_date_start = $this->first_subscription_date; $this->first_subscription_date_end = dol_time_plus_duree($this->first_subscription_date_start, 1, 'y'); $this->first_subscription_amount = 10; @@ -2356,6 +2364,7 @@ class Adherent extends CommonObject $this->last_subscription_date_start = $this->first_subscription_date; $this->last_subscription_date_end = dol_time_plus_duree($this->last_subscription_date_start, 1, 'y'); $this->last_subscription_amount = 10; + return 1; } diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php index 954ea42f9b4..6fa3058dca1 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -67,12 +67,16 @@ class Members extends DolibarrApi } $member = new Adherent($this->db); - $result = $member->fetch($id); + if ($id == 0) { + $result = $member->initAsSpecimen(); + } else { + $result = $member->fetch($id); + } if (!$result) { throw new RestException(404, 'member not found'); } - if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { + if (!DolibarrApi::_checkAccessToResource('adherent', $member->id) && $id > 0) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } diff --git a/htdocs/adherents/class/subscription.class.php b/htdocs/adherents/class/subscription.class.php index 1e6356ee6e4..2ea1c310d5a 100644 --- a/htdocs/adherents/class/subscription.class.php +++ b/htdocs/adherents/class/subscription.class.php @@ -156,7 +156,7 @@ class Subscription extends CommonObject } else { $type = $this->fk_type; } - $sql .= " VALUES (".$this->fk_adherent.", '".$type."', '".$this->db->idate($now)."',"; + $sql .= " VALUES (".$this->fk_adherent.", '".$this->db->escape($type)."', '".$this->db->idate($now)."',"; $sql .= " '".$this->db->idate($this->dateh)."',"; $sql .= " '".$this->db->idate($this->datef)."',"; $sql .= " ".$this->amount.","; @@ -174,7 +174,7 @@ class Subscription extends CommonObject } if (!$error && !$notrigger) { - $this->context = array('member'=>$member); + $this->context = array('member' => $member); // Call triggers $result = $this->call_trigger('MEMBER_SUBSCRIPTION_CREATE', $user); if ($result < 0) { $error++; } diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index 7a48883fd55..f0544e1e914 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -688,61 +688,6 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea { print info_admin($debuginfo); } - - - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } - - /* - if ($action != 'presend') { - print '
'; - print ''; // ancre - */ - // Documents - /*$objref = dol_sanitizeFileName($object->ref); - $relativepath = $comref . '/' . $comref . '.pdf'; - $filedir = $conf->emailcollector->dir_output . '/' . $objref; - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->emailcollector->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->emailcollector->create; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('emailcollector', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); - */ - /* - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('emailcollector')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - - print '
'; - - $MAXEVENT = 10; - - $morehtmlright = ''; - $morehtmlright .= $langs->trans("SeeAll"); - $morehtmlright .= ''; - - // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'emailcollector_emailcollector', $socid, 1, '', $MAXEVENT, '', $morehtmlright); - - print '
'; - } - */ - - //Select mail models is same action as presend - /* - if (GETPOST('modelselected')) $action = 'presend'; - - // Presend form - $modelmail='inventory'; - $defaulttopic='InformationMessage'; - $diroutput = $conf->product->dir_output.'/inventory'; - $trackid = 'stockinv'.$object->id; - - include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - */ } // End of page diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php index 488997b5b78..d9540d30995 100644 --- a/htdocs/admin/mails_senderprofile_list.php +++ b/htdocs/admin/mails_senderprofile_list.php @@ -427,7 +427,7 @@ print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorde $topicmail = "Information"; //$modelmail="subscription"; $objecttmp = new EmailSenderProfile($db); -//$trackid='sub'.$object->id; +//$trackid = (($action == 'testhtml') ? "testhtml" : "test"); include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 5834324fa2b..80a608a0581 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -78,15 +78,15 @@ class DolibarrApi * @return array */ /* Disabled, most APIs does not share same signature for method index - function index() - { - return array( - 'success' => array( - 'code' => 200, - 'message' => __class__.' is up and running!' - ) - ); - }*/ + function index() + { + return array( + 'success' => array( + 'code' => 200, + 'message' => __class__.' is up and running!' + ) + ); + }*/ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** @@ -221,11 +221,9 @@ class DolibarrApi } } - if (!empty($object->thirdparty) && is_object($object->thirdparty)) - { + if (!empty($object->thirdparty) && is_object($object->thirdparty)) { $this->_cleanObjectDatas($object->thirdparty); } - return $object; } diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 5fff08b80ab..9408898a984 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -229,9 +229,7 @@ class Documents extends DolibarrApi if ($result <= 0) { throw new RestException(500, 'Error generating document'); } - } - else - { + } else { throw new RestException(403, 'Generation not available for this modulepart'); } @@ -277,6 +275,8 @@ class Documents extends DolibarrApi } $id = (empty($id) ? 0 : $id); + $recursive = 0; + $type = 'files'; if ($modulepart == 'societe' || $modulepart == 'thirdparty') { @@ -474,11 +474,27 @@ class Documents extends DolibarrApi } $upload_dir = $conf->categorie->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'category').$object->id."/photos/".dol_sanitizeFileName($object->ref); + } elseif ($modulepart == 'ecm') { + throw new RestException(500, 'Modulepart Ecm not implemented yet.'); + // // require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php'; + + // if (!DolibarrApiAccess::$user->rights->ecm->read) { + // throw new RestException(401); + // } + + // // $object = new EcmDirectory($this->db); + // // $result = $object->fetch($ref); + // // if (!$result) { + // // throw new RestException(404, 'EcmDirectory not found'); + // // } + // $upload_dir = $conf->ecm->dir_output; + // $type = 'all'; + // $recursive = 0; } else { throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); } - $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); + $filearray = dol_dir_list($upload_dir, $type, $recursive, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); if (empty($filearray)) { throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$object->id.(!empty($object->ref) ? ' or Ref '.$object->ref : '').' does not return any document.'); } @@ -592,9 +608,7 @@ class Documents extends DolibarrApi { $tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; } - } - else - { + } else { throw new RestException(500, 'Error while fetching Task '.$ref); } } @@ -619,10 +633,8 @@ class Documents extends DolibarrApi $modulepart = 'propale'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $object = new Propal($this->db); - } - // TODO Implement additional moduleparts - else - { + } else { + // TODO Implement additional moduleparts throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); } @@ -660,9 +672,7 @@ class Documents extends DolibarrApi { throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); } - } - else - { + } else { if ($modulepart == 'invoice') $modulepart = 'facture'; if ($modulepart == 'member') $modulepart = 'adherent'; @@ -700,20 +710,16 @@ class Documents extends DolibarrApi } $fhandle = @fopen($destfiletmp, 'w'); - if ($fhandle) - { + if ($fhandle) { $nbofbyteswrote = fwrite($fhandle, $newfilecontent); fclose($fhandle); @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK)); - } - else - { + } else { throw new RestException(500, "Failed to open file '".$destfiletmp."' for write"); } $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1); - if (!$result) - { + if (!$result) { throw new RestException(500, "Failed to move file into '".$destfile."'"); } diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php index 2a7271fed4a..cffcc8a962d 100644 --- a/htdocs/asset/list.php +++ b/htdocs/asset/list.php @@ -339,7 +339,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "SendAssetsRef"; $modelmail = "asset"; $objecttmp = new Asset($db); -$trackid = 'xxxx'.$object->id; +$trackid = 'asset'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index 6143f795b1d..1135f5df5dd 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -439,7 +439,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "SendBillOfMaterialsRef"; $modelmail = "bom"; $objecttmp = new BOM($db); -$trackid = 'xxxx'.$object->id; +$trackid = 'bom'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index 9f3679ac44a..b838aac8cd9 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -738,19 +738,17 @@ class BOM extends CommonObject public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) { global $db, $conf, $langs, $hookmanager; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("BillOfMaterials").''; + $label = img_picto('', $this->picto).' '.$langs->trans("BillOfMaterials").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; - if (isset($this->status)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } $url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index fbe9891522c..59d5a6b6691 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -524,7 +524,7 @@ class ActionComm extends CommonObject $resql = $this->db->query($sql); if ($resql) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id"); + $this->ref =$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id"); // Now insert assigned users if (!$error) diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index d784ff8d834..d81c0fd288a 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -1613,7 +1613,6 @@ class Propal extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET"; - $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").","; $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").","; @@ -1637,7 +1636,6 @@ class Propal extends CommonObject $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").","; $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; - $sql .= " WHERE rowid=".$this->id; $this->db->begin(); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 69d85a25e7c..e69b2dfb8da 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1273,15 +1273,6 @@ if (empty($reshook)) if ($error) $action = 'edit_extras'; } - if ($action == 'set_thirdparty' && $usercancreate) - { - $object->fetch($id); - $object->setValueFrom('fk_soc', $socid, '', '', 'date', '', $user, 'ORDER_MODIFY'); - - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); - exit(); - } - // add lines from objectlinked if ($action == 'import_lines_from_object' && $usercancreate @@ -2025,7 +2016,6 @@ if ($action == 'create' && $usercancreate) $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
'; // Ref customer $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index a01b6dfb924..a86a751dcb5 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -3918,7 +3918,7 @@ class Commande extends CommonOrder if (!dol_strlen($modele)) { $modele = 'einstein'; - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->COMMANDE_ADDON_PDF)) { $modele = $conf->global->COMMANDE_ADDON_PDF; @@ -4012,7 +4012,6 @@ class OrderLine extends CommonOrderLine */ public $commande_id; - // From llx_commandedet public $fk_parent_line; public $fk_facture; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 6944f7aeb51..e93491ceee4 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -1356,7 +1356,10 @@ class Account extends CommonObject global $conf, $langs, $user; $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("BankAccount").''; + $label = img_picto('', $this->picto).' '.$langs->trans("BankAccount").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
'.$langs->trans('Label').': '.$this->label; $label .= '
'.$langs->trans('AccountNumber').': '.$this->number; $label .= '
'.$langs->trans('IBAN').': '.$this->iban; @@ -1375,9 +1378,6 @@ class Account extends CommonObject $label .= '
'.$langs->trans('AccountAccounting').': '.length_accountg($this->account_number); $label .= '
'.$langs->trans('AccountancyJournal').': '.$this->accountancy_journal; } - if (isset($this->status)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 668417c0ee2..5c8031f2702 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -56,9 +56,16 @@ class PaymentVarious extends CommonObject */ public $ref; + /** + * @var int timestamp + */ public $tms; public $datep; public $datev; + + /** + * @var int sens of operation + */ public $sens; public $amount; public $type_payment; @@ -90,6 +97,16 @@ class PaymentVarious extends CommonObject */ public $fk_bank; + /** + * @var int transaction category + */ + public $categorie_transaction; + + /** + * @var int Account ID + */ + public $accountid; + /** * @var int ID */ diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 22bd08da1ba..6c1b77fb58b 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -262,7 +262,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "Information"; //$modelmail="subscription"; $objecttmp = new Account($db); -//$trackid='sub'.$object->id; +$trackid = 'bank'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index 55ad8914a9e..fdc3e57bdba 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -343,7 +343,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "SendCashControlRef"; $modelmail = "cashcontrol"; $objecttmp = new CashControl($db); -$trackid = 'xxxx'.$object->id; +$trackid = 'cashfence'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 5771ead70f1..e4187a4e906 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -498,7 +498,7 @@ class FactureRec extends CommonInvoice $sql .= ', f.remise_percent, f.remise_absolue, f.remise'; $sql .= ', f.date_lim_reglement as dlr'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; - $sql .= ', f.modelpdf'; + $sql .= ', f.modelpdf as model_pdf'; $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project'; $sql .= ', f.fk_account'; $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate'; @@ -562,7 +562,8 @@ class FactureRec extends CommonInvoice $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->user_author = $obj->fk_user_author; - $this->modelpdf = $obj->modelpdf; + $this->modelpdf = $obj->model_pdf; // deprecatd + $this->model_pdf = $obj->model_pdf; $this->rang = $obj->rang; $this->special_code = $obj->special_code; $this->frequency = $obj->frequency; @@ -1894,8 +1895,6 @@ class FactureLigneRec extends CommonInvoiceLine */ public $table_element = 'facturedet_rec'; - public $date_start_fill; - public $date_end_fill; /** diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 797a2a58ddb..5049ed41e57 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -144,8 +144,12 @@ class Facture extends CommonInvoice public $close_code; //! Commentaire si mis a paye sans paiement complet public $close_note; - //! 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) + + /** + * 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) + */ public $paye; + //! key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos', ...) public $module_source; //! key of pos source ('0', '1', ...) @@ -623,7 +627,7 @@ class Facture extends CommonInvoice $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL'); $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL'); $sql .= ", '".$this->db->idate($this->date)."'"; - $sql .= ", ".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null'); + $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'"); $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"); @@ -637,7 +641,8 @@ class Facture extends CommonInvoice $sql .= ", ".($this->fk_project ? $this->fk_project : "null"); $sql .= ", ".$this->cond_reglement_id; $sql .= ", ".$this->mode_reglement_id; - $sql .= ", '".$this->db->idate($this->date_lim_reglement)."', '".$this->db->escape($this->modelpdf)."'"; + $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'"; + $sql .= ", ".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null"); $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null"); $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null"); $sql .= ", ".($this->situation_final ? $this->situation_final : 0); @@ -751,7 +756,7 @@ class Facture extends CommonInvoice $newinvoiceline->origin_id = $this->lines[$i]->id; // Auto set date of service ? - if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only + if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only { $newinvoiceline->date_start = $originaldatewhen; } @@ -1052,7 +1057,8 @@ class Facture extends CommonInvoice $facture->note_public = $this->note_public; $facture->note_private = $this->note_private; $facture->ref_client = $this->ref_client; - $facture->modelpdf = $this->modelpdf; + $facture->modelpdf = $this->modelpdf; // deprecated + $facture->model_pdf = $this->modelpdf; $facture->fk_project = $this->fk_project; $facture->cond_reglement_id = $this->cond_reglement_id; $facture->mode_reglement_id = $this->mode_reglement_id; @@ -2436,14 +2442,14 @@ class Facture extends CommonInvoice * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @param int $batch_rule 0=do not decrement batch, else batch rule to use - * 1=take in batches ordered by sellby and eatby dates + * @param int $batch_rule 0=do not decrement batch, else batch rule to use, 1=take in batches ordered by sellby and eatby dates * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK */ public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) { global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $productStatic = null; $warehouseStatic = null; if ($batch_rule > 0) { @@ -2488,7 +2494,7 @@ class Facture extends CommonInvoice // Check parameters if ($this->type == self::TYPE_REPLACEMENT) // if this is a replacement invoice { - // Controle que facture source connue + // Check that source invoice is known if ($this->fk_facture_source <= 0) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement")); @@ -4332,7 +4338,7 @@ class Facture extends CommonInvoice $modele = 'crabe'; $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type; - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->$thisTypeConfName)) { $modele = $conf->global->$thisTypeConfName; diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index c37f36dd4e5..5614659eac0 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -77,9 +77,6 @@ $hookmanager->initHooks(array('invoiceindex')); $now = dol_now(); -$facturestatic = new Facture($db); -$facturesupplierstatic = new FactureFournisseur($db); - $form = new Form($db); $formfile = new FormFile($db); $thirdpartystatic = new Societe($db); @@ -139,8 +136,10 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles */ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { + $tmpinvoice = new Facture($db); + $sql = "SELECT f.rowid, f.ref, f.datef as date, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.ref_client"; - $sql .= ", f.type"; + $sql .= ", f.type, f.fk_statut as status, f.paye"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; $sql .= ", s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur"; @@ -161,9 +160,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $reshook = $hookmanager->executeHooks('printFieldListWhereCustomerDraft', $parameters); $sql .= $hookmanager->resPrint; - $sql .= " GROUP BY f.rowid, f.ref, f.datef, f.total, f.tva, f.total_ttc, f.ref_client, f.type, "; - $sql .= "s.email, s.nom, s.rowid, s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur"; - $sql .= ", cc.rowid, cc.code"; + $sql .= " GROUP BY f.rowid, f.ref, f.datef, f.total, f.tva, f.total_ttc, f.ref_client, f.type, f.fk_statut, f.paye,"; + $sql .= " s.email, s.nom, s.rowid, s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur,"; + $sql .= " cc.rowid, cc.code"; // Add Group from hooks $parameters = array(); @@ -198,14 +197,16 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $obj = $db->fetch_object($resql); - $facturestatic->id = $obj->rowid; - $facturestatic->ref = $obj->ref; - $facturestatic->date = $db->jdate($obj->date); - $facturestatic->type = $obj->type; - $facturestatic->total_ht = $obj->total_ht; - $facturestatic->total_tva = $obj->total_tva; - $facturestatic->total_ttc = $obj->total_ttc; - $facturestatic->ref_client = $obj->ref_client; + $tmpinvoice->id = $obj->rowid; + $tmpinvoice->ref = $obj->ref; + $tmpinvoice->date = $db->jdate($obj->date); + $tmpinvoice->type = $obj->type; + $tmpinvoice->total_ht = $obj->total_ht; + $tmpinvoice->total_tva = $obj->total_tva; + $tmpinvoice->total_ttc = $obj->total_ttc; + $tmpinvoice->ref_client = $obj->ref_client; + $tmpinvoice->statut = $obj->status; + $tmpinvoice->paye = $obj->paye; $companystatic->id = $obj->socid; $companystatic->name = $obj->name; @@ -219,7 +220,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; print ''; - print $facturestatic->getNomUrl(1, ''); + print $tmpinvoice->getNomUrl(1, ''); print ''; print ''; print $companystatic->getNomUrl(1, 'customer'); @@ -248,7 +249,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) */ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { - $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type, f.ref_supplier"; + $facturesupplierstatic = new FactureFournisseur($db); + + $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type, f.ref_supplier, f.fk_statut as status, f.paye"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; $sql .= ", s.code_fournisseur, s.code_compta_fournisseur"; @@ -298,6 +301,8 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $facturesupplierstatic->total_ttc = $obj->total_ttc; $facturesupplierstatic->ref_supplier = $obj->ref_supplier; $facturesupplierstatic->type = $obj->type; + $facturesupplierstatic->statut = $obj->status; + $facturesupplierstatic->paye = $obj->paye; $companystatic->id = $obj->socid; $companystatic->name = $obj->name; @@ -343,9 +348,9 @@ print '
'; if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $langs->load("boxes"); - $facstatic = new Facture($db); + $tmpinvoice = new Facture($db); - $sql = "SELECT f.rowid, f.ref, f.fk_statut, f.type, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.paye, f.tms"; + $sql = "SELECT f.rowid, f.ref, f.fk_statut as status, f.type, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.paye, f.tms"; $sql .= ", f.date_lim_reglement as datelimite"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid"; @@ -400,14 +405,15 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) continue; } - $facturestatic->ref = $obj->ref; - $facturestatic->id = $obj->rowid; - $facturestatic->total_ht = $obj->total_ht; - $facturestatic->total_tva = $obj->total_tva; - $facturestatic->total_ttc = $obj->total_ttc; - $facturestatic->statut = $obj->fk_statut; - $facturestatic->date_lim_reglement = $db->jdate($obj->datelimite); - $facturestatic->type = $obj->type; + $tmpinvoice->ref = $obj->ref; + $tmpinvoice->id = $obj->rowid; + $tmpinvoice->total_ht = $obj->total_ht; + $tmpinvoice->total_tva = $obj->total_tva; + $tmpinvoice->total_ttc = $obj->total_ttc; + $tmpinvoice->statut = $obj->status; + $tmpinvoice->paye = $obj->paye; + $tmpinvoice->date_lim_reglement = $db->jdate($obj->datelimite); + $tmpinvoice->type = $obj->type; $thirdpartystatic->id = $obj->socid; $thirdpartystatic->name = $obj->name; @@ -426,10 +432,10 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ''; print ''; @@ -437,7 +443,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $filename = dol_sanitizeFileName($obj->ref); $filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($obj->ref); $urlsource = $_SERVER['PHP_SELF'].'?facid='.$obj->rowid; - print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); + print $formfile->getDocumentsLink($tmpinvoice->element, $filename, $filedir); print '
'; - print $facturestatic->getNomUrl(1, ''); + print $tmpinvoice->getNomUrl(1, ''); print ''; - if ($facturestatic->hasDelay()) { + if ($tmpinvoice->hasDelay()) { print img_warning($langs->trans("Late")); } print '
'; print ''; @@ -447,7 +453,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; print ''.price($obj->total_ttc).''; print ''.dol_print_date($db->jdate($obj->tms), 'day').''; - print ''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3, $obj->am).''; + print ''.$tmpinvoice->getLibStatut(3, $obj->am).''; print ''; $total_ttc += $obj->total_ttc; @@ -484,7 +490,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $langs->load("boxes"); $facstatic = new FactureFournisseur($db); - $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.libelle, ff.total_ht, ff.total_tva, ff.total_ttc, ff.tms, ff.paye"; + $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut as status, ff.libelle, ff.total_ht, ff.total_tva, ff.total_ttc, ff.tms, ff.paye"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid"; $sql .= ", s.code_fournisseur, s.code_compta_fournisseur, s.email"; @@ -542,6 +548,8 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $facstatic->total_ht = $obj->total_ht; $facstatic->total_tva = $obj->total_tva; $facstatic->total_ttc = $obj->total_ttc; + $facstatic->statut = $obj->status; + $facstatic->paye = $obj->paye; $thirdpartystatic->id = $obj->socid; $thirdpartystatic->name = $obj->name; @@ -564,7 +572,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; print ''.price($obj->total_ttc).''; print ''.dol_print_date($db->jdate($obj->tms), 'day').''; - print ''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3).''; + print ''.$facstatic->getLibStatut(3).''; print ''; $total += $obj->total_ht; $total_ttc += $obj->total_ttc; @@ -600,7 +608,7 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $langs->load("boxes"); $donationstatic = new Don($db); - $sql = "SELECT d.rowid, d.lastname, d.firstname, d.societe, d.datedon as date, d.tms as dm, d.amount, d.fk_statut"; + $sql = "SELECT d.rowid, d.lastname, d.firstname, d.societe, d.datedon as date, d.tms as dm, d.amount, d.fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."don as d"; $sql .= " WHERE d.entity IN (".getEntity('donation').")"; // Add where from hooks @@ -648,6 +656,9 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $donationstatic->ref = $objp->rowid; $donationstatic->lastname = $objp->lastname; $donationstatic->firstname = $objp->firstname; + $donationstatic->date = $objp->date; + $donationstatic->statut = $objp->status; + $donationstatic->status = $objp->status; $label = $donationstatic->getFullName($langs); if ($objp->societe) $label .= ($label ? ' - ' : '').$objp->societe; @@ -657,7 +668,7 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) print ''.$label.''; print ''.price($objp->amount).''; print ''.dol_print_date($db->jdate($objp->dm), 'day').''; - print ''.$donationstatic->LibStatut($objp->fk_statut, 3).''; + print ''.$donationstatic->getLibStatut(3).''; print ''; $i++; @@ -737,6 +748,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $chargestatic->ref = $obj->rowid; $chargestatic->label = $obj->label; $chargestatic->paye = $obj->paye; + $chargestatic->status = $obj->paye; print ''; print ''.$chargestatic->getNomUrl(1).''; @@ -786,7 +798,7 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $sql .= ", s.nom as name, s.email"; $sql .= ", s.rowid as socid"; $sql .= ", s.code_client, s.code_compta"; - $sql .= ", c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva as total_tva, c.total_ttc,"; + $sql .= ", c.rowid, c.ref, c.facture, c.fk_statut as status, c.total_ht, c.tva as total_tva, c.total_ttc,"; $sql .= " cc.rowid as country_id, cc.code as country_code"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -860,6 +872,8 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $commandestatic->id = $obj->rowid; $commandestatic->ref = $obj->ref; + $commandestatic->statut = $obj->status; + $commandestatic->billed = $obj->facture; print ''; print ''; @@ -886,7 +900,7 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; print ''.price($obj->total_ttc).''; print ''.price($obj->total_ttc - $obj->tot_fttc).''; - print ''.$commandestatic->LibStatut($obj->fk_statut, $obj->facture, 3).''; + print ''.$commandestatic->getLibStatut(3).''; print ''; $tot_ht += $obj->total_ht; $tot_ttc += $obj->total_ttc; @@ -922,9 +936,9 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user */ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { - $facstatic = new Facture($db); + $tmpinvoice = new Facture($db); - $sql = "SELECT f.rowid, f.ref, f.fk_statut, f.datef, f.type, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.paye, f.tms"; + $sql = "SELECT f.rowid, f.ref, f.fk_statut as status, f.datef, f.type, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.paye, f.tms"; $sql .= ", f.date_lim_reglement as datelimite"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; @@ -987,14 +1001,15 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) continue; } - $facturestatic->ref = $obj->ref; - $facturestatic->id = $obj->rowid; - $facturestatic->total_ht = $obj->total_ht; - $facturestatic->total_tva = $obj->total_tva; - $facturestatic->total_ttc = $obj->total_ttc; - $facturestatic->type = $obj->type; - $facturestatic->statut = $obj->fk_statut; - $facturestatic->date_lim_reglement = $db->jdate($obj->datelimite); + $tmpinvoice->ref = $obj->ref; + $tmpinvoice->id = $obj->rowid; + $tmpinvoice->total_ht = $obj->total_ht; + $tmpinvoice->total_tva = $obj->total_tva; + $tmpinvoice->total_ttc = $obj->total_ttc; + $tmpinvoice->type = $obj->type; + $tmpinvoice->statut = $obj->status; + $tmpinvoice->paye = $obj->paye; + $tmpinvoice->date_lim_reglement = $db->jdate($obj->datelimite); $societestatic->id = $obj->socid; $societestatic->name = $obj->name; @@ -1012,10 +1027,10 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ''; print ''; @@ -1023,7 +1038,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $filename = dol_sanitizeFileName($obj->ref); $filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($obj->ref); $urlsource = $_SERVER['PHP_SELF'].'?facid='.$obj->rowid; - print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); + print $formfile->getDocumentsLink($tmpinvoice->element, $filename, $filedir); print '
'; - print $facturestatic->getNomUrl(1, ''); + print $tmpinvoice->getNomUrl(1, ''); print ''; - if ($facturestatic->hasDelay()) { + if ($tmpinvoice->hasDelay()) { print img_warning($langs->trans("Late")); } print '
'; print ''; @@ -1034,7 +1049,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; print ''.price($obj->total_ttc).''; print ''.price($obj->am).''; - print ''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3, $obj->am, $obj->type).''; + print ''.$tmpinvoice->getLibStatut(3, $obj->am).''; print ''; $total_ttc += $obj->total_ttc; @@ -1080,7 +1095,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU { $facstatic = new FactureFournisseur($db); - $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.type, ff.libelle as label, ff.total_ht, ff.total_tva, ff.total_ttc, ff.paye"; + $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut as status, ff.type, ff.libelle as label, ff.total_ht, ff.total_tva, ff.total_ttc, ff.paye"; $sql .= ", ff.date_lim_reglement"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; @@ -1153,6 +1168,8 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $facstatic->total_ht = $obj->total_ht; $facstatic->total_tva = $obj->total_tva; $facstatic->total_ttc = $obj->total_ttc; + $facstatic->statut = $obj->status; + $facstatic->paye = $obj->paye; $societestatic->id = $obj->socid; $societestatic->name = $obj->name; @@ -1172,7 +1189,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; print ''.price($obj->total_ttc).''; print ''.price($obj->am).''; - print ''.$facstatic->LibStatut($obj->paye, $obj->fk_statut, 3, $obj->am, $obj->type).''; + print ''.$facstatic->getLibStatut(3, $obj->am).''; print ''; $total += $obj->total_ht; $total_ttc += $obj->total_ttc; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 6e018e0bb84..2ea2497efbb 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -538,10 +538,12 @@ class ChargeSociales extends CommonObject if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; } - if (empty($this->ref)) $this->ref = $this->label; - $label = ''.$langs->trans("SocialContribution").''; + $label = img_picto('', 'tax').''.$langs->trans("SocialContribution").''; + if (isset($this->paye)) { + $label .= ' '.$this->getLibStatut(5); + } if (!empty($this->ref)) $label .= '
'.$langs->trans('Ref').': '.$this->ref; if (!empty($this->label)) diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 956c78c1679..ad646af15b0 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -8,7 +8,7 @@ * Copyright (C) 2013-2016 Alexandre Spangaro * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2018-2020 Frédéric France * Copyright (C) 2019 Josep Lluís Amador * Copyright (C) 2020 Open-Dsi * @@ -55,7 +55,7 @@ $action = (GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view'); $confirm = GETPOST('confirm', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $id = GETPOST('id', 'int'); -$socid = GETPOST('socid', 'int'); +$socid = GETPOST('socid', 'int'); $object = new Contact($db); $extrafields = new ExtraFields($db); @@ -178,15 +178,15 @@ if (empty($reshook)) $object->entity = (GETPOSTISSET('entity') ?GETPOST('entity', 'int') : $conf->entity); $object->socid = GETPOST("socid", 'int'); - $object->lastname = GETPOST("lastname", 'alpha'); - $object->firstname = GETPOST("firstname", 'alpha'); - $object->civility_code = GETPOST("civility_code", 'alpha'); - $object->poste = GETPOST("poste", 'alpha'); - $object->address = GETPOST("address", 'alpha'); - $object->zip = GETPOST("zipcode", 'alpha'); - $object->town = GETPOST("town", 'alpha'); - $object->country_id = GETPOST("country_id", 'int'); - $object->state_id = GETPOST("state_id", 'int'); + $object->lastname = (string) GETPOST("lastname", 'alpha'); + $object->firstname = (string) GETPOST("firstname", 'alpha'); + $object->civility_code = (string) GETPOST("civility_code", 'alpha'); + $object->poste = (string) GETPOST("poste", 'alpha'); + $object->address = (string) GETPOST("address", 'alpha'); + $object->zip = (string) GETPOST("zipcode", 'alpha'); + $object->town = (string) GETPOST("town", 'alpha'); + $object->country_id = (int) GETPOST("country_id", 'int'); + $object->state_id = (int) GETPOST("state_id", 'int'); //$object->jabberid = GETPOST("jabberid", 'alpha'); //$object->skype = GETPOST("skype", 'alpha'); //$object->twitter = GETPOST("twitter", 'alpha'); @@ -196,22 +196,22 @@ if (empty($reshook)) if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { - $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); + $object->socialnetworks[$key] = (string) GETPOST($key, 'alphanohtml'); } } } - $object->email = GETPOST("email", 'alpha'); + $object->email = (string) GETPOST("email", 'alpha'); $object->no_email = GETPOST("no_email", "int"); - $object->phone_pro = GETPOST("phone_pro", 'alpha'); - $object->phone_perso = GETPOST("phone_perso", 'alpha'); - $object->phone_mobile = GETPOST("phone_mobile", 'alpha'); - $object->fax = GETPOST("fax", 'alpha'); + $object->phone_pro = (string) GETPOST("phone_pro", 'alpha'); + $object->phone_perso = (string) GETPOST("phone_perso", 'alpha'); + $object->phone_mobile = (string) GETPOST("phone_mobile", 'alpha'); + $object->fax = (string) GETPOST("fax", 'alpha'); $object->priv = GETPOST("priv", 'int'); - $object->note_public = GETPOST("note_public", 'restricthtml'); - $object->note_private = GETPOST("note_private", 'restricthtml'); + $object->note_public = (string) GETPOST("note_public", 'restricthtml'); + $object->note_private = (string) GETPOST("note_private", 'restricthtml'); $object->roles = GETPOST("roles", 'array'); - $object->statut = 1; //Defult status to Actif + $object->statut = 1; //Default status to Actif // Note: Correct date should be completed with location to have exact GM time of birth. $object->birthday = dol_mktime(0, 0, 0, GETPOST("birthdaymonth", 'int'), GETPOST("birthdayday", 'int'), GETPOST("birthdayyear", 'int')); @@ -225,9 +225,9 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST("lastname")) - { - $error++; $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label")); + if (!GETPOST("lastname")) { + $error++; + $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label")); $action = 'create'; } @@ -236,7 +236,8 @@ if (empty($reshook)) $id = $object->create($user); if ($id <= 0) { - $error++; $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); + $error++; + $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); $action = 'create'; } else { // Categories association @@ -278,14 +279,12 @@ if (empty($reshook)) $result = $object->fetch($id); $object->oldcopy = clone $object; - $object->old_lastname = GETPOST("old_lastname"); - $object->old_firstname = GETPOST("old_firstname"); + $object->old_lastname = (string) GETPOST("old_lastname", 'alpha'); + $object->old_firstname = (string) GETPOST("old_firstname", 'alpha'); $result = $object->delete(); - if ($result > 0) - { - if ($backtopage) - { + if ($result > 0) { + if ($backtopage) { header("Location: ".$backtopage); exit; } else { @@ -360,22 +359,22 @@ if (empty($reshook)) $object->oldcopy = clone $object; - $object->old_lastname = GETPOST("old_lastname", 'alpha'); - $object->old_firstname = GETPOST("old_firstname", 'alpha'); + $object->old_lastname = (string) GETPOST("old_lastname", 'alpha'); + $object->old_firstname = (string) GETPOST("old_firstname", 'alpha'); $object->socid = GETPOST("socid", 'int'); - $object->lastname = GETPOST("lastname", 'alpha'); - $object->firstname = GETPOST("firstname", 'alpha'); - $object->civility_code = GETPOST("civility_code", 'alpha'); - $object->poste = GETPOST("poste", 'alpha'); + $object->lastname = (string) GETPOST("lastname", 'alpha'); + $object->firstname = (string) GETPOST("firstname", 'alpha'); + $object->civility_code = (string) GETPOST("civility_code", 'alpha'); + $object->poste = (string) GETPOST("poste", 'alpha'); - $object->address = GETPOST("address", 'alpha'); - $object->zip = GETPOST("zipcode", 'alpha'); - $object->town = GETPOST("town", 'alpha'); - $object->state_id = GETPOST("state_id", 'int'); - $object->country_id = GETPOST("country_id", 'int'); + $object->address = (string) GETPOST("address", 'alpha'); + $object->zip = (string) GETPOST("zipcode", 'alpha'); + $object->town = (string) GETPOST("town", 'alpha'); + $object->state_id = GETPOST("state_id", 'int'); + $object->country_id = GETPOST("country_id", 'int'); - $object->email = GETPOST("email", 'alpha'); + $object->email = (string) GETPOST("email", 'alpha'); $object->no_email = GETPOST("no_email", "int"); //$object->jabberid = GETPOST("jabberid", 'alpha'); //$object->skype = GETPOST("skype", 'alpha'); @@ -386,17 +385,17 @@ if (empty($reshook)) if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if (GETPOSTISSET($key) && GETPOST($key, 'alphanohtml') != '') { - $object->socialnetworks[$key] = GETPOST($key, 'alphanohtml'); + $object->socialnetworks[$key] = (string) GETPOST($key, 'alphanohtml'); } } } - $object->phone_pro = GETPOST("phone_pro", 'alpha'); - $object->phone_perso = GETPOST("phone_perso", 'alpha'); - $object->phone_mobile = GETPOST("phone_mobile", 'alpha'); - $object->fax = GETPOST("fax", 'alpha'); - $object->priv = GETPOST("priv", 'int'); - $object->note_public = GETPOST("note_public", 'restricthtml'); - $object->note_private = GETPOST("note_private", 'restricthtml'); + $object->phone_pro = (string) GETPOST("phone_pro", 'alpha'); + $object->phone_perso = (string) GETPOST("phone_perso", 'alpha'); + $object->phone_mobile = (string) GETPOST("phone_mobile", 'alpha'); + $object->fax = (string) GETPOST("fax", 'alpha'); + $object->priv = (string) GETPOST("priv", 'int'); + $object->note_public = (string) GETPOST("note_public", 'restricthtml'); + $object->note_private = (string) GETPOST("note_private", 'restricthtml'); $object->roles = GETPOST("roles", 'array'); // Fill array 'array_options' with data from add form @@ -1559,7 +1558,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $modelmail = 'contact'; $defaulttopic = 'Information'; $diroutput = $conf->contact->dir_output; - $trackid = 'con'.$object->id; + $trackid = 'ctc'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 1f1012fb726..1185ce5ecf8 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -131,11 +131,18 @@ class Contact extends CommonObject public $civility; /** - * Address - * @var string + * @var string Address */ public $address; + + /** + * @var string zip code + */ public $zip; + + /** + * @var string Town + */ public $town; public $state_id; // Id of department @@ -201,10 +208,29 @@ class Contact extends CommonObject */ public $jabberid; + /** + * @var string filename for photo + */ public $photo; + + /** + * @var string phone pro + */ public $phone_pro; + + /** + * @var string phone perso + */ public $phone_perso; + + /** + * @var string phone mobile + */ public $phone_mobile; + + /** + * @var string fax + */ public $fax; /** @@ -253,9 +279,12 @@ class Contact extends CommonObject $this->db = $db; $this->statut = 1; // By default, status is enabled - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0; - if (empty($conf->mailing->enabled)) $this->fields['no_email']['enabled'] = 0; - + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->mailing->enabled)) { + $this->fields['no_email']['enabled'] = 0; + } // typical ['s.nom'] is used for third-parties if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $this->fields['fk_soc']['enabled'] = 0; @@ -268,10 +297,8 @@ class Contact extends CommonObject } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } @@ -1308,7 +1335,8 @@ class Contact extends CommonObject $label .= '
'; } - $label .= img_picto('', $this->picto).' '.$langs->trans("Contact").''; + $label .= img_picto('', $this->picto).' '.$langs->trans("Contact").''; + $label .= ' '.$this->getLibStatut(4); $label .= '
'.$langs->trans("Name").': '.$this->getFullName($langs); //if ($this->civility_id) $label.= '
' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code if (!empty($this->poste)) $label .= '
'.$langs->trans("Poste").': '.$this->poste; @@ -1474,6 +1502,7 @@ class Contact extends CommonObject // Initialise parameters $this->id = 0; + $this->entity = 1; $this->specimen = 1; $this->lastname = 'DOLIBARR'; $this->firstname = 'SPECIMEN'; diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 4d30977bf6a..72f404b51db 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -891,7 +891,7 @@ while ($i < min($num, $limit)) if (!empty($arrayfields['p.lastname']['checked'])) { print ''; - print $contactstatic->getNomUrl(1, '', 0); + print $contactstatic->getNomUrl(1); print ''; if (!$i) $totalarray['nbfield']++; } diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 145ff92cdb4..99544b1037d 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -727,7 +727,7 @@ class Contrat extends CommonObject $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated $this->fk_projet = $obj->fk_project; // deprecated $this->fk_project = $obj->fk_project; @@ -2419,7 +2419,7 @@ class Contrat extends CommonObject if (!dol_strlen($modele)) { $modele = 'strato'; - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) { $modele = $conf->global->CONTRACT_ADDON_PDF; diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 80228628c61..ad36a6e5ee7 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -60,7 +60,10 @@ if ($action == 'add' && !empty($permissiontoadd)) if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited } // Ignore special fields - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; + if (in_array($key, array('rowid', 'entity', 'import_key'))) continue; + if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) { + if (!in_array(abs($val['visible']), array(1, 3))) continue; // Only 1 and 3 that are case to create + } // Set value to insert if (in_array($object->fields[$key]['type'], array('text', 'html'))) { @@ -141,7 +144,10 @@ if ($action == 'update' && !empty($permissiontoadd)) if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited } // Ignore special fields - if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; + if (in_array($key, array('rowid', 'entity', 'import_key'))) continue; + if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) { + if (!in_array(abs($val['visible']), array(1, 3, 4))) continue; // Only 1 and 3 and 4 that are case to update + } // Set value to update if (preg_match('/^(text|html)/', $object->fields[$key]['type'])) { diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index cb7944e1cac..75d95eaa21b 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -518,15 +518,17 @@ abstract class CommonInvoice extends CommonObject * @param int $status Id status * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=long label + picto * @param integer $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, -1 otherwise) - * @param int $type Type invoice + * @param int $type Type invoice. If -1, we use $this->type * @return string Label of status */ - public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0) + public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = -1) { // phpcs:enable global $langs; $langs->load('bills'); + if ($type == -1) $type = $this->type; + $statusType = 'status0'; $prefix = 'Short'; if (!$paye) { @@ -931,6 +933,9 @@ abstract class CommonInvoiceLine extends CommonObjectLine */ public $total_ttc; + public $date_start_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_start at creation + public $date_end_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_end at creation + /** * List of cumulative options: * Bit 0: 0 si TVA normal - 1 si TVA NPR @@ -939,13 +944,7 @@ abstract class CommonInvoiceLine extends CommonObjectLine */ public $info_bits = 0; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct(DoliDB $db) - { - $this->db = $db; - } + public $special_code = 0; + + public $fk_multicurrency; } diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 2bd32df1f05..1dd68accbc9 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -347,6 +347,11 @@ abstract class CommonObject */ public $fk_account; + /** + * @var string Open ID + */ + public $openid; + /** * @var string Public note * @see update_note() @@ -7507,8 +7512,7 @@ abstract class CommonObject // Depending on field type ('datetime', ...) if ($this->isDate($info)) { - if (empty($this->{$field})) - { + if (empty($this->{$field})) { $queryarray[$field] = null; } else { $queryarray[$field] = $this->db->idate($this->{$field}); @@ -7526,16 +7530,27 @@ abstract class CommonObject } elseif ($this->isDuration($info)) { // $this->{$field} may be null, '', 0, '0', 123, '123' - if ($this->{$field} != '' || !empty($info['notnull'])) $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) { + if (!isset($this->{$field})) { + $queryarray[$field] = 0; + } else { + $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + } + } else $queryarray[$field] = null; } elseif ($this->isInt($info) || $this->isFloat($info)) { if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity; else { // $this->{$field} may be null, '', 0, '0', 123, '123' - if ($this->{$field} != '' || !empty($info['notnull'])) { - if ($this->isInt($info)) $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 - if ($this->isFloat($info)) $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) { + if (!isset($this->{$field})) { + $queryarray[$field] = 0; + } elseif ($this->isInt($info)) { + $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + } elseif ($this->isFloat($info)) { + $queryarray[$field] = (double) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1 + } } else $queryarray[$field] = null; } } else { @@ -7912,6 +7927,7 @@ abstract class CommonObject unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update. if (array_key_exists('ref', $fieldvalues)) $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data + // Add quotes and escape on fields with type string $keys = array(); $values = array(); $tmp = array(); @@ -7922,7 +7938,7 @@ abstract class CommonObject $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]); } - // Clean and check mandatory + // Clean and check mandatory fields foreach ($keys as $key) { if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index c7e95aa1fbc..0d4cfbe4f34 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -19,7 +19,7 @@ /** * \file htdocs/core/class/commonobjectline.class.php * \ingroup core - * \brief File of the superclass of classes of lines of business objects (invoice, contract, PROPAL, commands, etc. ...) + * \brief File of the superclass of classes of lines of business objects (invoice, contract, proposal, orders, etc. ...) */ diff --git a/htdocs/core/class/commonorder.class.php b/htdocs/core/class/commonorder.class.php index e7c40d60bfd..b78af3fdaa8 100644 --- a/htdocs/core/class/commonorder.class.php +++ b/htdocs/core/class/commonorder.class.php @@ -121,6 +121,12 @@ abstract class CommonOrderLine extends CommonObjectLine */ public $remise_percent; + /** + * VAT code + * @var string + */ + public $vat_src_code; + /** * VAT % * @var float @@ -151,4 +157,6 @@ abstract class CommonOrderLine extends CommonObjectLine public $info_bits = 0; public $special_code = 0; + + public $fk_multicurrency; } diff --git a/htdocs/core/class/events.class.php b/htdocs/core/class/events.class.php index fc0c4533b7d..1b8a9eb3291 100644 --- a/htdocs/core/class/events.class.php +++ b/htdocs/core/class/events.class.php @@ -141,7 +141,7 @@ class Events // extends CommonObject // Clean parameters $this->description = trim($this->description); - if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent = $_SERVER['HTTP_USER_AGENT']; + if (empty($this->user_agent)) $this->user_agent = (empty($_SERVER['HTTP_USER_AGENT'])?'':$_SERVER['HTTP_USER_AGENT']); // Check parameters if (empty($this->description)) { $this->error = 'ErrorBadValueForParameterCreateEventDesc'; return -1; } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index fac12b48d52..f36b513c9c9 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -6448,7 +6448,7 @@ class Form * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice. * * @param string $htmlname Name of html select area - * @param string $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...) + * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...) * @param string $id Preselected key * @param string $moreparam Add more parameters onto the select tag * @param int $disableFiltering If set to 1, results are not filtered with searched string diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index f932e739ad1..c41c61be536 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -79,9 +79,10 @@ class FormFile * @param string $sectiondir If upload must be done inside a particular directory (if sectiondir defined, sectionid must not be) * @param int $usewithoutform 0=Default, 1=Disable
and style to use in existing area * @param int $capture 1=Add tag capture="capture" to force use of micro or video recording to generate file. When setting this to 1, you must also provide a value for $accept. + * @param int $disablemulti 0=Default, 1=Disable multiple file upload * @return int <0 if KO, >0 if OK */ - public function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '', $sectiondir = '', $usewithoutform = 0, $capture = 0) + public function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '', $sectiondir = '', $usewithoutform = 0, $capture = 0, $disablemulti = 0) { // phpcs:enable global $conf, $langs, $hookmanager; @@ -170,7 +171,7 @@ class FormFile $out .= 'global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic') ? ' name="userfile"' : ' name="userfile[]" multiple'); - $out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD)) ? ' name="userfile"' : ' name="userfile[]" multiple'); + $out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $disablemulti) ? ' name="userfile"' : ' name="userfile[]" multiple'); $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : ''); $out .= (!empty($accept) ? ' accept="'.$accept.'"' : ' accept=""'); $out .= (!empty($capture) ? ' capture="capture"' : ''); diff --git a/htdocs/core/lib/date.lib.php b/htdocs/core/lib/date.lib.php index 284bcffe4bb..cbfaa883da7 100644 --- a/htdocs/core/lib/date.lib.php +++ b/htdocs/core/lib/date.lib.php @@ -619,7 +619,7 @@ function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $specialdayrule = array(); // Check to ensure we use correct parameters - if ((($timestampEnd - $timestampStart) % 86400) != 0) return 'ErrorDates must use same hours and must be GMT dates'; + if ((($timestampEnd - $timestampStart) % 86400) != 0) return 'Error Dates must use same hours and must be GMT dates'; if (empty($country_code)) $country_code = $mysoc->country_code; diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index f8087dc396e..8ebac12eb2c 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -6235,9 +6235,14 @@ function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) { - $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tacking number'; + $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number'; $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url'; } + if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) + { + $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment'; + $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url'; + } } else { $substitutionarray['__ID__'] = $object->id; $substitutionarray['__REF__'] = $object->ref; @@ -6359,6 +6364,11 @@ function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number; $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url; } + if (is_object($object) && $object->element == 'reception') + { + $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number; + $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url; + } if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) { diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 9d8673578dd..7d00fee0773 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -944,9 +944,8 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."
\n"; // Define $sqlstring - if (function_exists('mb_strrpos')) - { - $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8'); + if (function_exists('mb_strrpos')) { + $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8'); } else { $posnumstart = strrpos($maskwithnocode, $maskcounter); } // Pos of counter in final string (from 0 to ...) diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 19b46f8f75c..0f0b2474d51 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -1319,11 +1319,11 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr global $daytoparse; $tmparray = dol_getdate($daytoparse, true); // detail of current day - $idw = $tmparray['wday']; + $idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK)?0:1)); global $numstartworkingday, $numendworkingday; $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } @@ -1702,12 +1702,13 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ global $numstartworkingday, $numendworkingday; $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. + if (($idw + 1 < $numstartworkingday) || ($idw + 1 > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } $tableCell = ''; + //$tableCell .= 'idw='.$idw.' '.$conf->global->MAIN_START_WEEK.' '.$numstartworkingday.'-'.$numendworkingday; $placeholder = ''; if ($alreadyspent) { diff --git a/htdocs/core/lib/ticket.lib.php b/htdocs/core/lib/ticket.lib.php index 826e2d6bc98..ee2dc1cd095 100644 --- a/htdocs/core/lib/ticket.lib.php +++ b/htdocs/core/lib/ticket.lib.php @@ -1,7 +1,7 @@ * Copyright (C) 2016 Christophe Battarel - * Copyright (C) 2019 Frédéric France + * Copyright (C) 2019-2020 Frédéric France * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -84,8 +84,7 @@ function ticket_prepare_head($object) $head[$h][2] = 'tabTicket'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && empty($user->socid)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && empty($user->socid)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/ticket/contact.php?track_id='.$object->track_id; $head[$h][1] = $langs->trans('ContactsAddresses'); @@ -133,10 +132,8 @@ function ticket_prepare_head($object) $head[$h][2] = 'tabTicketLogs'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'ticket', 'remove'); - return $head; } @@ -159,13 +156,11 @@ function showDirectPublicLink($object) } $out = ''; - if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) - { + if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { $out .= ''.$langs->trans("PublicInterfaceNotEnabled").''; } else { $out .= img_picto('', 'object_globe.png').' '.$langs->trans("TicketPublicAccess").':
'; - if ($url) - { + if ($url) { $out .= ''; $out .= ajax_autoselect("directpubliclink", 0); } else { @@ -208,7 +203,7 @@ function llxHeaderTicket($title, $head = "", $disablejs = 0, $disablehead = 0, $ { global $user, $conf, $langs, $mysoc; - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, 1); // Show html headers print ''; print '
'; @@ -216,8 +211,7 @@ function llxHeaderTicket($title, $head = "", $disablejs = 0, $disablehead = 0, $ // Define urllogo if (!empty($conf->global->TICKET_SHOW_COMPANY_LOGO) || !empty($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC)) { // Print logo - if (!empty($conf->global->TICKET_SHOW_COMPANY_LOGO)) - { + if (!empty($conf->global->TICKET_SHOW_COMPANY_LOGO)) { $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png'; if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { @@ -231,8 +225,7 @@ function llxHeaderTicket($title, $head = "", $disablejs = 0, $disablehead = 0, $ } // Output html code for logo - if ($urllogo || !empty($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC)) - { + if ($urllogo || !empty($conf->global->TICKET_PUBLIC_INTERFACE_TOPIC)) { print '
'; print '
'; if ($urllogo) { @@ -246,7 +239,7 @@ function llxHeaderTicket($title, $head = "", $disablejs = 0, $disablehead = 0, $ } print '
'; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print ''; + print ''; } print '
'; } @@ -317,13 +310,21 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $sql .= " a.fk_contact,"; $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql .= ", sp.lastname, sp.firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", m.lastname, m.firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", o.ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", o.ref"; + if (is_object($filterobj) && get_class($filterobj) == 'Societe') { + $sql .= ", sp.lastname, sp.firstname"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { + $sql .= ", m.lastname, m.firstname"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { + $sql .= ", o.ref"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { + $sql .= ", o.ref"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { + $sql .= ", o.ref"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { + $sql .= ", o.ref"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { + $sql .= ", o.ref"; + } $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; @@ -335,60 +336,67 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id; } - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { + if (is_object($filterobj) && get_class($filterobj) == 'Societe') { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') { $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er"; $sql .= " ON er.resource_type = 'dolresource'"; $sql .= " AND er.element_id = a.id"; $sql .= " AND er.resource_id = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", ".MAIN_DB_PREFIX."product as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { + $sql .= ", ".MAIN_DB_PREFIX."adherent as m"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { + $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { + $sql .= ", ".MAIN_DB_PREFIX."product as o"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { + $sql .= ", ".MAIN_DB_PREFIX."ticket as o"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { + $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { + $sql .= ", ".MAIN_DB_PREFIX."contrat as o"; + } $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; if ($force_filter_contact === false) { - if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql .= " AND a.fk_soc = ".$filterobj->id; - elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql .= " AND a.fk_project = ".$filterobj->id; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') - { + if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) { + $sql .= " AND a.fk_soc = ".$filterobj->id; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) { + $sql .= " AND a.fk_project = ".$filterobj->id; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') - { + } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') - { + } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') - { + } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') - { + } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; - } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') - { + } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; } } // Condition on actioncode - if (!empty($actioncode)) - { - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else { - if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'"; + if (!empty($actioncode)) { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + if ($actioncode == 'AC_OTH') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_OTH_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } } } else { if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; @@ -411,11 +419,17 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id"; $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto"; $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action - if (is_object($filterobj) && get_class($filterobj) == 'Societe') $sql2 .= ", '' as lastname, '' as firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2 .= ", '' as lastname, '' as firstname"; - elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql2 .= ", '' as ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql2 .= ", '' as ref"; - elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql2 .= ", '' as ref"; + if (is_object($filterobj) && get_class($filterobj) == 'Societe') { + $sql2 .= ", '' as lastname, '' as firstname"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { + $sql2 .= ", '' as lastname, '' as firstname"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { + $sql2 .= ", '' as ref"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { + $sql2 .= ", '' as ref"; + } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { + $sql2 .= ", '' as ref"; + } $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u"; $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email. $sql2 .= " AND mc.statut = 1"; @@ -434,13 +448,11 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no dol_syslog("company.lib::show_actions_done", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if ($obj->type == 'action') { @@ -512,8 +524,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no dol_print_error($db); } - if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) - { + if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) { $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; @@ -533,8 +544,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $out .= ''; if ($objcon && get_class($objcon) == 'Contact' && - (is_null($filterobj) || get_class($filterobj) == 'Societe')) - { + (is_null($filterobj) || get_class($filterobj) == 'Societe')) { $out .= ''; } else { $out .= ''; @@ -553,8 +563,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no //$out.=''; $out .= ''.$langs->trans("Search").' : '; - if ($donetodo) - { + if ($donetodo) { $out .= ''; } $out .= ''.$langs->trans("Type").' '; @@ -581,8 +590,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $out .= '
'; } - - - - - - if (!empty($footer)) { $out .= ''; } - $out .= '
'."\n"; // end timeline-item $out .= ''; @@ -867,11 +820,73 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $out .= "\n"; } - if ($noprint) return $out; else print $out; } +/** + * Get timeline icon + * @param ActionComm $actionstatic actioncomm + * @param array $histo histo + * @param int $key key + * @return string + */ +function getTicketTimelineIcon($actionstatic, &$histo, $key) +{ + global $conf, $langs; + $out = ''."\n"; + $iconClass = 'fa fa-comments'; + $img_picto = ''; + $colorClass = ''; + $pictoTitle = ''; + + if ($histo[$key]['percent'] == -1) { + $colorClass = 'timeline-icon-not-applicble'; + $pictoTitle = $langs->trans('StatusNotApplicable'); + } elseif ($histo[$key]['percent'] == 0) { + $colorClass = 'timeline-icon-todo'; + $pictoTitle = $langs->trans('StatusActionToDo').' (0%)'; + } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) { + $colorClass = 'timeline-icon-in-progress'; + $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)'; + } elseif ($histo[$key]['percent'] >= 100) { + $colorClass = 'timeline-icon-done'; + $pictoTitle = $langs->trans('StatusActionDone').' (100%)'; + } + + if ($actionstatic->code == 'AC_TICKET_CREATE') { + $iconClass = 'fa fa-ticket'; + } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') { + $iconClass = 'fa fa-pencil'; + } elseif ($actionstatic->code == 'TICKET_MSG') { + $iconClass = 'fa fa-comments'; + } elseif ($actionstatic->code == 'TICKET_MSG_PRIVATE') { + $iconClass = 'fa fa-mask'; + } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + if ($actionstatic->type_picto) { + $img_picto = img_picto('', $actionstatic->type_picto); + } else { + if ($actionstatic->type_code == 'AC_RDV') { + $iconClass = 'fa fa-handshake'; + } elseif ($actionstatic->type_code == 'AC_TEL') { + $iconClass = 'fa fa-phone'; + } elseif ($actionstatic->type_code == 'AC_FAX') { + $iconClass = 'fa fa-fax'; + } elseif ($actionstatic->type_code == 'AC_EMAIL') { + $iconClass = 'fa fa-envelope'; + } elseif ($actionstatic->type_code == 'AC_INT') { + $iconClass = 'fa fa-shipping-fast'; + } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') { + $iconClass = 'fa fa-robot'; + } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) { + $iconClass = 'fa fa-robot'; + } + } + } + + $out .= ''.$img_picto.''."\n"; + return $out; +} /** * getTicketActionCommEcmList diff --git a/htdocs/core/modules/modApi.class.php b/htdocs/core/modules/modApi.class.php index 729840e7259..32b16a74703 100644 --- a/htdocs/core/modules/modApi.class.php +++ b/htdocs/core/modules/modApi.class.php @@ -81,7 +81,7 @@ class modApi extends DolibarrModules // Dependencies $this->hidden = false; // A condition to hide module $this->depends = array(); // List of modules id that must be enabled if this module is enabled - $this->requiredby = array(); // List of modules id to disable if this one is disabled + $this->requiredby = array('modZapier'); // List of modules id to disable if this one is disabled $this->conflictwith = array(); // List of modules id this module is in conflict with $this->phpmin = array(5, 4); // Minimum version of PHP required by module $this->langfiles = array("other"); diff --git a/htdocs/core/modules/modProduct.class.php b/htdocs/core/modules/modProduct.class.php index a3ea922f03e..7908fcaa4ba 100644 --- a/htdocs/core/modules/modProduct.class.php +++ b/htdocs/core/modules/modProduct.class.php @@ -628,7 +628,7 @@ class modProduct extends DolibarrModules $this->import_label[$r] = "SuppliersPricesOfProductsOrServices"; // Translation key $this->import_icon[$r] = $this->picto; $this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon - $this->import_tables_array[$r] = array('sp'=>MAIN_DB_PREFIX.'product_fournisseur_price'); + $this->import_tables_array[$r] = array('sp'=>MAIN_DB_PREFIX.'product_fournisseur_price', 'extra'=>MAIN_DB_PREFIX.'product_fournisseur_price_extrafields'); $this->import_tables_creator_array[$r] = array('sp'=>'fk_user'); $this->import_fields_array[$r] = array(//field order as per structure of table llx_product_fournisseur_price, without optional fields 'sp.fk_product'=>"ProductOrService*", @@ -664,6 +664,23 @@ class modProduct extends DolibarrModules $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.packaging' => 'PackagingForThisProduct')); } + // Add extra fields + $import_extrafield_sample = array(); + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'product_fournisseur_price' AND entity IN (0, ".$conf->entity.")"; + $resql = $this->db->query($sql); + if ($resql) // This can fail when class is used on old database (during migration for example) + { + while ($obj = $this->db->fetch_object($resql)) + { + $fieldname = 'extra.'.$obj->name; + $fieldlabel = ucfirst($obj->label); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); + $import_extrafield_sample[$fieldname] = $fieldlabel; + } + } + // End add extra fields + $this->import_fieldshidden_array[$r] = array('extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'product_fournisseur_price'); // aliastable.field => ('user->id' or 'lastrowid-'.tableparent) + $this->import_convertvalue_array[$r] = array( 'sp.fk_soc'=>array('rule'=>'fetchidfromref', 'classfile'=>'/societe/class/societe.class.php', 'class'=>'Societe', 'method'=>'fetch', 'element'=>'ThirdParty'), 'sp.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product') diff --git a/htdocs/core/modules/modZapier.class.php b/htdocs/core/modules/modZapier.class.php index 9239fc99bf2..ee7589c6537 100644 --- a/htdocs/core/modules/modZapier.class.php +++ b/htdocs/core/modules/modZapier.class.php @@ -49,7 +49,7 @@ class modZapier extends DolibarrModules // It is used to group modules by family in module setup page $this->family = "interface"; // Module position in the family on 2 digits ('01', '10', '20', ...) - $this->module_position = '22'; + $this->module_position = '26'; // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); // Module label (no space allowed), used if translation string 'ModuleZapierName' not found (Zapier is name of module). @@ -116,7 +116,7 @@ class modZapier extends DolibarrModules // A condition to hide module $this->hidden = false; // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) - $this->depends = array(); + $this->depends = array('modApi'); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) $this->requiredby = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) diff --git a/htdocs/core/tpl/card_presend.tpl.php b/htdocs/core/tpl/card_presend.tpl.php index 99f9b250306..92a767a23ea 100644 --- a/htdocs/core/tpl/card_presend.tpl.php +++ b/htdocs/core/tpl/card_presend.tpl.php @@ -75,7 +75,7 @@ if ($action == 'presend') $outputlangs = new Translate('', $conf); $outputlangs->setDefaultLang($newlang); // Load traductions files required by page - $outputlangs->loadLangs(array('commercial', 'bills', 'orders', 'contracts', 'members', 'propal', 'products', 'supplier_proposal', 'interventions')); + $outputlangs->loadLangs(array('commercial', 'bills', 'orders', 'contracts', 'members', 'propal', 'products', 'supplier_proposal', 'interventions', 'receptions')); } $topicmail = ''; diff --git a/htdocs/core/triggers/interface_20_all_Logevents.class.php b/htdocs/core/triggers/interface_20_all_Logevents.class.php index dc1ef1ab4a2..e1bcaf85034 100644 --- a/htdocs/core/triggers/interface_20_all_Logevents.class.php +++ b/htdocs/core/triggers/interface_20_all_Logevents.class.php @@ -174,7 +174,7 @@ class InterfaceLogevents extends DolibarrTriggers $event->dateevent = $date; $event->label = $text; $event->description = $desc; - $event->user_agent = $_SERVER["HTTP_USER_AGENT"]; + $event->user_agent = (empty($_SERVER["HTTP_USER_AGENT"])?'':$_SERVER["HTTP_USER_AGENT"]); $result = $event->create($user); if ($result > 0) { diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php index 6fb09f9a1b3..25816cd591e 100644 --- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php +++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php @@ -554,9 +554,10 @@ class InterfaceActionsAuto extends DolibarrTriggers $member = $this->context['member']; if (!is_object($member)) { // This should not happen + dol_syslog("Execute a trigger MEMBER_SUBSCRIPTION_CREATE with context key 'member' not an object"); include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $member = new Adherent($this->db); - $member->fetch($this->fk_adherent); + $member->fetch($object->fk_adherent); } if (empty($object->actionmsg2)) $object->actionmsg2 = $langs->transnoentities("MemberSubscriptionAddedInDolibarr", $object->id, $member->getFullName($langs)); @@ -733,6 +734,29 @@ class InterfaceActionsAuto extends DolibarrTriggers } } + // If trackid is not defined, we set it + if (empty($object->trackid)) { + // See also similar list into emailcollector.class.php + if (preg_match('/^COMPANY_/', $action)) { $object->trackid = 'thi'.$object->id; } + elseif (preg_match('/^CONTACT_/', $action)) { $object->trackid = 'ctc'.$object->id; } + elseif (preg_match('/^CONTRACT_/', $action)) { $object->trackid = 'con'.$object->id; } + elseif (preg_match('/^PROPAL_/', $action)) { $object->trackid = 'pro'.$object->id; } + elseif (preg_match('/^ORDER_/', $action)) { $object->trackid = 'ord'.$object->id; } + elseif (preg_match('/^BILL_/', $action)) { $object->trackid = 'inv'.$object->id; } + elseif (preg_match('/^FICHINTER_/', $action)) { $object->trackid = 'int'.$object->id; } + elseif (preg_match('/^SHIPPING_/', $action)) { $object->trackid = 'shi'.$object->id; } + elseif (preg_match('/^RECEPTION_/', $action)) { $object->trackid = 'rec'.$object->id; } + elseif (preg_match('/^PROPOSAL_SUPPLIER/', $action)) { $object->trackid = 'spr'.$object->id; } + elseif (preg_match('/^ORDER_SUPPLIER_/', $action)) { $object->trackid = 'sor'.$object->id; } + elseif (preg_match('/^BILL_SUPPLIER_/', $action)) { $object->trackid = 'sin'.$object->id; } + elseif (preg_match('/^MEMBER_SUBSCRIPTION_/', $action)) { $object->trackid = 'sub'.$object->id; } + elseif (preg_match('/^MEMBER_/', $action)) { $object->trackid = 'mem'.$object->id; } + elseif (preg_match('/^PROJECT_/', $action)) { $object->trackid = 'proj'.$object->id; } + elseif (preg_match('/^TASK_/', $action)) { $object->trackid = 'tas'.$object->id; } + elseif (preg_match('/^TICKET_/', $action)) { $object->trackid = 'tic'.$object->id; } + else $object->trackid = ''; + } + $object->actionmsg = dol_concatdesc($langs->transnoentities("Author").': '.$user->login, $object->actionmsg); dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); @@ -766,7 +790,7 @@ class InterfaceActionsAuto extends DolibarrTriggers $elementid = $object->id; // id of object $elementtype = $object->element; - $elementmodule = $object->module; + $elementmodule = (empty($object->module) ? '' : $object->module); if ($object->element == 'subscription') { $elementid = $object->fk_adherent; $elementtype = 'member'; @@ -790,14 +814,14 @@ class InterfaceActionsAuto extends DolibarrTriggers $actioncomm->authorid = $user->id; // User saving action $actioncomm->userownerid = $user->id; // Owner of action // Fields defined when action is an email (content should be into object->actionmsg to be added into note, subject into object->actionms2 to be added into label) - $actioncomm->email_msgid = $object->email_msgid; - $actioncomm->email_from = $object->email_from; - $actioncomm->email_sender = $object->email_sender; - $actioncomm->email_to = $object->email_to; - $actioncomm->email_tocc = $object->email_tocc; - $actioncomm->email_tobcc = $object->email_tobcc; - $actioncomm->email_subject = $object->email_subject; - $actioncomm->errors_to = $object->errors_to; + $actioncomm->email_msgid = empty($object->email_msgid) ? null : $object->email_msgid; + $actioncomm->email_from = empty($object->email_from) ? null : $object->email_from; + $actioncomm->email_sender = empty($object->email_sender) ? null : $object->email_sender; + $actioncomm->email_to = empty($object->email_to) ? null : $object->email_to; + $actioncomm->email_tocc = empty($object->email_tocc) ? null : $object->email_tocc; + $actioncomm->email_tobcc = empty($object->email_tobcc) ? null : $object->email_tobcc; + $actioncomm->email_subject = empty($object->email_subject) ? null : $object->email_subject; + $actioncomm->errors_to = empty($object->errors_to) ? null : $object->errors_to; // Object linked (if link is for thirdparty, contact, project it is a recording error. We should not have links in link table // for such objects because there is already a dedicated field into table llx_actioncomm or llx_actioncomm_resources. @@ -820,7 +844,7 @@ class InterfaceActionsAuto extends DolibarrTriggers $ret = $actioncomm->create($user); // User creating action - if ($ret > 0 && $conf->global->MAIN_COPY_FILE_IN_EVENT_AUTO) { + if ($ret > 0 && !empty($conf->global->MAIN_COPY_FILE_IN_EVENT_AUTO)) { if (is_array($object->attachedfiles) && array_key_exists('paths', $object->attachedfiles) && count($object->attachedfiles['paths']) > 0) { foreach ($object->attachedfiles['paths'] as $key=>$filespath) { $srcfile = $filespath; diff --git a/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php b/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php index 4224b46db89..de81e54165a 100644 --- a/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php +++ b/htdocs/core/triggers/interface_99_modZapier_ZapierTriggers.class.php @@ -85,8 +85,28 @@ class InterfaceZapierTriggers extends DolibarrTriggers switch ($action) { // Users - //case 'USER_CREATE': - //case 'USER_MODIFY': + 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); + } + $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); + } + $logtriggeraction = true; + break; //case 'USER_NEW_PASSWORD': //case 'USER_ENABLEDISABLE': //case 'USER_DELETE': @@ -124,6 +144,12 @@ class InterfaceZapierTriggers extends DolibarrTriggers //case 'USERGROUP_MODIFY': //case 'USERGROUP_DELETE': + // Categories + // case 'CATEGORY_CREATE': + // case 'CATEGORY_MODIFY': + // case 'CATEGORY_DELETE': + // case 'CATEGORY_SET_MULTILANGS': + // Companies case 'COMPANY_CREATE': $resql = $this->db->query($sql); @@ -305,12 +331,6 @@ class InterfaceZapierTriggers extends DolibarrTriggers // case 'MEMBER_RESILIATE': // case 'MEMBER_DELETE': - // Categories - // case 'CATEGORY_CREATE': - // case 'CATEGORY_MODIFY': - // case 'CATEGORY_DELETE': - // case 'CATEGORY_SET_MULTILANGS': - // Projects // case 'PROJECT_CREATE': // case 'PROJECT_MODIFY': @@ -325,6 +345,21 @@ class InterfaceZapierTriggers extends DolibarrTriggers // case 'TASK_TIMESPENT_CREATE': // case 'TASK_TIMESPENT_MODIFY': // case 'TASK_TIMESPENT_DELETE': + case 'TICKET_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); + } + $logtriggeraction = true; + break; + // case 'TICKET_MODIFY': + // break; + // case 'TICKET_DELETE': + // break; // Shipping // case 'SHIPPING_CREATE': @@ -439,13 +474,13 @@ function cleanObjectDatas($toclean) // 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(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; } @@ -453,7 +488,7 @@ function cleanObjectDatas($toclean) /** * Clean sensible object datas * - * @param object $toclean Object to clean + * @param Object $toclean Object to clean * @return Object Object with cleaned properties */ function cleanAgendaEventsDatas($toclean) diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index bb4f0717a5a..e163f146678 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -152,8 +152,8 @@ class Don extends CommonObject /** * Returns the donation status label (draft, valid, abandoned, paid) * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status */ public function getLibStatut($mode = 0) { @@ -164,9 +164,9 @@ class Don extends CommonObject /** * Return the label of a given status * - * @param int $status Id statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut + * @param int $status Id statut + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status */ public function LibStatut($status, $mode = 0) { @@ -922,7 +922,10 @@ class Don extends CommonObject if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("Donation").''; + $label = img_picto('', $this->picto).' '.$langs->trans("Donation").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } if (!empty($this->id)) { $label .= '
'.$langs->trans('Ref').': '.$this->id; $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); diff --git a/htdocs/emailcollector/class/emailcollector.class.php b/htdocs/emailcollector/class/emailcollector.class.php index aed02f40531..1776e9855d5 100644 --- a/htdocs/emailcollector/class/emailcollector.class.php +++ b/htdocs/emailcollector/class/emailcollector.class.php @@ -1342,6 +1342,15 @@ class EmailCollector extends CommonObject $trackid = $reg[1].$reg[2]; $objectid = $reg[2]; + // See also list into interface_50_modAgenda_ActionsAuto + if ($reg[1] == 'thi') + { + $objectemail = new Societe($this->db); + } + if ($reg[1] == 'ctc') + { + $objectemail = new Contact($this->db); + } if ($reg[1] == 'inv') { $objectemail = new Facture($this->db); @@ -1350,14 +1359,14 @@ class EmailCollector extends CommonObject { $objectemail = new Project($this->db); } + if ($reg[1] == 'tas') + { + $objectemail = new Task($this->db); + } if ($reg[1] == 'con') { $objectemail = new Contact($this->db); } - if ($reg[1] == 'thi') - { - $objectemail = new Societe($this->db); - } if ($reg[1] == 'use') { $objectemail = new User($this->db); @@ -1370,6 +1379,10 @@ class EmailCollector extends CommonObject { $objectemail = new RecruitmentCandidature($this->db); } + if ($reg[1] == 'mem') + { + $objectemail = new Adherent($this->db); + } } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) { // This is an external reference, we check if we have it in our database if (!is_object($objectemail)) { diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index 018269632ef..bc97a26d7ff 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -2495,7 +2495,7 @@ class Expedition extends CommonObject if (!dol_strlen($modele)) { $modele = 'rouget'; - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->EXPEDITION_ADDON_PDF)) { $modele = $conf->global->EXPEDITION_ADDON_PDF; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index 611cf72593a..f533d0e7851 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -2207,7 +2207,7 @@ class ExpenseReport extends CommonObject $langs->load("trips"); if (!dol_strlen($modele)) { - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) { $modele = $conf->global->EXPENSEREPORT_ADDON_PDF; diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 71cc3c40da5..d86c1b21abf 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -689,7 +689,7 @@ class Fichinter extends CommonObject if (!dol_strlen($modele)) { $modele = 'soleil'; - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->FICHEINTER_ADDON_PDF)) { $modele = $conf->global->FICHEINTER_ADDON_PDF; diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php index c9e689ffd4c..23940c04e70 100644 --- a/htdocs/fichinter/class/fichinterrec.class.php +++ b/htdocs/fichinter/class/fichinterrec.class.php @@ -281,7 +281,7 @@ class FichinterRec extends Fichinter $this->note_public = $obj->note_public; $this->user_author = $obj->fk_user_author; $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated $this->rang = $obj->rang; $this->special_code = $obj->special_code; $this->frequency = $obj->frequency; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 1bf32782bdb..d69d85d65cc 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -123,7 +123,6 @@ class FactureFournisseur extends CommonInvoice /** * Set to 1 if the invoice is completely paid, otherwise is 0 * @var int - * @deprecated Use statuses stored in self::statut */ public $paye; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index b5a0111e4f4..600e60265d5 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -1084,7 +1084,7 @@ if (empty($reshook)) // Actions to send emails $triggersendname = 'ORDER_SUPPLIER_SENTBYMAIL'; $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO'; - $trackid = 'sor'.$object->id; + $trackid = 'sord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -2875,7 +2875,7 @@ if ($action == 'create') $defaulttopic = 'SendOrderRef'; $diroutput = $conf->fournisseur->commande->dir_output; $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO'; - $trackid = 'sor'.$object->id; + $trackid = 'sord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index af963952765..709cbdb84f7 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -1548,7 +1548,7 @@ if (empty($reshook)) $triggersendname = 'BILL_SUPPLIER_SENTBYMAIL'; $paramname = 'id'; $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO'; - $trackid = 'sin'.$object->id; + $trackid = 'sinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -3308,7 +3308,7 @@ if ($action == 'create') $defaulttopic = 'SendBillRef'; $diroutput = $conf->fournisseur->facture->dir_output; $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO'; - $trackid = 'sin'.$object->id; + $trackid = 'sinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 06b12e3afaa..1834e23e7bc 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -109,6 +109,7 @@ $year_lim = GETPOST('year_lim', 'int'); $toselect = GETPOST('toselect', 'array'); $search_btn = GETPOST('button_search', 'alpha'); $search_remove_btn = GETPOST('button_removefilter', 'alpha'); +$search_categ_sup = trim(GETPOST("search_categ_sup", 'int')); $option = GETPOST('option'); if ($option == 'late') { @@ -260,6 +261,7 @@ if (empty($reshook)) $filter = ''; $option = ''; $socid = ""; + $search_categ_sup = 0; } // Mass actions @@ -304,6 +306,7 @@ $sql .= " u.login"; // We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0) // TODO Better solution to be able to sort on already payed or remain to pay is to store amount_payed in a denormalized field. if (!$search_all) $sql .= ', SUM(pf.amount) as dynamount_payed'; +if ($search_categ_sup) $sql .= ", cs.fk_categorie, cs.fk_soc"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); @@ -316,6 +319,8 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; +if (!empty($search_categ_sup)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; + $sql .= ', '.MAIN_DB_PREFIX.'facture_fourn as f'; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; if (!$search_all) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid'; @@ -376,6 +381,8 @@ $sql .= dolSqlDateFilter("f.datef", $day, $month, $year); $sql .= dolSqlDateFilter("f.date_lim_reglement", $day_lim, $month_lim, $year_lim); if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; if ($search_label) $sql .= natural_search('f.libelle', $search_label); +if ($search_categ_sup > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); +if ($search_categ_sup == -2) $sql .= " AND cs.fk_categorie IS NULL"; if ($search_status != '' && $search_status >= 0) { $sql .= " AND f.fk_statut = ".$search_status; @@ -497,6 +504,8 @@ if ($resql) if ($show_files) $param .= '&show_files='.urlencode($show_files); if ($option) $param .= "&option=".urlencode($option); if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if ($search_categ_sup > 0) $param .= '&search_categ_sup='.urlencode($search_categ_sup); + // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -608,6 +617,15 @@ if ($resql) $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter .= ''; } + + if (!empty($conf->categorie->enabled)) + { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('SuppliersCategoriesShort').': '; + $moreforfilter .= $formother->select_categories('supplier', $search_categ_sup, 'search_categ_sup', 1); + $moreforfilter .= '
'; + } $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index 5cd43424760..2f2c9145beb 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -55,8 +55,8 @@ $now = dol_now(); $childids = $user->getAllChildIds(1); -$morefilter = 'AND employee = 1'; -if (!empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; +$morefilter = ''; +if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) $morefilter = 'AND employee = 1'; $error = 0; diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index a0f640f0cd3..262185df4c5 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -1102,7 +1102,7 @@ class Holiday extends CommonObject /** - * Check that a user is not on holiday for a particular timestamp + * Check that a user is not on holiday for a particular timestamp. Can check approved leave requests and not into public holidays of company. * * @param int $fk_user Id user * @param integer $timestamp Time stamp date for a day (YYYY-MM-DD) without hours (= 12:00AM in english and not 12:00PM that is 12:00) @@ -1117,6 +1117,7 @@ class Holiday extends CommonObject $isavailablemorning = true; $isavailableafternoon = true; + // Check into leave requests $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut"; $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp"; $sql .= " WHERE cp.entity IN (".getEntity('holiday').")"; @@ -1161,7 +1162,10 @@ class Holiday extends CommonObject } } else dol_print_error($this->db); - return array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon); + $result = array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon); + if (!$isavailablemorning) $result['morning_reason'] = 'leave_request'; + if (!$isavailableafternoon) $result['afternoon_reason'] = 'leave_request'; + return $result; } diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index f16375209e1..615ab6cfa44 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -487,8 +487,8 @@ if ($resql) if (!empty($arrayfields['cp.fk_user']['checked'])) { - $morefilter = 'AND employee = 1'; - if (!empty($conf->global->HOLIDAY_FOR_NON_SALARIES_TOO)) $morefilter = ''; + $morefilter = ''; + if (!empty($conf->global->HOLIDAY_HIDE_FOR_NON_SALARIES)) $morefilter = 'AND employee = 1'; // User $disabled = 0; diff --git a/htdocs/hrm/index.php b/htdocs/hrm/index.php index 3955e3f849a..a713ec86100 100644 --- a/htdocs/hrm/index.php +++ b/htdocs/hrm/index.php @@ -294,6 +294,7 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) $expensereportstatic->id = $obj->rowid; $expensereportstatic->ref = $obj->ref; $expensereportstatic->statut = $obj->status; + $expensereportstatic->status = $obj->status; $userstatic->id = $obj->uid; $userstatic->lastname = $obj->lastname; diff --git a/htdocs/install/mysql/tables/llx_ecm_directories.sql b/htdocs/install/mysql/tables/llx_ecm_directories.sql index a02a72118b2..4616a763b81 100644 --- a/htdocs/install/mysql/tables/llx_ecm_directories.sql +++ b/htdocs/install/mysql/tables/llx_ecm_directories.sql @@ -30,7 +30,7 @@ CREATE TABLE llx_ecm_directories fullpath varchar(750), extraparams varchar(255), -- for stock other parameters with json format date_c datetime, - date_m timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_c integer, fk_user_m integer, acl text diff --git a/htdocs/install/mysql/tables/llx_ecm_files.sql b/htdocs/install/mysql/tables/llx_ecm_files.sql index 030081b66b7..635945a256d 100644 --- a/htdocs/install/mysql/tables/llx_ecm_files.sql +++ b/htdocs/install/mysql/tables/llx_ecm_files.sql @@ -35,7 +35,7 @@ CREATE TABLE llx_ecm_files gen_or_uploaded varchar(12), -- 'generated' or 'uploaded' extraparams varchar(255), -- for stocking other parameters with json format date_c datetime, - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_c integer, fk_user_m integer, acl text -- for future permission 'per file' diff --git a/htdocs/install/mysql/tables/llx_reception.sql b/htdocs/install/mysql/tables/llx_reception.sql index 71cc000ffc1..7989f80cf58 100644 --- a/htdocs/install/mysql/tables/llx_reception.sql +++ b/htdocs/install/mysql/tables/llx_reception.sql @@ -29,7 +29,7 @@ create table llx_reception fk_projet integer DEFAULT NULL, ref_ext varchar(30), -- reference into an external system (not used by dolibarr) - ref_int varchar(30), -- reference into an internal system (used by dolibarr to store extern id like paypal info) + ref_int varchar(30), -- reference into an internal system (deprecated) ref_supplier varchar(30), -- customer number date_creation datetime, -- date de creation diff --git a/htdocs/langs/en_US/recruitment.lang b/htdocs/langs/en_US/recruitment.lang index a50fa92ec9f..b775e78552e 100644 --- a/htdocs/langs/en_US/recruitment.lang +++ b/htdocs/langs/en_US/recruitment.lang @@ -71,3 +71,5 @@ YourCandidature=Your application YourCandidatureAnswerMessage=Thanks you for your application.
... JobClosedTextCandidateFound=The job position is closed. The position has been filled. JobClosedTextCanceled=The job position is closed. +ExtrafieldsJobPosition=Complementary attributes (job positions) +ExtrafieldsCandidatures=Complementary attributes (job applications) diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index d580029a5cc..d57a9b154a3 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -1092,14 +1092,15 @@ if (!function_exists("llxHeader")) * @param string $morequerystring Query string to add to the link "print" to get same parameters (use only if autodetect fails) * @param string $morecssonbody More CSS on body tag. * @param string $replacemainareaby Replace call to main_area() by a print of this string + * @param int $disablenofollow Disable the "nofollow" on page * @return void */ - function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '') + function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '', $disablenofollow = 0) { global $conf; // html header - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow); $tmpcsstouse = 'sidebar-collapse'.($morecssonbody ? ' '.$morecssonbody : ''); // If theme MD and classic layer, we open the menulayer by default. @@ -1557,7 +1558,8 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead // For backward compatibility with old modules if (empty($conf->headerdone)) { - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); + $disablenofollow = 0; + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow); print ''; } diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index f3564a3ff20..f350e65ee8e 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -308,11 +308,12 @@ class MyObject extends CommonObject unset($object->fk_user_creat); unset($object->import_key); - // Clear fields - $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - $object->status = self::STATUS_DRAFT; + if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } + if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } + if (property_exists($object, 'date_modification')) { $object->date_modification = null; } // ... // Clear extrafields that are unique if (is_array($object->array_options) && count($object->array_options) > 0) diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php index ee10229bfdc..6b63e878f64 100644 --- a/htdocs/mrp/class/mo.class.php +++ b/htdocs/mrp/class/mo.class.php @@ -987,12 +987,12 @@ class Mo extends CommonObject $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("ManufacturingOrder").''; + $label = img_picto('', $this->picto).' '.$langs->trans("ManufacturingOrder").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; - if (isset($this->status)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id; if ($option == 'production') $url = dol_buildpath('/mrp/mo_production.php', 1).'?id='.$this->id; diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php index 84484956df8..ea0dd4c2181 100644 --- a/htdocs/mrp/mo_card.php +++ b/htdocs/mrp/mo_card.php @@ -37,10 +37,10 @@ $langs->loadLangs(array("mrp", "other")); // Get parameters $id = GETPOST('id', 'int'); -$ref = GETPOST('ref', 'alpha'); +$ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); -$confirm = GETPOST('confirm', 'alpha'); -$cancel = GETPOST('cancel', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'mocard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); diff --git a/htdocs/mrp/mo_list.php b/htdocs/mrp/mo_list.php index 3c9312d50f6..beeefbd19ff 100644 --- a/htdocs/mrp/mo_list.php +++ b/htdocs/mrp/mo_list.php @@ -345,7 +345,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "SendMoRef"; $modelmail = "mo"; $objecttmp = new Mo($db); -$trackid = 'xxxx'.$object->id; +$trackid = 'mo'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/multicurrency/class/multicurrency.class.php b/htdocs/multicurrency/class/multicurrency.class.php index ec4b55f39dc..bb4df7060e9 100644 --- a/htdocs/multicurrency/class/multicurrency.class.php +++ b/htdocs/multicurrency/class/multicurrency.class.php @@ -628,46 +628,48 @@ class MultiCurrency extends CommonObject { global $conf, $db, $langs; + include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + $urlendpoint = 'http://apilayer.net/api/live?access_key='.$key; //$urlendpoint.='&format=1'; $urlendpoint .= (empty($conf->global->MULTICURRENCY_APP_SOURCE) ? '' : '&source='.$conf->global->MULTICURRENCY_APP_SOURCE); dol_syslog("Call url endpoint ".$urlendpoint); - // FIXME Use getURLContent() function instead. - $ch = curl_init($urlendpoint); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $response = curl_exec($ch); - curl_close($ch); - $response = json_decode($response); + $resget = getURLContent($urlendpoint, 'GET', '', 1, array(), array('http', 'https'), 1); - if ($response->success) - { - $TRate = $response->quotes; - $timestamp = $response->timestamp; + if ($resget['content']) { + $response = $resget['content']; + $response = json_decode($response); - if (self::recalculRates($TRate) >= 0) + if ($response->success) { - foreach ($TRate as $currency_code => $rate) + $TRate = $response->quotes; + $timestamp = $response->timestamp; + + if (self::recalculRates($TRate) >= 0) { - $code = substr($currency_code, 3, 3); - $obj = new MultiCurrency($db); - if ($obj->fetch(null, $code) > 0) + foreach ($TRate as $currency_code => $rate) { - $obj->updateRate($rate); - } elseif ($addifnotfound) - { - self::addRateFromDolibarr($code, $rate); + $code = substr($currency_code, 3, 3); + $obj = new MultiCurrency($db); + if ($obj->fetch(null, $code) > 0) + { + $obj->updateRate($rate); + } elseif ($addifnotfound) + { + self::addRateFromDolibarr($code, $rate); + } } } + + return 1; + } else { + dol_syslog("Failed to call endpoint ".$response->error->info, LOG_WARNING); + setEventMessages($langs->trans('multicurrency_syncronize_error', $response->error->info), null, 'errors'); + + return -1; } - - return 1; - } else { - dol_syslog("Failed to call endpoint ".$response->error->info, LOG_WARNING); - setEventMessages($langs->trans('multicurrency_syncronize_error', $response->error->info), null, 'errors'); - - return -1; } } diff --git a/htdocs/multicurrency/multicurrency_rate.php b/htdocs/multicurrency/multicurrency_rate.php index ad2b0e8ddf6..ffab711e1cd 100644 --- a/htdocs/multicurrency/multicurrency_rate.php +++ b/htdocs/multicurrency/multicurrency_rate.php @@ -63,7 +63,7 @@ $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (!$sortfield) $sortfield = "cr.date_sync"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortorder) $sortorder = "DESC"; // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks @@ -233,7 +233,7 @@ print dol_get_fiche_head($head, 'ratelist', $langs->trans("ModuleSetup"), -1, "m // ACTION -if ($action != "updateRate" && $action != "deleteRate") { +if ($action != "updateRate") { print ''; print ''; print ''."\n"; @@ -252,7 +252,7 @@ if ($action != "updateRate" && $action != "deleteRate") { print ''; print ' '; - print ' '; + print ' '; print ''; if (!$i) $totalarray['nbfield']++; diff --git a/htdocs/opensurvey/fonctions.php b/htdocs/opensurvey/fonctions.php index 4a3cb591b97..208646c0a23 100644 --- a/htdocs/opensurvey/fonctions.php +++ b/htdocs/opensurvey/fonctions.php @@ -77,11 +77,10 @@ function llxHeaderSurvey($title, $head = "", $disablejs = 0, $disablehead = 0, $ //$replacemainarea = (empty($conf->dol_hide_leftmenu) ? '
' : '').'
'; - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers + top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, 1); // Show html headers + print ''; - - print ''."\n"; print '
'."\n"; print ''."\n"; @@ -116,7 +115,7 @@ function llxHeaderSurvey($title, $head = "", $disablejs = 0, $disablehead = 0, $ print '>'; print '
'; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print ''; + print ''; } print '
'; } diff --git a/htdocs/product/class/html.formproduct.class.php b/htdocs/product/class/html.formproduct.class.php index 3b74180f237..eed18bbf8bd 100644 --- a/htdocs/product/class/html.formproduct.class.php +++ b/htdocs/product/class/html.formproduct.class.php @@ -206,7 +206,7 @@ class FormProduct /** * Return list of warehouses * - * @param string|int $selected Id of preselected warehouse ('' for no value, 'ifone'=select value if one value otherwise no value) + * @param string|int $selected Id of preselected warehouse ('' or '-1' for no value, 'ifone'=select value if one value otherwise no value, '-2' to use the default value from setup) * @param string $htmlname Name of html select html * @param string $filterstatus warehouse status filter, following comma separated filter options can be used * 'warehouseopen' = select products from open warehouses, @@ -250,10 +250,10 @@ class FormProduct if (strpos($htmlname, 'search_') !== 0) { if (empty($user->fk_warehouse) || $user->fk_warehouse == -1) { - if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $selected = $conf->global->MAIN_DEFAULT_WAREHOUSE; + if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $selected = $conf->global->MAIN_DEFAULT_WAREHOUSE; } else { - if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $selected = $user->fk_warehouse; + if (($selected == '-2' || $selected == 'ifone') && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $selected = $user->fk_warehouse; } } diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index ef3da905990..2826d2fe4e3 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -300,9 +300,9 @@ if (empty($reshook)) $multicurrency_price = price2num(GETPOST("multicurrency_price", 'alpha')); $multicurrency_code = GETPOST("multicurrency_code", 'alpha'); - $ret = $object->update_buyprice($quantity, $newprice, $user, $_POST["price_base_type"], $supplier, $_POST["oselDispo"], $ref_fourn, $tva_tx, $_POST["charges"], $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', $multicurrency_price, $_POST["multicurrency_price_base_type"], $multicurrency_tx, $multicurrency_code, $supplier_description, $barcode, $fk_barcode_type); + $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', $multicurrency_price, GETPOST("multicurrency_price_base_type"), $multicurrency_tx, $multicurrency_code, $supplier_description, $barcode, $fk_barcode_type); } else { - $ret = $object->update_buyprice($quantity, $newprice, $user, $_POST["price_base_type"], $supplier, $_POST["oselDispo"], $ref_fourn, $tva_tx, $_POST["charges"], $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type); + $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type); } if ($ret < 0) { @@ -655,7 +655,7 @@ if ($id > 0 || $ref) } $currencies = json_encode($currencies); - print << -SCRIPT; +END; } else { // Price qty min print '
'; diff --git a/htdocs/product/inventory/inventory.php b/htdocs/product/inventory/inventory.php index 67906022057..dab4f6d1fa7 100644 --- a/htdocs/product/inventory/inventory.php +++ b/htdocs/product/inventory/inventory.php @@ -120,7 +120,7 @@ if (empty($reshook)) // Actions to send emails /*$triggersendname = 'MYOBJECT_SENTBYMAIL'; $autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; - $trackid='myobject'.$object->id; + $trackid='stockinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';*/ if (GETPOST('addline', 'alpha')) { diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index 879a6196450..747abda86b8 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -324,7 +324,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "Information"; $modelmail = "inventory"; $objecttmp = new Inventory($db); -$trackid = 'inve'.$object->id; +$trackid = 'stockinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index 5abf87c497e..d2f9494e857 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -258,7 +258,7 @@ if ($action == 'create') // Parent entrepot print ''; // Description @@ -690,7 +690,7 @@ if ($action == 'create') // Ref print ''; - print ''; + print ''; // Parent entrepot print ''; diff --git a/htdocs/product/stock/stockatdate.php b/htdocs/product/stock/stockatdate.php index 8dabfdbf673..431bec3fd89 100644 --- a/htdocs/product/stock/stockatdate.php +++ b/htdocs/product/stock/stockatdate.php @@ -345,7 +345,7 @@ print '   '.$langs->trans('Warehouse').' '; -print $formproduct->selectWarehouses($fk_warehouse, 'fk_warehouse', '', 1); +print $formproduct->selectWarehouses((GETPOSTISSET('fk_warehouse') ? $fk_warehouse : 'ifone'), 'fk_warehouse', '', 1); print ''; $parameters = array(); diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php index 361e70c3cf7..cb16f4685bf 100644 --- a/htdocs/projet/activity/perday.php +++ b/htdocs/projet/activity/perday.php @@ -48,8 +48,7 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'per $mine = 0; if ($mode == 'mine') $mine = 1; -$projectid = ''; -$projectid = isset($_GET["id"]) ? $_GET["id"] : $_POST["projectid"]; +$projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int"); $hookmanager->initHooks(array('timesheetperdaycard')); @@ -612,20 +611,24 @@ if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) } } -$statusofholidaytocheck = '3'; +$statusofholidaytocheck = Holiday::STATUS_APPROVED; $isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $daytoparse, $statusofholidaytocheck); // $daytoparse is a date with hours = 0 $isavailable[$daytoparse] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day -$tmparray = dol_getdate($daytoparse, true); // detail of current day -$idw = $tmparray['wday']; +$test = num_public_holiday($daytoparse, $daytoparse + 86400, $mysoc->country_code); +if ($test) $isavailable[$daytoparse] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday'); +$tmparray = dol_getdate($daytoparse, true); // detail of current day +// For monday, must be 0 for monday if MAIN_START_WEEK = 1, must be 1 for monday if MAIN_START_WEEK = 0 +$idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK)?0:1)); +// numstartworkingday and numendworkingday are default start and end date of working days (1 means sunday if MAIN_START_WEEK is 0, 1 means monday if MAIN_START_WEEK is 1) $cssweekend = ''; -if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. +if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } -$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); +$tmpday = dol_time_plus_duree($daytoparse, $idw, 'd'); $cssonholiday = ''; if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; @@ -651,20 +654,6 @@ if ($conf->use_javascript_ajax) //print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print ''; - $tmparray = dol_getdate($daytoparse, true); // detail of current day - $idw = $tmparray['wday']; - - $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. - { - $cssweekend = 'weekend'; - } - - $cssonholiday = ''; - if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$daytoparse]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; print ''; @@ -752,20 +741,6 @@ if (count($tasksarray) > 0) //print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print ''; - $tmparray = dol_getdate($daytoparse, true); // detail of current day - $idw = $tmparray['wday']; - - $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. - { - $cssweekend = 'weekend'; - } - - $cssonholiday = ''; - if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$daytoparse]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; print ' diff --git a/htdocs/projet/activity/permonth.php b/htdocs/projet/activity/permonth.php index 5c8111b049f..bbbf3827fc9 100644 --- a/htdocs/projet/activity/permonth.php +++ b/htdocs/projet/activity/permonth.php @@ -46,8 +46,7 @@ $taskid = GETPOST('taskid', 'int'); $mine = 0; if ($mode == 'mine') $mine = 1; -$projectid = ''; -$projectid = isset($_GET["id"]) ? $_GET["id"] : $_POST["projectid"]; +$projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int"); // Security check $socid = 0; @@ -502,7 +501,10 @@ $colspan = 5; // By default, we can edit only tasks we are assigned to $restrictviewformytask = (empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED) ? 1 : 0); +// Get if user is available or not for each day $isavailable = array(); +// TODO See code into perweek.php to initialize isavailable array + if (count($tasksarray) > 0) { diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php index 748f1c307d4..1f808304991 100644 --- a/htdocs/projet/activity/perweek.php +++ b/htdocs/projet/activity/perweek.php @@ -48,8 +48,7 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'per $mine = 0; if ($mode == 'mine') $mine = 1; -$projectid = ''; -$projectid = isset($_GET["id"]) ? $_GET["id"] : $_POST["projectid"]; +$projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int"); $hookmanager->initHooks(array('timesheetperweekcard')); @@ -364,7 +363,6 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac } - /* * View */ @@ -530,11 +528,16 @@ for ($idw = 0; $idw < 7; $idw++) //print dol_print_date($dayinloopwithouthours, 'dayhour').' '; //print dol_print_date($dayinloopfromfirstdaytoshow, 'dayhour').'
'; - $statusofholidaytocheck = '3'; + $statusofholidaytocheck = Holiday::STATUS_APPROVED; $isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoprocess->id, $dayinloopfromfirstdaytoshow, $statusofholidaytocheck); $isavailable[$dayinloopfromfirstdaytoshow] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day + + $test = num_public_holiday($dayinloopfromfirstdaytoshow, $dayinloopfromfirstdaytoshow + 86400, $mysoc->country_code); + if ($test) $isavailable[$dayinloopfromfirstdaytoshow] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday'); } +//var_dump($isavailable); + $moreforfilter = ''; @@ -656,7 +659,7 @@ for ($idw = 0; $idw < 7; $idw++) $dayinloop = dol_time_plus_duree($startday, $idw, 'd'); $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } @@ -689,7 +692,7 @@ if ($conf->use_javascript_ajax) for ($idw = 0; $idw < 7; $idw++) { $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } @@ -700,7 +703,6 @@ if ($conf->use_javascript_ajax) if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; - print ''; } print ''; @@ -775,7 +777,7 @@ if (count($tasksarray) > 0) for ($idw = 0; $idw < 7; $idw++) { $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } @@ -803,10 +805,9 @@ if (count($tasksarray) > 0) print ' - '.$langs->trans("ExpectedWorkedHours").': '.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).''; print ''; - for ($idw = 0; $idw < 7; $idw++) - { + for ($idw = 0; $idw < 7; $idw++) { $cssweekend = ''; - if (($idw + 1) < $numstartworkingday || ($idw + 1) > $numendworkingday) // This is a day is not inside the setup of working days, so we use a week-end css. + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. { $cssweekend = 'weekend'; } diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php index be54c9f568b..2df22bc933e 100644 --- a/htdocs/projet/class/task.class.php +++ b/htdocs/projet/class/task.class.php @@ -1900,7 +1900,7 @@ class Task extends CommonObject if (!dol_strlen($modele)) { $modele = 'nodefault'; - if ($this->modelpdf) { + if (!empty($this->modelpdf)) { $modele = $this->modelpdf; } elseif (!empty($conf->global->PROJECT_TASK_ADDON_PDF)) { $modele = $conf->global->PROJECT_TASK_ADDON_PDF; diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index bf706550318..6c08dd6c384 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -484,7 +484,7 @@ print_barre_liste($form->textwithpicto($title, $texthelp), $page, $_SERVER["PHP_ $topicmail = "Information"; $modelmail = "project"; $objecttmp = new Project($db); -$trackid = 'prj'.$object->id; +$trackid = 'proj'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/public/demo/index.php b/htdocs/public/demo/index.php index 982f3b18686..dbfeeebbf58 100644 --- a/htdocs/public/demo/index.php +++ b/htdocs/public/demo/index.php @@ -272,7 +272,7 @@ print "\n"; print '
'; print '
'; -print ''; +print ''; print '
'; print '
'; @@ -447,11 +447,9 @@ $db->close(); */ function llxHeaderVierge($title, $head = "") { - global $user, $conf, $langs; - top_httphead(); - top_htmlhead($head, $title, 0, 0, array(), array('public/demo/demo.css')); + top_htmlhead($head, $title, 0, 0, array(), array('public/demo/demo.css'), 0, 1); print '
'."\n"; } diff --git a/htdocs/public/donations/donateurs_code.php b/htdocs/public/donations/donateurs_code.php index 511809d58ac..70b55981816 100644 --- a/htdocs/public/donations/donateurs_code.php +++ b/htdocs/public/donations/donateurs_code.php @@ -35,7 +35,7 @@ if (!defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined */ function llxHeaderVierge() { - print 'Export agenda cal'; + print 'List of donators'; } /** * Header function diff --git a/htdocs/public/members/new.php b/htdocs/public/members/new.php index 923c57b4692..8ada0a9b291 100644 --- a/htdocs/public/members/new.php +++ b/htdocs/public/members/new.php @@ -123,7 +123,7 @@ function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $ print '>'; print '
'; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print '
'.$langs->trans("PoweredBy").'
'; + print '
'.$langs->trans("PoweredBy").'
'; } print ''; } diff --git a/htdocs/public/onlinesign/newonlinesign.php b/htdocs/public/onlinesign/newonlinesign.php index 1291035760f..b71f5a84cd0 100644 --- a/htdocs/public/onlinesign/newonlinesign.php +++ b/htdocs/public/onlinesign/newonlinesign.php @@ -129,7 +129,7 @@ $conf->dol_hide_topmenu = 1; $conf->dol_hide_leftmenu = 1; $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '
' : '').'
'; -llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea); +llxHeader($head, $langs->trans("OnlineSignature"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea, 1); // Check link validity for param 'source' if (!empty($source) && in_array($ref, array('member_ref', 'contractline_ref', 'invoice_ref', 'order_ref', ''))) @@ -185,7 +185,7 @@ if ($urllogo) print '>'; print '
'; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print '
'.$langs->trans("PoweredBy").'
'; + print '
'.$langs->trans("PoweredBy").'
'; } print '
'; } diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 89992d00ff9..03dbf71051b 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -390,7 +390,7 @@ if ($action == 'dopayment') // Called when choosing Stripe mode. // When using the Charge API architecture, this code is called after clicking the 'dopayment' with the Charge API architecture. -// When using the PaymentIntent API architecture, the Stripe customer is already created when creating PaymentItent when showing payment page and the payment is already ok. +// When using the PaymentIntent API architecture, the Stripe customer is already created when creating PaymentIntent when showing payment page and the payment is already ok. if ($action == 'charge' && !empty($conf->stripe->enabled)) { $amountstripe = $amount; @@ -400,6 +400,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'); if (!in_array($currency, $arrayzerounitcurrency)) $amountstripe = $amountstripe * 100; + dol_syslog("--- newpayment.php Execute action = ".$action, LOG_DEBUG, 0, '_stripe'); dol_syslog("POST keys : ".join(',', array_keys($_POST)), LOG_DEBUG, 0, '_stripe'); dol_syslog("POST values: ".join(',', $_POST), LOG_DEBUG, 0, '_stripe'); @@ -419,7 +420,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) $error = 0; $errormessage = ''; - // When using the Charge API architecture + // When using the old Charge API architecture if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) { try { @@ -695,7 +696,7 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) dol_syslog("onlinetoken=".$_SESSION["onlinetoken"]." FinalPaymentAmt=".$_SESSION["FinalPaymentAmt"]." currencyCodeType=".$_SESSION["currencyCodeType"]." payerID=".$_SESSION['payerID']." TRANSACTIONID=".$_SESSION['TRANSACTIONID'], LOG_DEBUG, 0, '_stripe'); dol_syslog("FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_stripe'); dol_syslog("error=".$error." errormessage=".$errormessage, LOG_DEBUG, 0, '_stripe'); - dol_syslog("Now call the redirect to paymentok or paymentko", LOG_DEBUG, 0, '_stripe'); + dol_syslog("Now call the redirect to paymentok or paymentko, URL = ".($error ? $urlko : $urlok), LOG_DEBUG, 0, '_stripe'); if ($error) { @@ -787,7 +788,7 @@ if ($urllogo) print '>'; print ''; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print '
'.$langs->trans("PoweredBy").'
'; + print '
'.$langs->trans("PoweredBy").'
'; } print ''; } @@ -948,7 +949,7 @@ if ($source == 'order') $directdownloadlink = $order->getLastMainDocLink('commande'); if ($directdownloadlink) { - print '
'; + print '
'; print img_mime($order->last_main_doc, ''); print $langs->trans("DownloadDocument").''; } diff --git a/htdocs/public/payment/paymentko.php b/htdocs/public/payment/paymentko.php index 7a52098163d..e2d28044de5 100644 --- a/htdocs/public/payment/paymentko.php +++ b/htdocs/public/payment/paymentko.php @@ -238,7 +238,7 @@ if ($urllogo) print '>'; print ''; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print '
'.$langs->trans("PoweredBy").'
'; + print '
'.$langs->trans("PoweredBy").'
'; } print ''; } diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index 409da4cd346..98907ee9d02 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -178,7 +178,7 @@ if ($urllogo) print '>'; print ''; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print '
'.$langs->trans("PoweredBy").'
'; + print '
'.$langs->trans("PoweredBy").'
'; } print ''; } diff --git a/htdocs/public/recruitment/view.php b/htdocs/public/recruitment/view.php index 654dc0e696d..a76b49d1394 100644 --- a/htdocs/public/recruitment/view.php +++ b/htdocs/public/recruitment/view.php @@ -140,7 +140,7 @@ if ($action == "view" || $action == "presend" || $action == "close" || $action = $triggersendname = 'CANDIDATURE_SENTBYMAIL'; $paramname = 'id'; $autocopy = 'MAIN_MAIL_AUTOCOPY_CANDIDATURE_TO'; // used to know the automatic BCC to add -$trackid = 'can'.$object->id; +$trackid = 'recruitmentcandidature'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -165,7 +165,7 @@ $arrayofjs = array(); $arrayofcss = array(); $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '
' : '').'
'; -llxHeader($head, $langs->trans("PositionToBeFilled"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea); +llxHeader($head, $langs->trans("PositionToBeFilled"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea, 1); print ''."\n"; @@ -211,7 +211,7 @@ if ($urllogo) print '>'; print '
'; if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { - print '
'.$langs->trans("PoweredBy").'
'; + print '
'.$langs->trans("PoweredBy").'
'; } print '
'; } diff --git a/htdocs/public/ticket/create_ticket.php b/htdocs/public/ticket/create_ticket.php index bd7b5416efb..1c81faca1ad 100644 --- a/htdocs/public/ticket/create_ticket.php +++ b/htdocs/public/ticket/create_ticket.php @@ -222,7 +222,7 @@ if (empty($reshook) && $action == 'create_ticket' && GETPOST('add', 'alpha')) { $message .= $langs->transnoentities('TicketNewEmailBodyInfosTicket').'
'; $url_public_ticket = ($conf->global->TICKET_URL_PUBLIC_INTERFACE ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/' : dol_buildpath('/public/ticket/view.php', 2)).'?track_id='.$object->track_id; - $infos_new_ticket = $langs->transnoentities('TicketNewEmailBodyInfosTrackId', ''.$object->track_id.'').'
'; + $infos_new_ticket = $langs->transnoentities('TicketNewEmailBodyInfosTrackId', ''.$object->track_id.'').'
'; $infos_new_ticket .= $langs->transnoentities('TicketNewEmailBodyInfosTrackUrl').'

'; $message .= $infos_new_ticket; @@ -272,7 +272,7 @@ if (empty($reshook) && $action == 'create_ticket' && GETPOST('add', 'alpha')) { $message_admin .= ''; $message_admin .= '

'.$langs->trans('Message').' :
'.$object->message.'

'; - $message_admin .= '

'.$langs->trans('SeeThisTicketIntomanagementInterface').'

'; + $message_admin .= '

'.$langs->trans('SeeThisTicketIntomanagementInterface').'

'; $from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->TICKET_NOTIFICATION_EMAIL_FROM.'>'; $replyto = $from; diff --git a/htdocs/public/ticket/index.php b/htdocs/public/ticket/index.php index 2455e04797a..b3e8a5e237e 100644 --- a/htdocs/public/ticket/index.php +++ b/htdocs/public/ticket/index.php @@ -71,9 +71,9 @@ llxHeaderTicket($langs->trans("Tickets"), "", 0, 0, $arrayofjs, $arrayofcss); print '
'; print '

'.($conf->global->TICKET_PUBLIC_TEXT_HOME ? $conf->global->TICKET_PUBLIC_TEXT_HOME : $langs->trans("TicketPublicDesc")).'

'; print '
'; -print '

'.dol_escape_htmltag($langs->trans("CreateTicket")).'
'; -print '

'.dol_escape_htmltag($langs->trans("ViewMyTicketList")).'
'; -print '
'.img_picto('', 'ticket').'
'.dol_escape_htmltag($langs->trans("ShowTicketWithTrackId")).'
'; +print '

'.dol_escape_htmltag($langs->trans("CreateTicket")).'
'; +print '

'.dol_escape_htmltag($langs->trans("ViewMyTicketList")).'
'; +print '
'.img_picto('', 'ticket').'
'.dol_escape_htmltag($langs->trans("ShowTicketWithTrackId")).'
'; print '
'; print '
'; print '
'; diff --git a/htdocs/public/ticket/list.php b/htdocs/public/ticket/list.php index 9e7d5eacfa8..0f9542c986a 100644 --- a/htdocs/public/ticket/list.php +++ b/htdocs/public/ticket/list.php @@ -563,7 +563,7 @@ if ($action == "view_ticketlist") // Subject if (!empty($arrayfields['t.subject']['checked'])) { print ''; } diff --git a/htdocs/public/ticket/view.php b/htdocs/public/ticket/view.php index 3b0e2d0cdcc..02c7c9e51d8 100644 --- a/htdocs/public/ticket/view.php +++ b/htdocs/public/ticket/view.php @@ -374,7 +374,7 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a print load_fiche_titre($langs->trans('TicketMessagesList'), '', 'object_conversation'); $object->viewTicketMessages(false, true, $object->dao); } else { - print '
Not Allowed
'.$langs->trans('Back').'
'; + print '
Not Allowed
'.$langs->trans('Back').'
'; } } else { print '
'.$langs->trans("TicketPublicMsgViewLogIn").'
'; diff --git a/htdocs/reception/card.php b/htdocs/reception/card.php index 560147f46d3..62fc287fba3 100644 --- a/htdocs/reception/card.php +++ b/htdocs/reception/card.php @@ -2068,116 +2068,13 @@ if ($action == 'create') print '
'; } - if ($action == 'presend') - { - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->reception->dir_output.'/'.$ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('receptions'); - } - // Build document if it not exists - if (!$file || !is_readable($file)) - { - $result = $object->generateDocument(GETPOST('model') ?GETPOST('model') : $object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db, $object->error, $object->errors); - exit; - } - $fileparams = dol_most_recent_file($conf->reception->dir_output.'/reception/'.$ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; - } - print '
'; - print '
'; - print '
'; - print load_fiche_titre($langs->trans('SendReceptionByEMail')); - print dol_get_fiche_head(''); - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels'] = (empty($newlang) ? $langs->defaultlang : $newlang); - $formmail->fromtype = (GETPOST('fromtype') ?GETPOST('fromtype') : (!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user')); - if ($formmail->fromtype === 'user') { - $formmail->fromid = $user->id; - } - $formmail->trackid = 'shi'.$object->id; - if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail = dolAddEmailTrackId($formmail->frommail, 'shi'.$object->id); - } - $formmail->withfrom = 1; - $liste = array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key=>$value) $liste[$key] = $value; - $formmail->withto = GETPOST("sendto") ?GETPOST("sendto") : $liste; - $formmail->withtocc = $liste; - $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic = $outputlangs->trans('SendReceptionRef', '__RECEPTIONREF__'); - $formmail->withfile = 2; - $formmail->withbody = 1; - $formmail->withdeliveryreceipt = 1; - $formmail->withcancel = 1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object, $langs); - $formmail->substit['__RECEPTIONREF__'] = $object->ref; - $formmail->substit['__RECEPTIONTRACKNUM__'] = $object->tracking_number; - $formmail->substit['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url; - //Find the good contact adress - if ($typeobject == 'commande' && $object->$typeobject->id && !empty($conf->commande->enabled)) { - $objectsrc = new Commande($db); - $objectsrc->fetch($object->$typeobject->id); - } - if ($typeobject == 'propal' && $object->$typeobject->id && !empty($conf->propal->enabled)) { - $objectsrc = new Propal($db); - $objectsrc->fetch($object->$typeobject->id); - } - $custcontact = ''; - $contactarr = array(); - if (is_object($objectsrc)) // For the case the reception was created without orders - { - $contactarr = $objectsrc->liste_contact(-1, 'external'); - } - if (is_array($contactarr) && count($contactarr) > 0) { - foreach ($contactarr as $contact) { - if ($contact['libelle'] == $langs->trans('TypeContact_commande_external_CUSTOMER')) { - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $contactstatic = new Contact($db); - $contactstatic->fetch($contact['id']); - $custcontact = $contactstatic->getFullName($langs, 1); - } - } - if (!empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; - } - } - // Tableau des parametres complementaires - $formmail->param['action'] = 'send'; - $formmail->param['models'] = 'reception_send'; - $formmail->param['models_id'] = GETPOST('modelmailselected', 'int'); - $formmail->param['receptionid'] = $object->id; - $formmail->param['returnurl'] = $_SERVER["PHP_SELF"].'?id='.$object->id; - // Init list of files - if (GETPOST("mode") == 'init') - { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } - // Show form - print $formmail->get_form(); - print dol_get_fiche_end(); - } + // Presend form + $modelmail = 'shipping_send'; + $defaulttopic = 'SendReceptionRef'; + $diroutput = $conf->reception->dir_output; + $trackid = 'rec'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } diff --git a/htdocs/reception/class/reception.class.php b/htdocs/reception/class/reception.class.php index 766db0e3479..d64c3c999a7 100644 --- a/htdocs/reception/class/reception.class.php +++ b/htdocs/reception/class/reception.class.php @@ -7,7 +7,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2014-2015 Marcos García - * Copyright (C) 2014-2015 Francis Appels + * Copyright (C) 2014-2020 Francis Appels * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2018 Quentin Vial-Gouteyron @@ -223,7 +223,6 @@ class Reception extends CommonObject $sql .= "ref"; $sql .= ", entity"; $sql .= ", ref_supplier"; - $sql .= ", ref_int"; $sql .= ", date_creation"; $sql .= ", fk_user_author"; $sql .= ", date_reception"; @@ -246,7 +245,6 @@ class Reception extends CommonObject $sql .= "'(PROV)'"; $sql .= ", ".$conf->entity; $sql .= ", ".($this->ref_supplier ? "'".$this->db->escape($this->ref_supplier)."'" : "null"); - $sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null"); $sql .= ", '".$this->db->idate($now)."'"; $sql .= ", ".$user->id; $sql .= ", ".($this->date_reception > 0 ? "'".$this->db->idate($this->date_reception)."'" : "null"); @@ -364,7 +362,7 @@ class Reception extends CommonObject // Check parameters if (empty($id) && empty($ref) && empty($ref_ext)) return -1; - $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_supplier, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut"; + $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_supplier, e.ref_ext, e.fk_user_author, e.fk_statut"; $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height"; $sql .= ", e.date_reception as date_reception, e.model_pdf, e.date_delivery"; $sql .= ", e.fk_shipping_method, e.tracking_number"; @@ -394,7 +392,6 @@ class Reception extends CommonObject $this->socid = $obj->socid; $this->ref_supplier = $obj->ref_supplier; $this->ref_ext = $obj->ref_ext; - $this->ref_int = $obj->ref_int; $this->statut = $obj->fk_statut; $this->user_author_id = $obj->fk_user_author; $this->date_creation = $this->db->jdate($obj->date_creation); @@ -402,7 +399,6 @@ class Reception extends CommonObject $this->date_reception = $this->db->jdate($obj->date_reception); // TODO deprecated $this->date_reception = $this->db->jdate($obj->date_reception); // Date real $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planed - $this->fk_delivery_address = $obj->fk_address; $this->model_pdf = $obj->model_pdf; $this->modelpdf = $obj->model_pdf; // deprecated $this->shipping_method_id = $obj->fk_shipping_method; @@ -777,7 +773,6 @@ class Reception extends CommonObject if (isset($this->socid)) $this->socid = trim($this->socid); if (isset($this->fk_user_author)) $this->fk_user_author = trim($this->fk_user_author); if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid); - if (isset($this->fk_delivery_address)) $this->fk_delivery_address = trim($this->fk_delivery_address); if (isset($this->shipping_method_id)) $this->shipping_method_id = trim($this->shipping_method_id); if (isset($this->tracking_number)) $this->tracking_number = trim($this->tracking_number); if (isset($this->statut)) $this->statut = (int) $this->statut; @@ -787,8 +782,8 @@ class Reception extends CommonObject if (isset($this->size_units)) $this->size_units = trim($this->size_units); if (isset($this->weight_units)) $this->weight_units = trim($this->weight_units); if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight); - if (isset($this->note_private)) $this->note = trim($this->note_private); - if (isset($this->note_public)) $this->note = trim($this->note_public); + if (isset($this->note_private)) $this->note_private = trim($this->note_private); + if (isset($this->note_public)) $this->note_public = trim($this->note_public); if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); @@ -798,7 +793,6 @@ class Reception extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET"; - $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").","; $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").","; $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").","; @@ -1193,7 +1187,6 @@ class Reception extends CommonObject $this->date_reception = $now + 24 * 3600; $this->entrepot_id = 0; - $this->fk_delivery_address = 0; $this->socid = 1; $this->commande_id = 0; diff --git a/htdocs/recruitment/class/recruitmentcandidature.class.php b/htdocs/recruitment/class/recruitmentcandidature.class.php index 4d01bc4b0db..6c61ae55a1a 100644 --- a/htdocs/recruitment/class/recruitmentcandidature.class.php +++ b/htdocs/recruitment/class/recruitmentcandidature.class.php @@ -277,11 +277,13 @@ class RecruitmentCandidature extends CommonObject unset($object->fk_user_creat); unset($object->import_key); - // Clear fields - $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - $object->status = self::STATUS_DRAFT; + if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } + if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } + if (property_exists($object, 'date_modification')) { $object->date_modification = null; } + // ... // Clear extrafields that are unique if (is_array($object->array_options) && count($object->array_options) > 0) @@ -713,14 +715,14 @@ class RecruitmentCandidature extends CommonObject $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("RecruitmentCandidature").''; + $label = img_picto('', $this->picto).' '.$langs->trans("RecruitmentCandidature").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; $label .= '
'.$langs->trans('Email').': '.$this->email; $label .= '
'.$langs->trans('Name').': '.$this->getFullName($langs); - if (isset($this->status)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } $url = dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?id='.$this->id; @@ -1006,12 +1008,11 @@ class RecruitmentCandidature extends CommonObject $langs->load("recruitment@recruitment"); if (!dol_strlen($modele)) { - $modele = 'standard_recruitmentcandidature'; - - if ($this->modelpdf) { - $modele = $this->modelpdf; - } elseif (!empty($conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF)) { + if (!empty($conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF)) + { $modele = $conf->global->RECRUITMENTCANDIDATURE_ADDON_PDF; + } else { + $modele = ''; // No default value. For job application, we allow to disable all PDF generation } } diff --git a/htdocs/recruitment/class/recruitmentjobposition.class.php b/htdocs/recruitment/class/recruitmentjobposition.class.php index fdc5ab30eaa..a75e915baee 100644 --- a/htdocs/recruitment/class/recruitmentjobposition.class.php +++ b/htdocs/recruitment/class/recruitmentjobposition.class.php @@ -115,7 +115,7 @@ class RecruitmentJobPosition extends CommonObject 'description' => array('type'=>'html', 'label'=>'Description', 'enabled'=>'1', 'position'=>65, 'notnull'=>0, 'visible'=>3,), 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>101, 'notnull'=>0, 'visible'=>0,), 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>102, 'notnull'=>0, 'visible'=>0,), - 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-4,), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,), 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',), 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,), @@ -290,11 +290,12 @@ class RecruitmentJobPosition extends CommonObject unset($object->fk_user_creat); unset($object->import_key); - // Clear fields - $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - $object->status = self::STATUS_DRAFT; + if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; } + if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); } + if (property_exists($object, 'date_modification')) { $object->date_modification = null; } // ... // Clear extrafields that are unique if (is_array($object->array_options) && count($object->array_options) > 0) @@ -816,13 +817,13 @@ class RecruitmentJobPosition extends CommonObject $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("PositionToBeFilled").''; + $label = img_picto('', $this->picto).' '.$langs->trans("PositionToBeFilled").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; $label .= '
'.$langs->trans('Label').': '.$this->label; - if (isset($this->status)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } $url = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?id='.$this->id; @@ -1092,12 +1093,11 @@ class RecruitmentJobPosition extends CommonObject $langs->load("recruitment"); if (!dol_strlen($modele)) { - $modele = 'standard_recruitmentjobposition'; - - if ($this->model_pdf) { - $modele = $this->model_pdf; - } elseif (!empty($conf->global->RECRUITMENTJOBPOSITION_ADDON_PDF)) { + if (!empty($conf->global->RECRUITMENTJOBPOSITION_ADDON_PDF)) + { $modele = $conf->global->RECRUITMENTJOBPOSITION_ADDON_PDF; + } else { + $modele = ''; // No default value. For job position, we allow to disable all PDF generation } } diff --git a/htdocs/recruitment/recruitmentcandidature_card.php b/htdocs/recruitment/recruitmentcandidature_card.php index d688ca31c8d..1fbd64208f4 100644 --- a/htdocs/recruitment/recruitmentcandidature_card.php +++ b/htdocs/recruitment/recruitmentcandidature_card.php @@ -60,8 +60,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -dol_include_once('/recruitment/class/recruitmentcandidature.class.php'); -dol_include_once('/recruitment/lib/recruitment_recruitmentcandidature.lib.php'); +require_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentjobposition.class.php'; +require_once DOL_DOCUMENT_ROOT.'/recruitment/class/recruitmentcandidature.class.php'; +require_once DOL_DOCUMENT_ROOT.'/recruitment/lib/recruitment_recruitmentcandidature.lib.php'; // Load translation files required by the page $langs->loadLangs(array("recruitment", "other", "users")); @@ -233,6 +234,9 @@ if (empty($reshook)) // Create user from a member if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) { if ($result > 0) { + $jobposition = new RecruitmentJobPosition($db); + $jobposition->fetch($object->fk_recruitmentjobposition); + // Creation user $nuser = new User($db); $nuser->login = GETPOST('login', 'alphanohtml'); @@ -243,6 +247,7 @@ if (empty($reshook)) $nuser->personal_mobile = $object->phone; $nuser->birth = $object->date_birth; $nuser->salary = $object->remuneration_proposed; + $nuser->fk_user = $jobposition->fk_user_supervisor; // Supervisor $result = $nuser->create($user); diff --git a/htdocs/recruitment/recruitmentjobposition_list.php b/htdocs/recruitment/recruitmentjobposition_list.php index 72349c94914..c942975a91d 100644 --- a/htdocs/recruitment/recruitmentjobposition_list.php +++ b/htdocs/recruitment/recruitmentjobposition_list.php @@ -388,7 +388,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "SendRecruitmentJobPositionRef"; $modelmail = "recruitmentjobposition"; $objecttmp = new RecruitmentJobPosition($db); -$trackid = 'xxxx'.$object->id; +$trackid = 'recruitmentjobposition'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/salaries/admin/salaries_extrafields.php b/htdocs/salaries/admin/salaries_extrafields.php index 3e527c7fba5..62073f8177b 100644 --- a/htdocs/salaries/admin/salaries_extrafields.php +++ b/htdocs/salaries/admin/salaries_extrafields.php @@ -69,7 +69,7 @@ print load_fiche_titre($langs->trans("SalariesSetup"), $linkback, 'title_setup') $head = salaries_admin_prepare_head(); -print dol_get_fiche_head($head, 'attributes', $langs->trans("Salaries"), -1, 'user'); +print dol_get_fiche_head($head, 'attributes', $langs->trans("Salaries"), -1, 'payment'); require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; diff --git a/htdocs/salaries/card.php b/htdocs/salaries/card.php index 6fbb576bb26..1e4376811a2 100644 --- a/htdocs/salaries/card.php +++ b/htdocs/salaries/card.php @@ -274,6 +274,13 @@ if ($action == 'create') print $form->selectDate((empty($datev) ?-1 : $datev), "datev", '', '', '', 'add', 1, 1); print '
'; + // Employee + print ''; + // Label print ''; - // Employee - print ''; - // Amount print ''; } diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php index d04c735eeed..9a89ad8e81c 100644 --- a/htdocs/user/class/api_users.class.php +++ b/htdocs/user/class/api_users.class.php @@ -153,13 +153,16 @@ class Users extends DolibarrApi //if (!DolibarrApiAccess::$user->rights->user->user->lire) { //throw new RestException(401); //} - - $result = $this->useraccount->fetch($id); + 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); } @@ -286,11 +289,11 @@ class Users extends DolibarrApi //} // 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");*/ + 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; @@ -327,9 +330,10 @@ class Users extends DolibarrApi 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') { @@ -461,7 +465,9 @@ class Users extends DolibarrApi $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.")"; + if ($group_ids) { + $sql .= " AND t.rowid IN (".$group_ids.")"; + } // Add sql filters if ($sqlfilters) { if (!DolibarrApi::_checkFilters($sqlfilters)) { @@ -483,13 +489,11 @@ class Users extends DolibarrApi $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $group_static = new UserGroup($this->db); if ($group_static->fetch($obj->rowid)) { @@ -562,8 +566,8 @@ class Users extends DolibarrApi /** * Clean sensible object datas * - * @param Object $object Object to clean - * @return Object Object with cleaned properties + * @param Object $object Object to clean + * @return Object Object with cleaned properties */ protected function _cleanObjectDatas($object) { @@ -681,8 +685,9 @@ class Users extends DolibarrApi { $account = array(); foreach (Users::$FIELDS as $field) { - if (!isset($data[$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 197194245e4..31c884e9f2c 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -87,13 +87,19 @@ class User extends CommonObject */ public $personal_email; - /** * @var array array of socialnetworks */ public $socialnetworks; - public $job; // job position + /** + * @var string job position + */ + public $job; + + /** + * @var string user signature + */ public $signature; /** @@ -113,12 +119,40 @@ class User extends CommonObject public $state_id; // The state/department public $state_code; public $state; + + /** + * @var string office phone + */ public $office_phone; + + /** + * @var string office fax + */ public $office_fax; + + /** + * @var string phone mobile + */ public $user_mobile; + + /** + * @var string personal phone mobile + */ public $personal_mobile; + + /** + * @var int 1 if admin 0 if standard user + */ public $admin; + + /** + * @var string user login + */ public $login; + + /** + * @var string user apikey + */ public $api_key; /** @@ -141,6 +175,11 @@ class User extends CommonObject */ public $pass_indatabase_crypted; + /** + * @var string Temporary password + */ + public $pass_temp; + /** * Date creation record (datec) * @@ -155,9 +194,14 @@ class User extends CommonObject */ public $datem; - //! If this is defined, it is an external user + /** + * @var int If this is defined, it is an external user + */ public $socid; - //! If this is defined, it is a user created from a contact + + /** + * @var int If this is defined, it is a user created from a contact + */ public $contact_id; /** @@ -170,27 +214,71 @@ class User extends CommonObject */ public $fk_user; + /** + * @var int User ID of expense validator + */ public $fk_user_expense_validator; + + /** + * @var int User ID of holidays validator + */ public $fk_user_holiday_validator; + /** + * @string clicktodial url + */ public $clicktodial_url; + + /** + * @var string clicktodial login + */ public $clicktodial_login; + + /** + * @var string clicktodial password + */ public $clicktodial_password; + + /** + * @var string clicktodial poste + */ public $clicktodial_poste; public $datelastlogin; public $datepreviouslogin; public $datestartvalidity; public $dateendvalidity; + + /** + * @var string photo filename + */ public $photo; public $lang; - public $rights; // Array of permissions user->rights->permx - public $all_permissions_are_loaded; // All permission are loaded - public $nb_rights; // Number of rights granted to the user - private $_tab_loaded = array(); // Cache array of already loaded permissions + /** + * @var stdClass Class of permissions user->rights->permx + */ + public $rights; - public $conf; // To store personal config + /** + * @var int All permissions are loaded + */ + public $all_permissions_are_loaded; + + /** + * @var int Number of rights granted to the user + */ + public $nb_rights; + + /** + * @var array Cache array of already loaded permissions + */ + private $_tab_loaded = array(); + + /** + * @var stdClass To store personal config + */ + public $conf; public $default_values; // To store default values for user public $lastsearch_values_tmp; // To store current search criterias for user public $lastsearch_values; // To store last saved search criterias for user @@ -208,7 +296,10 @@ class User extends CommonObject public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment public $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment - public $color; // Define background color for user in agenda + /** + * @var string Define background color for user in agenda + */ + public $color; public $dateemployment; // Define date of employment by company public $dateemploymentend; // Define date of employment end by company @@ -317,7 +408,8 @@ class User extends CommonObject } 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 + } else { + // The fetch was forced on an entity 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 { @@ -337,21 +429,19 @@ 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; - $this->ref_ext = $obj->ref_ext; + $this->ref_ext = $obj->ref_ext; - $this->ldap_sid = $obj->ldap_sid; - $this->lastname = $obj->lastname; + $this->ldap_sid = $obj->ldap_sid; + $this->lastname = $obj->lastname; $this->firstname = $obj->firstname; - $this->employee = $obj->employee; + $this->employee = $obj->employee; $this->login = $obj->login; $this->gender = $obj->gender; @@ -422,7 +512,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 @@ -442,23 +534,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); @@ -469,8 +560,7 @@ class User extends CommonObject $result = $this->loadDefaultValues(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -494,20 +584,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]; } @@ -517,10 +603,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]); } } @@ -557,50 +641,56 @@ class User extends CommonObject $this->db->begin(); - if (!empty($rid)) - { + if (!empty($rid)) { + $module = $perms = $subperms = ''; + // 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"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def"; - $sql .= " WHERE id = '".$this->db->escape($rid)."'"; - $sql .= " AND entity = ".$entity; + $sql .= " WHERE id = ".((int) $rid); + $sql .= " AND entity = ".((int) $entity); $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); - $module = $obj->module; - $perms = $obj->perms; - $subperms = $obj->subperms; + + if ($obj) { + $module = $obj->module; + $perms = $obj->perms; + $subperms = $obj->subperms; + } } else { $error++; dol_print_error($this->db); } // Where pour la liste des droits a ajouter - $whereforadd = "id=".$this->db->escape($rid); + $whereforadd = "id=".((int) $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='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))"; + } elseif (!empty($perms)) { + $whereforadd .= " OR (module='".$this->db->escape($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"; @@ -610,19 +700,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++; } @@ -632,14 +724,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 } @@ -675,6 +768,8 @@ class User extends CommonObject $this->db->begin(); if (!empty($rid)) { + $module = $perms = $subperms = ''; + // Si on a demande supression d'un droit en particulier, on recupere // les caracteristiques module, perms et subperms de ce droit. $sql = "SELECT module, perms, subperms"; @@ -685,19 +780,26 @@ class User extends CommonObject $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); - $module = $obj->module; - $perms = $obj->perms; - $subperms = $obj->subperms; + + if ($obj) { + $module = $obj->module; + $perms = $obj->perms; + $subperms = $obj->subperms; + } } else { $error++; dol_print_error($this->db); } // Where pour la liste des droits a supprimer - $wherefordel = "id=".$this->db->escape($rid); + $wherefordel = "id=".((int) $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='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)"; + } + if ($perms == 'lire' || $perms == 'read') { + $wherefordel .= " OR (module='".$this->db->escape($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 @@ -714,8 +816,7 @@ class User extends CommonObject } // 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"; @@ -725,8 +826,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 @@ -734,19 +834,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++; } @@ -756,14 +856,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 } @@ -786,7 +887,7 @@ class User extends CommonObject public function clearrights() { dol_syslog(get_class($this)."::clearrights reset user->rights"); - $this->rights = ''; + $this->rights = null; $this->nb_rights = 0; $this->all_permissions_are_loaded = 0; $this->_tab_loaded = array(); @@ -805,16 +906,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; } @@ -827,43 +925,52 @@ 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 ($obj) { + $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++; - $this->rights->$module->$perms->$subperms = 1; - } else { - if (empty($this->rights->$module->$perms)) $this->nb_rights++; - $this->rights->$module->$perms = 1; + if (!empty($perms)) { + if (!isset($this->rights) || !is_object($this->rights)) { + $this->rights = new stdClass(); // For avoid error + } + if (!empty($module)) { + if (!isset($this->rights->$module) || !is_object($this->rights->$module)) { + $this->rights->$module = new stdClass(); + } + if (!empty($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++; + } + $this->rights->$module->$perms = 1; + } } } } @@ -878,8 +985,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 { @@ -893,34 +999,48 @@ 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 ($obj) { + $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++; - $this->rights->$module->$perms->$subperms = 1; - } else { - 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 (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = 1; + if (!empty($perms)) { + if (!isset($this->rights) || !is_object($this->rights)) { + $this->rights = new stdClass(); // For avoid error + } + if (!empty($module)) { + if (!isset($this->rights->$module) || !is_object($this->rights->$module)) { + $this->rights->$module = new stdClass(); + } + if (!empty($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 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 (!isset($this->rights->$module->$perms) || !is_object($this->rights->$module->$perms)) { + $this->rights->$module->$perms = 1; + } + } + } } } $i++; @@ -929,11 +1049,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; @@ -956,8 +1079,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(); @@ -968,16 +1094,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 { @@ -1056,68 +1182,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; @@ -1147,7 +1262,9 @@ class User extends CommonObject // Clean parameters $this->setUpperOrLowerCase(); $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); @@ -1174,13 +1291,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(); @@ -1191,20 +1306,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); @@ -1220,22 +1332,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 { @@ -1301,22 +1412,24 @@ class User extends CommonObject // 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(); @@ -1377,33 +1490,31 @@ class User extends CommonObject // 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 { @@ -1415,8 +1526,7 @@ class User extends CommonObject } } - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->id; } else { @@ -1461,7 +1571,9 @@ class User extends CommonObject $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++; } @@ -1527,14 +1639,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; @@ -1551,7 +1661,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)."'"; @@ -1579,10 +1691,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'); @@ -1593,39 +1713,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'; @@ -1635,8 +1755,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; @@ -1664,23 +1783,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'; @@ -1689,8 +1805,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; @@ -1719,8 +1834,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); @@ -1737,25 +1851,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 { @@ -1790,8 +1902,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; @@ -1822,8 +1933,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); } @@ -1831,17 +1941,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)."'"; @@ -1850,16 +1960,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 @@ -1867,11 +1974,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++; @@ -1884,11 +1989,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 } @@ -1912,8 +2018,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); @@ -1948,8 +2053,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); } @@ -1963,7 +2067,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); @@ -1971,8 +2077,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"; @@ -2019,8 +2124,7 @@ class User extends CommonObject $trackid ); - if ($mailfile->sendfile()) - { + if ($mailfile->sendfile()) { return 1; } else { $langs->trans("errors"); @@ -2054,10 +2158,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; @@ -2103,8 +2205,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 { @@ -2144,21 +2245,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 { @@ -2197,21 +2297,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 { @@ -2267,14 +2366,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 .= '
'; @@ -2285,28 +2387,37 @@ class User extends CommonObject $label .= img_picto('', $this->picto).' '.$langs->trans("User").''; $label .= ' '.$this->getLibStatut(4); $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 .= ''; - 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'); @@ -2317,28 +2428,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).'"'; @@ -2359,22 +2479,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.='
'; @@ -2385,8 +2516,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; } @@ -2408,22 +2542,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; @@ -2453,8 +2589,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'); @@ -2464,7 +2599,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); } @@ -2486,9 +2623,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; } @@ -2531,63 +2672,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; @@ -2600,18 +2755,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); @@ -2623,7 +2783,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; } @@ -2634,7 +2796,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() { @@ -2677,6 +2839,7 @@ class User extends CommonObject $this->statut = 1; $this->entity = 1; + return 1; } /** @@ -2693,10 +2856,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; @@ -2727,8 +2888,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; @@ -2754,19 +2914,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; @@ -2833,11 +2997,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; @@ -2869,10 +3031,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; @@ -2921,15 +3081,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; @@ -2952,29 +3112,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]); } } @@ -3000,8 +3155,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 @@ -3010,15 +3164,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; } @@ -3037,8 +3194,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; @@ -3050,10 +3206,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 } @@ -3106,10 +3260,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); @@ -3139,10 +3291,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'; @@ -3167,23 +3317,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 { @@ -3210,10 +3363,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 { @@ -3248,19 +3399,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)) { @@ -3297,8 +3447,7 @@ class User extends CommonObject */ public function findUserIdByEmail($email) { - if ($this->findUserIdByEmailCache[$email]) - { + if ($this->findUserIdByEmailCache[$email]) { return $this->findUserIdByEmailCache[$email]; } @@ -3309,25 +3458,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; } diff --git a/htdocs/user/class/usergroup.class.php b/htdocs/user/class/usergroup.class.php index 2998658d7fc..882d33bd562 100644 --- a/htdocs/user/class/usergroup.class.php +++ b/htdocs/user/class/usergroup.class.php @@ -307,33 +307,33 @@ class UserGroup extends CommonObject if (!empty($rid)) { + $module = $perms = $subperms = ''; + // 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"; $sql .= " FROM ".MAIN_DB_PREFIX."rights_def"; - $sql .= " WHERE id = '".$this->db->escape($rid)."'"; - $sql .= " AND entity = ".$entity; + $sql .= " WHERE id = ".((int) $rid); + $sql .= " AND entity = ".((int) $entity); $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); - $module = $obj->module; - $perms = $obj->perms; - $subperms = $obj->subperms; + if ($obj) { + $module = $obj->module; + $perms = $obj->perms; + $subperms = $obj->subperms; + } } else { $error++; dol_print_error($this->db); } // Where pour la liste des droits a ajouter - $whereforadd = "id=".$this->db->escape($rid); - // Ajout des droits induits - if ($subperms) $whereforadd .= " OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))"; - elseif ($perms) $whereforadd .= " OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)"; - - // Pour compatibilite, si lowid = 0, on est en mode ajout de tout - // TODO A virer quand sera gere par l'appelant - //if (substr($rid,-1,1) == 0) $whereforadd="module='$module'"; + $whereforadd = "id=".((int) $rid); + // Find also rights that are herited to add them too + if ($subperms) $whereforadd .= " OR (module='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND (subperms='lire' OR subperms='read'))"; + elseif ($perms) $whereforadd .= " OR (module='".$this->db->escape($module)."' AND (perms='lire' OR perms='read') AND subperms IS NULL)"; } else { // Where pour la liste des droits a ajouter if (!empty($allmodule)) @@ -348,7 +348,7 @@ class UserGroup extends CommonObject } } - // Ajout des droits de la liste whereforadd + // Add permission of the list $whereforadd if (!empty($whereforadd)) { //print "$module-$perms-$subperms"; @@ -425,6 +425,8 @@ class UserGroup extends CommonObject if (!empty($rid)) { + $module = $perms = $subperms = ''; + // Si on a demande supression d'un droit en particulier, on recupere // les caracteristiques module, perms et subperms de ce droit. $sql = "SELECT module, perms, subperms"; @@ -435,9 +437,11 @@ class UserGroup extends CommonObject $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); - $module = $obj->module; - $perms = $obj->perms; - $subperms = $obj->subperms; + if ($obj) { + $module = $obj->module; + $perms = $obj->perms; + $subperms = $obj->subperms; + } } else { $error++; dol_print_error($this->db); @@ -446,14 +450,14 @@ class UserGroup 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='".$this->db->escape($module)."' AND perms='".$this->db->escape($perms)."' AND subperms IS NOT NULL)"; + if ($perms == 'lire' || $perms == 'read') $wherefordel .= " OR (module='".$this->db->escape($module)."')"; // Pour compatibilite, si lowid = 0, on est en mode suppression de tout // TODO A virer quand sera gere par l'appelant //if (substr($rid,-1,1) == 0) $wherefordel="module='$module'"; } else { - // Where pour la liste des droits a supprimer + // Add permission of the list $wherefordel if (!empty($allmodule)) { if ($allmodule == 'allmodules') @@ -461,7 +465,7 @@ class UserGroup extends CommonObject $wherefordel = 'allmodules'; } else { $wherefordel = "module='".$this->db->escape($allmodule)."'"; - if (!empty($allperms)) $whereforadd .= " AND perms='".$this->db->escape($allperms)."'"; + if (!empty($allperms)) $wherefordel .= " AND perms='".$this->db->escape($allperms)."'"; } } } @@ -484,8 +488,12 @@ class UserGroup extends CommonObject $i = 0; while ($i < $num) { + $nid = 0; + $obj = $this->db->fetch_object($result); - $nid = $obj->id; + if ($obj) { + $nid = $obj->id; + } $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_rights"; $sql .= " WHERE fk_usergroup = $this->id AND fk_id=".$nid; @@ -565,22 +573,24 @@ class UserGroup extends CommonObject { $obj = $this->db->fetch_object($resql); - $module = $obj->module; - $perms = $obj->perms; - $subperms = $obj->subperms; + if ($obj) { + $module = $obj->module; + $perms = $obj->perms; + $subperms = $obj->subperms; - if ($perms) - { - if (!isset($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 ($perms) { - 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++; - $this->rights->$module->$perms = 1; + if (!isset($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++; + $this->rights->$module->$perms = 1; + } } } diff --git a/htdocs/zapier/class/api_zapier.class.php b/htdocs/zapier/class/api_zapier.class.php index 6118aa71241..bb3e42f5f05 100644 --- a/htdocs/zapier/class/api_zapier.class.php +++ b/htdocs/zapier/class/api_zapier.class.php @@ -93,14 +93,13 @@ class ZapierApi extends DolibarrApi * Get list of possibles choices for module * * Return an array with hook informations - * @param integer $id ID * - * @return array|mixed data + * @return array data * * @url GET /getmoduleschoices/ * @throws RestException */ - public function getModulesChoices($id) + public function getModulesChoices() { if (!DolibarrApiAccess::$user->rights->zapier->read) { throw new RestException(401); @@ -110,6 +109,7 @@ class ZapierApi extends DolibarrApi 'orders' => 'Orders', 'thirdparties' => 'Thirparties', 'contacts' => 'Contacts', + 'users' => 'Users', ); // $result = $this->hook->fetch($id); // if (! $result ) { @@ -244,6 +244,7 @@ class ZapierApi extends DolibarrApi $fields = array( 'url', ); + dol_syslog("API Zapier create hook receive : " . print_r($request_data, true), LOG_DEBUG); $result = $this->validate($request_data, $fields); foreach ($request_data as $field => $value) { diff --git a/htdocs/zapier/class/hook.class.php b/htdocs/zapier/class/hook.class.php index e7ce317096d..8e6d3fa725f 100644 --- a/htdocs/zapier/class/hook.class.php +++ b/htdocs/zapier/class/hook.class.php @@ -126,7 +126,7 @@ class Hook extends CommonObject ), 'module' => array( 'type' => 'varchar(128)', - 'label' => 'Url', + 'label' => 'Module', 'enabled' => 1, 'visible' => 1, 'position' => 30, @@ -137,7 +137,7 @@ class Hook extends CommonObject ), 'action' => array( 'type' => 'varchar(128)', - 'label' => 'Url', + 'label' => 'Action', 'enabled' => 1, 'visible' => 1, 'position' => 30, diff --git a/htdocs/zapier/hook_card.php b/htdocs/zapier/hook_card.php index ab081f1cf58..548b79de866 100644 --- a/htdocs/zapier/hook_card.php +++ b/htdocs/zapier/hook_card.php @@ -101,12 +101,6 @@ if (empty($reshook)) { // Actions when printing a doc from card include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - - // Actions to send emails - $triggersendname = 'MYOBJECT_SENTBYMAIL'; - $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; - $trackid = 'myobject'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -391,19 +385,6 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; } - - //Select mail models is same action as presend - /* - if (GETPOST('modelselected')) $action = 'presend'; - - // Presend form - $modelmail='inventory'; - $defaulttopic='InformationMessage'; - $diroutput = $conf->product->dir_output.'/inventory'; - $trackid = 'stockinv'.$object->id; - - include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - */ } // End of page diff --git a/htdocs/zapier/hook_list.php b/htdocs/zapier/hook_list.php index 8450ec3e0d8..59432aea44b 100644 --- a/htdocs/zapier/hook_list.php +++ b/htdocs/zapier/hook_list.php @@ -354,7 +354,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort $topicmail = "SendHookRef"; $modelmail = "hook"; $objecttmp = new Hook($db); -$trackid = 'xxxx'.$object->id; +$trackid = 'zapier'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { diff --git a/test/phpunit/CodingPhpTest.php b/test/phpunit/CodingPhpTest.php index 4326f536f92..52c00978c54 100644 --- a/test/phpunit/CodingPhpTest.php +++ b/test/phpunit/CodingPhpTest.php @@ -255,7 +255,7 @@ class CodingPhpTest extends PHPUnit\Framework\TestCase //if ($reg[0] != 'db') $ok=false; } //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n"; - $this->assertTrue($ok, 'Found a $this->db->idate to forge a sql request without quotes around this date field '.$file['relativename'].' :: '.$val[0]); + $this->assertTrue($ok, 'Found a $this->db->idate to forge a sql request without quotes around this date field '.$file['relativename']); //exit; @@ -274,7 +274,7 @@ class CodingPhpTest extends PHPUnit\Framework\TestCase //if ($reg[0] != 'db') $ok=false; } //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n"; - $this->assertTrue($ok, 'Found non escaped string in building of a sql request '.$file['relativename'].': '.$val[0].' - Bad.'); + $this->assertTrue($ok, 'Found non escaped string in building of a sql request '.$file['relativename'].' - Bad.'); //exit; // Check string ='".$this->xxx with xxx that is not 'escape'. It means we forget a db->escape when forging sql request. diff --git a/test/phpunit/FactureRecTest.php b/test/phpunit/FactureRecTest.php index 3778989945a..0250b659e47 100644 --- a/test/phpunit/FactureRecTest.php +++ b/test/phpunit/FactureRecTest.php @@ -183,22 +183,18 @@ class FactureRecTest extends PHPUnit\Framework\TestCase { $retAr=array(); - if (get_class($oA) !== get_class($oB)) - { + if (get_class($oA) !== get_class($oB)) { $retAr[]="Supplied objects are not of same class."; } else { $oVarsA=get_object_vars($oA); $oVarsB=get_object_vars($oB); $aKeys=array_keys($oVarsA); - foreach ($aKeys as $sKey) - { + foreach ($aKeys as $sKey) { if (in_array($sKey, $fieldstoignorearray)) continue; - if (! $ignoretype && $oVarsA[$sKey] !== $oVarsB[$sKey]) - { + if (! $ignoretype && ($oVarsA[$sKey] !== $oVarsB[$sKey])) { $retAr[]=$sKey.' : '.(is_object($oVarsA[$sKey])?get_class($oVarsA[$sKey]):$oVarsA[$sKey]).' <> '.(is_object($oVarsB[$sKey])?get_class($oVarsB[$sKey]):$oVarsB[$sKey]); } - if ($ignoretype && $oVarsA[$sKey] != $oVarsB[$sKey]) - { + if ($ignoretype && ($oVarsA[$sKey] != $oVarsB[$sKey])) { $retAr[]=$sKey.' : '.(is_object($oVarsA[$sKey])?get_class($oVarsA[$sKey]):$oVarsA[$sKey]).' <> '.(is_object($oVarsB[$sKey])?get_class($oVarsB[$sKey]):$oVarsB[$sKey]); } } diff --git a/test/phpunit/FactureTest.php b/test/phpunit/FactureTest.php index 17cc4176a87..26396ae2c30 100644 --- a/test/phpunit/FactureTest.php +++ b/test/phpunit/FactureTest.php @@ -241,7 +241,7 @@ class FactureTest extends PHPUnit\Framework\TestCase 'ref','statut','paye','specimen','ref','actiontypecode','actionmsg2','actionmsg','mode_reglement','cond_reglement', 'cond_reglement_doc','situation_cycle_ref','situation_counter','situation_final','multicurrency_total_ht','multicurrency_total_tva', 'multicurrency_total_ttc','fk_multicurrency','multicurrency_code','multicurrency_tx', - 'retained_warranty' ,'retained_warranty_date_limit', 'retained_warranty_fk_cond_reglement', 'specimen' + 'retained_warranty' ,'retained_warranty_date_limit', 'retained_warranty_fk_cond_reglement', 'specimen', 'trackid' ) ); $this->assertEquals($arraywithdiff, array()); // Actual, Expected @@ -362,22 +362,18 @@ class FactureTest extends PHPUnit\Framework\TestCase { $retAr=array(); - if (get_class($oA) !== get_class($oB)) - { + if (get_class($oA) !== get_class($oB)) { $retAr[]="Supplied objects are not of same class."; } else { $oVarsA=get_object_vars($oA); $oVarsB=get_object_vars($oB); $aKeys=array_keys($oVarsA); - foreach ($aKeys as $sKey) - { + foreach ($aKeys as $sKey) { if (in_array($sKey, $fieldstoignorearray)) continue; - if (! $ignoretype && $oVarsA[$sKey] !== $oVarsB[$sKey]) - { + if (! $ignoretype && ($oVarsA[$sKey] !== $oVarsB[$sKey])) { $retAr[]=$sKey.' : '.(is_object($oVarsA[$sKey])?get_class($oVarsA[$sKey]):$oVarsA[$sKey]).' <> '.(is_object($oVarsB[$sKey])?get_class($oVarsB[$sKey]):$oVarsB[$sKey]); } - if ($ignoretype && $oVarsA[$sKey] != $oVarsB[$sKey]) - { + if ($ignoretype && ($oVarsA[$sKey] != $oVarsB[$sKey])) { $retAr[]=$sKey.' : '.(is_object($oVarsA[$sKey])?get_class($oVarsA[$sKey]):$oVarsA[$sKey]).' <> '.(is_object($oVarsB[$sKey])?get_class($oVarsB[$sKey]):$oVarsB[$sKey]); } } diff --git a/test/phpunit/Functions2LibTest.php b/test/phpunit/Functions2LibTest.php index 21fa1f29257..be050b83b4f 100644 --- a/test/phpunit/Functions2LibTest.php +++ b/test/phpunit/Functions2LibTest.php @@ -148,6 +148,13 @@ class Functions2LibTest extends PHPUnit\Framework\TestCase */ public function testIsValidMailDomain() { + $mail = 'bidon@unvalid.unvalid'; + $result = isValidMailDomain($mail); + $this->assertEquals(0, $result, 'Email isValidMailDomain('.$mail.') should return 0 (not valid) but returned '.$result); + + $mail = 'bidon@dolibarr.org'; + $result = isValidMailDomain($mail); + $this->assertEquals(1, $result, 'Email isValidMailDomain('.$mail.') should return 1 (valid) but returned '.$result); } /** diff --git a/test/phpunit/LangTest.php b/test/phpunit/LangTest.php index c064a03e2f8..8b614d77948 100644 --- a/test/phpunit/LangTest.php +++ b/test/phpunit/LangTest.php @@ -191,9 +191,9 @@ class LangTest extends PHPUnit\Framework\TestCase print 'Check lang file '.$file."\n"; $filecontent=file_get_contents(DOL_DOCUMENT_ROOT.'/langs/'.$code.'/'.$file); - $result=strpos($filecontent, '%'); - print __METHOD__." Result for checking we don't have bad percent char = ".$result."\n"; - $this->assertTrue($result===false, 'Found a bad percent char % instead of % into file '.$code.'/'.$file); + $result=strpos($filecontent, '%'); // A special % char we don't want. We want the common one. + //print __METHOD__." Result for checking we don't have bad percent char = ".$result."\n"; + $this->assertTrue($result === false, 'Found a bad percent char % instead of % into file '.$code.'/'.$file); } } diff --git a/test/phpunit/UserGroupTest.php b/test/phpunit/UserGroupTest.php index 7e3cdd24b3a..3ec92449f08 100644 --- a/test/phpunit/UserGroupTest.php +++ b/test/phpunit/UserGroupTest.php @@ -257,15 +257,10 @@ class UserGroupTest extends PHPUnit\Framework\TestCase $langs=$this->savlangs; $db=$this->savdb; - /*$result=$localobject->setstatus(0); - print __METHOD__." id=".$localobject->id." result=".$result."\n"; - $this->assertLessThan($result, 0); - */ + $result = $localobject->generateDocument('templatenamethadoesnotexist', $langs); + print __METHOD__." result=".$result."\n"; + $this->assertEquals(-1, $result, 'Calling generateDocument with a not existing template should return 0'); - /*$localobject->info($localobject->id); - print __METHOD__." localobject->date_creation=".$localobject->date_creation."\n"; - $this->assertNotEquals($localobject->date_creation, ''); - */ return $localobject->id; } diff --git a/test/phpunit/UserTest.php b/test/phpunit/UserTest.php index d5c1be0b4d2..a8486451c47 100644 --- a/test/phpunit/UserTest.php +++ b/test/phpunit/UserTest.php @@ -200,7 +200,7 @@ class UserTest extends PHPUnit\Framework\TestCase $newlocalobject=new User($this->savdb); $newlocalobject->initAsSpecimen(); $this->changeProperties($newlocalobject); - $this->assertEquals($this->objCompare($localobject, $newlocalobject, true, array('id','socid','societe_id','specimen','note','ref','pass','pass_indatabase','pass_indatabase_crypted','datec','datem','datelastlogin','datepreviouslogin')), array()); // Actual, Expected + $this->assertEquals($this->objCompare($localobject, $newlocalobject, true, array('id','socid','societe_id','specimen','note','ref','pass','pass_indatabase','pass_indatabase_crypted','pass_temp','datec','datem','datelastlogin','datepreviouslogin','trackid')), array()); // Actual, Expected return $localobject; } @@ -340,12 +340,11 @@ class UserTest extends PHPUnit\Framework\TestCase $oVarsB=get_object_vars($oB); $aKeys=array_keys($oVarsA); foreach ($aKeys as $sKey) { - if (in_array($sKey, $fieldstoignorearray)) - continue; - if (! $ignoretype && $oVarsA[$sKey] !== $oVarsB[$sKey]) { + if (in_array($sKey, $fieldstoignorearray)) continue; + if (! $ignoretype && ($oVarsA[$sKey] !== $oVarsB[$sKey])) { $retAr[]=$sKey.' : '.(is_object($oVarsA[$sKey])?get_class($oVarsA[$sKey]):$oVarsA[$sKey]).' <> '.(is_object($oVarsB[$sKey])?get_class($oVarsB[$sKey]):$oVarsB[$sKey]); } - if ($ignoretype && $oVarsA[$sKey] != $oVarsB[$sKey]) { + if ($ignoretype && ($oVarsA[$sKey] != $oVarsB[$sKey])) { $retAr[]=$sKey.' : '.(is_object($oVarsA[$sKey])?get_class($oVarsA[$sKey]):$oVarsA[$sKey]).' <> '.(is_object($oVarsB[$sKey])?get_class($oVarsB[$sKey]):$oVarsB[$sKey]); } }
'.$langs->trans("FormCreateRate").''.$form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code', 'alpha') : $multicurrency_code), 'multicurrency_code', 0, " code != '".$conf->currency."'", true).''.$langs->trans('Rate').''; print ''; @@ -521,9 +521,9 @@ if ($resql) { $selected = 0; if (in_array($obj->rowid, $arrayofselected)) $selected = 1; - print 'rowid.'" class="like-link " style="margin-right:15px;important">'.img_picto('edit', 'edit').''; - print 'rowid.'" class="like-link" style="margin-right:45px;important">'.img_picto('delete', 'delete').''; - print ''; + print 'rowid.'">'.img_picto('edit', 'edit').''; + print 'rowid.'">'.img_picto('delete', 'delete').''; + print ''; } print '
'.$langs->trans("PriceQtyMin").'
'.$langs->trans("AddIn").''; - print $formproduct->selectWarehouses('ifone', 'fk_parent', '', 1); + print img_picto('', 'stock').$formproduct->selectWarehouses((GETPOSTISSET('fk_parent') ? GETPOST('fk_parent', 'int') : 'ifone'), 'fk_parent', '', 1); print '
'.$langs->trans("Ref").'
'.$langs->trans("LocationSummary").'
'.$langs->trans("LocationSummary").'
'.$langs->trans("AddIn").''; diff --git a/htdocs/product/stock/class/entrepot.class.php b/htdocs/product/stock/class/entrepot.class.php index 170b1395984..14e25bad513 100644 --- a/htdocs/product/stock/class/entrepot.class.php +++ b/htdocs/product/stock/class/entrepot.class.php @@ -707,14 +707,14 @@ class Entrepot extends CommonObject $result = ''; - $label = img_picto('', $this->picto).' '.$langs->trans("Warehouse").''; + $label = img_picto('', $this->picto).' '.$langs->trans("Warehouse").''; + if (isset($this->statut)) { + $label .= ' '.$this->getLibStatut(5); + } $label .= '
'.$langs->trans('Ref').': '.(empty($this->ref) ? (empty($this->label) ? $this->libelle : $this->label) : $this->ref); if (!empty($this->lieu)) { $label .= '
'.$langs->trans('LocationSummary').': '.$this->lieu; } - if (isset($this->statut)) { - $label .= '
'.$langs->trans("Status").": ".$this->getLibStatut(5); - } $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id; diff --git a/htdocs/product/stock/list.php b/htdocs/product/stock/list.php index f8700a1884e..f2c7133618b 100644 --- a/htdocs/product/stock/list.php +++ b/htdocs/product/stock/list.php @@ -530,7 +530,6 @@ if ($num) $warehouse->{$key} = $obj->{$key}; } - // Show here line of result print '
 
 
 
 
'; - print ''.$obj->subject.''; + print ''.$obj->subject.''; print '
'; + print $form->editfieldkey('Employee', 'fk_user', '', $object, 0, 'string', '', 1).''; + $noactive = 0; // We keep active and unactive users + print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, 'AND employee=1', 0, '', 'maxwidth300', $noactive); + print '
'; print $form->editfieldkey('Label', 'label', '', $object, 0, 'string', '', 1).''; @@ -292,13 +299,6 @@ if ($action == 'create') print $form->selectDate($dateep, "dateep", '', '', '', 'add'); print '
'; - print $form->editfieldkey('Employee', 'fk_user', '', $object, 0, 'string', '', 1).''; - $noactive = 0; // We keep active and unactive users - print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, 'AND employee=1', 0, '', 'maxwidth300', $noactive); - print '
'; print $form->editfieldkey('Amount', 'amount', '', $object, 0, 'string', '', 1).''; diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 509c1419a00..08e839ecee1 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -2,6 +2,7 @@ /* Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2018 Pierre Chéné * Copyright (C) 2019 Cedric Ancelin + * Copyright (C) 2020 Frédéric France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -68,7 +69,7 @@ class Thirdparties extends DolibarrApi * Return an array with thirdparty informations * * @param int $id Id of third party to load - * @return array|mixed data without useless information + * @return Object Cleaned Societe object * * @throws RestException */ @@ -83,7 +84,7 @@ class Thirdparties extends DolibarrApi * Return an array with thirdparty informations * * @param string $email Email of third party to load - * @return array|mixed data without useless information + * @return Object Cleaned Societe object * * @url GET email/{email} * @@ -100,7 +101,7 @@ class Thirdparties extends DolibarrApi * Return an array with thirdparty informations * * @param string $barcode Barcode of third party to load - * @return array|mixed data without useless information + * @return Object Cleaned Societe object * * @url GET barcode/{barcode} * @@ -154,9 +155,9 @@ class Thirdparties extends DolibarrApi $sql .= " AND t.fk_stcomm = st.id"; if ($mode == 1) $sql .= " AND t.client IN (1, 3)"; - if ($mode == 2) $sql .= " AND t.client IN (2, 3)"; - if ($mode == 3) $sql .= " AND t.client IN (0)"; - if ($mode == 4) $sql .= " AND t.fournisseur IN (1)"; + elseif ($mode == 2) $sql .= " AND t.client IN (2, 3)"; + elseif ($mode == 3) $sql .= " AND t.client IN (0)"; + elseif ($mode == 4) $sql .= " AND t.fournisseur IN (1)"; // Select thirdparties of given category if ($category > 0) { @@ -188,8 +189,7 @@ class Thirdparties extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -249,7 +249,7 @@ class Thirdparties extends DolibarrApi * * @param int $id Id of thirdparty to update * @param array $request_data Datas - * @return int + * @return Object|boolean */ public function put($id, $request_data = null) { @@ -271,8 +271,9 @@ class Thirdparties extends DolibarrApi $this->company->$field = $value; } - if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) + if ($this->company->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) { return $this->get($id); + } return false; } @@ -1840,7 +1841,7 @@ class Thirdparties extends DolibarrApi * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records) * @param string $email Email of third party (Warning, this can return several records) * @param string $ref_alias Name_alias of third party (Warning, this can return several records) - * @return array|mixed data without useless information + * @return Object cleaned Societe object * * @throws RestException */ @@ -1850,8 +1851,11 @@ class Thirdparties extends DolibarrApi if (!DolibarrApiAccess::$user->rights->societe->lire) { throw new RestException(401); } - - $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias); + if ($rowid == 0) { + $result = $this->company->initAsSpecimen(); + } else { + $result = $this->company->fetch($rowid, $ref, $ref_ext, $barcode, $idprof1, $idprof2, $idprof3, $idprof4, $idprof5, $idprof6, $email, $ref_alias); + } if (!$result) { throw new RestException(404, 'Thirdparty not found'); } diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 5bca91b0700..e67f28c4dab 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1660,7 +1660,7 @@ class Societe extends CommonObject $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; + $this->modelpdf = $obj->model_pdf; // deprecated $this->default_lang = $obj->default_lang; $this->logo = $obj->logo; $this->logo_squarred = $obj->logo_squarred; @@ -3765,6 +3765,7 @@ class Societe extends CommonObject // Initialize parameters $this->id = 0; + $this->entity = 1; $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog'); $this->nom = $this->name; // For backward compatibility $this->ref_ext = 'Ref ext'; diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index a703816ce71..066d68b8902 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -495,7 +495,7 @@ if (empty($reshook)) // Actions to send emails $triggersendname = 'PROPOSAL_SUPPLIER_SENTBYMAIL'; $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO'; - $trackid = 'spr'.$object->id; + $trackid = 'spro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -1952,7 +1952,7 @@ if ($action == 'create') $defaulttopic = 'SendAskRef'; $diroutput = $conf->supplier_proposal->dir_output; $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO'; - $trackid = 'spr'.$object->id; + $trackid = 'spro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; } diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index 863ec318798..e189d149bf7 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -1699,13 +1699,13 @@ class SupplierProposal extends CommonObject $resql = $this->db->query($sql); if ($resql) { - $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : $this->modelpdf; + $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : (empty($this->modelpdf) ? '' : $this->modelpdf); $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED'; if ($status == 2) { $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED'; - $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : $this->modelpdf; + $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : (empty($this->modelpdf) ? '' : $this->modelpdf); if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists { diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php index 55e00f68c70..39855b866cb 100644 --- a/htdocs/theme/eldy/global.inc.php +++ b/htdocs/theme/eldy/global.inc.php @@ -331,15 +331,15 @@ span.timesheetalreadyrecorded input { border-bottom: solid 1px rgba(0,0,0,0.4); margin-right: 1px !important; } -td.weekend { - background-color: #eee; -} td.onholidaymorning, td.onholidayafternoon { background-color: #fdf6f2; } td.onholidayallday { background-color: #f4eede; } +td.weekend { /* must be after td.onholidayallday */ + background-color: #eee; +} /* td.leftborder, td.hide0 { border-left: 1px solid #ccc; @@ -1272,11 +1272,11 @@ table[summary="list_of_modules"] .fa-cog { .minwidth500imp { min-width: 250px !important; } } -.widthcentpercentminusx { - width: calc(100% - 50px) !important; +select.widthcentpercentminusx, input.widthcentpercentminusx { + width: calc(100% - 52px) !important; display: inline-block; } -.widthcentpercentminusxx { +select.widthcentpercentminusxx, input.widthcentpercentminusxx { width: calc(100% - 70px) !important; display: inline-block; } diff --git a/htdocs/ticket/class/api_tickets.class.php b/htdocs/ticket/class/api_tickets.class.php index bce4d03fd92..5ba67060552 100644 --- a/htdocs/ticket/class/api_tickets.class.php +++ b/htdocs/ticket/class/api_tickets.class.php @@ -29,542 +29,544 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php'; */ class Tickets extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - public static $FIELDS = array( - 'subject', - 'message' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + public static $FIELDS = array( + 'subject', + 'message' + ); - /** - * @var array $FIELDS_MESSAGES Mandatory fields, checked when create and update object - */ - public static $FIELDS_MESSAGES = array( - 'track_id', - 'message' - ); + /** + * @var array $FIELDS_MESSAGES Mandatory fields, checked when create and update object + */ + public static $FIELDS_MESSAGES = array( + 'track_id', + 'message' + ); - /** - * @var Ticket $ticket {@type Ticket} - */ - public $ticket; + /** + * @var Ticket $ticket {@type Ticket} + */ + public $ticket; - /** - * Constructor - */ - public function __construct() - { - global $db; - $this->db = $db; - $this->ticket = new Ticket($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + $this->ticket = new Ticket($this->db); + } - /** - * Get properties of a Ticket object. - * - * Return an array with ticket informations - * - * @param int $id ID of ticket - * @return array|mixed Data without useless information - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function get($id) - { - return $this->getCommon($id, '', ''); - } + /** + * Get properties of a Ticket object. + * + * Return an array with ticket informations + * + * @param int $id ID of ticket + * @return array|mixed Data without useless information + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function get($id) + { + return $this->getCommon($id, '', ''); + } - /** - * Get properties of a Ticket object from track id - * - * Return an array with ticket informations - * - * @param string $track_id Tracking ID of ticket - * @return array|mixed Data without useless information - * - * @url GET track_id/{track_id} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByTrackId($track_id) - { - return $this->getCommon(0, $track_id, ''); - } + /** + * Get properties of a Ticket object from track id + * + * Return an array with ticket informations + * + * @param string $track_id Tracking ID of ticket + * @return array|mixed Data without useless information + * + * @url GET track_id/{track_id} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByTrackId($track_id) + { + return $this->getCommon(0, $track_id, ''); + } - /** - * Get properties of a Ticket object from ref - * - * Return an array with ticket informations - * - * @param string $ref Reference for ticket - * @return array|mixed Data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByRef($ref) - { - try { - return $this->getCommon(0, '', $ref); - } catch (Exception $e) - { - throw $e; - } - } + /** + * Get properties of a Ticket object from ref + * + * Return an array with ticket informations + * + * @param string $ref Reference for ticket + * @return array|mixed Data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByRef($ref) + { + try { + return $this->getCommon(0, '', $ref); + } catch (Exception $e) + { + throw $e; + } + } - /** - * Get properties of a Ticket object - * Return an array with ticket informations - * - * @param int $id ID of ticket - * @param string $track_id Tracking ID of ticket - * @param string $ref Reference for ticket - * @return array|mixed Data without useless information - */ - private function getCommon($id = 0, $track_id = '', $ref = '') - { - if (!DolibarrApiAccess::$user->rights->ticket->read) { - throw new RestException(403); - } + /** + * Get properties of a Ticket object + * Return an array with ticket informations + * + * @param int $id ID of ticket + * @param string $track_id Tracking ID of ticket + * @param string $ref Reference for ticket + * @return array|mixed Data without useless information + */ + private function getCommon($id = 0, $track_id = '', $ref = '') + { + if (!DolibarrApiAccess::$user->rights->ticket->read) { + throw new RestException(403); + } - // Check parameters - if (!$id && !$track_id && !$ref) { - throw new RestException(401, 'Wrong parameters'); - } - - $result = $this->ticket->fetch($id, $ref, $track_id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } - - // String for user assigned - if ($this->ticket->fk_user_assign > 0) { - $userStatic = new User($this->db); - $userStatic->fetch($this->ticket->fk_user_assign); - $this->ticket->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; - } - - // Messages of ticket - $messages = array(); - $this->ticket->loadCacheMsgsTicket(); - if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) { - $num = count($this->ticket->cache_msgs_ticket); - $i = 0; - while ($i < $num) { - if ($this->ticket->cache_msgs_ticket[$i]['fk_user_author'] > 0) { - $user_action = new User($this->db); - $user_action->fetch($this->ticket->cache_msgs_ticket[$i]['fk_user_author']); - } - - // Now define messages - $messages[] = array( - 'id' => $this->ticket->cache_msgs_ticket[$i]['id'], - 'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], - 'fk_user_action_socid' => $user_action->socid, - 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), - 'message' => $this->ticket->cache_msgs_ticket[$i]['message'], - 'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'], - 'private' => $this->ticket->cache_msgs_ticket[$i]['private'] - ); - $i++; - } - $this->ticket->messages = $messages; - } - - // History - $history = array(); - $this->ticket->loadCacheLogsTicket(); - if (is_array($this->ticket->cache_logs_ticket) && count($this->ticket->cache_logs_ticket) > 0) { - $num = count($this->ticket->cache_logs_ticket); - $i = 0; - while ($i < $num) { - if ($this->ticket->cache_logs_ticket[$i]['fk_user_create'] > 0) { - $user_action = new User($this->db); - $user_action->fetch($this->ticket->cache_logs_ticket[$i]['fk_user_create']); - } - - // Now define messages - $history[] = array( - 'id' => $this->ticket->cache_logs_ticket[$i]['id'], - 'fk_user_author' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], - 'fk_user_action' => $this->ticket->cache_logs_ticket[$i]['fk_user_create'], - 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), - 'message' => $this->ticket->cache_logs_ticket[$i]['message'], - 'datec' => $this->ticket->cache_logs_ticket[$i]['datec'], - ); - $i++; - } - $this->ticket->history = $history; - } - - - if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - return $this->_cleanObjectDatas($this->ticket); - } - - /** - * List tickets - * - * Get a list of tickets - * - * @param int $socid Filter list with thirdparty ID - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101') and (t.fk_statut:=:1)" - * - * @return array Array of ticket objects - * - */ - public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '') - { - global $db, $conf; - - $obj_ret = array(); - - if (!$socid && DolibarrApiAccess::$user->socid) { - $socid = DolibarrApiAccess::$user->socid; - } - - // If the internal user must only see his customers, force searching by him - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { - $search_sale = DolibarrApiAccess::$user->id; - } - - $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { - $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - } - $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t"; - - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale - } - - $sql .= ' WHERE t.entity IN ('.getEntity('ticket', 1).')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { - $sql .= " AND t.fk_soc = sc.fk_soc"; - } - if ($socid > 0) { - $sql .= " AND t.fk_soc = ".$socid; - } - if ($search_sale > 0) { - $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - } - - // Insert sale filter - if ($search_sale > 0) { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) { - $obj = $this->db->fetch_object($result); - $ticket_static = new Ticket($this->db); - if ($ticket_static->fetch($obj->rowid)) { - if ($ticket_static->fk_user_assign > 0) { - $userStatic = new User($this->db); - $userStatic->fetch($ticket_static->fk_user_assign); - $ticket_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; - } - $obj_ret[] = $this->_cleanObjectDatas($ticket_static); - } - $i++; - } + // Check parameters + if (($id < 0) && !$track_id && !$ref) { + throw new RestException(401, 'Wrong parameters'); + } + if ($id == 0) { + $result = $this->ticket->initAsSpecimen(); } else { - throw new RestException(503, 'Error when retrieve ticket list'); + $result = $this->ticket->fetch($id, $ref, $track_id); } - if (!count($obj_ret)) { - throw new RestException(404, 'No ticket found'); - } - return $obj_ret; - } + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } - /** - * Create ticket object - * - * @param array $request_data Request datas - * @return int ID of ticket - */ - public function post($request_data = null) - { - $ticketstatic = new Ticket($this->db); - if (!DolibarrApiAccess::$user->rights->ticket->write) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validate($request_data); + // String for user assigned + if ($this->ticket->fk_user_assign > 0) { + $userStatic = new User($this->db); + $userStatic->fetch($this->ticket->fk_user_assign); + $this->ticket->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; + } - foreach ($request_data as $field => $value) { - $this->ticket->$field = $value; - } - if (empty($this->ticket->ref)) { - $this->ticket->ref = $ticketstatic->getDefaultRef(); - } - if (empty($this->ticket->track_id)) { - $this->ticket->track_id = generate_random_id(16); - } + // Messages of ticket + $messages = array(); + $this->ticket->loadCacheMsgsTicket(); + if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) { + $num = count($this->ticket->cache_msgs_ticket); + $i = 0; + while ($i < $num) { + if ($this->ticket->cache_msgs_ticket[$i]['fk_user_author'] > 0) { + $user_action = new User($this->db); + $user_action->fetch($this->ticket->cache_msgs_ticket[$i]['fk_user_author']); + } - if ($this->ticket->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors)); - } + // Now define messages + $messages[] = array( + 'id' => $this->ticket->cache_msgs_ticket[$i]['id'], + 'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], + 'fk_user_action_socid' => $user_action->socid, + 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), + 'message' => $this->ticket->cache_msgs_ticket[$i]['message'], + 'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'], + 'private' => $this->ticket->cache_msgs_ticket[$i]['private'] + ); + $i++; + } + $this->ticket->messages = $messages; + } - return $this->ticket->id; - } + // History + $history = array(); + $this->ticket->loadCacheLogsTicket(); + if (is_array($this->ticket->cache_logs_ticket) && count($this->ticket->cache_logs_ticket) > 0) { + $num = count($this->ticket->cache_logs_ticket); + $i = 0; + while ($i < $num) { + if ($this->ticket->cache_logs_ticket[$i]['fk_user_create'] > 0) { + $user_action = new User($this->db); + $user_action->fetch($this->ticket->cache_logs_ticket[$i]['fk_user_create']); + } - /** - * Create ticket object - * - * @param array $request_data Request datas - * @return int ID of ticket - * - */ - public function postNewMessage($request_data = null) - { - $ticketstatic = new Ticket($this->db); - if (!DolibarrApiAccess::$user->rights->ticket->write) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validateMessage($request_data); + // Now define messages + $history[] = array( + 'id' => $this->ticket->cache_logs_ticket[$i]['id'], + 'fk_user_author' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], + 'fk_user_action' => $this->ticket->cache_logs_ticket[$i]['fk_user_create'], + 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), + 'message' => $this->ticket->cache_logs_ticket[$i]['message'], + 'datec' => $this->ticket->cache_logs_ticket[$i]['datec'], + ); + $i++; + } + $this->ticket->history = $history; + } - foreach ($request_data as $field => $value) { - $this->ticket->$field = $value; - } - $ticketMessageText = $this->ticket->message; - $result = $this->ticket->fetch('', '', $this->ticket->track_id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } - $this->ticket->message = $ticketMessageText; - if (!$this->ticket->createTicketMessage(DolibarrApiAccess::$user)) { - throw new RestException(500); - } - return $this->ticket->id; - } + if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + return $this->_cleanObjectDatas($this->ticket); + } - /** - * Update ticket - * - * @param int $id Id of ticket to update - * @param array $request_data Datas - * @return int - * - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->ticket->write) { - throw new RestException(401); - } + /** + * List tickets + * + * Get a list of tickets + * + * @param int $socid Filter list with thirdparty ID + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101') and (t.fk_statut:=:1)" + * + * @return array Array of ticket objects + * + */ + public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '') + { + global $db, $conf; - $result = $this->ticket->fetch($id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } + $obj_ret = array(); - if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!$socid && DolibarrApiAccess::$user->socid) { + $socid = DolibarrApiAccess::$user->socid; + } - foreach ($request_data as $field => $value) { - $this->ticket->$field = $value; - } + // If the internal user must only see his customers, force searching by him + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { + $search_sale = DolibarrApiAccess::$user->id; + } - if ($this->ticket->update($id, DolibarrApiAccess::$user)) { - return $this->get($id); - } + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } + $sql .= " FROM ".MAIN_DB_PREFIX."ticket as t"; - return false; - } + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } - /** - * Delete ticket - * - * @param int $id Ticket ID - * @return array - * - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->ticket->delete) { - throw new RestException(401); - } - $result = $this->ticket->fetch($id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } + $sql .= ' WHERE t.entity IN ('.getEntity('ticket', 1).')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socid > 0) { + $sql .= " AND t.fk_soc = ".$socid; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } - if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + // Insert sale filter + if ($search_sale > 0) { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - if (!$this->ticket->delete($id)) { - throw new RestException(500); - } + $sql .= $this->db->order($sortfield, $sortorder); - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Ticket deleted' - ) - ); - } + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - /** - * Validate fields before create or update object - * - * @param array $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $ticket = array(); - foreach (Tickets::$FIELDS as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $ticket[$field] = $data[$field]; - } - return $ticket; - } + $sql .= $this->db->plimit($limit, $offset); + } - /** - * Validate fields before create or update object message - * - * @param array $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validateMessage($data) - { - $ticket = array(); - foreach (Tickets::$FIELDS_MESSAGES as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $ticket[$field] = $data[$field]; - } - return $ticket; - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($result); + $ticket_static = new Ticket($this->db); + if ($ticket_static->fetch($obj->rowid)) { + if ($ticket_static->fk_user_assign > 0) { + $userStatic = new User($this->db); + $userStatic->fetch($ticket_static->fk_user_assign); + $ticket_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; + } + $obj_ret[] = $this->_cleanObjectDatas($ticket_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve ticket list'); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No ticket found'); + } + return $obj_ret; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - * - * @todo use an array for properties to clean - * - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + /** + * Create ticket object + * + * @param array $request_data Request datas + * @return int ID of ticket + */ + public function post($request_data = null) + { + $ticketstatic = new Ticket($this->db); + if (!DolibarrApiAccess::$user->rights->ticket->write) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); - // Other attributes to clean - $attr2clean = array( - "contact", - "contact_id", - "ref_previous", - "ref_next", - "ref_ext", - "table_element_line", - "statut", - "country", - "country_id", - "country_code", - "barcode_type", - "barcode_type_code", - "barcode_type_label", - "barcode_type_coder", - "mode_reglement_id", - "cond_reglement_id", - "cond_reglement", - "fk_delivery_address", - "shipping_method_id", - "modelpdf", - "fk_account", - "note_public", - "note_private", - "note", - "total_ht", - "total_tva", - "total_localtax1", - "total_localtax2", - "total_ttc", - "fk_incoterms", - "label_incoterms", - "location_incoterms", - "name", - "lastname", - "firstname", - "civility_id", - "canvas", - "cache_msgs_ticket", - "cache_logs_ticket", - "cache_types_tickets", - "cache_category_tickets", - "regeximgext", - "statuts_short", - "statuts" - ); - foreach ($attr2clean as $toclean) { - unset($object->$toclean); - } + foreach ($request_data as $field => $value) { + $this->ticket->$field = $value; + } + if (empty($this->ticket->ref)) { + $this->ticket->ref = $ticketstatic->getDefaultRef(); + } + if (empty($this->ticket->track_id)) { + $this->ticket->track_id = generate_random_id(16); + } - // If object has lines, remove $db property - if (isset($object->lines) && count($object->lines) > 0) { - $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) { - $this->_cleanObjectDatas($object->lines[$i]); - } - } + if ($this->ticket->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors)); + } - // If object has linked objects, remove $db property - if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) { - foreach ($object->linkedObjects as $type_object => $linked_object) { - foreach ($linked_object as $object2clean) { - $this->_cleanObjectDatas($object2clean); - } - } - } - return $object; - } + return $this->ticket->id; + } + + /** + * Create ticket object + * + * @param array $request_data Request datas + * @return int ID of ticket + * + */ + public function postNewMessage($request_data = null) + { + $ticketstatic = new Ticket($this->db); + if (!DolibarrApiAccess::$user->rights->ticket->write) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validateMessage($request_data); + + foreach ($request_data as $field => $value) { + $this->ticket->$field = $value; + } + $ticketMessageText = $this->ticket->message; + $result = $this->ticket->fetch('', '', $this->ticket->track_id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } + $this->ticket->message = $ticketMessageText; + if (!$this->ticket->createTicketMessage(DolibarrApiAccess::$user)) { + throw new RestException(500); + } + return $this->ticket->id; + } + + /** + * Update ticket + * + * @param int $id Id of ticket to update + * @param array $request_data Datas + * @return int + * + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->ticket->write) { + throw new RestException(401); + } + + $result = $this->ticket->fetch($id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } + + if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + foreach ($request_data as $field => $value) { + $this->ticket->$field = $value; + } + + if ($this->ticket->update($id, DolibarrApiAccess::$user)) { + return $this->get($id); + } + + return false; + } + + /** + * Delete ticket + * + * @param int $id Ticket ID + * @return array + * + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->ticket->delete) { + throw new RestException(401); + } + $result = $this->ticket->fetch($id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } + + if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if (!$this->ticket->delete($id)) { + throw new RestException(500); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Ticket deleted' + ) + ); + } + + /** + * Validate fields before create or update object + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $ticket = array(); + foreach (Tickets::$FIELDS as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $ticket[$field] = $data[$field]; + } + return $ticket; + } + + /** + * Validate fields before create or update object message + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validateMessage($data) + { + $ticket = array(); + foreach (Tickets::$FIELDS_MESSAGES as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $ticket[$field] = $data[$field]; + } + return $ticket; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + * + * @todo use an array for properties to clean + * + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); + + // Other attributes to clean + $attr2clean = array( + "contact", + "contact_id", + "ref_previous", + "ref_next", + "ref_ext", + "table_element_line", + "statut", + "country", + "country_id", + "country_code", + "barcode_type", + "barcode_type_code", + "barcode_type_label", + "barcode_type_coder", + "mode_reglement_id", + "cond_reglement_id", + "cond_reglement", + "fk_delivery_address", + "shipping_method_id", + "modelpdf", + "fk_account", + "note_public", + "note_private", + "note", + "total_ht", + "total_tva", + "total_localtax1", + "total_localtax2", + "total_ttc", + "fk_incoterms", + "label_incoterms", + "location_incoterms", + "name", + "lastname", + "firstname", + "civility_id", + "canvas", + "cache_msgs_ticket", + "cache_logs_ticket", + "cache_types_tickets", + "cache_category_tickets", + "regeximgext", + "statuts_short", + "statuts" + ); + foreach ($attr2clean as $toclean) { + unset($object->$toclean); + } + + // If object has lines, remove $db property + if (isset($object->lines) && count($object->lines) > 0) { + $nboflines = count($object->lines); + for ($i = 0; $i < $nboflines; $i++) { + $this->_cleanObjectDatas($object->lines[$i]); + } + } + + // If object has linked objects, remove $db property + if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) { + foreach ($object->linkedObjects as $type_object => $linked_object) { + foreach ($linked_object as $object2clean) { + $this->_cleanObjectDatas($object2clean); + } + } + } + return $object; + } } diff --git a/htdocs/ticket/class/ticket.class.php b/htdocs/ticket/class/ticket.class.php index 0b7ce39a83c..e5818fa7762 100644 --- a/htdocs/ticket/class/ticket.class.php +++ b/htdocs/ticket/class/ticket.class.php @@ -108,7 +108,7 @@ class Ticket extends CommonObject /** * @var int Ticket statut - * @deprecated + * @deprecated */ public $fk_statut; @@ -197,6 +197,9 @@ class Ticket extends CommonObject */ public $notify_tiers_at_create; + /** + * @var string msgid + */ public $email_msgid; public $lines; @@ -1076,7 +1079,7 @@ class Ticket extends CommonObject * Initialise object with example values * Id must be 0 if object instance is a specimen * - * @return void + * @return int */ public function initAsSpecimen() { @@ -1101,6 +1104,7 @@ class Ticket extends CommonObject $this->date_read = ''; $this->date_close = ''; $this->tms = ''; + return 1; } /** diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php index 3d82c9b6cf2..32cf9eccfe3 100644 --- a/htdocs/ticket/list.php +++ b/htdocs/ticket/list.php @@ -584,7 +584,7 @@ if ($mode == 'mine') { $topicmail = "SendTicketRef"; $modelmail = "ticket"; $objecttmp = new Ticket($db); -$trackid = 'tick'.$object->id; +$trackid = 'tic'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) diff --git a/htdocs/user/bank.php b/htdocs/user/bank.php index 2f2c1ee0a86..b1f0b7d4785 100644 --- a/htdocs/user/bank.php +++ b/htdocs/user/bank.php @@ -76,6 +76,8 @@ if (!$bankid) } if (empty($account->userid)) $account->userid = $object->id; +$permissiontoaddbankaccount = (!empty($user->rights->salaries->write) || !empty($user->rights->hrm->employee->write) || !empty($user->rights->user->creer)); + /* * Actions @@ -172,8 +174,7 @@ if ($action == 'update' && !$cancel) $result = $account->update($user); - if (!$result) - { + if (!$result) { setEventMessages($account->error, $account->errors, 'errors'); $action = 'edit'; // Force chargement page edition } else { @@ -183,32 +184,28 @@ if ($action == 'update' && !$cancel) } // update personal email -if ($action == 'setpersonal_email') -{ - $object->personal_email = GETPOST('personal_email'); +if ($action == 'setpersonal_email') { + $object->personal_email = (string) GETPOST('personal_email', 'alphanohtml'); $result = $object->update($user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // update personal mobile -if ($action == 'setpersonal_mobile') -{ - $object->personal_mobile = GETPOST('personal_mobile'); +if ($action == 'setpersonal_mobile') { + $object->personal_mobile = (string) GETPOST('personal_mobile', 'alphanohtml'); $result = $object->update($user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // update default_c_exp_tax_cat -if ($action == 'setdefault_c_exp_tax_cat') -{ +if ($action == 'setdefault_c_exp_tax_cat') { $object->default_c_exp_tax_cat = GETPOST('default_c_exp_tax_cat', 'int'); $result = $object->update($user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // update default range -if ($action == 'setdefault_range') -{ +if ($action == 'setdefault_range') { $object->default_range = GETPOST('default_range', 'int'); $result = $object->update($user); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); @@ -505,7 +502,13 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco $morehtmlright = ''; if ($account->id == 0) { - $morehtmlright = dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create'); + if ($permissiontoaddbankaccount) { + $morehtmlright = dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create'); + } else { + $morehtmlright = dolGetButtonTitle($langs->trans('Add'), 'NotEnoughPermission', 'fa fa-plus-circle', '', '', -2); + } + } else { + $morehtmlright = dolGetButtonTitle($langs->trans('Add'), 'AlreadyOneBankAccount', 'fa fa-plus-circle', '', '', -2); } print load_fiche_titre($langs->trans("BankAccounts"), $morehtmlright, 'bank_account'); @@ -571,8 +574,8 @@ if ($action != 'edit' && $action != 'create') // If not bank account yet, $acco // Edit/Delete print ''; - if ($user->rights->hrm->employee->write || $user->rights->user->creer) { - print ''; + if ($permissiontoaddbankaccount) { + print ''; print img_picto($langs->trans("Modify"), 'edit'); print ''; } diff --git a/htdocs/user/card.php b/htdocs/user/card.php index b7b3fdc689e..6a928e0bfee 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -690,12 +690,6 @@ llxHeader('', $langs->trans("UserCard")); if ($action == 'create' || $action == 'adduserldap') { - /* ************************************************************************** */ - /* */ - /* Affichage fiche en mode creation */ - /* */ - /* ************************************************************************** */ - print load_fiche_titre($langs->trans("NewUser"), '', 'user'); print ''.$langs->trans("CreateInternalUserDesc")."
\n"; @@ -704,11 +698,7 @@ if ($action == 'create' || $action == 'adduserldap') if (!empty($conf->ldap->enabled) && (isset($conf->global->LDAP_SYNCHRO_ACTIVE) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')) { - /* - * Affiche formulaire d'ajout d'un compte depuis LDAP - * si on est en synchro LDAP vers Dolibarr - */ - + // Show form to add an account from LDAP if sync LDAP -> Dolibarr is set $ldap = new Ldap(); $result = $ldap->connect_bind(); if ($result >= 0) @@ -1272,12 +1262,7 @@ if ($action == 'create' || $action == 'adduserldap') print ""; } else { - /* ************************************************************************** */ - /* */ - /* View and edition */ - /* */ - /* ************************************************************************** */ - + // View and edit mode if ($id > 0) { $object->fetch($id, '', '', 1); @@ -1576,10 +1561,12 @@ if ($action == 'create' || $action == 'adduserldap') if (!empty($conf->stock->enabled) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; - $warehousestatic = new Entrepot($db); - $warehousestatic->fetch($object->fk_warehouse); print '
'.$langs->trans("DefaultWarehouse").''; - print $warehousestatic->getNomUrl(1); + if ($object->fk_warehouse > 0) { + $warehousestatic = new Entrepot($db); + $warehousestatic->fetch($object->fk_warehouse); + print $warehousestatic->getNomUrl(1); + } print '