zapier for dolibarr

This commit is contained in:
Frédéric FRANCE 2019-05-19 21:12:22 +02:00
parent c92994f7ed
commit aef850f6d3
No known key found for this signature in database
GPG Key ID: 06809324E4B2ABC1
36 changed files with 5847 additions and 0 deletions

7
dev/examples/zapier/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
build
docs
node_modules
*.log
.environment
.env
.zapierapprc

View File

@ -0,0 +1,7 @@
language: node_js
node_js:
- 8.10.0
before_script: 'npm install -g zapier-platform-cli'
script: 'zapier test'
notifications:
email: false

View File

@ -0,0 +1,56 @@
{
"table_rowid": "id",
"id": 6764,
"ref": null,
"type_id": "5",
"type_code": "AC_RDV",
"type": null,
"type_color": null,
"code": null,
"label": "azerty",
"datec": null,
"datem": null,
"authorid": null,
"usermodid": null,
"datep": 1555365600,
"datef": 1555538399,
"durationp": 172799,
"fulldayevent": 1,
"punctual": 1,
"percentage": "-1",
"location": "",
"transparency": 1,
"priority": 0,
"userassigned": {
"1": {
"id": "1",
"transparency": 1
}
},
"userownerid": "1",
"userdoneid": null,
"usertodo": null,
"userdone": null,
"socid": null,
"contactid": null,
"elementtype": "",
"icalname": null,
"icalcolor": null,
"actions": [],
"email_msgid": null,
"email_from": null,
"email_sender": null,
"email_to": null,
"email_tocc": null,
"email_tobcc": null,
"email_subject": null,
"errors_to": null,
"import_key": null,
"linkedObjectsIds": null,
"fk_project": 0,
"modelpdf": null,
"note_public": null,
"note_private": null,
"note": "wxcvbn",
"duree": 0
}

View File

@ -0,0 +1,76 @@
const testAuth = (z , bundle) => {
const url = bundle.authData.url+'/api/index.php/login';
// 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
const promise = z.request({
url: url,
});
// 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');
}
return response;
});
};
const getSessionKey = (z, bundle) => {
const url = bundle.authData.url + '/api/index.php/login';
const promise = z.request({
method: 'POST',
url: url,
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'
};
});
};
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'
},
{
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
},
// assuming "login" is a key returned from the test
connectionLabel: '{{login}}'
};

View File

@ -0,0 +1,83 @@
// create a particular thirdparty by name
const createThirdparty = async (z, bundle) => {
const apiurl = bundle.authData.url + '/api/index.php/thirdparties';
const response = await z.request({
method: 'POST',
url: apiurl,
body: JSON.stringify({
name: bundle.inputData.name,
name_alias: bundle.inputData.name_alias,
address: bundle.inputData.address,
zip: bundle.inputData.zip,
town: bundle.inputData.town,
email: bundle.inputData.email,
client: bundle.inputData.client,
fournisseur: bundle.inputData.fournisseur,
code_client: bundle.inputData.code_client,
code_fournisseur: bundle.inputData.code_fournisseur,
sens: 'fromzapier'
})
});
const result = z.JSON.parse(response.content);
// api returns an integer when ok, a json when ko
return result.response || {id: response};
};
module.exports = {
key: 'thirdparty',
noun: 'Thirdparty',
display: {
label: 'Create Thirdparty',
description: 'Creates a thirdparty.'
},
operation: {
inputFields: [
{key: 'name', required: true},
{key: 'name_alias', required: false},
{key: 'address', required: false},
{key: 'zip', required: false},
{key: 'town', required: false},
{key: 'email', required: false},
{key: 'client', type: 'integer', required: false},
{key: 'fournisseur', type: 'integer', required: false},
{key: 'code_client', required: false},
{key: 'code_fournisseur', required: false}
],
perform: createThirdparty,
sample: {
id: 1,
name: 'DUPOND',
name_alias: 'DUPOND Ltd',
address: 'Rue des Canaries',
zip: '34090',
town: 'MONTPELLIER',
phone: '0123456789',
fax: '2345678901',
email: 'robot@domain.com',
client: 1,
fournisseur: 0,
code_client: 'CU1903-1234',
code_fournisseur: 'SU1903-2345'
},
outputFields: [
{key: 'id', label: 'ID'},
{key: 'name', label: 'Name'},
{key: 'name_alias', label: 'Name alias'},
{key: 'address', label: 'Address'},
{key: 'zip', label: 'Zip'},
{key: 'town', label: 'Town'},
{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: 'code_client', label: 'Customer code'},
{key: 'code_fournisseur', label: 'Supplier code'}
]
}
};

View File

@ -0,0 +1,72 @@
const triggerThirdparty = require('./triggers/thirdparty');
const triggerOrder = require('./triggers/order');
const triggerAction = require('./triggers/action');
const searchThirdparty = require('./searches/thirdparty');
const createThirdparty = require('./creates/thirdparty');
const authentication = 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;
};
// 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;
};
// We can roll up all our behaviors in an App.
const App = {
// This is just shorthand to reference the installed dependencies you have. Zapier will
// need to know these before we can upload
version: require('./package.json').version,
platformVersion: require('zapier-platform-core').version,
authentication: authentication,
// beforeRequest & afterResponse are optional hooks into the provided HTTP client
beforeRequest: [
includeSessionKeyHeader
],
afterResponse: [
sessionRefreshIf401
],
// If you want to define optional resources to simplify creation of triggers, searches, creates - do that here!
resources: {
},
// If you want your trigger to show up, you better include it here!
triggers: {
[triggerThirdparty.key]: triggerThirdparty,
[triggerOrder.key]: triggerOrder,
[triggerAction.key]: triggerAction
},
// If you want your searches to show up, you better include it here!
searches: {
[searchThirdparty.key]: searchThirdparty,
},
// If you want your creates to show up, you better include it here!
creates: {
[createThirdparty.key]: createThirdparty,
}
};
// Finally, export the app.
module.exports = App;

405
dev/examples/zapier/package-lock.json generated Normal file
View File

@ -0,0 +1,405 @@
{
"name": "Dolibarr",
"version": "1.0.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@types/node": {
"version": "8.10.20",
"resolved": "https://registry.npmjs.org/@types/node/-/node-8.10.20.tgz",
"integrity": "sha512-M7x8+5D1k/CuA6jhiwuSCmE8sbUWJF0wYsjcig9WrXvwUI5ArEoUBdOXpV4JcEMrLp02/QbDjw+kI+vQeKyQgg==",
"optional": true
},
"asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
},
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
"dev": true
},
"bluebird": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.0.tgz",
"integrity": "sha1-eRQg1/VR7qKJdFOop3ZT+WYG1nw="
},
"brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"dev": true,
"requires": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"browser-stdout": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz",
"integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==",
"dev": true
},
"combined-stream": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.6.tgz",
"integrity": "sha1-cj599ugBrFYTETp+RFqbactjKBg=",
"requires": {
"delayed-stream": "~1.0.0"
}
},
"commander": {
"version": "2.15.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz",
"integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==",
"dev": true
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
"dev": true
},
"content-disposition": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ="
},
"debug": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
"integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"dev": true,
"requires": {
"ms": "2.0.0"
}
},
"delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk="
},
"diff": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz",
"integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==",
"dev": true
},
"dotenv": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-5.0.1.tgz",
"integrity": "sha512-4As8uPrjfwb7VXC+WnLCbXK7y+Ueb2B3zgNCePYfhxS1PYeaO1YTeplffTEcbfLhvFNGLAz90VvJs9yomG7bow=="
},
"encoding": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz",
"integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=",
"requires": {
"iconv-lite": "~0.4.13"
}
},
"escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
"integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=",
"dev": true
},
"form-data": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.2.tgz",
"integrity": "sha1-SXBJi+YEwgwAXU9cI67NIda0kJk=",
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "1.0.6",
"mime-types": "^2.1.12"
}
},
"fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
},
"glob": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz",
"integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==",
"dev": true,
"requires": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.0.4",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
}
},
"growl": {
"version": "1.10.5",
"resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz",
"integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==",
"dev": true
},
"has-flag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
"integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=",
"dev": true
},
"he": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz",
"integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=",
"dev": true
},
"iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
"dev": true,
"requires": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
"dev": true
},
"is-stream": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
"integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ="
},
"json-tryparse": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/json-tryparse/-/json-tryparse-1.0.5.tgz",
"integrity": "sha1-Khy6CLTjEjNo+p+2o01GQwBFeyc="
},
"jsonschema": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.1.1.tgz",
"integrity": "sha1-PO3o4+QR03eHLu+8n98mODy8Ptk="
},
"lodash": {
"version": "4.17.11",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz",
"integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg=="
},
"mime-db": {
"version": "1.38.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.38.0.tgz",
"integrity": "sha512-bqVioMFFzc2awcdJZIzR3HjZFX20QhilVS7hytkKrv7xFAn8bM1gzc/FOX2awLISvWe0PV8ptFKcon+wZ5qYkg=="
},
"mime-types": {
"version": "2.1.22",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.22.tgz",
"integrity": "sha512-aGl6TZGnhm/li6F7yx82bJiBZwgiEa4Hf6CNr8YO+r5UHr53tSTYZb102zyU50DOWWKeOv0uQLRL0/9EiKWCog==",
"requires": {
"mime-db": "~1.38.0"
}
},
"minimatch": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"dev": true,
"requires": {
"brace-expansion": "^1.1.7"
}
},
"minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=",
"dev": true
},
"mkdirp": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"dev": true,
"requires": {
"minimist": "0.0.8"
}
},
"mocha": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz",
"integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==",
"dev": true,
"requires": {
"browser-stdout": "1.3.1",
"commander": "2.15.1",
"debug": "3.1.0",
"diff": "3.5.0",
"escape-string-regexp": "1.0.5",
"glob": "7.1.2",
"growl": "1.10.5",
"he": "1.1.1",
"minimatch": "3.0.4",
"mkdirp": "0.5.1",
"supports-color": "5.4.0"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
"dev": true
},
"node-fetch": {
"version": "1.7.1",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.1.tgz",
"integrity": "sha512-j8XsFGCLw79vWXkZtMSmmLaOk9z5SQ9bV/tkbZVCqvgwzrjAGq66igobLofHtF63NvMTp2WjytpsNTGKa+XRIQ==",
"requires": {
"encoding": "^0.1.11",
"is-stream": "^1.0.1"
}
},
"oauth-sign": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
"integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ=="
},
"once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"dev": true,
"requires": {
"wrappy": "1"
}
},
"path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
"dev": true
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"semver": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz",
"integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg=="
},
"should": {
"version": "13.2.3",
"resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz",
"integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==",
"dev": true,
"requires": {
"should-equal": "^2.0.0",
"should-format": "^3.0.3",
"should-type": "^1.4.0",
"should-type-adaptors": "^1.0.1",
"should-util": "^1.0.0"
}
},
"should-equal": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz",
"integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==",
"dev": true,
"requires": {
"should-type": "^1.4.0"
}
},
"should-format": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz",
"integrity": "sha1-m/yPdPo5IFxT04w01xcwPidxJPE=",
"dev": true,
"requires": {
"should-type": "^1.3.0",
"should-type-adaptors": "^1.0.1"
}
},
"should-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz",
"integrity": "sha1-B1bYzoRt/QmEOmlHcZ36DUz/XPM=",
"dev": true
},
"should-type-adaptors": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz",
"integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==",
"dev": true,
"requires": {
"should-type": "^1.3.0",
"should-util": "^1.0.0"
}
},
"should-util": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.0.tgz",
"integrity": "sha1-yYzaN0qmsZDfi6h8mInCtNtiAGM=",
"dev": true
},
"supports-color": {
"version": "5.4.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz",
"integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==",
"dev": true,
"requires": {
"has-flag": "^3.0.0"
}
},
"wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
"dev": true
},
"zapier-platform-core": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/zapier-platform-core/-/zapier-platform-core-8.0.1.tgz",
"integrity": "sha512-vuAe7JkFQ88AeQ//NwwNEh8ZjiZr30GRWtwYo7Wo/nx1cqZwq+CRc9zJU2WRrhJfJOtOOTUF6w+pArBTtMOC5A==",
"requires": {
"@types/node": "8.10.20",
"bluebird": "3.5.0",
"content-disposition": "0.5.2",
"dotenv": "5.0.1",
"form-data": "2.3.2",
"lodash": "4.17.11",
"node-fetch": "1.7.1",
"oauth-sign": "0.9.0",
"semver": "5.6.0",
"zapier-platform-schema": "8.0.1"
}
},
"zapier-platform-schema": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/zapier-platform-schema/-/zapier-platform-schema-8.0.1.tgz",
"integrity": "sha512-97KJ0xVLtpU4BiXVaMTPQpiA0T6CQIEzWfzAWwJAWbu5336+6DMFUzDWN4bANBeD3CIsRHHPcZkP8n/17U05ag==",
"requires": {
"jsonschema": "1.1.1",
"lodash": "4.17.10"
},
"dependencies": {
"lodash": {
"version": "4.17.10",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.10.tgz",
"integrity": "sha512-UejweD1pDoXu+AD825lWwp4ZGtSwgnpZxb3JDViD7StjQz+Nb/6l093lx4OQ0foGWNRoc19mWy7BzL+UAK2iVg=="
}
}
}
}
}

View File

@ -0,0 +1,24 @@
{
"name": "Dolibarr",
"version": "1.0.2",
"description": "An app for connecting Dolibarr to the Zapier platform.",
"repository": "frederic34/ZapierForDolibarr",
"homepage": "https://netlogic-dev.fr/",
"author": "Frédéric France <fred@fredericfrance.fr>",
"license": "BSD-3-Clause",
"main": "index.js",
"scripts": {
"test": "mocha --recursive"
},
"engines": {
"node": "8.10.0",
"npm": ">=5.6.0"
},
"dependencies": {
"zapier-platform-core": "8.0.1"
},
"devDependencies": {
"mocha": "^5.2.0",
"should": "^13.2.0"
}
}

View File

@ -0,0 +1,66 @@
module.exports = {
key: 'thirdparty',
// You'll want to provide some helpful display labels and descriptions
// for users. Zapier will put them into the UX.
noun: 'Thirdparty',
display: {
label: 'Find a Thirdparty',
description: 'Search for thirdparty.'
},
// `operation` is where we make the call to your API to do the search
operation: {
// This search only has one search field. Your searches might have just one, or many
// search fields.
inputFields: [
{
key: 'name',
type: 'string',
label: 'Name',
helpText: 'Name to limit to the search to (i.e. The company or %company%).'
}
],
perform: (z, bundle) => {
const url = bundle.authData.url + '/api/index.php/thirdparties/';
// Put the search value in a query param. The details of how to build
// a search URL will depend on how your API works.
const options = {
params: {
sqlfilters: "t.nom like \'%"+bundle.inputData.name+"%\'"
}
};
return z.request(url, options).then(response => JSON.parse(response.content));
},
// 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,
name: 'DOE',
firstname: 'John',
authorId: 1,
directions: '1. Boil Noodles\n2.Serve with sauce',
style: 'italian'
},
// 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', label: 'ID'},
{key: 'createdAt', label: 'Created At'},
{key: 'name', label: 'Name'},
{key: 'firstname', label: 'Firstname'},
{key: 'directions', label: 'Directions'},
{key: 'authorId', label: 'Author ID'},
{key: 'style', label: 'Style'}
]
}
};

View File

@ -0,0 +1,17 @@
require('should');
const zapier = require('zapier-platform-core');
// Use this to make test calls into your app:
const App = require('../index');
const appTester = zapier.createAppTester(App);
describe('My App', () => {
it('should test something', (done) => {
const x = 1;
x.should.eql(1);
done();
});
});

View File

@ -0,0 +1,156 @@
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: 'action',
action: bundle.inputData.action
};
const url = bundle.authData.url + '/api/index.php/zapierapi/hook';
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: url,
method: 'POST',
body: JSON.stringify(data)
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const unsubscribeHook = (z, bundle) => {
// bundle.subscribeData contains the parsed response JSON from the subscribe
// request made initially.
z.console.log('unsuscribing hook!');
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: bundle.authData.url + '/api/index.php/zapierapi/hook/' + bundle.subscribeData.id,
method: 'DELETE',
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const getAction = (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 action = {
id: bundle.cleanedRequest.id,
ref: bundle.cleanedRequest.ref,
ref_client: bundle.cleanedRequest.ref_client,
name: bundle.cleanedRequest.name,
firstname: bundle.cleanedRequest.firstname,
usertodo__name: bundle.cleanedRequest.usertodo__name,
location: bundle.cleanedRequest.location,
label: bundle.cleanedRequest.label,
authorId: bundle.cleanedRequest.authorId,
createdAt: bundle.cleanedRequest.createdAt,
module: bundle.cleanedRequest.module,
datep: bundle.cleanedRequest.datep,
datef: bundle.cleanedRequest.datef,
fulldayevent: bundle.cleanedRequest.fulldayevent,
transparency: bundle.cleanedRequest.transparency,
icalname: bundle.cleanedRequest.icalname,
icalcolor: bundle.cleanedRequest.icalcolor,
note: bundle.cleanedRequest.note,
note_public: bundle.cleanedRequest.note_public,
note_private: bundle.cleanedRequest.note_private,
action: bundle.cleanedRequest.action
};
return [action];
};
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',
};
return z.request(options).then((response) => [JSON.parse(response.content)]);
};
// 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: bundle.authData.url + '/api/index.php/zapierapi/getactionschoices/actions',
// };
// return z.request(options).then((response) => JSON.parse(response.content));
// };
// We recommend writing your actions separate like this and rolling them
// into the App definition at the end.
module.exports = {
key: 'action',
// You'll want to provide some helpful display labels and descriptions
// for users. Zapier will put them into the UX.
noun: 'Action',
display: {
label: 'New Agenda',
description: 'Trigger when a new agenda with action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
operation: {
// `inputFields` can define the fields a user could provide,
// we'll pass them in as `bundle.inputData` later.
inputFields: [
{
key: 'action',
type: 'string',
helpText: 'Which action of agenda this should trigger on.',
choices: {
create: "Create",
modify: "Modify",
delete: "Delete",
}
}
],
type: 'hook',
performSubscribe: subscribeHook,
performUnsubscribe: unsubscribeHook,
perform: getAction,
performList: getFallbackRealAction,
// 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,
name: 'Best Spagetti Ever',
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', 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'}
]
}
};

View File

@ -0,0 +1,148 @@
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: 'order',
action: bundle.inputData.action
};
const url = bundle.authData.url + '/api/index.php/zapierapi/hook';
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: url,
method: 'POST',
body: JSON.stringify(data)
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const unsubscribeHook = (z, bundle) => {
// bundle.subscribeData contains the parsed response JSON from the subscribe
// request made initially.
z.console.log('unsuscribing hook!');
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: bundle.authData.url + '/api/index.php/zapierapi/hook/' + bundle.subscribeData.id,
method: 'DELETE',
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const getOrder = (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 order = {
id: bundle.cleanedRequest.id,
ref: bundle.cleanedRequest.ref,
ref_client: bundle.cleanedRequest.ref_client,
name: bundle.cleanedRequest.name,
firstname: bundle.cleanedRequest.firstname,
directions: bundle.cleanedRequest.directions,
authorId: bundle.cleanedRequest.authorId,
createdAt: bundle.cleanedRequest.createdAt,
note_public: bundle.cleanedRequest.note_public,
note_private: bundle.cleanedRequest.note_private,
action: bundle.cleanedRequest.action
};
return [order];
};
const getFallbackRealOrder = (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/orders/0',
};
return z.request(options).then((response) => [JSON.parse(response.content)]);
};
// 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: bundle.authData.url + '/api/index.php/zapierapi/getactionschoices/orders',
// };
// return z.request(options).then((response) => JSON.parse(response.content));
// };
// We recommend writing your orders separate like this and rolling them
// into the App definition at the end.
module.exports = {
key: 'order',
// You'll want to provide some helpful display labels and descriptions
// for users. Zapier will put them into the UX.
noun: 'Order',
display: {
label: 'New Order',
description: 'Trigger when a new order with action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
operation: {
// `inputFields` can define the fields a user could provide,
// we'll pass them in as `bundle.inputData` later.
inputFields: [
{
key: 'action',
type: 'string',
helpText: 'Which action of order this should trigger on.',
choices: {
create: "Create",
modify: "Modify",
validate: "Validate",
}
}
],
type: 'hook',
performSubscribe: subscribeHook,
performUnsubscribe: unsubscribeHook,
perform: getOrder,
performList: getFallbackRealOrder,
// 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,
name: 'Best Spagetti Ever',
authorId: 1,
directions: '1. Boil Noodles\n2.Serve with sauce',
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', label: 'ID'},
{key: 'createdAt', label: 'Created At'},
{key: 'name', label: 'Name'},
{key: 'directions', label: 'Directions'},
{key: 'authorId', label: 'Author ID'},
{key: 'module', label: 'Module'},
{key: 'action', label: 'Action'}
]
}
};

View File

@ -0,0 +1,175 @@
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: 'company',
action: bundle.inputData.action
};
const url = bundle.authData.url + '/api/index.php/zapierapi/hook';
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: url,
method: 'POST',
body: JSON.stringify(data)
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const unsubscribeHook = (z, bundle) => {
// bundle.subscribeData contains the parsed response JSON from the subscribe
// request made initially.
z.console.log('unsuscribing hook!');
// You can build requests and our client will helpfully inject all the variables
// you need to complete. You can also register middleware to control this.
const options = {
url: bundle.authData.url + '/api/index.php/zapierapi/hook/' + bundle.subscribeData.id,
method: 'DELETE',
};
// You may return a promise or a normal data structure from any perform method.
return z.request(options).then((response) => JSON.parse(response.content));
};
const getThirdparty = (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 thirdparty = {
id: bundle.cleanedRequest.id,
name: bundle.cleanedRequest.name,
name_alias: bundle.cleanedRequest.name_alias,
firstname: bundle.cleanedRequest.firstname,
address: bundle.cleanedRequest.address,
zip: bundle.cleanedRequest.zip,
town: bundle.cleanedRequest.town,
email: bundle.cleanedRequest.email,
client: bundle.cleanedRequest.client,
fournisseur: bundle.cleanedRequest.fournisseur,
code_client: bundle.cleanedRequest.code_client,
code_fournisseur: bundle.cleanedRequest.code_fournisseur,
authorId: bundle.cleanedRequest.authorId,
createdAt: bundle.cleanedRequest.createdAt,
action: bundle.cleanedRequest.action
};
return [thirdparty];
};
const getFallbackRealThirdparty = (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/thirdparties/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",
// 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: 'thirdparty',
// You'll want to provide some helpful display labels and descriptions
// for users. Zapier will put them into the UX.
noun: 'Thirdparty',
display: {
label: 'New Thirdparty',
description: 'Trigger when a new thirdpaty action is done in Dolibarr.'
},
// `operation` is where the business logic goes.
operation: {
// `inputFields` can define the fields a user could provide,
// we'll pass them in as `bundle.inputData` later.
inputFields: [
{
key: 'action',
type: 'string',
helpText: 'Which action of thirdparty this should trigger on.',
choices: {
create: "Create",
modify: "Modify",
validate: "Validate",
}
}
],
type: 'hook',
performSubscribe: subscribeHook,
performUnsubscribe: unsubscribeHook,
perform: getThirdparty,
performList: getFallbackRealThirdparty,
// 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,
name: 'DOE',
name_alias: 'DOE Ltd',
firstname: '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', 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: 'action', label: 'Action'},
{key: 'client', label: 'Customer/Prospect 0/1/2/3'},
{key: 'fournisseur', label: 'Supplier 0/1'},
{key: 'code_client', label: 'Customer code'},
{key: 'code_fournisseur', label: 'Supplier code'}
]
}
};

View File

@ -0,0 +1,375 @@
<?php
/* Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \defgroup zapier Module Zapier
* \brief Zapier module descriptor.
*
* \file htdocs/zapier/core/modules/modZapier.class.php
* \ingroup zapier
* \brief Description and activation file for module Zapier
*/
include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
/**
* Description and activation class for module Zapier
*/
class modZapier extends DolibarrModules
{
/**
* Constructor. Define names, constants, directories, boxes, permissions
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
global $langs,$conf;
$this->db = $db;
// Id for module (must be unique).
// Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id).
$this->numero = 792000; // TODO Go on page https://wiki.dolibarr.org/index.php/List_of_modules_id to reserve id number for your module
// Key text used to identify module (for permissions, menus, etc...)
$this->rights_class = 'zapier';
// Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...'
// 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 = 100;
// 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).
$this->name = preg_replace('/^mod/i', '', get_class($this));
// Module description, used if translation string 'ModuleZapierDesc' not found (Zapier is name of module).
$this->description = "ZapierDescription";
// Used only if file README.md and README-LL.md not found.
$this->descriptionlong = "Zapier description (Long)";
// Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z'
$this->version = 'development';
//Url to the file with your last numberversion of this module
//$this->url_last_version = 'http://www.example.com/versionmodule.txt';
// Key used in llx_const table to save module status enabled/disabled (where ZAPIERFORDOLIBARR is value of property name of module in uppercase)
$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
// Name of image file used for this module.
// If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
// If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module'
$this->picto = 'technic';
// Define some features supported by module (triggers, login, substitutions, menus, css, etc...)
$this->module_parts = array(
// Set this to 1 if module has its own trigger directory (core/triggers)
'triggers' => 1,
// Set this to 1 if module has its own login method file (core/login)
'login' => 0,
// Set this to 1 if module has its own substitution function file (core/substitutions)
'substitutions' => 0,
// Set this to 1 if module has its own menus handler directory (core/menus)
'menus' => 0,
// Set this to 1 if module overwrite template dir (core/tpl)
'tpl' => 0,
// Set this to 1 if module has its own barcode directory (core/modules/barcode)
'barcode' => 0,
// Set this to 1 if module has its own models directory (core/modules/xxx)
'models' => 0,
// Set this to 1 if module has its own theme directory (theme)
'theme' => 0,
// Set this to relative path of css file if module has its own css file
'css' => array(
// '/zapier/css/zapier.css.php',
),
// Set this to relative path of js file if module must load a js on all pages
'js' => array(
// '/zapier/js/zapier.js.php',
),
// Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context 'all'
'hooks' => array(
// 'data' => array(
// 'hookcontext1',
// 'hookcontext2',
// ),
// 'entity' => '0',
),
// Set this to 1 if feature of module are opened to external users
'moduleforexternal' => 0,
);
// Data directories to create when module is enabled.
// Example: this->dirs = array("/zapier/temp","/zapier/subdir");
$this->dirs = array("/zapier/temp");
// Config pages. Put here list of php page, stored into zapier/admin directory, to use to setup module.
$this->config_page_url = array("setup.php@zapier");
// Dependencies
// 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();
// 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', ...)
$this->conflictwith = array();
$this->langfiles = array("zapier@zapier");
// Minimum version of PHP required by module
//$this->phpmin = array(5, 5);
// Minimum version of Dolibarr required by module
$this->need_dolibarr_version = array(10, 0);
// Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
$this->warnings_activation = array();
// Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
$this->warnings_activation_ext = array();
// $this->automatic_activation = array(
// 'FR'=>'ZapierWasAutomaticallyActivatedBecauseOfYourCountryChoice',
// );
// If true, can't be disabled
// $this->always_enabled = true;
// Constants
// List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive)
// Example: $this->const=array(
// 1 => array('ZAPIERFORDOLIBARR_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1),
// 2 => array('ZAPIERFORDOLIBARR_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1)
// );
$this->const = array(
// 1 => array('ZAPIERFORDOLIBARR_MYCONSTANT', 'chaine', 'avalue', 'This is a constant to add', 1, 'allentities', 1)
);
// Some keys to add into the overwriting translation tables
/*$this->overwrite_translation = array(
'en_US:ParentCompany'=>'Parent company or reseller',
'fr_FR:ParentCompany'=>'Maison mère ou revendeur'
)*/
if (! isset($conf->zapier) || ! isset($conf->zapier->enabled)) {
$conf->zapier=new stdClass();
$conf->zapier->enabled=0;
}
// Array to add new pages in new tabs
$this->tabs = array();
// Example:
// $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@zapier:$user->rights->zapier->read:/zapier/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1
// $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@zapier:$user->rights->othermodule->read:/zapier/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key.
// $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname
//
// Where objecttype can be
// 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member)
// 'contact' to add a tab in contact view
// 'contract' to add a tab in contract view
// 'group' to add a tab in group view
// 'intervention' to add a tab in intervention view
// 'invoice' to add a tab in customer invoice view
// 'invoice_supplier' to add a tab in supplier invoice view
// 'member' to add a tab in fundation member view
// 'opensurveypoll' to add a tab in opensurvey poll view
// 'order' to add a tab in customer order view
// 'order_supplier' to add a tab in supplier order view
// 'payment' to add a tab in payment view
// 'payment_supplier' to add a tab in supplier payment view
// 'product' to add a tab in product view
// 'propal' to add a tab in propal view
// 'project' to add a tab in project view
// 'stock' to add a tab in stock view
// 'thirdparty' to add a tab in third party view
// 'user' to add a tab in user view
// Dictionaries
$this->dictionaries=array();
/* Example:
$this->dictionaries=array(
'langs'=>'mylangfile@zapier',
// List of tables we want to see into dictonnary editor
'tabname'=>array(MAIN_DB_PREFIX."table1",MAIN_DB_PREFIX."table2",MAIN_DB_PREFIX."table3"),
// Label of tables
'tablib'=>array("Table1","Table2","Table3"),
// Request to select fields
'tabsql'=>array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f','SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f','SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'),
// Sort order
'tabsqlsort'=>array("label ASC","label ASC","label ASC"),
// List of fields (result of select to show dictionary)
'tabfield'=>array("code,label","code,label","code,label"),
// List of fields (list of fields to edit a record)
'tabfieldvalue'=>array("code,label","code,label","code,label"),
// List of fields (list of fields for insert)
'tabfieldinsert'=>array("code,label","code,label","code,label"),
// Name of columns with primary key (try to always name it 'rowid')
'tabrowid'=>array("rowid","rowid","rowid"),
// Condition to show each dictionary
'tabcond'=>array($conf->zapier->enabled,$conf->zapier->enabled,$conf->zapier->enabled)
);
*/
// Boxes/Widgets
// Add here list of php file(s) stored in zapier/core/boxes that contains class to show a widget.
$this->boxes = array(
// 0 => array(
// 'file' => 'zapierwidget1.php@zapier',
// 'note' => 'Widget provided by Zapier',
// 'enabledbydefaulton' => 'Home',
// ),
//1=>array('file'=>'zapierwidget2.php@zapier','note'=>'Widget provided by Zapier'),
//2=>array('file'=>'zapierwidget3.php@zapier','note'=>'Widget provided by Zapier')
);
// Cronjobs (List of cron jobs entries to add when module is enabled)
// unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week
$this->cronjobs = array(
// 0 => array(
// 'label' => 'MyJob label',
// 'jobtype' => 'method',
// 'class' => '/zapier/class/myobject.class.php',
// 'objectname' => 'MyObject',
// 'method' => 'doScheduledJob',
// 'parameters' => '',
// 'comment' => 'Comment',
// 'frequency' => 2,
// 'unitfrequency' => 3600,
// 'status' => 0,
// 'test' => '$conf->zapier->enabled',
// 'priority' => 50,
// ),
);
// Example: $this->cronjobs=array(
// 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->zapier->enabled', 'priority'=>50),
// 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->zapier->enabled', 'priority'=>50)
// );
// Permissions
// Permission array used by this module
$this->rights = array();
$r=0;
// Permission id (must not be already used)
$this->rights[$r][0] = $this->numero + $r;
// Permission label
$this->rights[$r][1] = 'Read myobject of Zapier';
// Permission by default for new user (0/1)
$this->rights[$r][3] = 1;
// In php code, permission will be checked by test if ($user->rights->zapier->level1->level2)
$this->rights[$r][4] = 'read';
// In php code, permission will be checked by test if ($user->rights->zapier->level1->level2)
$this->rights[$r][5] = '';
$r++;
$this->rights[$r][0] = $this->numero + $r;
$this->rights[$r][1] = 'Create/Update myobject of Zapier';
$this->rights[$r][3] = 1;
$this->rights[$r][4] = 'write';
$this->rights[$r][5] = '';
$r++;
$this->rights[$r][0] = $this->numero + $r;
$this->rights[$r][1] = 'Delete myobject of Zapier';
$this->rights[$r][3] = 1;
$this->rights[$r][4] = 'delete';
$this->rights[$r][5] = '';
// Main menu entries
$this->menu = array(); // List of menus to add
$r=0;
// Add here entries to declare new menus
// $this->menu[$r++]=array(
// 'fk_menu' => '', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
// 'type' => 'top', // This is a Top menu entry
// 'titre' => 'Zapier',
// 'mainmenu' => 'zapier',
// 'leftmenu' => '',
// 'url' => '/zapier/zapierindex.php',
// 'langs' => 'zapier@zapier', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
// 'position' => 1000+$r,
// 'enabled' => '$conf->zapier->enabled', // Define condition to show or hide menu entry. Use '$conf->zapier->enabled' if entry must be visible if module is enabled.
// 'perms' => '1', // Use 'perms'=>'$user->rights->zapier->level1->level2' if you want your menu with a permission rules
// 'target' => '',
// 'user' => 2, // 0=Menu for internal users, 1=external users, 2=both
// );
/*
$this->menu[$r++]=array(
'fk_menu'=>'fk_mainmenu=zapier', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
'type'=>'left', // This is a Left menu entry
'titre'=>'List MyObject',
'mainmenu'=>'zapier',
'leftmenu'=>'zapier_myobject_list',
'url'=>'/zapier/myobject_list.php',
'langs'=>'zapier@zapier', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
'position'=>1000+$r,
'enabled'=>'$conf->zapier->enabled', // Define condition to show or hide menu entry. Use '$conf->zapier->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected.
'perms'=>'1', // Use 'perms'=>'$user->rights->zapier->level1->level2' if you want your menu with a permission rules
'target'=>'',
'user'=>2, // 0=Menu for internal users, 1=external users, 2=both
);
$this->menu[$r++]=array(
'fk_menu'=>'fk_mainmenu=zapier,fk_leftmenu=zapier', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
'type'=>'left', // This is a Left menu entry
'titre'=>'New MyObject',
'mainmenu'=>'zapier',
'leftmenu'=>'zapier_myobject_new',
'url'=>'/zapier/myobject_page.php?action=create',
'langs'=>'zapier@zapier', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
'position'=>1000+$r,
'enabled'=>'$conf->zapier->enabled', // Define condition to show or hide menu entry. Use '$conf->zapier->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected.
'perms'=>'1', // Use 'perms'=>'$user->rights->zapier->level1->level2' if you want your menu with a permission rules
'target'=>'',
'user'=>2, // 0=Menu for internal users, 1=external users, 2=both
);
*/
// Exports
$r=1;
/* EXPORT */
/*
$langs->load("zapier@zapier");
$this->export_code[$r]=$this->rights_class.'_'.$r;
$this->export_label[$r]='MyObjectLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
$this->export_icon[$r]='myobject@zapier';
$keyforclass = 'MyObject'; $keyforclassfile='/mymobule/class/myobject.class.php'; $keyforelement='myobject';
include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
$keyforselect='myobject'; $keyforaliasextra='extra'; $keyforelement='myobject';
include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
//$this->export_dependencies_array[$r]=array('mysubobject'=>'ts.rowid', 't.myfield'=>array('t.myfield2','t.myfield3')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields)
$this->export_sql_start[$r]='SELECT DISTINCT ';
$this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'myobject as t';
$this->export_sql_end[$r] .=' WHERE 1 = 1';
$this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('myobject').')';
$r++; */
}
/**
* Function called when module is enabled.
* The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
* It also creates data directories
*
* @param string $options Options when enabling module ('', 'noboxes')
* @return int 1 if OK, 0 if KO
*/
public function init($options = '')
{
$result = $this->_load_tables('/zapier/sql/');
if ($result < 0) return -1; // Do not activate module if not allowed errors found on module SQL queries (the _load_table run sql with run_sql with error allowed parameter to 'default')
// Create extrafields
//include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
//$extrafields = new ExtraFields($this->db);
//$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', 0, 0, '', '', 'zapier@zapier', '$conf->zapier->enabled');
//$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', 0, 0, '', '', 'zapier@zapier', '$conf->zapier->enabled');
//$result3=$extrafields->addExtraField('myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'zapier@zapier', '$conf->zapier->enabled');
//$result4=$extrafields->addExtraField('myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'zapier@zapier', '$conf->zapier->enabled');
//$result5=$extrafields->addExtraField('myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', 0, 0, '', '', 'zapier@zapier', '$conf->zapier->enabled');
$sql = array();
return $this->_init($sql, $options);
}
/**
* Function called when module is disabled.
* Remove from database constants, boxes and permissions from Dolibarr database.
* Data directories are not deleted
*
* @param string $options Options when enabling module ('', 'noboxes')
* @return int 1 if OK, 0 if KO
*/
public function remove($options = '')
{
$sql = array();
return $this->_remove($sql, $options);
}
}

View File

@ -0,0 +1,567 @@
<?php
/* Copyright (C) 2017-2019 Frédéric France <frederic.france@netlogic.fr>
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file core/triggers/interface_99_modZapier_ZapierTriggers.class.php
* \ingroup zapier
* \brief Example trigger.
*
*
* \remarks You can create other triggers by copying this one.
* - File name should be either:
* - interface_99_modZapier_MyTrigger.class.php
* - interface_99_all_MyTrigger.class.php
* - The file must stay in core/triggers
* - The class name must be InterfaceMytrigger
* - The constructor method must be named InterfaceMytrigger
* - The name property name must be MyTrigger
*/
require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php';
/**
* Class of triggers for Zapier module
*/
class InterfaceZapierTriggers extends DolibarrTriggers
{
/**
* @var DoliDB Database handler
*/
protected $db;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
$this->name = preg_replace('/^Interface/i', '', get_class($this));
$this->family = "demo";
$this->description = "Zapier triggers.";
// 'development', 'experimental', 'dolibarr' or version
$this->version = 'development';
$this->picto = 'zapier@zapier';
}
/**
* Trigger name
*
* @return string Name of trigger file
*/
public function getName()
{
return $this->name;
}
/**
* Trigger description
*
* @return string Description of trigger file
*/
public function getDesc()
{
return $this->description;
}
/**
* Function called when a Dolibarrr business event is done.
* All functions "runTrigger" are triggered if file
* is inside directory core/triggers
*
* @param string $action Event action code
* @param CommonObject $object Object
* @param User $user Object user
* @param Translate $langs Object langs
* @param Conf $conf Object conf
* @return int <0 if KO, 0 if no triggered ran, >0 if OK
*/
public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf)
{
global $db;
if (empty($conf->zapier->enabled)) {
// Module not active, we do nothing
return 0;
}
$logtriggeraction = false;
if ($action!='') {
$actions = explode('_', $action);
$sql = 'SELECT rowid, url FROM '.MAIN_DB_PREFIX.'zapier_hook WHERE';
$sql .= ' module="'.$db->escape(strtolower($actions[0])).'" AND action="'.$db->escape(strtolower($actions[1])).'"';
//setEventMessages($sql, null);
}
switch ($action) {
// Users
//case 'USER_CREATE':
//case 'USER_MODIFY':
//case 'USER_NEW_PASSWORD':
//case 'USER_ENABLEDISABLE':
//case 'USER_DELETE':
//case 'USER_SETINGROUP':
//case 'USER_REMOVEFROMGROUP':
case 'USER_LOGIN':
//$logtriggeraction = true;
break;
case 'USER_LOGIN_FAILED':
//$logtriggeraction = true;
break;
case 'USER_LOGOUT':
//$logtriggeraction = true;
break;
// Warning: To increase performances, this action is triggered only if constant MAIN_ACTIVATE_UPDATESESSIONTRIGGER is set to 1.
//case 'USER_UPDATE_SESSION':
case 'DOSSIERISOLATION_CREATE':
//$logtriggeraction = true;
break;
case 'DOSSIERISOLATION_MODIFY':
//$logtriggeraction = true;
break;
case 'DOSSIERISOLATION_DELETE':
//$logtriggeraction = true;
break;
// Actions
case 'ACTION_MODIFY':
//$logtriggeraction = true;
break;
case 'ACTION_CREATE':
$resql = $db->query($sql);
// TODO voir comment regrouper les webhooks en un post
while ($resql && $obj = $db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$cleaned = cleanAgendaEventsDatas($cleaned);
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
//setEventMessages($obj['url'], null);
}
$logtriggeraction = true;
break;
case 'ACTION_DELETE':
//$logtriggeraction = true;
break;
// Groups
//case 'GROUP_CREATE':
//case 'GROUP_MODIFY':
//case 'GROUP_DELETE':
// Companies
case 'COMPANY_CREATE':
$resql = $db->query($sql);
while ($resql && $obj = $db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'COMPANY_MODIFY':
$resql = $db->query($sql);
while ($resql && $obj = $db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'COMPANY_DELETE':
//$logtriggeraction = true;
break;
// Contacts
case 'CONTACT_CREATE':
case 'CONTACT_MODIFY':
case 'CONTACT_DELETE':
case 'CONTACT_ENABLEDISABLE':
// Products
case 'PRODUCT_CREATE':
case 'PRODUCT_MODIFY':
case 'PRODUCT_DELETE':
case 'PRODUCT_PRICE_MODIFY':
case 'PRODUCT_SET_MULTILANGS':
case 'PRODUCT_DEL_MULTILANGS':
//Stock mouvement
case 'STOCK_MOVEMENT':
//MYECMDIR
case 'MYECMDIR_DELETE':
case 'MYECMDIR_CREATE':
case 'MYECMDIR_MODIFY':
// Customer orders
case 'ORDER_CREATE':
$resql = $db->query($sql);
while ($resql && $obj = $db->fetch_array($resql)) {
$cleaned = cleanObjectDatas(dol_clone($object));
$json = json_encode($cleaned);
// call the zapierPostWebhook() function
zapierPostWebhook($obj['url'], $json);
}
$logtriggeraction = true;
break;
case 'ORDER_CLONE':
break;
case 'ORDER_VALIDATE':
break;
case 'ORDER_DELETE':
case 'ORDER_CANCEL':
case 'ORDER_SENTBYMAIL':
case 'ORDER_CLASSIFY_BILLED':
case 'ORDER_SETDRAFT':
case 'LINEORDER_INSERT':
case 'LINEORDER_UPDATE':
case 'LINEORDER_DELETE':
// Supplier orders
case 'ORDER_SUPPLIER_CREATE':
case 'ORDER_SUPPLIER_CLONE':
case 'ORDER_SUPPLIER_VALIDATE':
case 'ORDER_SUPPLIER_DELETE':
case 'ORDER_SUPPLIER_APPROVE':
case 'ORDER_SUPPLIER_REFUSE':
case 'ORDER_SUPPLIER_CANCEL':
case 'ORDER_SUPPLIER_SENTBYMAIL':
case 'ORDER_SUPPLIER_DISPATCH':
case 'LINEORDER_SUPPLIER_DISPATCH':
case 'LINEORDER_SUPPLIER_CREATE':
case 'LINEORDER_SUPPLIER_UPDATE':
// Proposals
case 'PROPAL_CREATE':
case 'PROPAL_CLONE':
case 'PROPAL_MODIFY':
case 'PROPAL_VALIDATE':
case 'PROPAL_SENTBYMAIL':
case 'PROPAL_CLOSE_SIGNED':
//$logtriggeraction = true;
break;
case 'PROPAL_CLOSE_REFUSED':
//$logtriggeraction = true;
break;
case 'PROPAL_DELETE':
//$logtriggeraction = true;
break;
case 'LINEPROPAL_INSERT':
case 'LINEPROPAL_UPDATE':
case 'LINEPROPAL_DELETE':
// SupplierProposal
case 'SUPPLIER_PROPOSAL_CREATE':
case 'SUPPLIER_PROPOSAL_CLONE':
case 'SUPPLIER_PROPOSAL_MODIFY':
case 'SUPPLIER_PROPOSAL_VALIDATE':
case 'SUPPLIER_PROPOSAL_SENTBYMAIL':
case 'SUPPLIER_PROPOSAL_CLOSE_SIGNED':
case 'SUPPLIER_PROPOSAL_CLOSE_REFUSED':
case 'SUPPLIER_PROPOSAL_DELETE':
case 'LINESUPPLIER_PROPOSAL_INSERT':
case 'LINESUPPLIER_PROPOSAL_UPDATE':
case 'LINESUPPLIER_PROPOSAL_DELETE':
// Contracts
case 'CONTRACT_CREATE':
case 'CONTRACT_ACTIVATE':
case 'CONTRACT_CANCEL':
case 'CONTRACT_CLOSE':
case 'CONTRACT_DELETE':
case 'LINECONTRACT_INSERT':
case 'LINECONTRACT_UPDATE':
case 'LINECONTRACT_DELETE':
// Bills
case 'BILL_CREATE':
//$logtriggeraction = true;
break;
case 'BILL_CLONE':
case 'BILL_MODIFY':
case 'BILL_VALIDATE':
case 'BILL_UNVALIDATE':
//$logtriggeraction = true;
break;
case 'BILL_SENTBYMAIL':
//$logtriggeraction = true;
break;
case 'BILL_CANCEL':
//$logtriggeraction = true;
break;
case 'BILL_DELETE':
//$logtriggeraction = true;
break;
case 'BILL_PAYED':
case 'LINEBILL_INSERT':
case 'LINEBILL_UPDATE':
case 'LINEBILL_DELETE':
//Supplier Bill
case 'BILL_SUPPLIER_CREATE':
case 'BILL_SUPPLIER_UPDATE':
case 'BILL_SUPPLIER_DELETE':
case 'BILL_SUPPLIER_PAYED':
case 'BILL_SUPPLIER_UNPAYED':
case 'BILL_SUPPLIER_VALIDATE':
case 'BILL_SUPPLIER_UNVALIDATE':
case 'LINEBILL_SUPPLIER_CREATE':
case 'LINEBILL_SUPPLIER_UPDATE':
case 'LINEBILL_SUPPLIER_DELETE':
// Payments
case 'PAYMENT_CUSTOMER_CREATE':
case 'PAYMENT_SUPPLIER_CREATE':
case 'PAYMENT_ADD_TO_BANK':
case 'PAYMENT_DELETE':
// Online
case 'PAYMENT_PAYBOX_OK':
case 'PAYMENT_PAYPAL_OK':
case 'PAYMENT_STRIPE_OK':
// Donation
case 'DON_CREATE':
case 'DON_UPDATE':
case 'DON_DELETE':
// Interventions
case 'FICHINTER_CREATE':
case 'FICHINTER_MODIFY':
case 'FICHINTER_VALIDATE':
case 'FICHINTER_DELETE':
case 'LINEFICHINTER_CREATE':
case 'LINEFICHINTER_UPDATE':
case 'LINEFICHINTER_DELETE':
// Members
case 'MEMBER_CREATE':
case 'MEMBER_VALIDATE':
case 'MEMBER_SUBSCRIPTION':
case 'MEMBER_MODIFY':
case 'MEMBER_NEW_PASSWORD':
case 'MEMBER_RESILIATE':
case 'MEMBER_DELETE':
// Categories
case 'CATEGORY_CREATE':
case 'CATEGORY_MODIFY':
case 'CATEGORY_DELETE':
case 'CATEGORY_SET_MULTILANGS':
// Projects
case 'PROJECT_CREATE':
case 'PROJECT_MODIFY':
case 'PROJECT_DELETE':
// Project tasks
case 'TASK_CREATE':
case 'TASK_MODIFY':
case 'TASK_DELETE':
// Task time spent
case 'TASK_TIMESPENT_CREATE':
case 'TASK_TIMESPENT_MODIFY':
case 'TASK_TIMESPENT_DELETE':
// Shipping
case 'SHIPPING_CREATE':
case 'SHIPPING_MODIFY':
case 'SHIPPING_VALIDATE':
case 'SHIPPING_SENTBYMAIL':
case 'SHIPPING_BILLED':
case 'SHIPPING_CLOSED':
case 'SHIPPING_REOPEN':
//$logtriggeraction = true;
break;
case 'SHIPPING_DELETE':
//$logtriggeraction = true;
break;
}
if ($logtriggeraction) {
dol_syslog("Trigger '" . $this->name . "' for action '.$action.' launched by " . __FILE__ . " id=" . $object->id);
}
return 0;
}
}
/**
* Post webhook in zapier with object data
*
* @param string $url url provided by zapier
* @param string $json data to send
* @return void
*/
function zapierPostWebhook($url, $json)
{
$headers = array('Accept: application/json', 'Content-Type: application/json');
// TODO supprimer le webhook en cas de mauvaise réponse
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
curl_close($ch);
}
/**
* Clean sensible object datas
*
* @param object $toclean Object to clean
* @return array Array of cleaned object properties
*/
function cleanObjectDatas($toclean)
{
// Remove $db object property for object
unset($toclean->db);
// Remove linkedObjects. We should already have linkedObjectIds that avoid huge responses
unset($toclean->linkedObjects);
unset($toclean->lines); // should be ->lines
unset($toclean->fields);
unset($toclean->oldline);
unset($toclean->error);
unset($toclean->errors);
unset($toclean->ref_previous);
unset($toclean->ref_next);
unset($toclean->ref_int);
unset($toclean->projet); // Should be fk_project
unset($toclean->project); // Should be fk_project
unset($toclean->author); // Should be fk_user_author
unset($toclean->timespent_old_duration);
unset($toclean->timespent_id);
unset($toclean->timespent_duration);
unset($toclean->timespent_date);
unset($toclean->timespent_datehour);
unset($toclean->timespent_withhour);
unset($toclean->timespent_fk_user);
unset($toclean->timespent_note);
unset($toclean->statuts);
unset($toclean->statuts_short);
unset($toclean->statuts_logo);
unset($toclean->statuts_long);
unset($toclean->element);
unset($toclean->fk_element);
unset($toclean->table_element);
unset($toclean->table_element_line);
unset($toclean->picto);
unset($toclean->skip_update_total);
unset($toclean->context);
// Remove the $oldcopy property because it is not supported by the JSON
// encoder. The following error is generated when trying to serialize
// it: "Error encoding/decoding JSON: Type is not supported"
// Note: Event if this property was correctly handled by the JSON
// encoder, it should be ignored because keeping it would let the API
// have a very strange behavior: calling PUT and then GET on the same
// resource would give different results:
// PUT /objects/{id} -> returns object with oldcopy = previous version of the object
// GET /objects/{id} -> returns object with oldcopy empty
unset($toclean->oldcopy);
// If object has lines, remove $db property
if (isset($toclean->lines) && count($toclean->lines) > 0) {
$nboflines = count($toclean->lines);
for ($i=0; $i < $nboflines; $i++) {
$this->cleanObjectDatas($toclean->lines[$i]);
}
}
// If object has linked objects, remove $db property
/*
if(isset($toclean->linkedObjects) && count($toclean->linkedObjects) > 0) {
foreach($toclean->linkedObjects as $type_object => $linked_object) {
foreach($linked_object as $toclean2clean) {
$this->cleanObjectDatas($toclean2clean);
}
}
}*/
return $toclean;
}
/**
* Clean sensible object datas
*
* @param object $toclean Object to clean
* @return array Array of cleaned object properties
*/
function cleanAgendaEventsDatas($toclean)
{
unset($toclean->usermod);
unset($toclean->libelle);
//unset($toclean->array_options);
unset($toclean->context);
unset($toclean->canvas);
unset($toclean->contact);
unset($toclean->contact_id);
unset($toclean->thirdparty);
unset($toclean->user);
unset($toclean->origin);
unset($toclean->origin_id);
unset($toclean->ref_ext);
unset($toclean->statut);
unset($toclean->country);
unset($toclean->country_id);
unset($toclean->country_code);
unset($toclean->barcode_type);
unset($toclean->barcode_type_code);
unset($toclean->barcode_type_label);
unset($toclean->barcode_type_coder);
unset($toclean->mode_reglement_id);
unset($toclean->cond_reglement_id);
unset($toclean->cond_reglement);
unset($toclean->fk_delivery_address);
unset($toclean->shipping_method_id);
unset($toclean->fk_account);
unset($toclean->total_ht);
unset($toclean->total_tva);
unset($toclean->total_localtax1);
unset($toclean->total_localtax2);
unset($toclean->total_ttc);
unset($toclean->fk_incoterms);
unset($toclean->libelle_incoterms);
unset($toclean->location_incoterms);
unset($toclean->name);
unset($toclean->lastname);
unset($toclean->firstname);
unset($toclean->civility_id);
unset($toclean->contact);
unset($toclean->societe);
return $toclean;
}

View File

@ -0,0 +1,53 @@
# Copyright (C) 2019 Frédéric FRANCE <frederic.france@free.fr>
#
# 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
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Generic
#
# Module label 'ModuleZapierForDolibarrName'
ModuleZapierForDolibarrName = ZapierForDolibarr
# Module description 'ModuleZapierForDolibarrDesc'
ModuleZapierForDolibarrDesc = ZapierForDolibarr description
#
# Admin page
#
ZapierForDolibarrSetup = ZapierForDolibarr setup
Settings = Settings
ZapierForDolibarrSetupPage = ZapierForDolibarr setup page
ZAPIERFORDOLIBARR_MYPARAM1 = My param 1
ZAPIERFORDOLIBARR_MYPARAM1Tooltip = My param 1 tooltip
ZAPIERFORDOLIBARR_MYPARAM2=My param 2
ZAPIERFORDOLIBARR_MYPARAM2Tooltip=My param 2 tooltip
#
# About page
#
About = About
ZapierForDolibarrAbout = About ZapierForDolibarr
ZapierForDolibarrAboutPage = ZapierForDolibarr about page
#
# Sample page
#
MyPageName = My page name
#
# Sample widget
#
MyWidget = My widget
MyWidgetDescription = My widget description

View File

@ -0,0 +1,48 @@
# Copyright (C) 2019 Frédéric FRANCE <frederic.france@free.fr>
#
# 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
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Générique
#
# Module label 'ModuleZapierForDolibarrName'
ModuleZapierForDolibarrName = ZapierForDolibarr
# Module description 'ModuleZapierForDolibarrDesc'
ModuleZapierForDolibarrDesc = Description de ZapierForDolibarr
#
# Page d'administration
#
ZapierForDolibarrSetup = Configuration du module ZapierForDolibarr
Settings = Réglages
ZapierForDolibarrSetupPage = Page de configuration du module ZapierForDolibarr
#
# Page À propos
#
About = À propos
ZapierForDolibarrAbout = À propos de ZapierForDolibarr
ZapierForDolibarrAboutPage = Page à propos de ZapierForDolibarr
#
# Page d'exemple
#
MyPageName = Nom de ma page
#
# Box d'exemple
#
MyWidget = Mon widget
MyWidgetDescription = Description de mon widget

View File

@ -0,0 +1,76 @@
<?php
/* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2019 Frédéric FRANCE <frederic.france@free.fr>
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file zapier/admin/about.php
* \ingroup zapier
* \brief About page of module Zapier.
*/
// Load Dolibarr environment
require '../../main.inc.php';
// Libraries
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once '../lib/zapier.lib.php';
// Translations
$langs->loadLangs(array("errors","admin","zapier@zapier"));
// Access control
if (! $user->admin) accessforbidden();
// Parameters
$action = GETPOST('action', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');
/*
* Actions
*/
// None
/*
* View
*/
$form = new Form($db);
$page_name = "ZapierAbout";
llxHeader('', $langs->trans($page_name));
// Subheader
$linkback = '<a href="'.($backtopage?$backtopage:DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>';
print load_fiche_titre($langs->trans($page_name), $linkback, 'object_zapier@zapier');
// Configuration header
$head = zapierAdminPrepareHead();
dol_fiche_head($head, 'about', '', 0, 'zapier@zapier');
dol_include_once('/zapier/core/modules/modZapier.class.php');
$tmpmodule = new modZapier($db);
print $tmpmodule->getDescLong();
// Page end
dol_fiche_end();
llxFooter();
$db->close();

View File

@ -0,0 +1,124 @@
<?php
/* Copyright (C) 2004-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2019 Frédéric FRANCE <frederic.france@free.fr>
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file zapier/admin/setup.php
* \ingroup zapier
* \brief Zapier setup page.
*/
// Load Dolibarr environment
require '../../main.inc.php';
// Libraries
require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
require_once '../lib/zapier.lib.php';
// Translations
$langs->loadLangs(array("admin", "zapier@zapier"));
// Access control
if (! $user->admin) accessforbidden();
// Parameters
$action = GETPOST('action', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');
$arrayofparameters=array(
'ZAPIERFORDOLIBARR_MYPARAM1'=>array('css'=>'minwidth200','enabled'=>1),
'ZAPIERFORDOLIBARR_MYPARAM2'=>array('css'=>'minwidth500','enabled'=>1)
);
/*
* Actions
*/
if ((float) DOL_VERSION >= 6) {
include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
}
/*
* View
*/
$page_name = "ZapierSetup";
llxHeader('', $langs->trans($page_name));
// Subheader
$linkback = '<a href="'.($backtopage?$backtopage:DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1').'">'.$langs->trans("BackToModuleList").'</a>';
print load_fiche_titre($langs->trans($page_name), $linkback, 'object_zapier@zapier');
// Configuration header
$head = zapierAdminPrepareHead();
dol_fiche_head($head, 'settings', '', -1, "zapier@zapier");
// Setup page goes here
echo $langs->trans("ZapierSetupPage").'<br><br>';
if ($action == 'edit') {
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="update">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
foreach($arrayofparameters as $key => $val) {
print '<tr class="oddeven"><td>';
print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip'));
print '</td><td><input name="'.$key.'" class="flat '.(empty($val['css'])?'minwidth200':$val['css']).'" value="' . $conf->global->$key . '"></td></tr>';
}
print '</table>';
print '<br><div class="center">';
print '<input class="button" type="submit" value="'.$langs->trans("Save").'">';
print '</div>';
print '</form>';
print '<br>';
} else {
if (! empty($arrayofparameters)) {
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
foreach($arrayofparameters as $key => $val) {
print '<tr class="oddeven"><td>';
print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip'));
print '</td><td>' . $conf->global->$key . '</td></tr>';
}
print '</table>';
print '<div class="tabsAction">';
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit">'.$langs->trans("Modify").'</a>';
print '</div>';
} else
{
print '<br>'.$langs->trans("NothingToSetup");
}
}
// Page end
dol_fiche_end();
llxFooter();
$db->close();

View File

@ -0,0 +1,382 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
* Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
dol_include_once('/zapier/class/hook.class.php');
/**
* \file htdocs/modulebuilder/template/class/api_zapier.class.php
* \ingroup zapier
* \brief File for API management of hook.
*/
/**
* API class for zapier hook
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class ZapierApi extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'url',
);
/**
* @var Hook $hook {@type Hook}
*/
public $hook;
/**
* Constructor
*
* @url GET /
*
*/
public function __construct()
{
global $db, $conf;
$this->db = $db;
$this->hook = new Hook($this->db);
}
/**
* Get properties of a hook object
*
* Return an array with hook informations
*
* @param int $id ID of hook
* @return array|mixed data without useless information
*
* @url GET /hooks/{id}
* @throws RestException
*/
public function get($id)
{
if(! DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401);
}
$result = $this->hook->fetch($id);
if (! $result ) {
throw new RestException(404, 'Hook not found');
}
if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->hook);
}
/**
* Get list of possibles choices for module
*
* Return an array with hook informations
* @param integer $id ID
*
* @return array|mixed data
*
* @url GET /getmoduleschoices/
* @throws RestException
*/
public function getModulesChoices($id)
{
if(! DolibarrApiAccess::$user->rights->zapier->read) {
throw new RestException(401);
}
$arraychoices = array(
'invoices' => 'Invoices',
'orders' => 'Orders',
'thirdparties' => 'Thirparties',
'contacts' => 'Contacts',
);
// $result = $this->hook->fetch($id);
// if (! $result ) {
// throw new RestException(404, 'Hook not found');
// }
// if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
// throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
// }
return $arraychoices;
}
/**
* List hooks
*
* Get a list of hooks
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
* @return array Array of order objects
*
* @throws RestException
*
* @url GET /hooks/
*/
public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
{
global $db, $conf;
$obj_ret = array();
$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : '';
// Set to 1 if there is a field socid in table of object
$restrictonsocid = 0;
// If the internal user must only see his customers, force searching by him
$search_sale = 0;
if ($restrictonsocid && ! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) {
$search_sale = DolibarrApiAccess::$user->id;
}
$sql = "SELECT t.rowid";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
// We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql .= ", sc.fk_soc, sc.fk_user";
}
$sql.= " FROM ".MAIN_DB_PREFIX."hook_mytable as t";
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
$sql.= " WHERE 1 = 1";
// Example of use $mode
//if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
//if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
$tmpobject = new Hook($db);
if ($tmpobject->ismultientitymanaged) {
$sql.= ' AND t.entity IN ('.getEntity('hook').')';
}
if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
$sql.= " AND t.fk_soc = sc.fk_soc";
}
if ($restrictonsocid && $socid) {
$sql.= " AND t.fk_soc = ".$socid;
}
if ($restrictonsocid && $search_sale > 0) {
// Join for the needed table to filter by sale
$sql.= " AND t.rowid = sc.fk_soc";
}
// Insert sale filter
if ($restrictonsocid && $search_sale > 0) {
$sql .= " AND sc.fk_user = ".$search_sale;
}
if ($sqlfilters) {
if (! DolibarrApi::_checkFilters($sqlfilters)) {
throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
}
$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
$sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0) {
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result) {
$num = $db->num_rows($result);
while ($i < $num) {
$obj = $db->fetch_object($result);
$hook_static = new Hook($db);
if ($hook_static->fetch($obj->rowid)) {
$obj_ret[] = $this->_cleanObjectDatas($hook_static);
}
$i++;
}
} else {
throw new RestException(503, 'Error when retrieve hook list');
}
if (! count($obj_ret)) {
throw new RestException(404, 'No hook found');
}
return $obj_ret;
}
/**
* Create hook object
*
* @param array $request_data Request datas
* @return int ID of hook
*
* @url POST /hook/
*/
public function post($request_data = null)
{
// $debug = '<pre>'.print_r($request_data, true).'</pre>';
// $debug .= '<pre>'.print_r(DolibarrApiAccess::$user->rights->zapier, true).'</pre>';
// mail('frederic.france@free.fr', 'test hook', $debug);
if (! DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401);
}
// Check mandatory fields
$fields = array(
'url',
);
$result = $this->validate($request_data, $fields);
foreach($request_data as $field => $value) {
$this->hook->$field = $value;
}
$this->hook->fk_user = DolibarrApiAccess::$user->id;
// on crée le hook dans la base
if( ! $this->hook->create(DolibarrApiAccess::$user)) {
throw new RestException(500, "Error creating Hook", array_merge(array($this->hook->error), $this->hook->errors));
}
return array(
'id' => $this->hook->id,
);
}
/**
* Update hook
*
* @param int $id Id of hook to update
* @param array $request_data Datas
* @return int
*
* @url PUT /hooks/{id}
*/
/*public function put($id, $request_data = null)
{
if (! DolibarrApiAccess::$user->rights->zapier->write) {
throw new RestException(401);
}
$result = $this->hook->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Hook not found');
}
if( ! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach($request_data as $field => $value) {
if ($field == 'id') {
continue;
}
$this->hook->$field = $value;
}
if ($this->hook->update($id, DolibarrApiAccess::$user) > 0) {
return $this->get($id);
} else {
throw new RestException(500, $this->hook->error);
}
}*/
/**
* Delete hook
*
* @param int $id Hook ID
* @return array
*
* @url DELETE /hook/{id}
*/
public function delete($id)
{
if (! DolibarrApiAccess::$user->rights->zapier->delete) {
throw new RestException(401);
}
$result = $this->hook->fetch($id);
if (! $result) {
throw new RestException(404, 'Hook not found');
}
if (! DolibarrApi::_checkAccessToResource('hook', $this->hook->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (! $this->hook->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when deleting Hook : '.$this->hook->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Hook deleted'
)
);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
/**
* Clean sensible object datas
*
* @param object $object Object to clean
* @return array Array of cleaned object properties
*/
public function _cleanObjectDatas($object)
{
// phpcs:disable
$object = parent::_cleanObjectDatas($object);
/*unset($object->note);
unset($object->address);
unset($object->barcode_type);
unset($object->barcode_type_code);
unset($object->barcode_type_label);
unset($object->barcode_type_coder);*/
return $object;
}
/**
* Validate fields before create or update object
*
* @param array $data Array of data to validate
* @param array $fields Array of fields needed
* @return array
*
* @throws RestException
*/
private function validate($data, $fields)
{
$hook = array();
foreach ($fields as $field) {
if (!isset($data[$field])) {
throw new RestException(400, $field." field missing");
}
$hook[$field] = $data[$field];
}
return $hook;
}
}

View File

@ -0,0 +1,773 @@
<?php
/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/class/hook.class.php
* \ingroup zapier
* \brief This file is a CRUD class file for Hook (Create/Read/Update/Delete)
*/
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
/**
* Class for Hook
*/
class Hook extends CommonObject
{
/**
* @var string ID to identify managed object
*/
public $element = 'hook';
/**
* @var string Name of table without prefix where object is stored
*/
public $table_element = 'zapier_hook';
/**
* @var int Does hook support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
*/
public $ismultientitymanaged = 0;
/**
* @var int Does hook support extrafields ? 0=No, 1=Yes
*/
public $isextrafieldmanaged = 1;
/**
* @var string String with name of icon for hook. Must be the part after the 'object_' into object_hook.png
*/
public $picto = 'hook@zapier';
const STATUS_DRAFT = 0;
const STATUS_VALIDATED = 1;
const STATUS_DISABLED = -1;
/**
* 'type' if the field format ('integer', 'integer:Class:pathtoclass', 'varchar(x)', 'double(24,8)', 'text', 'html', 'datetime', 'timestamp', 'float')
* 'label' the translation key.
* 'enabled' is a condition when the field must be managed.
* 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). Using a negative value means field is not shown by default on list but can be selected for viewing)
* 'noteditable' says if field is not editable (1 or 0)
* 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
* 'default' is a default value for creation (can still be replaced by the global setup of default values)
* 'index' if we want an index in database.
* 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
* 'position' is the sort order of field.
* 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
* 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
* 'css' is the CSS style to use on field. For example: 'maxwidth200'
* 'help' is a string visible as a tooltip on field
* 'comment' is not used. You can store here any text of your choice. It is not used by application.
* 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
* 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
*/
/**
* @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
*/
public $fields = array(
'rowid' => array(
'type' => 'integer',
'label' => 'TechnicalID',
'enabled' => 1,
'visible' => -2,
'noteditable' => 1,
'notnull' => 1,
'index' => 1,
'position' => 1,
'comment' => 'Id',
),
'entity' => array(
'type' => 'integer',
'label' => 'Entity',
'enabled' => 1,
'visible' => 0,
'notnull' => 1,
'default' => 1,
'index' => 1,
'position' => 20,
),
'fk_user' => array(
'type' => 'integer',
'label' => 'UserOwner',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 510,
'foreignkey' => MAIN_DB_PREFIX.'user.rowid',
),
'url' => array(
'type' => 'varchar(255)',
'label' => 'Url',
'enabled' => 1,
'visible' => 1,
'position' => 30,
'searchall' => 1,
'css' => 'minwidth200',
'help' => 'Hook url',
'showoncombobox' => 1,
),
'module' => array(
'type' => 'varchar(128)',
'label' => 'Url',
'enabled' => 1,
'visible' => 1,
'position' => 30,
'searchall' => 1,
'css' => 'minwidth200',
'help' => 'Hook module',
'showoncombobox' => 1,
),
'action' => array(
'type' => 'varchar(128)',
'label' => 'Url',
'enabled' => 1,
'visible' => 1,
'position' => 30,
'searchall' => 1,
'css' => 'minwidth200',
'help' => 'Hook action trigger',
'showoncombobox' => 1,
),
'event' => array(
'type' => 'varchar(255)',
'label' => 'Event',
'enabled' => 1,
'visible' => 1,
'position' => 30,
'searchall' => 1,
'css' => 'minwidth200',
'help' => 'Event',
'showoncombobox' => 1,
),
'date_creation' => array(
'type' => 'datetime',
'label' => 'DateCreation',
'enabled' => 1,
'visible' => -2,
'notnull' => 1,
'position' => 500,
),
'import_key' => array(
'type' => 'varchar(14)',
'label' => 'ImportId',
'enabled' => 1,
'visible' => -2,
'notnull' => -1,
'index' => 0,
'position' => 1000,
),
'status' => array(
'type' => 'integer',
'label' => 'Status',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'default' => 0,
'index' => 1,
'position' => 1000,
'arrayofkeyval' => array(
0 => 'Draft',
1 => 'Active',
-1 => 'Canceled',
),
),
);
/**
* @var int ID
*/
public $rowid;
/**
* @var string Ref
*/
public $ref;
/**
* @var int Entity
*/
public $entity;
/**
* @var string label
*/
public $label;
/**
* @var string amount
*/
public $amount;
/**
* @var int Status
*/
public $status;
/**
* @var integer|string date_creation
*/
public $date_creation;
/**
* @var integer tms
*/
public $tms;
/**
* @var int ID
*/
public $fk_user_creat;
/**
* @var int ID
*/
public $fk_user_modif;
/**
* @var string import_key
*/
public $import_key;
// If this object has a subtable with lines
/**
* @var int Name of subtable line
*/
//public $table_element_line = 'hookdet';
/**
* @var int Field with ID of parent key if this field has a parent
*/
//public $fk_element = 'fk_hook';
/**
* @var int Name of subtable class that manage subtable lines
*/
//public $class_element_line = 'MyObjectline';
/**
* @var array Array of child tables (child tables to delete before deleting a record)
*/
//protected $childtables=array('hookdet');
/**
* @var MyObjectLine[] Array of subtable lines
*/
//public $lines = array();
/**
* Constructor
*
* @param DoliDb $db Database handler
*/
public function __construct(DoliDB $db)
{
global $conf, $langs, $user;
$this->db = $db;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
$this->fields['rowid']['visible']=0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled']=0;
}
// Unset fields that are disabled
foreach($this->fields as $key => $val) {
if (isset($val['enabled']) && empty($val['enabled'])) {
unset($this->fields[$key]);
}
}
// Translate some data of arrayofkeyval
foreach($this->fields as $key => $val) {
if (is_array($this->fields['status']['arrayofkeyval'])) {
foreach($this->fields['status']['arrayofkeyval'] as $key2 => $val2) {
$this->fields['status']['arrayofkeyval'][$key2]=$langs->trans($val2);
}
}
}
}
/**
* Create object into database
*
* @param User $user User that creates
* @param bool $notrigger false=launch triggers after, true=disable triggers
* @return int <0 if KO, Id of created object if OK
*/
public function create(User $user, $notrigger = false)
{
return $this->createCommon($user, $notrigger);
}
/**
* Clone an object into another one
*
* @param User $user User that creates
* @param int $fromid Id of object to clone
* @return mixed New object created, <0 if KO
*/
public function createFromClone(User $user, $fromid)
{
global $langs, $hookmanager, $extrafields;
$error = 0;
dol_syslog(__METHOD__, LOG_DEBUG);
$object = new self($this->db);
$this->db->begin();
// Load source object
$object->fetchCommon($fromid);
// Reset some properties
unset($object->id);
unset($object->fk_user_creat);
unset($object->import_key);
// Clear fields
$object->ref = "copy_of_".$object->ref;
$object->title = $langs->trans("CopyOf")." ".$object->title;
// ...
// Clear extrafields that are unique
if (is_array($object->array_options) && count($object->array_options) > 0) {
$extrafields->fetch_name_optionals_label($this->element);
foreach($object->array_options as $key => $option) {
$shortkey = preg_replace('/options_/', '', $key);
if (! empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
// var_dump($key);
// var_dump($clonedObj->array_options[$key]);
// exit;
unset($object->array_options[$key]);
}
}
}
// Create clone
$object->context['createfromclone'] = 'createfromclone';
$result = $object->createCommon($user);
if ($result < 0) {
$error++;
$this->error = $object->error;
$this->errors = $object->errors;
}
unset($object->context['createfromclone']);
// End
if (!$error) {
$this->db->commit();
return $object;
} else {
$this->db->rollback();
return -1;
}
}
/**
* Load object in memory from the database
*
* @param int $id Id object
* @param string $ref Ref
* @return int <0 if KO, 0 if not found, >0 if OK
*/
public function fetch($id, $ref = null)
{
$result = $this->fetchCommon($id, $ref);
if ($result > 0 && ! empty($this->table_element_line)) {
$this->fetchLines();
}
return $result;
}
/**
* Load object lines in memory from the database
*
* @return int <0 if KO, 0 if not found, >0 if OK
*/
/*public function fetchLines()
{
$this->lines=array();
// Load lines with object MyObjectLine
return count($this->lines)?1:0;
}*/
/**
* Load list of objects in memory from the database.
*
* @param string $sortorder Sort Order
* @param string $sortfield Sort field
* @param int $limit limit
* @param int $offset Offset
* @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
* @param string $filtermode Filter mode (AND or OR)
* @return array|int int <0 if KO, array of pages if OK
*/
public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
{
global $conf;
dol_syslog(__METHOD__, LOG_DEBUG);
$records=array();
$sql = 'SELECT';
$sql .= ' t.rowid';
// TODO Get all fields
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
$sql .= ' WHERE t.entity = '.$conf->entity;
// Manage filter
$sqlwhere = array();
if (count($filter) > 0) {
foreach ($filter as $key => $value) {
if ($key=='t.rowid') {
$sqlwhere[] = $key . '='. $value;
} elseif (strpos($key, 'date') !== false) {
$sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
} elseif ($key=='customsql') {
$sqlwhere[] = $value;
} else {
$sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
}
}
}
if (count($sqlwhere) > 0) {
$sql .= ' AND (' . implode(' '.$filtermode.' ', $sqlwhere).')';
}
if (!empty($sortfield)) {
$sql .= $this->db->order($sortfield, $sortorder);
}
if (!empty($limit)) {
$sql .= ' ' . $this->db->plimit($limit, $offset);
}
$resql = $this->db->query($sql);
if ($resql) {
$num = $this->db->num_rows($resql);
while ($obj = $this->db->fetch_object($resql)) {
$record = new self($this->db);
$record->id = $obj->rowid;
// TODO Get other fields
//var_dump($record->id);
$records[$record->id] = $record;
}
$this->db->free($resql);
return $records;
} else {
$this->errors[] = 'Error ' . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
return -1;
}
}
/**
* Update object into database
*
* @param User $user User that modifies
* @param bool $notrigger false=launch triggers after, true=disable triggers
* @return int <0 if KO, >0 if OK
*/
public function update(User $user, $notrigger = false)
{
return $this->updateCommon($user, $notrigger);
}
/**
* Delete object in database
*
* @param User $user User that deletes
* @param bool $notrigger false=launch triggers after, true=disable triggers
* @return int <0 if KO, >0 if OK
*/
public function delete(User $user, $notrigger = false)
{
return $this->deleteCommon($user, $notrigger);
//return $this->deleteCommon($user, $notrigger, 1);
}
/**
* Return a link to the object card (with optionaly the picto)
*
* @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
* @param string $option On what the link point to ('nolink', ...)
* @param int $notooltip 1=Disable tooltip
* @param string $morecss Add more css on link
* @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
* @return string String with URL
*/
public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
{
global $db, $conf, $langs, $hookmanager, $action;
global $dolibarr_main_authentication, $dolibarr_main_demo;
global $menumanager;
if (! empty($conf->dol_no_mouse_hover)) {
// Force disable tooltips
$notooltip=1;
}
$result = '';
$label = '<u>' . $langs->trans("Hook") . '</u>';
$label.= '<br>';
$label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
$url = dol_buildpath('/zapier/hook_card.php', 1).'?id='.$this->id;
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';
}
}
$linkclose='';
if (empty($notooltip)) {
if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
$label=$langs->trans("ShowMyObject");
$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
}
$linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
/*
$hookmanager->initHooks(array('hookdao'));
$parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint;
*/
} else {
$linkclose = ($morecss?' class="'.$morecss.'"':'');
}
$linkstart = '<a href="'.$url.'"';
$linkstart.=$linkclose.'>';
$linkend='</a>';
$result .= $linkstart;
if ($withpicto) {
$result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
}
if ($withpicto != 2) {
$result.= $this->ref;
}
$result .= $linkend;
//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
$hookmanager->initHooks(array('hookdao'));
$parameters = array(
'id' => $this->id,
'getnomurl' => $result,
);
// Note that $action and $object may have been modified by some hooks
$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);
if ($reshook > 0) {
$result = $hookmanager->resPrint;
} else {
$result .= $hookmanager->resPrint;
}
return $result;
}
/**
* Return label of the 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
* @return string Label of status
*/
public function getLibStatut($mode = 0)
{
return $this->LibStatut($this->status, $mode);
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Return the status
*
* @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
* @return string Label of status
*/
public function LibStatut($status, $mode = 0)
{
// phpcs:enable
if (empty($this->labelstatus)) {
global $langs;
//$langs->load("zapier@zapier");
$this->labelstatus[1] = $langs->trans('Enabled');
$this->labelstatus[0] = $langs->trans('Disabled');
}
if ($mode == 0) {
return $this->labelstatus[$status];
} elseif ($mode == 1) {
return $this->labelstatus[$status];
} elseif ($mode == 2) {
if ($status == 1) {
return img_picto($this->labelstatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
} elseif ($status == 0) {
return img_picto($this->labelstatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
}
} elseif ($mode == 3) {
if ($status == 1) return img_picto($this->labelstatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle');
elseif ($status == 0) return img_picto($this->labelstatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle');
} elseif ($mode == 4) {
if ($status == 1) return img_picto($this->labelstatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
elseif ($status == 0) return img_picto($this->labelstatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle').' '.$this->labelstatus[$status];
} elseif ($mode == 5) {
if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle');
elseif ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle');
} elseif ($mode == 6) {
if ($status == 1) {
return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status], 'statut4', '', false, 0, 0, '', 'valignmiddle');
} elseif ($status == 0) {
return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status], 'statut5', '', false, 0, 0, '', 'valignmiddle');
}
}
}
/**
* Load the info information in the object
*
* @param int $id Id of object
* @return void
*/
public function info($id)
{
$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
$sql.= ' fk_user_creat, fk_user_modif';
$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql.= ' WHERE t.rowid = '.$id;
$result=$this->db->query($sql);
if ($result) {
if ($this->db->num_rows($result)) {
$obj = $this->db->fetch_object($result);
$this->id = $obj->rowid;
if ($obj->fk_user_author) {
$cuser = new User($this->db);
$cuser->fetch($obj->fk_user_author);
$this->user_creation = $cuser;
}
if ($obj->fk_user_valid) {
$vuser = new User($this->db);
$vuser->fetch($obj->fk_user_valid);
$this->user_validation = $vuser;
}
if ($obj->fk_user_cloture) {
$cluser = new User($this->db);
$cluser->fetch($obj->fk_user_cloture);
$this->user_cloture = $cluser;
}
$this->date_creation = $this->db->jdate($obj->datec);
$this->date_modification = $this->db->jdate($obj->datem);
$this->date_validation = $this->db->jdate($obj->datev);
}
$this->db->free($result);
} else {
dol_print_error($this->db);
}
}
/**
* Initialise object with example values
* Id must be 0 if object instance is a specimen
*
* @return void
*/
public function initAsSpecimen()
{
$this->initAsSpecimenCommon();
}
/**
* Action executed by scheduler
* CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
*
* @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
*/
//public function doScheduledJob($param1, $param2, ...)
public function doScheduledJob()
{
global $conf, $langs;
//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
$error = 0;
$this->output = '';
$this->error='';
dol_syslog(__METHOD__, LOG_DEBUG);
$now = dol_now();
$this->db->begin();
// ...
$this->db->commit();
return $error;
}
}
/**
* Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects.
*/
/*
class MyObjectLine
{
// @var int ID
public $id;
// @var mixed Sample line property 1
public $prop1;
// @var mixed Sample line property 2
public $prop2;
}
*/

View File

@ -0,0 +1,261 @@
<?php
/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/myobject_agenda.php
* \ingroup mymodule
* \brief Page of MyObject events
*/
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
dol_include_once('/mymodule/class/myobject.class.php');
dol_include_once('/mymodule/lib/mymodule_myobject.lib.php');
// Load translation files required by the page
$langs->loadLangs(array("mymodule@mymodule","other"));
// Get parameters
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'alpha');
$cancel = GETPOST('cancel', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha');
if (GETPOST('actioncode', 'array'))
{
$actioncode=GETPOST('actioncode', 'array', 3);
if (! count($actioncode)) $actioncode='0';
}
else
{
$actioncode=GETPOST("actioncode", "alpha", 3)?GETPOST("actioncode", "alpha", 3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
}
$search_agenda_label=GETPOST('search_agenda_label');
// Security check - Protection if external user
//if ($user->societe_id > 0) access_forbidden();
//if ($user->societe_id > 0) $socid = $user->societe_id;
//$result = restrictedArea($user, 'mymodule', $id);
$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortfield) $sortfield='a.datep,a.id';
if (! $sortorder) $sortorder='DESC';
// Initialize technical objects
$object=new MyObject($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('myobjectagenda','globalcard')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('myobject');
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity] . "/" . $object->id;
/*
* Actions
*/
$parameters=array('id'=>$socid);
$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
// Cancel
if (GETPOST('cancel', 'alpha') && ! empty($backtopage))
{
header("Location: ".$backtopage);
exit;
}
// Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
{
$actioncode='';
$search_agenda_label='';
}
}
/*
* View
*/
$contactstatic = new Contact($db);
$form = new Form($db);
if ($object->id > 0)
{
$title=$langs->trans("Agenda");
//if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
$help_url = '';
llxHeader('', $title, $help_url);
if (! empty($conf->notification->enabled)) $langs->load("mails");
$head = myobjectPrepareHead($object);
dol_fiche_head($head, 'agenda', $langs->trans("MyObject"), -1, 'myobject@mymodule');
// Object card
// ------------------------------------------------------------
$linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
$morehtmlref='<div class="refidno">';
/*
// Ref customer
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
// Project
if (! empty($conf->projet->enabled))
{
$langs->load("projects");
$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
if ($user->rights->mymodule->creer)
{
if ($action != 'classify')
//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
$morehtmlref.=' : ';
if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>';
} else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
}
} else {
if (! empty($object->fk_project)) {
$proj = new Project($db);
$proj->fetch($object->fk_project);
$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
$morehtmlref.=$proj->ref;
$morehtmlref.='</a>';
} else {
$morehtmlref.='';
}
}
}*/
$morehtmlref.='</div>';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
$object->info($object->id);
print dol_print_object_info($object, 1);
print '</div>';
dol_fiche_end();
// Actions buttons
$objthirdparty=$object;
$objcon=new stdClass();
$out='';
$permok=$user->rights->agenda->myactions->create;
if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok)
{
//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
if (get_class($objthirdparty) == 'Societe') $out.='&amp;socid='.$objthirdparty->id;
$out.=(! empty($objcon->id)?'&amp;contactid='.$objcon->id:'').'&amp;backtopage=1&amp;percentage=-1';
//$out.=$langs->trans("AddAnAction").' ';
//$out.=img_picto($langs->trans("AddAnAction"),'filenew');
//$out.="</a>";
}
print '<div class="tabsAction">';
if (! empty($conf->agenda->enabled))
{
if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create))
{
print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>';
}
else
{
print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>';
}
}
print '</div>';
if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) ))
{
$param='&socid='.$socid;
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
print load_fiche_titre($langs->trans("ActionsOnMyObject"), '', '');
// List of all actions
$filters=array();
$filters['search_agenda_label']=$search_agenda_label;
// TODO Replace this with same code than into list.php
//show_actions_done($conf,$langs,$db,$object,null,0,$actioncode, '', $filters, $sortfield, $sortorder);
}
}
// End of page
llxFooter();
$db->close();

471
htdocs/zapier/hook_card.php Normal file
View File

@ -0,0 +1,471 @@
<?php
/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/myobject_card.php
* \ingroup mymodule
* \brief Page to create/edit/view myobject
*/
//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user
//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc
//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs
//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters
//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters
//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too.
//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value
//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler
//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
dol_include_once('/mymodule/class/myobject.class.php');
dol_include_once('/mymodule/lib/mymodule_myobject.lib.php');
// Load translation files required by the page
$langs->loadLangs(array("mymodule@mymodule","other"));
// Get parameters
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha');
$cancel = GETPOST('cancel', 'aZ09');
$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'myobjectcard'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha');
// Initialize technical objects
$object=new MyObject($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('myobjectcard','globalcard')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Initialize array of search criterias
$search_all=trim(GETPOST("search_all", 'alpha'));
$search=array();
foreach($object->fields as $key => $val)
{
if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha');
}
if (empty($action) && empty($id) && empty($ref)) $action='view';
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
// Security check - Protection if external user
//if ($user->societe_id > 0) access_forbidden();
//if ($user->societe_id > 0) $socid = $user->societe_id;
//$isdraft = (($object->statut == MyObject::STATUS_DRAFT) ? 1 : 0);
//$result = restrictedArea($user, 'mymodule', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
/*
* Actions
*
* Put here all code to do according to value of "action" parameter
*/
$parameters=array();
$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
$error=0;
$permissiontoadd = $user->rights->mymodule->write;
$permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0);
$backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1);
if (empty($backtopage)) {
if (empty($id)) $backtopage = $backurlforlist;
else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__');
}
$triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record
// Actions cancel, add, update, delete or clone
include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
// Actions when linking object each other
include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
// Actions when printing a doc from card
include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
// Actions to send emails
$trigger_name='MYOBJECT_SENTBYMAIL';
$autocopy='MAIN_MAIL_AUTOCOPY_MYOBJECT_TO';
$trackid='myobject'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
}
/*
* View
*
* Put here all code to build page
*/
$form=new Form($db);
$formfile=new FormFile($db);
llxHeader('', 'MyObject', '');
// Example : Adding jquery code
print '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
function init_myfunc()
{
jQuery("#myid").removeAttr(\'disabled\');
jQuery("#myid").attr(\'disabled\',\'disabled\');
}
init_myfunc();
jQuery("#mybutton").click(function() {
init_myfunc();
});
});
</script>';
// Part to create
if ($action == 'create')
{
print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("MyObject")));
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
dol_fiche_head(array(), '');
print '<table class="border centpercent">'."\n";
// Common attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php';
// Other attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php';
print '</table>'."\n";
dol_fiche_end();
print '<div class="center">';
print '<input type="submit" class="button" name="add" value="'.dol_escape_htmltag($langs->trans("Create")).'">';
print '&nbsp; ';
print '<input type="'.($backtopage?"submit":"button").'" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'"'.($backtopage?'':' onclick="javascript:history.go(-1)"').'>'; // Cancel for create does not post form if we don't know the backtopage
print '</div>';
print '</form>';
}
// Part to edit record
if (($id || $ref) && $action == 'edit')
{
print load_fiche_titre($langs->trans("MyObject"));
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
print '<input type="hidden" name="id" value="'.$object->id.'">';
dol_fiche_head();
print '<table class="border centpercent">'."\n";
// Common attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php';
// Other attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php';
print '</table>';
dol_fiche_end();
print '<div class="center"><input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">';
print ' &nbsp; <input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
print '</div>';
print '</form>';
}
// Part to show record
if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create')))
{
$res = $object->fetch_optionals();
$head = myobjectPrepareHead($object);
dol_fiche_head($head, 'card', $langs->trans("MyObject"), -1, 'myobject@mymodule');
$formconfirm = '';
// Confirmation to delete
if ($action == 'delete')
{
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1);
}
// Clone confirmation
if ($action == 'clone') {
// Create an array for form
$formquestion = array();
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneMyObject', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
}
// Confirmation of action xxxx
if ($action == 'xxx')
{
$formquestion=array();
/*
$forcecombo=0;
if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
$formquestion = array(
// 'text' => $langs->trans("ConfirmClone"),
// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
// array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
);
*/
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220);
}
// Call Hook formConfirm
$parameters = array('lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
// Print form confirm
print $formconfirm;
// Object card
// ------------------------------------------------------------
$linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
$morehtmlref='<div class="refidno">';
/*
// Ref bis
$morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mymodule->creer, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->mymodule->creer, 'string', '', null, null, '', 1);
// Thirdparty
$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1);
// Project
if (! empty($conf->projet->enabled))
{
$langs->load("projects");
$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
if ($user->rights->mymodule->write)
{
if ($action != 'classify')
$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>';
} else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
}
} else {
if (! empty($object->fk_project)) {
$proj = new Project($db);
$proj->fetch($object->fk_project);
$morehtmlref.=$proj->getNomUrl();
} else {
$morehtmlref.='';
}
}
}
*/
$morehtmlref.='</div>';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
print '<div class="fichecenter">';
print '<div class="fichehalfleft">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent">'."\n";
// Common attributes
//$keyforbreak='fieldkeytoswithonsecondcolumn';
include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php';
// Other attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
print '</table>';
print '</div>';
print '</div>';
print '<div class="clearboth"></div><br>';
dol_fiche_end();
// Buttons for actions
if ($action != 'presend' && $action != 'editline') {
print '<div class="tabsAction">'."\n";
$parameters=array();
$reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
// Send
print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n";
// Modify
if ($user->rights->mymodule->write)
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
}
else
{
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
}
// Clone
if ($user->rights->mymodule->write)
{
print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&amp;socid=' . $object->socid . '&amp;action=clone&amp;object=order">' . $langs->trans("ToClone") . '</a></div>';
}
/*
if ($user->rights->mymodule->write)
{
if ($object->status == 1)
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a>'."\n";
}
else
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a>'."\n";
}
}
*/
if ($user->rights->mymodule->delete)
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a>'."\n";
}
else
{
print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
}
}
print '</div>'."\n";
}
// Select mail models is same action as presend
if (GETPOST('modelselected')) {
$action = 'presend';
}
if ($action != 'presend')
{
print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre
// Documents
/*$objref = dol_sanitizeFileName($object->ref);
$relativepath = $comref . '/' . $comref . '.pdf';
$filedir = $conf->mymodule->dir_output . '/' . $objref;
$urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
$genallowed = $user->rights->mymodule->read; // If you can read, you can build the PDF to read content
$delallowed = $user->rights->mymodule->create; // If you can create/edit, you can remove a file on card
print $formfile->showdocuments('mymodule', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
*/
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject'));
$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
print '</div><div class="fichehalfright"><div class="ficheaddleft">';
$MAXEVENT = 10;
$morehtmlright = '<a href="'.dol_buildpath('/mymodule/myobject_info.php', 1).'?id='.$object->id.'">';
$morehtmlright.= $langs->trans("SeeAll");
$morehtmlright.= '</a>';
// List of actions on element
include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
$formactions = new FormActions($db);
$somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT, '', $morehtmlright);
print '</div></div></div>';
}
//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
llxFooter();
$db->close();

View File

@ -0,0 +1,166 @@
<?php
/* Copyright (C) 2007-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/myobject_document.php
* \ingroup mymodule
* \brief Tab for documents linked to MyObject
*/
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
dol_include_once('/mymodule/class/myobject.class.php');
dol_include_once('/mymodule/lib/mymodule_myobject.lib.php');
// Load translation files required by the page
$langs->loadLangs(array("mymodule@mymodule","companies","other","mails"));
$action=GETPOST('action', 'aZ09');
$confirm=GETPOST('confirm');
$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
$ref = GETPOST('ref', 'alpha');
// Security check - Protection if external user
//if ($user->societe_id > 0) access_forbidden();
//if ($user->societe_id > 0) $socid = $user->societe_id;
//$result = restrictedArea($user, 'mymodule', $id);
// Get parameters
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOST("page", 'int');
if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1
$offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortorder) $sortorder="ASC";
if (! $sortfield) $sortfield="name";
//if (! $sortfield) $sortfield="position_name";
// Initialize technical objects
$object=new MyObject($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('myobjectdocument','globalcard')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('myobject');
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
//if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/myobject/" . dol_sanitizeFileName($object->id);
if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/myobject/" . dol_sanitizeFileName($object->ref);
/*
* Actions
*/
include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
/*
* View
*/
$form = new Form($db);
$title=$langs->trans("MyObject").' - '.$langs->trans("Files");
$help_url='';
//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
llxHeader('', $title, $help_url);
if ($object->id)
{
/*
* Show tabs
*/
$head = myobjectPrepareHead($object);
dol_fiche_head($head, 'document', $langs->trans("MyObject"), -1, 'myobject@mymodule');
// Build file list
$filearray=dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC), 1);
$totalsize=0;
foreach($filearray as $key => $file)
{
$totalsize+=$file['size'];
}
// Object card
// ------------------------------------------------------------
$linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent">';
// Number of files
print '<tr><td class="titlefield">'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>';
// Total size
print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>';
print '</table>';
print '</div>';
dol_fiche_end();
$modulepart = 'mymodule';
//$permission = $user->rights->mymodule->create;
$permission = 1;
//$permtoedit = $user->rights->mymodule->create;
$permtoedit = 1;
$param = '&id=' . $object->id;
//$relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->id).'/';
$relativepathwithnofile='myobject/' . dol_sanitizeFileName($object->ref).'/';
include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
}
else
{
accessforbidden('', 0, 0);
}
// End of page
llxFooter();
$db->close();

642
htdocs/zapier/hook_list.php Normal file
View File

@ -0,0 +1,642 @@
<?php
/* Copyright (C) 2007-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/hook_list.php
* \ingroup mymodule
* \brief List page for hook
*/
//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user
//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc
//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs
//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters
//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters
//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session)
//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value
//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler
//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
//if (! defined("XFRAMEOPTIONS_ALLOWALL")) define('XFRAMEOPTIONS_ALLOWALL',1); // Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL'
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once __DIR__.'/class/hook.class.php';
// Load translation files required by the page
$langs->loadLangs(array("mymodule@mymodule","other"));
// The action 'add', 'create', 'edit', 'update', 'view', ...
$action = GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view';
// The bulk action (combo box choice into lists)
$massaction = GETPOST('massaction', 'alpha');
$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
$contextpage = GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'hooklist'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$id = GETPOST('id', 'int');
// Load variable for pagination
$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
$sortfield = GETPOST('sortfield', 'alpha');
$sortorder = GETPOST('sortorder', 'alpha');
$page = GETPOST('page', 'int');
if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
// If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
$page = 0;
}
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
//if (! $sortfield) $sortfield="p.date_fin";
//if (! $sortorder) $sortorder="DESC";
// Initialize technical objects
$object = new Hook($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction = $conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
// Note that conf->hooks_modules contains array
$hookmanager->initHooks(array('hooklist'));
// Fetch optionals attributes and labels
// Load $extrafields->attributes['hook']
$extralabels = $extrafields->fetch_name_optionals_label('hook');
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST)
if (! $sortfield) {
// Set here default search field. By default 1st field in definition.
$sortfield="t.".key($object->fields);
}
if (! $sortorder) {
$sortorder="ASC";
}
// Security check
$socid=0;
if ($user->societe_id > 0) {
// Protection if external user
//$socid = $user->societe_id;
accessforbidden();
}
//$result = restrictedArea($user, 'mymodule', $id, '');
// Initialize array of search criterias
$search_all=trim(GETPOST("search_all", 'alpha'));
$search=array();
foreach($object->fields as $key => $val) {
if (GETPOST('search_'.$key, 'alpha')) $search[$key]=GETPOST('search_'.$key, 'alpha');
}
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array();
foreach($object->fields as $key => $val) {
if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label'];
}
// Definition of fields for list
$arrayfields=array();
foreach($object->fields as $key => $val) {
// If $val['visible']==0, then we never show the field
if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']);
}
// Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
if (! empty($extrafields->attributes[$object->table_element]['list'][$key]))
$arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
}
}
$object->fields = dol_sort_array($object->fields, 'position');
$arrayfields = dol_sort_array($arrayfields, 'position');
/*
* Actions
*/
if (GETPOST('cancel', 'alpha')) {
$action='list';
$massaction='';
}
if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction='';
}
$parameters=array();
$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook)) {
// Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') ||GETPOST('button_removefilter', 'alpha')) {
// All tests are required to be compatible with all browsers
foreach($object->fields as $key => $val) {
$search[$key]='';
}
$toselect='';
$search_array_options=array();
}
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
$massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation
}
// Mass actions
$objectclass='Hook';
$objectlabel='Hook';
$permtoread = $user->rights->mymodule->read;
$permtodelete = $user->rights->mymodule->delete;
$uploaddir = $conf->mymodule->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}
/*
* View
*/
$form=new Form($db);
$now=dol_now();
//$help_url="EN:Module_Hook|FR:Module_Hook_FR|ES:Módulo_Hook";
$help_url='';
$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Hooks"));
// Build and execute select
// --------------------------------------------------------------------
$sql = 'SELECT ';
foreach($object->fields as $key => $val) {
$sql.='t.'.$key.', ';
}
// 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.', ' : '');
}
}
// Add fields from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql=preg_replace('/, $/', '', $sql);
$sql.= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
if ($object->ismultientitymanaged == 1) {
$sql.= " WHERE t.entity IN (".getEntity($object->element).")";
} else {
$sql.=" WHERE 1 = 1";
}
foreach($search as $key => $val) {
if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0);
if ($search[$key] != '') {
$sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search));
}
}
if ($search_all) {
$sql.= natural_search(array_keys($fieldstosearchall), $search_all);
}
// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
/* If a group by is required
$sql.= " GROUP BY "
foreach($object->fields as $key => $val)
{
$sql.='t.'.$key.', ';
}
// 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.', ' : '');
// Add where from hooks
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook
$sql.=$hookmanager->resPrint;
$sql=preg_replace('/, $/','', $sql);
*/
$sql.=$db->order($sortfield, $sortorder);
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql);
if (($page * $limit) > $nbtotalofrecords) {
// if total of record found is smaller than page * limit, goto and load page 0
$page = 0;
$offset = 0;
}
}
// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
$num = $nbtotalofrecords;
} else {
$sql.= $db->plimit($limit+1, $offset);
$resql=$db->query($sql);
if (! $resql) {
dol_print_error($db);
exit;
}
$num = $db->num_rows($resql);
}
// Direct jump if only one record found
if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) {
$obj = $db->fetch_object($resql);
$id = $obj->rowid;
header("Location: ".dol_buildpath('/zapierfordolibarr/hook_card.php', 1).'?id='.$id);
exit;
}
// Output page
// --------------------------------------------------------------------
llxHeader('', $title, $help_url);
// Example : Adding jquery code
print '<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
function init_myfunc()
{
jQuery("#myid").removeAttr(\'disabled\');
jQuery("#myid").attr(\'disabled\',\'disabled\');
}
init_myfunc();
jQuery("#mybutton").click(function() {
init_myfunc();
});
});
</script>';
$arrayofselected=is_array($toselect)?$toselect:array();
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
foreach($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach($search[$key] as $skey) {
$param.='&search_'.$key.'[]='.urlencode($skey);
}
} else {
$param.= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
// List of mass actions available
$arrayofmassactions = array(
//'presend'=>$langs->trans("SendByMail"),
//'builddoc'=>$langs->trans("PDFMerge"),
);
if ($user->rights->mymodule->delete) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
$newcardbutton='';
//if ($user->rights->mymodule->creer)
//{
$newcardbutton='<a class="butActionNew" href="hook_card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']).'"><span class="valignmiddle text-plus-circle">'.$langs->trans('New').'</span>';
$newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
$newcardbutton.= '</a>';
//}
//else
//{
// $newcardbutton='<a class="butActionNewRefused" href="#"><span class="valignmiddle text-plus-circle">'.$langs->trans('New').'</span>;
// $newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
// $newcardbutton.= '</a>';
//}
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, $newcardbutton, '', $limit);
// Add code for pre mass action (confirmation or email presend form)
$topicmail="SendHookRef";
$modelmail="hook";
$objecttmp=new Hook($db);
$trackid='xxxx'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($sall) {
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>';
}
$moreforfilter = '';
/*$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
$moreforfilter.= '</div>';*/
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
else $moreforfilter = $hookmanager->resPrint;
if (! empty($moreforfilter)) {
print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter;
print '</div>';
}
$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
// Fields title search
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
foreach($object->fields as $key => $val) {
$cssforfield='';
if (in_array($val['type'], array('date','datetime','timestamp'))) {
$cssforfield.=($cssforfield?' ':'').'center';
}
if (in_array($val['type'], array('timestamp'))) {
$cssforfield.=($cssforfield?' ':'').'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) {
$cssforfield.=($cssforfield?' ':'').'right';
}
if ($key == 'status') {
$cssforfield.=($cssforfield?' ':'').'center';
}
if (! empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield?' '.$cssforfield:'').'"><input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'"></td>';
}
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields);
$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action column
print '<td class="liste_titre right">';
$searchpicto=$form->showFilterButtons();
print $searchpicto;
print '</td>';
print '</tr>'."\n";
// Fields title label
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
foreach($object->fields as $key => $val) {
$cssforfield='';
if (in_array($val['type'], array('date','datetime','timestamp'))) $cssforfield.=($cssforfield?' ':'').'center';
if (in_array($val['type'], array('timestamp'))) $cssforfield.=($cssforfield?' ':'').'nowrap';
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield.=($cssforfield?' ':'').'right';
if ($key == 'status') {
$cssforfield.=($cssforfield?' ':'').'center';
}
if (! empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield?'class="'.$cssforfield.'"':''), $sortfield, $sortorder, ($cssforfield?$cssforfield.' ':''))."\n";
}
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields
$parameters = array(
'arrayfields' => $arrayfields,
'param' => $param,
'sortfield' => $sortfield,
'sortorder' => $sortorder,
);
$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action column
print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
print '</tr>'."\n";
// Detect if we need a fetch on each output line
$needToFetchEachLine=0;
if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
if (preg_match('/\$object/', $val)) {
// There is at least one compute field that use $object
$needToFetchEachLine++;
}
}
}
// Loop on record
// --------------------------------------------------------------------
$i=0;
$totalarray=array();
while ($i < min($num, $limit)) {
$obj = $db->fetch_object($resql);
if (empty($obj)) {
break; // Should not happen
}
// Store properties in $object
$object->id = $obj->rowid;
foreach($object->fields as $key => $val) {
if (isset($obj->$key)) $object->$key = $obj->$key;
}
// Show here line of result
print '<tr class="oddeven">';
foreach($object->fields as $key => $val) {
$cssforfield='';
if (in_array($val['type'], array('date','datetime','timestamp'))) {
$cssforfield.=($cssforfield?' ':'').'center';
} elseif ($key == 'status') {
$cssforfield.=($cssforfield?' ':'').'center';
}
if (in_array($val['type'], array('timestamp'))) $cssforfield.=($cssforfield?' ':'').'nowrap';
elseif ($key == 'ref') $cssforfield.=($cssforfield?' ':'').'nowrap';
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real'))) $cssforfield.=($cssforfield?' ':'').'right';
if (! empty($arrayfields['t.'.$key]['checked'])) {
print '<td';
if ($cssforfield || $val['css']) print ' class="';
print $cssforfield;
if ($cssforfield && $val['css']) print ' ';
print $val['css'];
if ($cssforfield || $val['css']) print '"';
print '>';
if ($key == 'status') print $object->getLibStatut(5);
elseif (in_array($val['type'], array('date','datetime','timestamp'))) print $object->showOutputField($val, $key, $db->jdate($obj->$key), '');
else print $object->showOutputField($val, $key, $obj->$key, '');
print '</td>';
if (! $i) $totalarray['nbfield']++;
if (! empty($val['isameasure']))
{
if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key;
$totalarray['val']['t.'.$key] += $obj->$key;
}
}
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
// Fields from hook
$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
$reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action column
print '<td class="nowrap center">';
if ($massactionbutton || $massaction) {
// If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected=0;
if (in_array($obj->rowid, $arrayofselected)) $selected=1;
print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
}
print '</td>';
if (! $i) $totalarray['nbfield']++;
print '</tr>';
$i++;
}
// Show total line
if (isset($totalarray['pos'])) {
print '<tr class="liste_total">';
$i=0;
while ($i < $totalarray['nbfield']) {
$i++;
if (! empty($totalarray['pos'][$i])) {
print '<td class="right">'.price($totalarray['val'][$totalarray['pos'][$i]]).'</td>';
} else {
if ($i == 1) {
if ($num < $limit) {
print '<td class="left">'.$langs->trans("Total").'</td>';
} else {
print '<td class="left">'.$langs->trans("Totalforthispage").'</td>';
}
} else {
print '<td></td>';
}
}
}
print '</tr>';
}
// If no record found
if ($num == 0) {
$colspan=1;
foreach($arrayfields as $key => $val) {
if (! empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
}
$db->free($resql);
$parameters = array(
'arrayfields' => $arrayfields,
'sql' => $sql,
);
$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '</table>'."\n";
print '</div>'."\n";
print '</form>'."\n";
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
$hidegeneratedfilelistifempty=1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty=0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db);
// Show list of available documents
$urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
$urlsource.=str_replace('&amp;', '&', $param);
$filedir=$diroutputmassaction;
$genallowed=$user->rights->mymodule->read;
$delallowed=$user->rights->mymodule->create;
print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
}
// End of page
llxFooter();
$db->close();

164
htdocs/zapier/hook_note.php Normal file
View File

@ -0,0 +1,164 @@
<?php
/* Copyright (C) 2007-2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/myobject_note.php
* \ingroup mymodule
* \brief Car with notes on MyObject
*/
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");
dol_include_once('/mymodule/class/myobject.class.php');
dol_include_once('/mymodule/lib/mymodule_myobject.lib.php');
// Load translation files required by the page
$langs->loadLangs(array("mymodule@mymodule","companies"));
// Get parameters
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'alpha');
$cancel = GETPOST('cancel', 'aZ09');
$backtopage = GETPOST('backtopage', 'alpha');
// Initialize technical objects
$object=new MyObject($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction=$conf->mymodule->dir_output . '/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('myobjectnote','globalcard')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
$extralabels = $extrafields->fetch_name_optionals_label('myobject');
// Security check - Protection if external user
//if ($user->societe_id > 0) access_forbidden();
//if ($user->societe_id > 0) $socid = $user->societe_id;
//$result = restrictedArea($user, 'mymodule', $id);
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
if ($id > 0 || ! empty($ref)) $upload_dir = $conf->mymodule->multidir_output[$object->entity] . "/" . $object->id;
$permissionnote=1;
//$permissionnote=$user->rights->mymodule->creer; // Used by the include of actions_setnotes.inc.php
/*
* Actions
*/
include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
/*
* View
*/
$form = new Form($db);
//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes';
$help_url='';
llxHeader('', $langs->trans('MyObject'), $help_url);
if ($id > 0 || ! empty($ref))
{
$object->fetch_thirdparty();
$head = myobjectPrepareHead($object);
dol_fiche_head($head, 'note', $langs->trans("MyObject"), -1, 'myobject@mymodule');
// Object card
// ------------------------------------------------------------
$linkback = '<a href="' .dol_buildpath('/mymodule/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
$morehtmlref='<div class="refidno">';
/*
// Ref customer
$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
// Thirdparty
$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
// Project
if (! empty($conf->projet->enabled))
{
$langs->load("projects");
$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
if ($user->rights->mymodule->creer)
{
if ($action != 'classify')
//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
$morehtmlref.=' : ';
if ($action == 'classify') {
//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
$morehtmlref.='<input type="hidden" name="action" value="classin">';
$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
$morehtmlref.='</form>';
} else {
$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
}
} else {
if (! empty($object->fk_project)) {
$proj = new Project($db);
$proj->fetch($object->fk_project);
$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
$morehtmlref.=$proj->ref;
$morehtmlref.='</a>';
} else {
$morehtmlref.='';
}
}
}*/
$morehtmlref.='</div>';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
$cssclass="titlefield";
include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
print '</div>';
dol_fiche_end();
}
// End of page
llxFooter();
$db->close();

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 360 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 683 B

View File

@ -0,0 +1,58 @@
<?php
/* Copyright (C) 2019 Frédéric FRANCE <frederic.france@free.fr>
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file zapier/lib/zapier.lib.php
* \ingroup zapier
* \brief Library files with common functions for ZapierForDolibarr
*/
/**
* Prepare admin pages header
*
* @return array
*/
function zapierAdminPrepareHead()
{
global $langs, $conf;
$langs->load("zapier@zapier");
$h = 0;
$head = array();
$head[$h][0] = dol_buildpath("/zapier/admin/setup.php", 1);
$head[$h][1] = $langs->trans("Settings");
$head[$h][2] = 'settings';
$h++;
$head[$h][0] = dol_buildpath("/zapier/admin/about.php", 1);
$head[$h][1] = $langs->trans("About");
$head[$h][2] = 'about';
$h++;
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
//$this->tabs = array(
// 'entity:+tabname:Title:@zapier:/zapier/mypage.php?id=__ID__'
//); // to add new tab
//$this->tabs = array(
// 'entity:-tabname:Title:@zapier:/zapier/mypage.php?id=__ID__'
//); // to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'zapier');
return $head;
}

View File

@ -0,0 +1,83 @@
<?php
/* Copyright (C) ---Put here your own copyright and developer email---
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/modulebuilder/template/lib/mymodule_myobject.lib.php
* \ingroup mymodule
* \brief Library files with common functions for MyObject
*/
/**
* Prepare array of tabs for MyObject
*
* @param MyObject $object MyObject
* @return array Array of tabs
*/
function myobjectPrepareHead($object)
{
global $db, $langs, $conf;
$langs->load("mymodule@mymodule");
$h = 0;
$head = array();
$head[$h][0] = dol_buildpath("/mymodule/myobject_card.php", 1).'?id='.$object->id;
$head[$h][1] = $langs->trans("Card");
$head[$h][2] = 'card';
$h++;
if (isset($object->fields['note_public']) || isset($object->fields['note_private']))
{
$nbNote = 0;
if (!empty($object->note_private)) $nbNote++;
if (!empty($object->note_public)) $nbNote++;
$head[$h][0] = dol_buildpath('/mymodule/myobject_note.php', 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
$head[$h][2] = 'note';
$h++;
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$upload_dir = $conf->mymodule->dir_output . "/myobject/" . dol_sanitizeFileName($object->ref);
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
$nbLinks=Link::count($db, $object->element, $object->id);
$head[$h][0] = dol_buildpath("/mymodule/myobject_document.php", 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Documents');
if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
$head[$h][2] = 'document';
$h++;
$head[$h][0] = dol_buildpath("/mymodule/myobject_agenda.php", 1).'?id='.$object->id;
$head[$h][1] = $langs->trans("Events");
$head[$h][2] = 'agenda';
$h++;
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
//$this->tabs = array(
// 'entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'
//); // to add new tab
//$this->tabs = array(
// 'entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'
//); // to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'myobject@mymodule');
return $head;
}

View File

@ -0,0 +1,22 @@
-- Copyright (C) ---Put here your own copyright and developer email---
--
-- 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
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see http://www.gnu.org/licenses/.
--ALTER TABLE llx_zapierfordolibarr_hook ADD INDEX idx_fieldobject (fieldobject);
--ALTER TABLE llx_zapierfordolibarr_hook ADD UNIQUE INDEX uk_zapierfordolibarr_hook_fieldxy(fieldx, fieldy);
--ALTER TABLE llx_zapierfordolibarr_hook ADD CONSTRAINT llx_zapierfordolibarr_hook_fk_field FOREIGN KEY (fk_field) REFERENCES llx_zapierfordolibarr_myotherobject(rowid);

View File

@ -0,0 +1,29 @@
-- Copyright (C) ---Put here your own copyright and developer email---
--
-- 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
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see http://www.gnu.org/licenses/.
CREATE TABLE llx_zapierfordolibarr_hook(
rowid integer AUTO_INCREMENT PRIMARY KEY,
entity integer DEFAULT 1 NOT NULL,
url varchar(255),
event varchar(255),
module varchar(128),
action varchar(128),
status integer,
date_creation DATETIME NOT NULL,
fk_user integer NOT NULL,
tms TIMESTAMP NOT NULL,
import_key varchar(14)
) ENGINE=innodb;

View File

@ -0,0 +1,23 @@
-- Copyright (C) ---Put here your own copyright and developer email---
--
-- 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
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see http://www.gnu.org/licenses/.
create table llx_zapierfordolibarr_hook_extrafields
(
rowid integer AUTO_INCREMENT PRIMARY KEY,
tms timestamp,
fk_object integer NOT NULL,
import_key varchar(14) -- import key
) ENGINE=innodb;

View File

@ -0,0 +1,238 @@
<?php
/* Copyright (C) 2001-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* 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
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/zapierfordolibarr/template/zapierfordolibarrindex.php
* \ingroup zapierfordolibarr
* \brief Home page of zapierfordolibarr top menu
*/
// Load Dolibarr environment
$res=0;
// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
$tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1;
while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; }
if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include substr($tmp, 0, ($i+1))."/main.inc.php";
if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include dirname(substr($tmp, 0, ($i+1)))."/main.inc.php";
// Try main.inc.php using relative path
if (! $res && file_exists("../main.inc.php")) $res=@include "../main.inc.php";
if (! $res && file_exists("../../main.inc.php")) $res=@include "../../main.inc.php";
if (! $res && file_exists("../../../main.inc.php")) $res=@include "../../../main.inc.php";
if (! $res) die("Include of main fails");
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
// Load translation files required by the page
$langs->loadLangs(array("zapierfordolibarr@zapierfordolibarr"));
$action=GETPOST('action', 'alpha');
// Securite acces client
if (! $user->rights->zapierfordolibarr->read) accessforbidden();
$socid=GETPOST('socid', 'int');
if (isset($user->societe_id) && $user->societe_id > 0)
{
$action = '';
$socid = $user->societe_id;
}
$max=5;
$now=dol_now();
/*
* Actions
*/
// None
/*
* View
*/
$form = new Form($db);
$formfile = new FormFile($db);
llxHeader("", $langs->trans("ZapierForDolibarrArea"));
print load_fiche_titre($langs->trans("ZapierForDolibarrArea"), '', 'zapierfordolibarr.png@zapierfordolibarr');
print '<div class="fichecenter"><div class="fichethirdleft">';
/* BEGIN MODULEBUILDER DRAFT MYOBJECT
// Draft MyObject
if (! empty($conf->zapierfordolibarr->enabled) && $user->rights->zapierfordolibarr->read)
{
$langs->load("orders");
$sql = "SELECT c.rowid, c.ref, c.ref_client, c.total_ht, c.tva as total_tva, c.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas";
$sql.= ", s.code_client";
$sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
$sql.= ", ".MAIN_DB_PREFIX."societe as s";
if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= " WHERE c.fk_soc = s.rowid";
$sql.= " AND c.fk_statut = 0";
$sql.= " AND c.entity IN (".getEntity('commande').")";
if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
if ($socid) $sql.= " AND c.fk_soc = ".$socid;
$resql = $db->query($sql);
if ($resql)
{
$total = 0;
$num = $db->num_rows($resql);
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<th colspan="3">'.$langs->trans("DraftOrders").($num?' <span class="badge">'.$num.'</span>':'').'</th></tr>';
$var = true;
if ($num > 0)
{
$i = 0;
while ($i < $num)
{
$obj = $db->fetch_object($resql);
print '<tr class="oddeven"><td class="nowrap">';
$orderstatic->id=$obj->rowid;
$orderstatic->ref=$obj->ref;
$orderstatic->ref_client=$obj->ref_client;
$orderstatic->total_ht = $obj->total_ht;
$orderstatic->total_tva = $obj->total_tva;
$orderstatic->total_ttc = $obj->total_ttc;
print $orderstatic->getNomUrl(1);
print '</td>';
print '<td class="nowrap">';
$companystatic->id=$obj->socid;
$companystatic->name=$obj->name;
$companystatic->client=$obj->client;
$companystatic->code_client = $obj->code_client;
$companystatic->code_fournisseur = $obj->code_fournisseur;
$companystatic->canvas=$obj->canvas;
print $companystatic->getNomUrl(1,'customer',16);
print '</td>';
print '<td class="right" class="nowrap">'.price($obj->total_ttc).'</td></tr>';
$i++;
$total += $obj->total_ttc;
}
if ($total>0)
{
print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td colspan="2" class="right">'.price($total)."</td></tr>";
}
}
else
{
print '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("NoOrder").'</td></tr>';
}
print "</table><br>";
$db->free($resql);
}
else
{
dol_print_error($db);
}
}
END MODULEBUILDER DRAFT MYOBJECT */
print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
$NBMAX=3;
$max=3;
/* BEGIN MODULEBUILDER LASTMODIFIED MYOBJECT
// Last modified myobject
if (! empty($conf->zapierfordolibarr->enabled) && $user->rights->zapierfordolibarr->read)
{
$sql = "SELECT s.rowid, s.nom as name, s.client, s.datec, s.tms, s.canvas";
$sql.= ", s.code_client";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql.= " WHERE s.client IN (1, 2, 3)";
$sql.= " AND s.entity IN (".getEntity($companystatic->element).")";
if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
if ($socid) $sql.= " AND s.rowid = $socid";
$sql .= " ORDER BY s.tms DESC";
$sql .= $db->plimit($max, 0);
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$i = 0;
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<th colspan="2">';
if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastCustomersOrProspects",$max);
else if (! empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print $langs->trans("BoxTitleLastModifiedProspects",$max);
else print $langs->trans("BoxTitleLastModifiedCustomers",$max);
print '</th>';
print '<th class="right">'.$langs->trans("DateModificationShort").'</th>';
print '</tr>';
if ($num)
{
while ($i < $num)
{
$objp = $db->fetch_object($resql);
$companystatic->id=$objp->rowid;
$companystatic->name=$objp->name;
$companystatic->client=$objp->client;
$companystatic->code_client = $objp->code_client;
$companystatic->code_fournisseur = $objp->code_fournisseur;
$companystatic->canvas=$objp->canvas;
print '<tr class="oddeven">';
print '<td class="nowrap">'.$companystatic->getNomUrl(1,'customer',48).'</td>';
print '<td class="right nowrap">';
print $companystatic->getLibCustProspStatut();
print "</td>";
print '<td class="right nowrap">'.dol_print_date($db->jdate($objp->tms),'day')."</td>";
print '</tr>';
$i++;
}
$db->free($resql);
}
else
{
print '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
}
print "</table><br>";
}
}
*/
print '</div></div></div>';
// End of page
llxFooter();
$db->close();