diff --git a/Gruntfile.js b/Gruntfile.js index d2cfd1fb5c..a892636cf7 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,245 +1,245 @@ module.exports = function (grunt) { - var jsFilesToMinify = [ - 'client/lib/jquery-2.0.2.min.js', - 'client/lib/underscore-min.js', - 'client/lib/backbone-min.js', - 'client/lib/handlebars.js', - 'client/lib/base64.js', - 'client/lib/jquery-ui.min.js', - 'client/lib/moment.min.js', - 'client/lib/moment-timezone-with-data.min.js', - 'client/lib/jquery.timepicker.min.js', - 'client/lib/jquery.autocomplete.js', - 'client/lib/bootstrap.min.js', - 'client/lib/bootstrap-datepicker.js', - 'client/lib/bull.min.js', - 'client/src/namespace.js', - 'client/src/exceptions.js', - 'client/src/app.js', - 'client/src/utils.js', - 'client/src/storage.js', - 'client/src/loader.js', - 'client/src/pre-loader.js', - 'client/src/ui.js', - 'client/src/acl.js', - 'client/src/model.js', - 'client/src/model-offline.js', - 'client/src/metadata.js', - 'client/src/language.js', - 'client/src/cache.js', - 'client/src/controller.js', - 'client/src/router.js', - 'client/src/date-time.js', - 'client/src/field-manager.js', - 'client/src/search-manager.js', - 'client/src/collection.js', - 'client/src/multi-collection.js', - 'client/src/view-helper.js', - 'client/src/layout-manager.js', - 'client/src/model-factory.js', - 'client/src/collection-factory.js', - 'client/src/models/settings.js', - 'client/src/models/user.js', - 'client/src/models/preferences.js', - 'client/src/controllers/base.js', - 'client/src/view.js', - ]; - - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - - mkdir: { - tmp: { - options: { - mode: 0775, - create: [ - 'build/tmp', - ] - }, + var jsFilesToMinify = [ + 'client/lib/jquery-2.0.2.min.js', + 'client/lib/underscore-min.js', + 'client/lib/backbone-min.js', + 'client/lib/handlebars.js', + 'client/lib/base64.js', + 'client/lib/jquery-ui.min.js', + 'client/lib/moment.min.js', + 'client/lib/moment-timezone-with-data.min.js', + 'client/lib/jquery.timepicker.min.js', + 'client/lib/jquery.autocomplete.js', + 'client/lib/bootstrap.min.js', + 'client/lib/bootstrap-datepicker.js', + 'client/lib/bull.min.js', + 'client/src/namespace.js', + 'client/src/exceptions.js', + 'client/src/app.js', + 'client/src/utils.js', + 'client/src/storage.js', + 'client/src/loader.js', + 'client/src/pre-loader.js', + 'client/src/ui.js', + 'client/src/acl.js', + 'client/src/model.js', + 'client/src/model-offline.js', + 'client/src/metadata.js', + 'client/src/language.js', + 'client/src/cache.js', + 'client/src/controller.js', + 'client/src/router.js', + 'client/src/date-time.js', + 'client/src/field-manager.js', + 'client/src/search-manager.js', + 'client/src/collection.js', + 'client/src/multi-collection.js', + 'client/src/view-helper.js', + 'client/src/layout-manager.js', + 'client/src/model-factory.js', + 'client/src/collection-factory.js', + 'client/src/models/settings.js', + 'client/src/models/user.js', + 'client/src/models/preferences.js', + 'client/src/controllers/base.js', + 'client/src/view.js', + ]; + + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + + mkdir: { + tmp: { + options: { + mode: 0775, + create: [ + 'build/tmp', + ] + }, - } - }, - clean: { - start: ['build/*'], - final: ['build/tmp'], - }, - less: { - bootstrap: { - options: { - yuicompress: true, - }, - files: { - 'frontend/client/css/bootstrap.css': 'frontend/less/espo/main.less', - }, - }, - }, - cssmin: { - minify: { - files: { - 'build/tmp/client/css/espo.min.css': [ - 'frontend/client/css/bootstrap.css', - 'frontend/client/css/datepicker.css', - 'frontend/client/css/jquery.timepicker.css', - ] - } - }, - }, - uglify: { - options: { - mangle: false, - banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n', - }, - 'build/tmp/client/espo.min.js': jsFilesToMinify.map(function (item) { - return 'frontend/' + item; - }) - }, - copy: { - frontendFolders: { - expand: true, - cwd: 'frontend/client', - src: [ - 'src/**', - 'res/**', - 'fonts/**', - 'cfg/**', - 'modules/**', - 'img/**', - 'css/**', - ], - dest: 'build/tmp/client', - }, - frontendHtml: { - src: 'frontend/html/reset.html', - dest: 'build/tmp/reset.html' - }, - frontendLib: { - expand: true, - dot: true, - cwd: 'frontend/client/lib', - src: '**', - dest: 'build/tmp/client/lib/', - }, - backend: { - expand: true, - dot: true, - src: [ - 'api/**', - 'application/**', - 'custom/**', - 'data/.data', - 'install/**', - 'vendor/**', - 'bootstrap.php', - 'cron.php', - 'rebuild.php', - 'index.php', - 'LICENSE.txt', - '.htaccess', - 'web.config', - ], - dest: 'build/tmp/', - }, - final: { - expand: true, - dot: true, - src: '**', - cwd: 'build/tmp', - dest: 'build/EspoCRM-<%= pkg.version %>/', - }, - }, - chmod: { - options: { - mode: '755' - }, - php: { - options: { - mode: '644' - }, - src: [ - 'build/EspoCRM-<%= pkg.version %>/**/*.php', - 'build/EspoCRM-<%= pkg.version %>/**/*.json', - 'build/EspoCRM-<%= pkg.version %>/**/*.config', - 'build/EspoCRM-<%= pkg.version %>/**/.htaccess', - 'build/EspoCRM-<%= pkg.version %>/client/**/*.js', - 'build/EspoCRM-<%= pkg.version %>/client/**/*.css', - 'build/EspoCRM-<%= pkg.version %>/client/**/*.tpl', - 'build/EspoCRM-<%= pkg.version %>/**/*.html', - 'build/EspoCRM-<%= pkg.version %>/**/*.txt', - ] - } - }, - replace: { - timestamp: { - options: { - patterns: [ - { - match: 'timestamp', - replacement: '<%= new Date().getTime() %>' - } - ] - }, - files: [ - { - src: 'frontend/html/main.html', - dest: 'build/tmp/main.html' - } - ] - }, - version: { - options: { - patterns: [ - { - match: 'version', - replacement: '<%= pkg.version %>' - } - ] - }, - files: [ - { - src: 'build/tmp/application/Espo/Core/defaults/config.php', - dest: 'build/tmp/application/Espo/Core/defaults/config.php' - } - ] - } - }, - compress: { - final: { - options: { - archive: 'build/EspoCRM-<%= pkg.version %>.zip', - mode: 'zip' - }, - src: ['**'], - cwd: 'build/EspoCRM-<%= pkg.version %>', - dest: 'EspoCRM-<%= pkg.version %>' - } - } - }); + } + }, + clean: { + start: ['build/*'], + final: ['build/tmp'], + }, + less: { + bootstrap: { + options: { + yuicompress: true, + }, + files: { + 'frontend/client/css/bootstrap.css': 'frontend/less/espo/main.less', + }, + }, + }, + cssmin: { + minify: { + files: { + 'build/tmp/client/css/espo.min.css': [ + 'frontend/client/css/bootstrap.css', + 'frontend/client/css/datepicker.css', + 'frontend/client/css/jquery.timepicker.css', + ] + } + }, + }, + uglify: { + options: { + mangle: false, + banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n', + }, + 'build/tmp/client/espo.min.js': jsFilesToMinify.map(function (item) { + return 'frontend/' + item; + }) + }, + copy: { + frontendFolders: { + expand: true, + cwd: 'frontend/client', + src: [ + 'src/**', + 'res/**', + 'fonts/**', + 'cfg/**', + 'modules/**', + 'img/**', + 'css/**', + ], + dest: 'build/tmp/client', + }, + frontendHtml: { + src: 'frontend/html/reset.html', + dest: 'build/tmp/reset.html' + }, + frontendLib: { + expand: true, + dot: true, + cwd: 'frontend/client/lib', + src: '**', + dest: 'build/tmp/client/lib/', + }, + backend: { + expand: true, + dot: true, + src: [ + 'api/**', + 'application/**', + 'custom/**', + 'data/.data', + 'install/**', + 'vendor/**', + 'bootstrap.php', + 'cron.php', + 'rebuild.php', + 'index.php', + 'LICENSE.txt', + '.htaccess', + 'web.config', + ], + dest: 'build/tmp/', + }, + final: { + expand: true, + dot: true, + src: '**', + cwd: 'build/tmp', + dest: 'build/EspoCRM-<%= pkg.version %>/', + }, + }, + chmod: { + options: { + mode: '755' + }, + php: { + options: { + mode: '644' + }, + src: [ + 'build/EspoCRM-<%= pkg.version %>/**/*.php', + 'build/EspoCRM-<%= pkg.version %>/**/*.json', + 'build/EspoCRM-<%= pkg.version %>/**/*.config', + 'build/EspoCRM-<%= pkg.version %>/**/.htaccess', + 'build/EspoCRM-<%= pkg.version %>/client/**/*.js', + 'build/EspoCRM-<%= pkg.version %>/client/**/*.css', + 'build/EspoCRM-<%= pkg.version %>/client/**/*.tpl', + 'build/EspoCRM-<%= pkg.version %>/**/*.html', + 'build/EspoCRM-<%= pkg.version %>/**/*.txt', + ] + } + }, + replace: { + timestamp: { + options: { + patterns: [ + { + match: 'timestamp', + replacement: '<%= new Date().getTime() %>' + } + ] + }, + files: [ + { + src: 'frontend/html/main.html', + dest: 'build/tmp/main.html' + } + ] + }, + version: { + options: { + patterns: [ + { + match: 'version', + replacement: '<%= pkg.version %>' + } + ] + }, + files: [ + { + src: 'build/tmp/application/Espo/Core/defaults/config.php', + dest: 'build/tmp/application/Espo/Core/defaults/config.php' + } + ] + } + }, + compress: { + final: { + options: { + archive: 'build/EspoCRM-<%= pkg.version %>.zip', + mode: 'zip' + }, + src: ['**'], + cwd: 'build/EspoCRM-<%= pkg.version %>', + dest: 'EspoCRM-<%= pkg.version %>' + } + } + }); - grunt.loadNpmTasks('grunt-contrib-clean'); - grunt.loadNpmTasks('grunt-mkdir'); - grunt.loadNpmTasks('grunt-contrib-less'); - grunt.loadNpmTasks('grunt-contrib-cssmin'); - grunt.loadNpmTasks('grunt-contrib-uglify'); - grunt.loadNpmTasks('grunt-contrib-copy'); - grunt.loadNpmTasks('grunt-replace'); - grunt.loadNpmTasks('grunt-contrib-compress'); - grunt.loadNpmTasks('grunt-chmod'); + grunt.loadNpmTasks('grunt-contrib-clean'); + grunt.loadNpmTasks('grunt-mkdir'); + grunt.loadNpmTasks('grunt-contrib-less'); + grunt.loadNpmTasks('grunt-contrib-cssmin'); + grunt.loadNpmTasks('grunt-contrib-uglify'); + grunt.loadNpmTasks('grunt-contrib-copy'); + grunt.loadNpmTasks('grunt-replace'); + grunt.loadNpmTasks('grunt-contrib-compress'); + grunt.loadNpmTasks('grunt-chmod'); - grunt.registerTask('default', [ - 'clean:start', - 'mkdir:tmp', - 'less', - 'cssmin', - 'uglify', - 'copy:frontendFolders', - 'copy:frontendHtml', - 'copy:frontendLib', - 'copy:backend', - 'replace', - 'copy:final', - 'chmod', - 'clean:final', - ]); + grunt.registerTask('default', [ + 'clean:start', + 'mkdir:tmp', + 'less', + 'cssmin', + 'uglify', + 'copy:frontendFolders', + 'copy:frontendHtml', + 'copy:frontendLib', + 'copy:backend', + 'replace', + 'copy:final', + 'chmod', + 'clean:final', + ]); }; diff --git a/application/Espo/Controllers/Admin.php b/application/Espo/Controllers/Admin.php index 9aa225f8a1..798990837c 100644 --- a/application/Espo/Controllers/Admin.php +++ b/application/Espo/Controllers/Admin.php @@ -27,60 +27,60 @@ use \Espo\Core\Exceptions\Error, class Admin extends \Espo\Core\Controllers\Base { - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } - public function actionRebuild($params, $data) - { - $result = $this->getContainer()->get('dataManager')->rebuild(); + public function actionRebuild($params, $data) + { + $result = $this->getContainer()->get('dataManager')->rebuild(); - return $result; - } + return $result; + } - public function actionClearCache($params, $data) - { - $result = $this->getContainer()->get('dataManager')->clearCache(); + public function actionClearCache($params, $data) + { + $result = $this->getContainer()->get('dataManager')->clearCache(); - return $result; - } + return $result; + } - public function actionJobs() - { - $scheduledJob = $this->getContainer()->get('scheduledJob'); + public function actionJobs() + { + $scheduledJob = $this->getContainer()->get('scheduledJob'); - return $scheduledJob->getAllNamesOnly(); - } + return $scheduledJob->getAllNamesOnly(); + } - public function actionUploadUpgradePackage($params, $data) - { - $upgradeManager = new \Espo\Core\UpgradeManager($this->getContainer()); + public function actionUploadUpgradePackage($params, $data) + { + $upgradeManager = new \Espo\Core\UpgradeManager($this->getContainer()); - $upgradeId = $upgradeManager->upload($data); - $manifest = $upgradeManager->getManifest(); + $upgradeId = $upgradeManager->upload($data); + $manifest = $upgradeManager->getManifest(); - return array( - 'id' => $upgradeId, - 'version' => $manifest['version'], - ); - } + return array( + 'id' => $upgradeId, + 'version' => $manifest['version'], + ); + } - public function actionRunUpgrade($params, $data) - { - $upgradeManager = new \Espo\Core\UpgradeManager($this->getContainer()); + public function actionRunUpgrade($params, $data) + { + $upgradeManager = new \Espo\Core\UpgradeManager($this->getContainer()); - $upgradeManager->install($data['id']); + $upgradeManager->install($data['id']); - return true; - } + return true; + } - public function actionCronMessage($params, $data) - { - return $this->getContainer()->get('scheduledJob')->getSetupMessage(); - } + public function actionCronMessage($params, $data) + { + return $this->getContainer()->get('scheduledJob')->getSetupMessage(); + } } diff --git a/application/Espo/Controllers/App.php b/application/Espo/Controllers/App.php index 9feba226de..09ae50b1c9 100644 --- a/application/Espo/Controllers/App.php +++ b/application/Espo/Controllers/App.php @@ -26,25 +26,25 @@ use \Espo\Core\Exceptions\BadRequest; class App extends \Espo\Core\Controllers\Record { - public function actionUser() - { - return array( - 'user' => $this->getUser()->toArray(), - 'acl' => $this->getAcl()->toArray(), - 'preferences' => $this->getPreferences()->toArray(), - 'token' => $this->getUser()->get('token') - ); - } - - public function actionDestroyAuthToken($params, $data) - { - $token = $data['token']; - if (empty($token)) { - throw new BadRequest(); - } + public function actionUser() + { + return array( + 'user' => $this->getUser()->toArray(), + 'acl' => $this->getAcl()->toArray(), + 'preferences' => $this->getPreferences()->toArray(), + 'token' => $this->getUser()->get('token') + ); + } + + public function actionDestroyAuthToken($params, $data) + { + $token = $data['token']; + if (empty($token)) { + throw new BadRequest(); + } - $auth = new \Espo\Core\Utils\Auth($this->getContainer()); - return $auth->destroyAuthToken($token); - } + $auth = new \Espo\Core\Utils\Auth($this->getContainer()); + return $auth->destroyAuthToken($token); + } } diff --git a/application/Espo/Controllers/Attachment.php b/application/Espo/Controllers/Attachment.php index a2baabbc2f..49fd0157d1 100644 --- a/application/Espo/Controllers/Attachment.php +++ b/application/Espo/Controllers/Attachment.php @@ -25,19 +25,19 @@ namespace Espo\Controllers; class Attachment extends \Espo\Core\Controllers\Record { - public function actionUpload($params, $data) - { - list($prefix, $contents) = explode(',', $data); - $contents = base64_decode($contents); - - $attachment = $this->getEntityManager()->getEntity('Attachment'); - $this->getEntityManager()->saveEntity($attachment); - $this->getContainer()->get('fileManager')->putContents('data/upload/' . $attachment->id, $contents); - - return array( - 'attachmentId' => $attachment->id - ); - } + public function actionUpload($params, $data) + { + list($prefix, $contents) = explode(',', $data); + $contents = base64_decode($contents); + + $attachment = $this->getEntityManager()->getEntity('Attachment'); + $this->getEntityManager()->saveEntity($attachment); + $this->getContainer()->get('fileManager')->putContents('data/upload/' . $attachment->id, $contents); + + return array( + 'attachmentId' => $attachment->id + ); + } } diff --git a/application/Espo/Controllers/AuthToken.php b/application/Espo/Controllers/AuthToken.php index 6372aa703e..5c1b441542 100644 --- a/application/Espo/Controllers/AuthToken.php +++ b/application/Espo/Controllers/AuthToken.php @@ -25,42 +25,42 @@ namespace Espo\Controllers; use \Espo\Core\Exceptions\Forbidden; class AuthToken extends \Espo\Core\Controllers\Record -{ - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } - - public function actionUpdate($params, $data) - { - throw new Forbidden(); - } - - public function actionCreate($params, $data) - { - throw new Forbidden(); - } - - public function actionListLinked($params, $data) - { - throw new Forbidden(); - } - - public function actionMassUpdate($params, $data) - { - throw new Forbidden(); - } - - public function actionCreateLink($params, $data) - { - throw new Forbidden(); - } - - public function actionRemoveLink($params, $data) - { - throw new Forbidden(); - } +{ + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } + + public function actionUpdate($params, $data) + { + throw new Forbidden(); + } + + public function actionCreate($params, $data) + { + throw new Forbidden(); + } + + public function actionListLinked($params, $data) + { + throw new Forbidden(); + } + + public function actionMassUpdate($params, $data) + { + throw new Forbidden(); + } + + public function actionCreateLink($params, $data) + { + throw new Forbidden(); + } + + public function actionRemoveLink($params, $data) + { + throw new Forbidden(); + } } diff --git a/application/Espo/Controllers/Email.php b/application/Espo/Controllers/Email.php index 1763f4c71f..f8ad821496 100644 --- a/application/Espo/Controllers/Email.php +++ b/application/Espo/Controllers/Email.php @@ -24,11 +24,11 @@ namespace Espo\Controllers; class Email extends \Espo\Core\Controllers\Record { - public function actionGetCopiedAttachments($params, $data, $request) - { - $id = $request->get('id'); - - return $this->getRecordService()->getCopiedAttachments($id); - } + public function actionGetCopiedAttachments($params, $data, $request) + { + $id = $request->get('id'); + + return $this->getRecordService()->getCopiedAttachments($id); + } } diff --git a/application/Espo/Controllers/EmailAccount.php b/application/Espo/Controllers/EmailAccount.php index a765f9563e..e6c86ec026 100644 --- a/application/Espo/Controllers/EmailAccount.php +++ b/application/Espo/Controllers/EmailAccount.php @@ -24,17 +24,17 @@ namespace Espo\Controllers; class EmailAccount extends \Espo\Core\Controllers\Record { - public function actionGetFolders($params, $data, $request) - { - return $this->getRecordService()->getFolders(array( - 'host' => $request->get('host'), - 'port' => $request->get('port'), - 'ssl' => $request->get('ssl'), - 'username' => $request->get('username'), - 'password' => $request->get('password'), - 'id' => $request->get('id') - )); + public function actionGetFolders($params, $data, $request) + { + return $this->getRecordService()->getFolders(array( + 'host' => $request->get('host'), + 'port' => $request->get('port'), + 'ssl' => $request->get('ssl'), + 'username' => $request->get('username'), + 'password' => $request->get('password'), + 'id' => $request->get('id') + )); - } + } } diff --git a/application/Espo/Controllers/EmailAddress.php b/application/Espo/Controllers/EmailAddress.php index f990466aa0..c01652e3b6 100644 --- a/application/Espo/Controllers/EmailAddress.php +++ b/application/Espo/Controllers/EmailAddress.php @@ -24,14 +24,14 @@ namespace Espo\Controllers; class EmailAddress extends \Espo\Core\Controllers\Record { - public function actionSearchInAddressBook($params, $data, $request) - { - $q = $request->get('q'); - $limit = intval($request->get('limit')); - if (empty($limit) || $limit > 30) { - $limit = 5; - } - return $this->getRecordService()->searchInAddressBook($q, $limit); - } + public function actionSearchInAddressBook($params, $data, $request) + { + $q = $request->get('q'); + $limit = intval($request->get('limit')); + if (empty($limit) || $limit > 30) { + $limit = 5; + } + return $this->getRecordService()->searchInAddressBook($q, $limit); + } } diff --git a/application/Espo/Controllers/EmailTemplate.php b/application/Espo/Controllers/EmailTemplate.php index 1cc8687fa1..2c2e00485f 100644 --- a/application/Espo/Controllers/EmailTemplate.php +++ b/application/Espo/Controllers/EmailTemplate.php @@ -26,20 +26,20 @@ use \Espo\Core\Exceptions\Error; class EmailTemplate extends \Espo\Core\Controllers\Record { - public function actionParse($params, $data, $request) - { - $id = $request->get('id'); - $emailAddress = $request->get('emailAddress'); - if (empty($id)) { - throw new Error(); - } - - return $this->getRecordService()->parse($id, array( - 'emailAddress' => $request->get('emailAddress'), - 'parentType' => $request->get('parentType'), - 'parentId' => $request->get('parentId'), - ), true); - } + public function actionParse($params, $data, $request) + { + $id = $request->get('id'); + $emailAddress = $request->get('emailAddress'); + if (empty($id)) { + throw new Error(); + } + + return $this->getRecordService()->parse($id, array( + 'emailAddress' => $request->get('emailAddress'), + 'parentType' => $request->get('parentType'), + 'parentId' => $request->get('parentId'), + ), true); + } } diff --git a/application/Espo/Controllers/Extension.php b/application/Espo/Controllers/Extension.php index 0cab3b960a..57968eaa4c 100644 --- a/application/Espo/Controllers/Extension.php +++ b/application/Espo/Controllers/Extension.php @@ -27,105 +27,105 @@ use \Espo\Core\Exceptions\Forbidden; class Extension extends \Espo\Core\Controllers\Record { - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } - public function actionUpload($params, $data, $request) - { - if (!$request->isPost()) { - throw new Forbidden(); - } + public function actionUpload($params, $data, $request) + { + if (!$request->isPost()) { + throw new Forbidden(); + } - $manager = new \Espo\Core\ExtensionManager($this->getContainer()); + $manager = new \Espo\Core\ExtensionManager($this->getContainer()); - $id = $manager->upload($data); - $manifest = $manager->getManifest(); + $id = $manager->upload($data); + $manifest = $manager->getManifest(); - return array( - 'id' => $id, - 'version' => $manifest['version'], - 'name' => $manifest['name'], - 'description' => $manifest['description'], - ); - } + return array( + 'id' => $id, + 'version' => $manifest['version'], + 'name' => $manifest['name'], + 'description' => $manifest['description'], + ); + } - public function actionInstall($params, $data, $request) - { - if (!$request->isPost()) { - throw new Forbidden(); - } + public function actionInstall($params, $data, $request) + { + if (!$request->isPost()) { + throw new Forbidden(); + } - $manager = new \Espo\Core\ExtensionManager($this->getContainer()); + $manager = new \Espo\Core\ExtensionManager($this->getContainer()); - $manager->install($data['id']); + $manager->install($data['id']); - return true; - } + return true; + } - public function actionUninstall($params, $data, $request) - { - if (!$request->isPost()) { - throw new Forbidden(); - } + public function actionUninstall($params, $data, $request) + { + if (!$request->isPost()) { + throw new Forbidden(); + } - $manager = new \Espo\Core\ExtensionManager($this->getContainer()); + $manager = new \Espo\Core\ExtensionManager($this->getContainer()); - $manager->uninstall($data['id']); + $manager->uninstall($data['id']); - return true; - } + return true; + } - public function actionCreate() - { - throw new Forbidden(); - } + public function actionCreate() + { + throw new Forbidden(); + } - public function actionUpdate() - { - throw new Forbidden(); - } + public function actionUpdate() + { + throw new Forbidden(); + } - public function actionPatch() - { - throw new Forbidden(); - } + public function actionPatch() + { + throw new Forbidden(); + } - public function actionListLinked() - { - throw new Forbidden(); - } + public function actionListLinked() + { + throw new Forbidden(); + } - public function actionDelete($params, $data, $request) - { - $manager = new \Espo\Core\ExtensionManager($this->getContainer()); + public function actionDelete($params, $data, $request) + { + $manager = new \Espo\Core\ExtensionManager($this->getContainer()); - $manager->delete($params['id']); + $manager->delete($params['id']); - return true; - } + return true; + } - public function actionMassUpdate() - { - throw new Forbidden(); - } + public function actionMassUpdate() + { + throw new Forbidden(); + } - public function actionMassDelete() - { - throw new Forbidden(); - } + public function actionMassDelete() + { + throw new Forbidden(); + } - public function actionCreateLink() - { - throw new Forbidden(); - } + public function actionCreateLink() + { + throw new Forbidden(); + } - public function actionRemoveLink() - { - throw new Forbidden(); - } + public function actionRemoveLink() + { + throw new Forbidden(); + } } diff --git a/application/Espo/Controllers/ExternalAccount.php b/application/Espo/Controllers/ExternalAccount.php index 38427406d1..7978f15464 100644 --- a/application/Espo/Controllers/ExternalAccount.php +++ b/application/Espo/Controllers/ExternalAccount.php @@ -27,98 +27,98 @@ use \Espo\Core\Exceptions\Forbidden; class ExternalAccount extends \Espo\Core\Controllers\Record { - public static $defaultAction = 'list'; - - public function actionList($params, $data, $request) - { - $integrations = $this->getEntityManager()->getRepository('Integration')->find(); - $arr = array(); - foreach ($integrations as $entity) { - if ($entity->get('enabled') && $this->getMetadata()->get('integrations.' . $entity->id .'.allowUserAccounts')) { - $arr[] = array( - 'id' => $entity->id - ); - } - } - return array( - 'list' => $arr - ); - } - - public function actionGetOAuth2Info($params, $data, $request) - { - $id = $request->get('id'); - list($integration, $userId) = explode('__', $id); - + public static $defaultAction = 'list'; + + public function actionList($params, $data, $request) + { + $integrations = $this->getEntityManager()->getRepository('Integration')->find(); + $arr = array(); + foreach ($integrations as $entity) { + if ($entity->get('enabled') && $this->getMetadata()->get('integrations.' . $entity->id .'.allowUserAccounts')) { + $arr[] = array( + 'id' => $entity->id + ); + } + } + return array( + 'list' => $arr + ); + } + + public function actionGetOAuth2Info($params, $data, $request) + { + $id = $request->get('id'); + list($integration, $userId) = explode('__', $id); + - if ($this->getUser()->id != $userId) { - throw new Forbidden(); - } - - $entity = $this->getEntityManager()->getEntity('Integration', $integration); - if ($entity) { - return array( - 'clientId' => $entity->get('clientId'), - 'redirectUri' => $this->getConfig()->get('siteUrl') . '/oauthcallback', - 'isConnected' => $this->getRecordService()->ping($integration, $userId) - ); - } - } + if ($this->getUser()->id != $userId) { + throw new Forbidden(); + } + + $entity = $this->getEntityManager()->getEntity('Integration', $integration); + if ($entity) { + return array( + 'clientId' => $entity->get('clientId'), + 'redirectUri' => $this->getConfig()->get('siteUrl') . '/oauthcallback', + 'isConnected' => $this->getRecordService()->ping($integration, $userId) + ); + } + } - public function actionRead($params, $data, $request) - { - list($integration, $userId) = explode('__', $params['id']); + public function actionRead($params, $data, $request) + { + list($integration, $userId) = explode('__', $params['id']); - if ($this->getUser()->id != $userId) { - throw new Forbidden(); - } - - $entity = $this->getEntityManager()->getEntity('ExternalAccount', $params['id']); - return $entity->toArray(); - } - - public function actionUpdate($params, $data) - { - return $this->actionPatch($params, $data); - } - - public function actionPatch($params, $data) - { - list($integration, $userId) = explode('__', $params['id']); - + if ($this->getUser()->id != $userId) { + throw new Forbidden(); + } + + $entity = $this->getEntityManager()->getEntity('ExternalAccount', $params['id']); + return $entity->toArray(); + } + + public function actionUpdate($params, $data) + { + return $this->actionPatch($params, $data); + } + + public function actionPatch($params, $data) + { + list($integration, $userId) = explode('__', $params['id']); + - if ($this->getUser()->id != $userId) { - throw new Forbidden(); - } - - if (isset($data['enabled']) && !$data['enabled']) { - $data['data'] = null; - } - - $entity = $this->getEntityManager()->getEntity('ExternalAccount', $params['id']); - $entity->set($data); - $this->getEntityManager()->saveEntity($entity); - - return $entity->toArray(); - } - - public function actionAuthorizationCode($params, $data, $request) - { - if (!$request->isPost()) { - throw new Error('Bad HTTP method type.'); - } - - $id = $data['id']; - $code = $data['code']; - - list($integration, $userId) = explode('__', $id); + if ($this->getUser()->id != $userId) { + throw new Forbidden(); + } + + if (isset($data['enabled']) && !$data['enabled']) { + $data['data'] = null; + } + + $entity = $this->getEntityManager()->getEntity('ExternalAccount', $params['id']); + $entity->set($data); + $this->getEntityManager()->saveEntity($entity); + + return $entity->toArray(); + } + + public function actionAuthorizationCode($params, $data, $request) + { + if (!$request->isPost()) { + throw new Error('Bad HTTP method type.'); + } + + $id = $data['id']; + $code = $data['code']; + + list($integration, $userId) = explode('__', $id); - if ($this->getUser()->id != $userId) { - throw new Forbidden(); - } - - $service = $this->getRecordService(); - return $service->authorizationCode($integration, $userId, $code); - } + if ($this->getUser()->id != $userId) { + throw new Forbidden(); + } + + $service = $this->getRecordService(); + return $service->authorizationCode($integration, $userId, $code); + } } diff --git a/application/Espo/Controllers/FieldManager.php b/application/Espo/Controllers/FieldManager.php index eeef95b79e..4606d3c4bd 100644 --- a/application/Espo/Controllers/FieldManager.php +++ b/application/Espo/Controllers/FieldManager.php @@ -23,70 +23,70 @@ namespace Espo\Controllers; use \Espo\Core\Exceptions\Error, - \Espo\Core\Exceptions\Forbidden, - \Espo\Core\Exceptions\NotFound; + \Espo\Core\Exceptions\Forbidden, + \Espo\Core\Exceptions\NotFound; class FieldManager extends \Espo\Core\Controllers\Base { - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } - public function actionRead($params, $data) - { - $data = $this->getContainer()->get('fieldManager')->read($params['name'], $params['scope']); + public function actionRead($params, $data) + { + $data = $this->getContainer()->get('fieldManager')->read($params['name'], $params['scope']); - if (!isset($data)) { - throw new NotFound(); - } + if (!isset($data)) { + throw new NotFound(); + } - return $data; - } + return $data; + } - public function actionCreate($params, $data) - { - if (empty($data['name'])) { - throw new Error("Field 'name' cannnot be empty"); - } + public function actionCreate($params, $data) + { + if (empty($data['name'])) { + throw new Error("Field 'name' cannnot be empty"); + } - $fieldManager = $this->getContainer()->get('fieldManager'); - $fieldManager->create($data['name'], $data, $params['scope']); + $fieldManager = $this->getContainer()->get('fieldManager'); + $fieldManager->create($data['name'], $data, $params['scope']); - try { - $this->getContainer()->get('dataManager')->rebuild($params['scope']); - } catch (Error $e) { - $fieldManager->delete($data['name'], $params['scope']); - throw new Error($e->getMessage()); - } + try { + $this->getContainer()->get('dataManager')->rebuild($params['scope']); + } catch (Error $e) { + $fieldManager->delete($data['name'], $params['scope']); + throw new Error($e->getMessage()); + } - return $fieldManager->read($data['name'], $params['scope']); - } + return $fieldManager->read($data['name'], $params['scope']); + } - public function actionUpdate($params, $data) - { - $fieldManager = $this->getContainer()->get('fieldManager'); - $fieldManager->update($params['name'], $data, $params['scope']); + public function actionUpdate($params, $data) + { + $fieldManager = $this->getContainer()->get('fieldManager'); + $fieldManager->update($params['name'], $data, $params['scope']); - if ($fieldManager->isChanged()) { - $this->getContainer()->get('dataManager')->rebuild($params['scope']); - } else { - $this->getContainer()->get('dataManager')->clearCache(); - } + if ($fieldManager->isChanged()) { + $this->getContainer()->get('dataManager')->rebuild($params['scope']); + } else { + $this->getContainer()->get('dataManager')->clearCache(); + } - return $fieldManager->read($params['name'], $params['scope']); - } + return $fieldManager->read($params['name'], $params['scope']); + } - public function actionDelete($params, $data) - { - $res = $this->getContainer()->get('fieldManager')->delete($params['name'], $params['scope']); + public function actionDelete($params, $data) + { + $res = $this->getContainer()->get('fieldManager')->delete($params['name'], $params['scope']); - $this->getContainer()->get('dataManager')->rebuildMetadata(); + $this->getContainer()->get('dataManager')->rebuildMetadata(); - return $res; - } + return $res; + } } diff --git a/application/Espo/Controllers/GlobalSearch.php b/application/Espo/Controllers/GlobalSearch.php index 23d8337b17..c4fcc72063 100644 --- a/application/Espo/Controllers/GlobalSearch.php +++ b/application/Espo/Controllers/GlobalSearch.php @@ -23,18 +23,18 @@ namespace Espo\Controllers; use \Espo\Core\Exceptions\Error, - \Espo\Core\Exceptions\Forbidden; + \Espo\Core\Exceptions\Forbidden; class GlobalSearch extends \Espo\Core\Controllers\Base { public function actionSearch($params, $data, $request) - { - $query = $params['query']; - - $offset = $request->get('offset'); - $maxSize = $request->get('maxSize'); - - return $this->getService('GlobalSearch')->find($query, $offset, $maxSize); - } + { + $query = $params['query']; + + $offset = $request->get('offset'); + $maxSize = $request->get('maxSize'); + + return $this->getService('GlobalSearch')->find($query, $offset, $maxSize); + } } diff --git a/application/Espo/Controllers/I18n.php b/application/Espo/Controllers/I18n.php index 1ec5cadf22..1072e0a960 100644 --- a/application/Espo/Controllers/I18n.php +++ b/application/Espo/Controllers/I18n.php @@ -26,7 +26,7 @@ class I18n extends \Espo\Core\Controllers\Base { public function actionRead($params, $data) - { - return $this->getContainer()->get('language')->getAll(); - } + { + return $this->getContainer()->get('language')->getAll(); + } } diff --git a/application/Espo/Controllers/Import.php b/application/Espo/Controllers/Import.php index 2c13a4e784..f4aa8dc666 100644 --- a/application/Espo/Controllers/Import.php +++ b/application/Espo/Controllers/Import.php @@ -27,61 +27,61 @@ use \Espo\Core\Exceptions\Error; use \Espo\Core\Exceptions\Forbidden; class Import extends \Espo\Core\Controllers\Base -{ - - protected function getFileManager() - { - return $this->getContainer()->get('fileManager'); - } - - protected function getEntityManager() - { - return $this->getContainer()->get('entityManager'); - } - - public function actionUploadFile($params, $data) - { - $contents = $data; - - $attachment = $this->getEntityManager()->getEntity('Attachment'); - $attachment->set('type', 'text/csv'); - $attachment->set('role', 'Import File'); - $this->getEntityManager()->saveEntity($attachment); - - $this->getFileManager()->putContents('data/upload/' . $attachment->id, $contents); - - return array( - 'attachmentId' => $attachment->id - ); - } - - public function actionRevert($params, $data) - { - return $this->getService('Import')->revert($data['entityType'], $data['idsToRemove']); - } - - public function actionCreate($params, $data) - { +{ + + protected function getFileManager() + { + return $this->getContainer()->get('fileManager'); + } + + protected function getEntityManager() + { + return $this->getContainer()->get('entityManager'); + } + + public function actionUploadFile($params, $data) + { + $contents = $data; + + $attachment = $this->getEntityManager()->getEntity('Attachment'); + $attachment->set('type', 'text/csv'); + $attachment->set('role', 'Import File'); + $this->getEntityManager()->saveEntity($attachment); + + $this->getFileManager()->putContents('data/upload/' . $attachment->id, $contents); + + return array( + 'attachmentId' => $attachment->id + ); + } + + public function actionRevert($params, $data) + { + return $this->getService('Import')->revert($data['entityType'], $data['idsToRemove']); + } + + public function actionCreate($params, $data) + { $importParams = array( - 'headerRow' => $data['headerRow'], - 'fieldDelimiter' => $data['fieldDelimiter'], - 'textQualifier' => $data['textQualifier'], - 'dateFormat' => $data['dateFormat'], - 'timeFormat' => $data['timeFormat'], - 'personNameFormat' => $data['personNameFormat'], - 'decimalMark' => $data['decimalMark'], - 'currency' => $data['currency'], - 'defaultValues' => $data['defaultValues'], - 'action' => $data['action'], + 'headerRow' => $data['headerRow'], + 'fieldDelimiter' => $data['fieldDelimiter'], + 'textQualifier' => $data['textQualifier'], + 'dateFormat' => $data['dateFormat'], + 'timeFormat' => $data['timeFormat'], + 'personNameFormat' => $data['personNameFormat'], + 'decimalMark' => $data['decimalMark'], + 'currency' => $data['currency'], + 'defaultValues' => $data['defaultValues'], + 'action' => $data['action'], ); $attachmentId = $data['attachmentId']; if (!$this->getAcl()->check($data['entityType'], 'edit')) { - throw new Forbidden(); + throw new Forbidden(); } - return $this->getService('Import')->import($data['entityType'], $data['fields'], $attachmentId, $importParams); - } + return $this->getService('Import')->import($data['entityType'], $data['fields'], $attachmentId, $importParams); + } } diff --git a/application/Espo/Controllers/Integration.php b/application/Espo/Controllers/Integration.php index 0e6b30e4ff..0e4a60576a 100644 --- a/application/Espo/Controllers/Integration.php +++ b/application/Espo/Controllers/Integration.php @@ -25,37 +25,37 @@ namespace Espo\Controllers; use \Espo\Core\Exceptions\Error; class Integration extends \Espo\Core\Controllers\Record -{ - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } - - public function actionIndex($params, $data, $request) - { - return false; - } +{ + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } + + public function actionIndex($params, $data, $request) + { + return false; + } - public function actionRead($params, $data, $request) - { - $entity = $this->getEntityManager()->getEntity('Integration', $params['id']); - return $entity->toArray(); - } - - public function actionUpdate($params, $data) - { - return $this->actionPatch($params, $data); - } - - public function actionPatch($params, $data) - { - $entity = $this->getEntityManager()->getEntity('Integration', $params['id']); - $entity->set($data); - $this->getEntityManager()->saveEntity($entity); - - return $entity->toArray(); - } + public function actionRead($params, $data, $request) + { + $entity = $this->getEntityManager()->getEntity('Integration', $params['id']); + return $entity->toArray(); + } + + public function actionUpdate($params, $data) + { + return $this->actionPatch($params, $data); + } + + public function actionPatch($params, $data) + { + $entity = $this->getEntityManager()->getEntity('Integration', $params['id']); + $entity->set($data); + $this->getEntityManager()->saveEntity($entity); + + return $entity->toArray(); + } } diff --git a/application/Espo/Controllers/Layout.php b/application/Espo/Controllers/Layout.php index a14eaf149f..2053358d4a 100644 --- a/application/Espo/Controllers/Layout.php +++ b/application/Espo/Controllers/Layout.php @@ -30,33 +30,33 @@ use \Espo\Core\Exceptions\Forbidden; class Layout extends \Espo\Core\Controllers\Base { public function actionRead($params, $data) - { - $data = $this->getContainer()->get('layout')->get($params['scope'], $params['name']); - if (empty($data)) { - throw new NotFound("Layout " . $params['scope'] . ":" . $params['name'] . ' is not found'); - } - return $data; - } + { + $data = $this->getContainer()->get('layout')->get($params['scope'], $params['name']); + if (empty($data)) { + throw new NotFound("Layout " . $params['scope'] . ":" . $params['name'] . ' is not found'); + } + return $data; + } - public function actionUpdate($params, $data) - { + public function actionUpdate($params, $data) + { if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); + throw new Forbidden(); } $result = $this->getContainer()->get('layout')->set($data, $params['scope'], $params['name']); - if ($result === false) { - throw new Error("Error while saving layout"); - } + if ($result === false) { + throw new Error("Error while saving layout"); + } - $this->getContainer()->get('dataManager')->updateCacheTimestamp(); + $this->getContainer()->get('dataManager')->updateCacheTimestamp(); - return $this->getContainer()->get('layout')->get($params['scope'], $params['name']); - } + return $this->getContainer()->get('layout')->get($params['scope'], $params['name']); + } - public function actionPatch($params, $data) - { + public function actionPatch($params, $data) + { return $this->actionUpdate($params, $data); - } + } } diff --git a/application/Espo/Controllers/Metadata.php b/application/Espo/Controllers/Metadata.php index d8effcfb78..3784c49413 100644 --- a/application/Espo/Controllers/Metadata.php +++ b/application/Espo/Controllers/Metadata.php @@ -26,7 +26,7 @@ class Metadata extends \Espo\Core\Controllers\Base { public function actionRead($params, $data) - { - return $this->getMetadata()->getAll(true); - } + { + return $this->getMetadata()->getAll(true); + } } diff --git a/application/Espo/Controllers/Notification.php b/application/Espo/Controllers/Notification.php index 03811feadf..51947dc17b 100644 --- a/application/Espo/Controllers/Notification.php +++ b/application/Espo/Controllers/Notification.php @@ -26,41 +26,41 @@ use \Espo\Core\Exceptions\Error; class Notification extends \Espo\Core\Controllers\Base { - public static $defaultAction = 'list'; + public static $defaultAction = 'list'; - public function actionList($params, $data, $request) - { - $scope = $params['scope']; - $id = $params['id']; - - $userId = $this->getUser()->id; - - $offset = intval($request->get('offset')); - $maxSize = intval($request->get('maxSize')); - - $params = array( - 'offset' => $offset, - 'maxSize' => $maxSize, - ); - - $result = $this->getService('Notification')->getList($userId, $params); - - return array( - 'total' => $result['total'], - 'list' => $result['collection']->toArray() - ); - } - - public function actionNotReadCount() - { - $userId = $this->getUser()->id; - return $this->getService('Notification')->getNotReadCount($userId); - } - - public function actionMarkAllRead($params, $data, $request) - { - $userId = $this->getUser()->id; - return $this->getService('Notification')->markAllRead($userId); - } + public function actionList($params, $data, $request) + { + $scope = $params['scope']; + $id = $params['id']; + + $userId = $this->getUser()->id; + + $offset = intval($request->get('offset')); + $maxSize = intval($request->get('maxSize')); + + $params = array( + 'offset' => $offset, + 'maxSize' => $maxSize, + ); + + $result = $this->getService('Notification')->getList($userId, $params); + + return array( + 'total' => $result['total'], + 'list' => $result['collection']->toArray() + ); + } + + public function actionNotReadCount() + { + $userId = $this->getUser()->id; + return $this->getService('Notification')->getNotReadCount($userId); + } + + public function actionMarkAllRead($params, $data, $request) + { + $userId = $this->getUser()->id; + return $this->getService('Notification')->markAllRead($userId); + } } diff --git a/application/Espo/Controllers/Preferences.php b/application/Espo/Controllers/Preferences.php index 0b7ceaf955..4e9518f64d 100644 --- a/application/Espo/Controllers/Preferences.php +++ b/application/Espo/Controllers/Preferences.php @@ -28,91 +28,91 @@ use \Espo\Core\Exceptions\BadRequest; use \Espo\Core\Exceptions\NotFound; class Preferences extends \Espo\Core\Controllers\Base -{ - protected function getPreferences() - { - return $this->getContainer()->get('preferences'); - } - - protected function getEntityManager() - { - return $this->getContainer()->get('entityManager'); - } - - protected function getCrypt() - { - return $this->getContainer()->get('crypt'); - } - - protected function handleUserAccess($userId) - { - if (!$this->getUser()->isAdmin()) { - if ($this->getUser()->id != $userId) { - throw new Forbidden(); - } - } - } - - public function actionDelete($params, $data) - { - $userId = $params['id']; - if (empty($userId)) { - throw new BadRequest(); - } - $this->handleUserAccess($userId); - - return $this->getEntityManager()->getRepository('Preferences')->resetToDefaults($userId); - } - - public function actionPatch($params, $data) - { - return $this->actionUpdate($params, $data); - } +{ + protected function getPreferences() + { + return $this->getContainer()->get('preferences'); + } + + protected function getEntityManager() + { + return $this->getContainer()->get('entityManager'); + } + + protected function getCrypt() + { + return $this->getContainer()->get('crypt'); + } + + protected function handleUserAccess($userId) + { + if (!$this->getUser()->isAdmin()) { + if ($this->getUser()->id != $userId) { + throw new Forbidden(); + } + } + } + + public function actionDelete($params, $data) + { + $userId = $params['id']; + if (empty($userId)) { + throw new BadRequest(); + } + $this->handleUserAccess($userId); + + return $this->getEntityManager()->getRepository('Preferences')->resetToDefaults($userId); + } + + public function actionPatch($params, $data) + { + return $this->actionUpdate($params, $data); + } - public function actionUpdate($params, $data) - { - $userId = $params['id']; - $this->handleUserAccess($userId); - - if (array_key_exists('smtpPassword', $data)) { - $data['smtpPassword'] = $this->getCrypt()->encrypt($data['smtpPassword']); - } - - $user = $this->getEntityManager()->getEntity('User', $userId); + public function actionUpdate($params, $data) + { + $userId = $params['id']; + $this->handleUserAccess($userId); + + if (array_key_exists('smtpPassword', $data)) { + $data['smtpPassword'] = $this->getCrypt()->encrypt($data['smtpPassword']); + } + + $user = $this->getEntityManager()->getEntity('User', $userId); - $entity = $this->getEntityManager()->getEntity('Preferences', $userId); - - if ($entity) { - $entity->set($data); - $this->getEntityManager()->saveEntity($entity); - - $entity->set('smtpEmailAddress', $user->get('emailAddress')); - $entity->set('name', $user->get('name')); - - $entity->clear('smtpPassword'); - - return $entity->toArray(); - } - throw new Error(); - } + $entity = $this->getEntityManager()->getEntity('Preferences', $userId); + + if ($entity) { + $entity->set($data); + $this->getEntityManager()->saveEntity($entity); + + $entity->set('smtpEmailAddress', $user->get('emailAddress')); + $entity->set('name', $user->get('name')); + + $entity->clear('smtpPassword'); + + return $entity->toArray(); + } + throw new Error(); + } public function actionRead($params) - { - $userId = $params['id']; - $this->handleUserAccess($userId); + { + $userId = $params['id']; + $this->handleUserAccess($userId); - $entity = $this->getEntityManager()->getEntity('Preferences', $userId); - $user = $this->getEntityManager()->getEntity('User', $userId); - - $entity->set('smtpEmailAddress', $user->get('emailAddress')); - $entity->set('name', $user->get('name')); - - $entity->clear('smtpPassword'); - - if ($entity) { - return $entity->toArray(); - } - throw new NotFound(); - } + $entity = $this->getEntityManager()->getEntity('Preferences', $userId); + $user = $this->getEntityManager()->getEntity('User', $userId); + + $entity->set('smtpEmailAddress', $user->get('emailAddress')); + $entity->set('name', $user->get('name')); + + $entity->clear('smtpPassword'); + + if ($entity) { + return $entity->toArray(); + } + throw new NotFound(); + } } diff --git a/application/Espo/Controllers/ScheduledJob.php b/application/Espo/Controllers/ScheduledJob.php index f06407812b..50d7f623f6 100644 --- a/application/Espo/Controllers/ScheduledJob.php +++ b/application/Espo/Controllers/ScheduledJob.php @@ -24,11 +24,11 @@ namespace Espo\Controllers; class ScheduledJob extends \Espo\Core\Controllers\Record { - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } } diff --git a/application/Espo/Controllers/ScheduledJobLogRecord.php b/application/Espo/Controllers/ScheduledJobLogRecord.php index 65483fa3ab..30b2e38835 100644 --- a/application/Espo/Controllers/ScheduledJobLogRecord.php +++ b/application/Espo/Controllers/ScheduledJobLogRecord.php @@ -24,11 +24,11 @@ namespace Espo\Controllers; class ScheduledJobLogRecord extends \Espo\Core\Controllers\Record { - protected function checkControllerAccess() - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - } + protected function checkControllerAccess() + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + } } diff --git a/application/Espo/Controllers/Settings.php b/application/Espo/Controllers/Settings.php index 5593787faa..d50a208fb4 100644 --- a/application/Espo/Controllers/Settings.php +++ b/application/Espo/Controllers/Settings.php @@ -27,48 +27,48 @@ use \Espo\Core\Exceptions\Forbidden; class Settings extends \Espo\Core\Controllers\Base { - protected function getConfigData() - { - $data = $this->getConfig()->getData($this->getUser()->isAdmin()); + protected function getConfigData() + { + $data = $this->getConfig()->getData($this->getUser()->isAdmin()); - $fieldDefs = $this->getMetadata()->get('entityDefs.Settings.fields'); + $fieldDefs = $this->getMetadata()->get('entityDefs.Settings.fields'); - foreach ($fieldDefs as $field => $d) { - if ($d['type'] == 'password') { - unset($data[$field]); - } - } - return $data; - } + foreach ($fieldDefs as $field => $d) { + if ($d['type'] == 'password') { + unset($data[$field]); + } + } + return $data; + } - public function actionRead($params, $data) - { - return $this->getConfigData(); - } + public function actionRead($params, $data) + { + return $this->getConfigData(); + } - public function actionUpdate($params, $data) - { - return $this->actionPatch($params, $data); - } + public function actionUpdate($params, $data) + { + return $this->actionPatch($params, $data); + } - public function actionPatch($params, $data) - { - if (!$this->getUser()->isAdmin()) { - throw new Forbidden(); - } + public function actionPatch($params, $data) + { + if (!$this->getUser()->isAdmin()) { + throw new Forbidden(); + } - $this->getConfig()->setData($data, $this->getUser()->isAdmin()); - $result = $this->getConfig()->save(); - if ($result === false) { - throw new Error('Cannot save settings'); - } + $this->getConfig()->setData($data, $this->getUser()->isAdmin()); + $result = $this->getConfig()->save(); + if ($result === false) { + throw new Error('Cannot save settings'); + } - /** Rebuild for Currency Settings */ - if (isset($data['baseCurrency']) || isset($data['currencyRates'])) { - $this->getContainer()->get('dataManager')->rebuildDatabase(array()); - } - /** END Rebuild for Currency Settings */ + /** Rebuild for Currency Settings */ + if (isset($data['baseCurrency']) || isset($data['currencyRates'])) { + $this->getContainer()->get('dataManager')->rebuildDatabase(array()); + } + /** END Rebuild for Currency Settings */ - return $this->getConfigData(); - } + return $this->getConfigData(); + } } diff --git a/application/Espo/Controllers/Stream.php b/application/Espo/Controllers/Stream.php index 6418c03252..ec9645197d 100644 --- a/application/Espo/Controllers/Stream.php +++ b/application/Espo/Controllers/Stream.php @@ -26,38 +26,38 @@ use \Espo\Core\Exceptions\Error; class Stream extends \Espo\Core\Controllers\Base { - const MAX_SIZE_LIMIT = 400; - - public static $defaultAction = 'list'; + const MAX_SIZE_LIMIT = 400; + + public static $defaultAction = 'list'; public function actionList($params, $data, $request) - { - $scope = $params['scope']; - $id = isset($params['id']) ? $params['id'] : null; - - $offset = intval($request->get('offset')); - $maxSize = intval($request->get('maxSize')); - $after = $request->get('after'); - - $service = $this->getService('Stream'); - - if (empty($maxSize)) { - $maxSize = self::MAX_SIZE_LIMIT; - } - if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) { - throw new Forbidden(); - } - - $result = $service->find($scope, $id, array( - 'offset' => $offset, - 'maxSize' => $maxSize, - 'after' => $after, - )); - - return array( - 'total' => $result['total'], - 'list' => $result['collection']->toArray() - ); - } + { + $scope = $params['scope']; + $id = isset($params['id']) ? $params['id'] : null; + + $offset = intval($request->get('offset')); + $maxSize = intval($request->get('maxSize')); + $after = $request->get('after'); + + $service = $this->getService('Stream'); + + if (empty($maxSize)) { + $maxSize = self::MAX_SIZE_LIMIT; + } + if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) { + throw new Forbidden(); + } + + $result = $service->find($scope, $id, array( + 'offset' => $offset, + 'maxSize' => $maxSize, + 'after' => $after, + )); + + return array( + 'total' => $result['total'], + 'list' => $result['collection']->toArray() + ); + } } diff --git a/application/Espo/Controllers/Team.php b/application/Espo/Controllers/Team.php index af5d7f6c2e..b0cc25bd27 100644 --- a/application/Espo/Controllers/Team.php +++ b/application/Espo/Controllers/Team.php @@ -24,6 +24,6 @@ namespace Espo\Controllers; class Team extends \Espo\Core\Controllers\Record { - + } diff --git a/application/Espo/Controllers/User.php b/application/Espo/Controllers/User.php index e6d1605e33..17a7138d01 100644 --- a/application/Espo/Controllers/User.php +++ b/application/Espo/Controllers/User.php @@ -27,31 +27,31 @@ use \Espo\Core\Exceptions\NotFound; use \Espo\Core\Exceptions\Forbidden; class User extends \Espo\Core\Controllers\Record -{ - public function actionAcl($params, $data, $request) - { - $userId = $request->get('id'); - if (empty($userId)) { - throw new Error(); - } - - if (!$this->getUser()->isAdmin() && $this->getUser()->id != $userId) { - throw new Forbidden(); - } - - $user = $this->getEntityManager()->getEntity('User', $userId); - if (empty($user)) { - throw new NotFound(); - } - - $acl = new \Espo\Core\Acl($user, $this->getConfig(), $this->getContainer()->get('fileManager'), $this->getMetadata()); - - return $acl->toArray(); - } - - public function actionChangeOwnPassword($params, $data) - { - return $this->getService('User')->changePassword($this->getUser()->id, $data['password']); - } +{ + public function actionAcl($params, $data, $request) + { + $userId = $request->get('id'); + if (empty($userId)) { + throw new Error(); + } + + if (!$this->getUser()->isAdmin() && $this->getUser()->id != $userId) { + throw new Forbidden(); + } + + $user = $this->getEntityManager()->getEntity('User', $userId); + if (empty($user)) { + throw new NotFound(); + } + + $acl = new \Espo\Core\Acl($user, $this->getConfig(), $this->getContainer()->get('fileManager'), $this->getMetadata()); + + return $acl->toArray(); + } + + public function actionChangeOwnPassword($params, $data) + { + return $this->getService('User')->changePassword($this->getUser()->id, $data['password']); + } } diff --git a/application/Espo/Core/Acl.php b/application/Espo/Core/Acl.php index e9ab36dcd8..03e09c6490 100644 --- a/application/Espo/Core/Acl.php +++ b/application/Espo/Core/Acl.php @@ -28,241 +28,241 @@ use \Espo\ORM\Entity; class Acl { - private $data = array(); + private $data = array(); - private $cacheFile; + private $cacheFile; - private $actionList = array('read', 'edit', 'delete'); + private $actionList = array('read', 'edit', 'delete'); - private $levelList = array('all', 'team', 'own', 'no'); - - protected $fileManager; - - protected $metadata; + private $levelList = array('all', 'team', 'own', 'no'); + + protected $fileManager; + + protected $metadata; - public function __construct(\Espo\Entities\User $user, $config = null, $fileManager = null, $metadata = null) - { - $this->user = $user; - - $this->metadata = $metadata; - - if (!$this->user->isFetched()) { - throw new Error(); - } - - $this->user->loadLinkMultipleField('teams'); - - if ($fileManager) { - $this->fileManager = $fileManager; - } - - $this->cacheFile = 'data/cache/application/acl/' . $user->id . '.php'; - - if ($config && $config->get('useCache') && file_exists($this->cacheFile)) { - $cached = include $this->cacheFile; - $this->data = $cached; - $this->initSolid(); - } else { - $this->load(); - $this->initSolid(); - if ($config && $fileManager && $config->get('useCache')) { - $this->buildCache(); - } - } + public function __construct(\Espo\Entities\User $user, $config = null, $fileManager = null, $metadata = null) + { + $this->user = $user; + + $this->metadata = $metadata; + + if (!$this->user->isFetched()) { + throw new Error(); + } + + $this->user->loadLinkMultipleField('teams'); + + if ($fileManager) { + $this->fileManager = $fileManager; + } + + $this->cacheFile = 'data/cache/application/acl/' . $user->id . '.php'; + + if ($config && $config->get('useCache') && file_exists($this->cacheFile)) { + $cached = include $this->cacheFile; + $this->data = $cached; + $this->initSolid(); + } else { + $this->load(); + $this->initSolid(); + if ($config && $fileManager && $config->get('useCache')) { + $this->buildCache(); + } + } - } - - public function checkScope($scope, $action = null, $isOwner = null, $inTeam = null, $entity = null) - { - if (array_key_exists($scope, $this->data)) { - if ($this->data[$scope] === false) { - return false; - } - if ($this->data[$scope] === true) { - return true; - } - if (!is_null($action)) { - if (array_key_exists($action, $this->data[$scope])) { - $value = $this->data[$scope][$action]; - - if ($value === 'all' || $value === true) { - return true; - } - - if (!$value || $value === 'no') { - return false; - } - - if (is_null($isOwner)) { - return true; - } - - if ($isOwner) { - if ($value === 'own' || $value === 'team') { - return true; - } - } - if ($inTeam === null && $entity) { - $inTeam = $this->checkInTeam($entity); - } - - if ($inTeam) { - if ($value === 'team') { - return true; - } - } - - return false; - } - } - return true; - } - return true; - } - - public function toArray() - { - return $this->data; - } + } + + public function checkScope($scope, $action = null, $isOwner = null, $inTeam = null, $entity = null) + { + if (array_key_exists($scope, $this->data)) { + if ($this->data[$scope] === false) { + return false; + } + if ($this->data[$scope] === true) { + return true; + } + if (!is_null($action)) { + if (array_key_exists($action, $this->data[$scope])) { + $value = $this->data[$scope][$action]; + + if ($value === 'all' || $value === true) { + return true; + } + + if (!$value || $value === 'no') { + return false; + } + + if (is_null($isOwner)) { + return true; + } + + if ($isOwner) { + if ($value === 'own' || $value === 'team') { + return true; + } + } + if ($inTeam === null && $entity) { + $inTeam = $this->checkInTeam($entity); + } + + if ($inTeam) { + if ($value === 'team') { + return true; + } + } + + return false; + } + } + return true; + } + return true; + } + + public function toArray() + { + return $this->data; + } - public function check($subject, $action = null, $isOwner = null, $inTeam = null) - { - if ($this->user->isAdmin()) { - return true; - } - if (is_string($subject)) { - return $this->checkScope($subject, $action, $isOwner, $inTeam); - } else { - $entity = $subject; - if ($entity instanceof Entity) { - $entityName = $entity->getEntityName(); - return $this->checkScope($entityName, $action, $this->checkIsOwner($entity), $inTeam, $entity); - } - } - } - - public function checkReadOnlyTeam($scope) - { - if (isset($this->data[$scope]) && isset($this->data[$scope]['read'])) { - return $this->data[$scope]['read'] === 'team'; - } - return false; - } - - public function checkReadOnlyOwn($scope) - { - if ($this->user->isAdmin()) { - return false; - } - if (isset($this->data[$scope]) && isset($this->data[$scope]['read'])) { - return $this->data[$scope]['read'] === 'own'; - } - return false; - } - - public function checkIsOwner($entity) - { - if ($this->user->isAdmin()) { - return false; - } - $userId = $this->user->id; - if ($userId === $entity->get('assignedUserId') || $userId === $entity->get('createdById')) { - return true; - } - return false; - } - - public function checkInTeam($entity) - { - $userTeamIds = $this->user->get('teamsIds'); - - if (!$entity->hasRelation('teams') || !$entity->hasField('teamsIds')) { - return false; - } - - if (!$entity->has('teamsIds')) { - $entity->loadLinkMultipleField('teams'); - } - - $teamIds = $entity->get('teamsIds'); - - if (empty($teamIds)) { - return false; - } - - foreach ($userTeamIds as $id) { - if (in_array($id, $teamIds)) { - return true; - } - } - return false; - } + public function check($subject, $action = null, $isOwner = null, $inTeam = null) + { + if ($this->user->isAdmin()) { + return true; + } + if (is_string($subject)) { + return $this->checkScope($subject, $action, $isOwner, $inTeam); + } else { + $entity = $subject; + if ($entity instanceof Entity) { + $entityName = $entity->getEntityName(); + return $this->checkScope($entityName, $action, $this->checkIsOwner($entity), $inTeam, $entity); + } + } + } + + public function checkReadOnlyTeam($scope) + { + if (isset($this->data[$scope]) && isset($this->data[$scope]['read'])) { + return $this->data[$scope]['read'] === 'team'; + } + return false; + } + + public function checkReadOnlyOwn($scope) + { + if ($this->user->isAdmin()) { + return false; + } + if (isset($this->data[$scope]) && isset($this->data[$scope]['read'])) { + return $this->data[$scope]['read'] === 'own'; + } + return false; + } + + public function checkIsOwner($entity) + { + if ($this->user->isAdmin()) { + return false; + } + $userId = $this->user->id; + if ($userId === $entity->get('assignedUserId') || $userId === $entity->get('createdById')) { + return true; + } + return false; + } + + public function checkInTeam($entity) + { + $userTeamIds = $this->user->get('teamsIds'); + + if (!$entity->hasRelation('teams') || !$entity->hasField('teamsIds')) { + return false; + } + + if (!$entity->has('teamsIds')) { + $entity->loadLinkMultipleField('teams'); + } + + $teamIds = $entity->get('teamsIds'); + + if (empty($teamIds)) { + return false; + } + + foreach ($userTeamIds as $id) { + if (in_array($id, $teamIds)) { + return true; + } + } + return false; + } - private function load() - { - $aclTables = array(); + private function load() + { + $aclTables = array(); - $userRoles = $this->user->get('roles'); - - foreach ($userRoles as $role) { - $aclTables[] = json_decode($role->get('data')); - } + $userRoles = $this->user->get('roles'); + + foreach ($userRoles as $role) { + $aclTables[] = json_decode($role->get('data')); + } - $teams = $this->user->get('teams'); - foreach ($teams as $team) { - $teamRoles = $team->get('roles'); - foreach ($teamRoles as $role) { - $aclTables[] = json_decode($role->get('data')); - } - } + $teams = $this->user->get('teams'); + foreach ($teams as $team) { + $teamRoles = $team->get('roles'); + foreach ($teamRoles as $role) { + $aclTables[] = json_decode($role->get('data')); + } + } - $this->data = $this->merge($aclTables); - } - - private function initSolid() - { - $data = $this->metadata->get('app.acl.solid', array()); - - foreach ($data as $entityName => $item) { - $this->data[$entityName] = $item; - } - } + $this->data = $this->merge($aclTables); + } + + private function initSolid() + { + $data = $this->metadata->get('app.acl.solid', array()); + + foreach ($data as $entityName => $item) { + $this->data[$entityName] = $item; + } + } - private function merge($tables) - { - $data = array(); - foreach ($tables as $table) { - foreach ($table as $scope => $row) { - if ($row == false) { - if (!isset($data[$scope])) { - $data[$scope] = false; - } - } else { - if (!isset($data[$scope])) { - $data[$scope] = array(); - } - if ($data[$scope] == false) { - $data[$scope] = array(); - } - foreach ($row as $action => $level) { - if (!isset($data[$scope][$action])) { - $data[$scope][$action] = $level; - } else { - if (array_search($data[$scope][$action], $this->levelList) > array_search($level, $this->levelList)) { - $data[$scope][$action] = $level; - } - } - } - } - } - } - return $data; - } + private function merge($tables) + { + $data = array(); + foreach ($tables as $table) { + foreach ($table as $scope => $row) { + if ($row == false) { + if (!isset($data[$scope])) { + $data[$scope] = false; + } + } else { + if (!isset($data[$scope])) { + $data[$scope] = array(); + } + if ($data[$scope] == false) { + $data[$scope] = array(); + } + foreach ($row as $action => $level) { + if (!isset($data[$scope][$action])) { + $data[$scope][$action] = $level; + } else { + if (array_search($data[$scope][$action], $this->levelList) > array_search($level, $this->levelList)) { + $data[$scope][$action] = $level; + } + } + } + } + } + } + return $data; + } - private function buildCache() - { - $contents = '<' . '?'. 'php return ' . var_export($this->data, true) . ';'; - $this->fileManager->putContents($this->cacheFile, $contents); - } + private function buildCache() + { + $contents = '<' . '?'. 'php return ' . var_export($this->data, true) . ';'; + $this->fileManager->putContents($this->cacheFile, $contents); + } } diff --git a/application/Espo/Core/Application.php b/application/Espo/Core/Application.php index 95f3b97b8c..29dee4f3a4 100644 --- a/application/Espo/Core/Application.php +++ b/application/Espo/Core/Application.php @@ -25,54 +25,54 @@ namespace Espo\Core; class Application { - private $metadata; + private $metadata; - private $container; + private $container; - private $slim; + private $slim; - private $auth; + private $auth; - /** + /** * Constructor */ public function __construct() { - $this->container = new Container(); + $this->container = new Container(); - date_default_timezone_set('UTC'); + date_default_timezone_set('UTC'); - $GLOBALS['log'] = $this->container->get('log'); + $GLOBALS['log'] = $this->container->get('log'); } - public function getSlim() - { - if (empty($this->slim)) { - $this->slim = $this->container->get('slim'); - } - return $this->slim; - } + public function getSlim() + { + if (empty($this->slim)) { + $this->slim = $this->container->get('slim'); + } + return $this->slim; + } - public function getMetadata() - { - if (empty($this->metadata)) { - $this->metadata = $this->container->get('metadata'); - } - return $this->metadata; - } + public function getMetadata() + { + if (empty($this->metadata)) { + $this->metadata = $this->container->get('metadata'); + } + return $this->metadata; + } protected function getAuth() { - if (empty($this->auth)) { - $this->auth = new \Espo\Core\Utils\Auth($this->container); - } - return $this->auth; + if (empty($this->auth)) { + $this->auth = new \Espo\Core\Utils\Auth($this->container); + } + return $this->auth; } - public function getContainer() - { - return $this->container; - } + public function getContainer() + { + return $this->container; + } public function run($name = 'default') { @@ -83,160 +83,160 @@ class Application public function runClient() { - $config = $this->getContainer()->get('config'); + $config = $this->getContainer()->get('config'); - $html = file_get_contents('main.html'); - $html = str_replace('{{cacheTimestamp}}', $config->get('cacheTimestamp', 0), $html); - $html = str_replace('{{useCache}}', $config->get('useCache') ? 'true' : 'false' , $html); - echo $html; - exit; + $html = file_get_contents('main.html'); + $html = str_replace('{{cacheTimestamp}}', $config->get('cacheTimestamp', 0), $html); + $html = str_replace('{{useCache}}', $config->get('useCache') ? 'true' : 'false' , $html); + echo $html; + exit; } public function runEntryPoint($entryPoint) { - if (empty($entryPoint)) { - throw new \Error(); - } + if (empty($entryPoint)) { + throw new \Error(); + } - $slim = $this->getSlim(); - $container = $this->getContainer(); + $slim = $this->getSlim(); + $container = $this->getContainer(); - $slim->get('/', function() {}); + $slim->get('/', function() {}); - $entryPointManager = new \Espo\Core\EntryPointManager($container); + $entryPointManager = new \Espo\Core\EntryPointManager($container); - $auth = $this->getAuth(); - $apiAuth = new \Espo\Core\Utils\Api\Auth($auth, $entryPointManager->checkAuthRequired($entryPoint), true); - $slim->add($apiAuth); + $auth = $this->getAuth(); + $apiAuth = new \Espo\Core\Utils\Api\Auth($auth, $entryPointManager->checkAuthRequired($entryPoint), true); + $slim->add($apiAuth); - $slim->hook('slim.before.dispatch', function () use ($entryPoint, $entryPointManager, $container) { - try { - $entryPointManager->run($entryPoint); - } catch (\Exception $e) { - $container->get('output')->processError($e->getMessage(), $e->getCode(), true); - } - }); + $slim->hook('slim.before.dispatch', function () use ($entryPoint, $entryPointManager, $container) { + try { + $entryPointManager->run($entryPoint); + } catch (\Exception $e) { + $container->get('output')->processError($e->getMessage(), $e->getCode(), true); + } + }); - $slim->run(); + $slim->run(); } public function runCron() { - $auth = $this->getAuth(); - $auth->useNoAuth(true); + $auth = $this->getAuth(); + $auth->useNoAuth(true); - $cronManager = new \Espo\Core\CronManager($this->container); - $cronManager->run(); + $cronManager = new \Espo\Core\CronManager($this->container); + $cronManager->run(); } public function runRebuild() { - $dataManager = $this->getContainer()->get('dataManager'); - $dataManager->rebuild(); + $dataManager = $this->getContainer()->get('dataManager'); + $dataManager->rebuild(); } public function isInstalled() { - $config = $this->getContainer()->get('config'); + $config = $this->getContainer()->get('config'); - if (file_exists($config->getConfigPath()) && $config->get('isInstalled')) { - return true; - } + if (file_exists($config->getConfigPath()) && $config->get('isInstalled')) { + return true; + } - return false; + return false; } - protected function routeHooks() - { - $container = $this->getContainer(); - $slim = $this->getSlim(); + protected function routeHooks() + { + $container = $this->getContainer(); + $slim = $this->getSlim(); - $auth = $this->getAuth(); + $auth = $this->getAuth(); - $apiAuth = new \Espo\Core\Utils\Api\Auth($auth); - $this->getSlim()->add($apiAuth); + $apiAuth = new \Espo\Core\Utils\Api\Auth($auth); + $this->getSlim()->add($apiAuth); - $this->getSlim()->hook('slim.before.dispatch', function () use ($slim, $container) { + $this->getSlim()->hook('slim.before.dispatch', function () use ($slim, $container) { - $route = $slim->router()->getCurrentRoute(); - $conditions = $route->getConditions(); + $route = $slim->router()->getCurrentRoute(); + $conditions = $route->getConditions(); - if (isset($conditions['useController']) && $conditions['useController'] == false) { - return; - } + if (isset($conditions['useController']) && $conditions['useController'] == false) { + return; + } - $routeOptions = call_user_func($route->getCallable()); - $routeKeys = is_array($routeOptions) ? array_keys($routeOptions) : array(); + $routeOptions = call_user_func($route->getCallable()); + $routeKeys = is_array($routeOptions) ? array_keys($routeOptions) : array(); - if (!in_array('controller', $routeKeys, true)) { - return $container->get('output')->render($routeOptions); - } + if (!in_array('controller', $routeKeys, true)) { + return $container->get('output')->render($routeOptions); + } - $params = $route->getParams(); - $data = $slim->request()->getBody(); + $params = $route->getParams(); + $data = $slim->request()->getBody(); - foreach ($routeOptions as $key => $value) { - if (strstr($value, ':')) { - $paramName = str_replace(':', '', $value); - $value = $params[$paramName]; - } - $controllerParams[$key] = $value; - } + foreach ($routeOptions as $key => $value) { + if (strstr($value, ':')) { + $paramName = str_replace(':', '', $value); + $value = $params[$paramName]; + } + $controllerParams[$key] = $value; + } - $params = array_merge($params, $controllerParams); + $params = array_merge($params, $controllerParams); - $controllerName = ucfirst($controllerParams['controller']); + $controllerName = ucfirst($controllerParams['controller']); - if (!empty($controllerParams['action'])) { - $actionName = $controllerParams['action']; - } else { - $httpMethod = strtolower($slim->request()->getMethod()); - $crudList = $container->get('config')->get('crud'); - $actionName = $crudList[$httpMethod]; - } + if (!empty($controllerParams['action'])) { + $actionName = $controllerParams['action']; + } else { + $httpMethod = strtolower($slim->request()->getMethod()); + $crudList = $container->get('config')->get('crud'); + $actionName = $crudList[$httpMethod]; + } - try { - $controllerManager = new \Espo\Core\ControllerManager($container); - $result = $controllerManager->process($controllerName, $actionName, $params, $data, $slim->request()); - $container->get('output')->render($result); - } catch (\Exception $e) { - $container->get('output')->processError($e->getMessage(), $e->getCode()); - } - }); + try { + $controllerManager = new \Espo\Core\ControllerManager($container); + $result = $controllerManager->process($controllerName, $actionName, $params, $data, $slim->request()); + $container->get('output')->render($result); + } catch (\Exception $e) { + $container->get('output')->processError($e->getMessage(), $e->getCode()); + } + }); - $this->getSlim()->hook('slim.after.router', function () use (&$slim) { - $slim->contentType('application/json'); + $this->getSlim()->hook('slim.after.router', function () use (&$slim) { + $slim->contentType('application/json'); - $res = $slim->response(); - $res->header('Expires', '0'); - $res->header('Last-Modified', gmdate("D, d M Y H:i:s") . " GMT"); - $res->header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); - $res->header('Pragma', 'no-cache'); - }); - } + $res = $slim->response(); + $res->header('Expires', '0'); + $res->header('Last-Modified', gmdate("D, d M Y H:i:s") . " GMT"); + $res->header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); + $res->header('Pragma', 'no-cache'); + }); + } - protected function initRoutes() - { - $routes = new \Espo\Core\Utils\Route($this->getContainer()->get('config'), $this->getMetadata(), $this->getContainer()->get('fileManager')); - $crudList = array_keys( $this->getContainer()->get('config')->get('crud') ); + protected function initRoutes() + { + $routes = new \Espo\Core\Utils\Route($this->getContainer()->get('config'), $this->getMetadata(), $this->getContainer()->get('fileManager')); + $crudList = array_keys( $this->getContainer()->get('config')->get('crud') ); - foreach ($routes->getAll() as $route) { + foreach ($routes->getAll() as $route) { - $method = strtolower($route['method']); - if (!in_array($method, $crudList)) { - $GLOBALS['log']->error('Route: Method ['.$method.'] does not exist. Please check your route ['.$route['route'].']'); - continue; - } + $method = strtolower($route['method']); + if (!in_array($method, $crudList)) { + $GLOBALS['log']->error('Route: Method ['.$method.'] does not exist. Please check your route ['.$route['route'].']'); + continue; + } $currentRoute = $this->getSlim()->$method($route['route'], function() use ($route) { //todo change "use" for php 5.4 - return $route['params']; - }); + return $route['params']; + }); - if (isset($route['conditions'])) { - $currentRoute->conditions($route['conditions']); - } - } - } + if (isset($route['conditions'])) { + $currentRoute->conditions($route['conditions']); + } + } + } } diff --git a/application/Espo/Core/Container.php b/application/Espo/Core/Container.php index 022ff4259b..aa3f75ec69 100644 --- a/application/Espo/Core/Container.php +++ b/application/Espo/Core/Container.php @@ -25,10 +25,10 @@ namespace Espo\Core; class Container { - private $data = array(); + private $data = array(); - /** + /** * Constructor */ public function __construct() @@ -38,38 +38,38 @@ class Container public function get($name) { - if (empty($this->data[$name])) { - $this->load($name); - } - return $this->data[$name]; + if (empty($this->data[$name])) { + $this->load($name); + } + return $this->data[$name]; } private function load($name) { - $loadMethod = 'load' . ucfirst($name); - if (method_exists($this, $loadMethod)) { - $obj = $this->$loadMethod(); - $this->data[$name] = $obj; - } else { - $className = '\Espo\Custom\Core\Loaders\\'.ucfirst($name); + $loadMethod = 'load' . ucfirst($name); + if (method_exists($this, $loadMethod)) { + $obj = $this->$loadMethod(); + $this->data[$name] = $obj; + } else { + $className = '\Espo\Custom\Core\Loaders\\'.ucfirst($name); if (!class_exists($className)) { - $className = '\Espo\Core\Loaders\\'.ucfirst($name); + $className = '\Espo\Core\Loaders\\'.ucfirst($name); } - if (class_exists($className)) { - $loadClass = new $className($this); - $this->data[$name] = $loadClass->load(); - } - } + if (class_exists($className)) { + $loadClass = new $className($this); + $this->data[$name] = $loadClass->load(); + } + } - return null; + return null; } protected function getServiceClassName($name, $default) { - $metadata = $this->get('metadata'); - $className = $metadata->get('app.serviceContainer.classNames.' . $name, $default); - return $className; + $metadata = $this->get('metadata'); + $className = $metadata->get('app.serviceContainer.classNames.' . $name, $default); + return $className; } private function loadSlim() @@ -77,161 +77,161 @@ class Container return new \Espo\Core\Utils\Api\Slim(); } - private function loadFileManager() + private function loadFileManager() { - return new \Espo\Core\Utils\File\Manager( - $this->get('config') - ); + return new \Espo\Core\Utils\File\Manager( + $this->get('config') + ); } - private function loadPreferences() + private function loadPreferences() { - return $this->get('entityManager')->getEntity('Preferences', $this->get('user')->id); + return $this->get('entityManager')->getEntity('Preferences', $this->get('user')->id); } - private function loadConfig() + private function loadConfig() { - return new \Espo\Core\Utils\Config( - new \Espo\Core\Utils\File\Manager() - ); + return new \Espo\Core\Utils\Config( + new \Espo\Core\Utils\File\Manager() + ); } - private function loadHookManager() + private function loadHookManager() { - return new \Espo\Core\HookManager( - $this - ); + return new \Espo\Core\HookManager( + $this + ); } - private function loadOutput() + private function loadOutput() { - return new \Espo\Core\Utils\Api\Output( - $this->get('slim') - ); + return new \Espo\Core\Utils\Api\Output( + $this->get('slim') + ); } - private function loadMailSender() + private function loadMailSender() { - $className = $this->getServiceClassName('mailSernder', '\\Espo\\Core\\Mail\\Sender'); - return new $className( - $this->get('config') - ); + $className = $this->getServiceClassName('mailSernder', '\\Espo\\Core\\Mail\\Sender'); + return new $className( + $this->get('config') + ); } - private function loadDateTime() + private function loadDateTime() { - return new \Espo\Core\Utils\DateTime( - $this->get('config')->get('dateFormat'), - $this->get('config')->get('timeFormat'), - $this->get('config')->get('timeZone') - ); + return new \Espo\Core\Utils\DateTime( + $this->get('config')->get('dateFormat'), + $this->get('config')->get('timeFormat'), + $this->get('config')->get('timeZone') + ); } - private function loadServiceFactory() + private function loadServiceFactory() { - return new \Espo\Core\ServiceFactory( - $this - ); + return new \Espo\Core\ServiceFactory( + $this + ); } - private function loadSelectManagerFactory() + private function loadSelectManagerFactory() { - return new \Espo\Core\SelectManagerFactory( - $this->get('entityManager'), - $this->get('user'), - $this->get('acl'), - $this->get('metadata') - ); + return new \Espo\Core\SelectManagerFactory( + $this->get('entityManager'), + $this->get('user'), + $this->get('acl'), + $this->get('metadata') + ); } - private function loadMetadata() + private function loadMetadata() { - return new \Espo\Core\Utils\Metadata( - $this->get('config'), - $this->get('fileManager') - ); + return new \Espo\Core\Utils\Metadata( + $this->get('config'), + $this->get('fileManager') + ); } - private function loadLayout() + private function loadLayout() { - return new \Espo\Core\Utils\Layout( - $this->get('fileManager'), - $this->get('metadata') - ); + return new \Espo\Core\Utils\Layout( + $this->get('fileManager'), + $this->get('metadata') + ); } - private function loadAcl() - { - $className = $this->getServiceClassName('acl', '\\Espo\\Core\\Acl'); - return new $className( - $this->get('user'), - $this->get('config'), - $this->get('fileManager'), - $this->get('metadata') - ); - } + private function loadAcl() + { + $className = $this->getServiceClassName('acl', '\\Espo\\Core\\Acl'); + return new $className( + $this->get('user'), + $this->get('config'), + $this->get('fileManager'), + $this->get('metadata') + ); + } - private function loadSchema() - { - return new \Espo\Core\Utils\Database\Schema\Schema( - $this->get('config'), - $this->get('metadata'), - $this->get('fileManager'), - $this->get('entityManager'), - $this->get('classParser') - ); - } + private function loadSchema() + { + return new \Espo\Core\Utils\Database\Schema\Schema( + $this->get('config'), + $this->get('metadata'), + $this->get('fileManager'), + $this->get('entityManager'), + $this->get('classParser') + ); + } - private function loadClassParser() - { - return new \Espo\Core\Utils\File\ClassParser( - $this->get('fileManager'), - $this->get('config'), - $this->get('metadata') - ); - } + private function loadClassParser() + { + return new \Espo\Core\Utils\File\ClassParser( + $this->get('fileManager'), + $this->get('config'), + $this->get('metadata') + ); + } - private function loadLanguage() - { - return new \Espo\Core\Utils\Language( - $this->get('fileManager'), - $this->get('config'), - $this->get('preferences') - ); - } - - private function loadCrypt() - { - return new \Espo\Core\Utils\Crypt( - $this->get('config') - ); - } + private function loadLanguage() + { + return new \Espo\Core\Utils\Language( + $this->get('fileManager'), + $this->get('config'), + $this->get('preferences') + ); + } + + private function loadCrypt() + { + return new \Espo\Core\Utils\Crypt( + $this->get('config') + ); + } - private function loadScheduledJob() - { - return new \Espo\Core\Cron\ScheduledJob( - $this - ); - } + private function loadScheduledJob() + { + return new \Espo\Core\Cron\ScheduledJob( + $this + ); + } - private function loadDataManager() - { - return new \Espo\Core\DataManager( - $this - ); - } + private function loadDataManager() + { + return new \Espo\Core\DataManager( + $this + ); + } - private function loadFieldManager() - { - return new \Espo\Core\Utils\FieldManager( - $this->get('metadata'), - $this->get('language') - ); - } + private function loadFieldManager() + { + return new \Espo\Core\Utils\FieldManager( + $this->get('metadata'), + $this->get('language') + ); + } - public function setUser($user) - { - $this->data['user'] = $user; - } + public function setUser($user) + { + $this->data['user'] = $user; + } } diff --git a/application/Espo/Core/ControllerManager.php b/application/Espo/Core/ControllerManager.php index 6c6b796c06..ee92f71c07 100644 --- a/application/Espo/Core/ControllerManager.php +++ b/application/Espo/Core/ControllerManager.php @@ -27,88 +27,88 @@ use \Espo\Core\Exceptions\NotFound; class ControllerManager { - private $config; + private $config; - private $metadata; + private $metadata; - private $container; + private $container; - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; - $this->config = $this->container->get('config'); - $this->metadata = $this->container->get('metadata'); - } + $this->config = $this->container->get('config'); + $this->metadata = $this->container->get('metadata'); + } protected function getConfig() - { - return $this->config; - } + { + return $this->config; + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - public function process($controllerName, $actionName, $params, $data, $request) - { - $customeClassName = '\\Espo\\Custom\\Controllers\\' . Util::normilizeClassName($controllerName); - if (class_exists($customeClassName)) { - $controllerClassName = $customeClassName; - } else { - $moduleName = $this->metadata->getScopeModuleName($controllerName); - if ($moduleName) { - $controllerClassName = '\\Espo\\Modules\\' . $moduleName . '\\Controllers\\' . Util::normilizeClassName($controllerName); - } else { - $controllerClassName = '\\Espo\\Controllers\\' . Util::normilizeClassName($controllerName); - } - } + public function process($controllerName, $actionName, $params, $data, $request) + { + $customeClassName = '\\Espo\\Custom\\Controllers\\' . Util::normilizeClassName($controllerName); + if (class_exists($customeClassName)) { + $controllerClassName = $customeClassName; + } else { + $moduleName = $this->metadata->getScopeModuleName($controllerName); + if ($moduleName) { + $controllerClassName = '\\Espo\\Modules\\' . $moduleName . '\\Controllers\\' . Util::normilizeClassName($controllerName); + } else { + $controllerClassName = '\\Espo\\Controllers\\' . Util::normilizeClassName($controllerName); + } + } - if ($data && stristr($request->getContentType(), 'application/json')) { - $data = json_decode($data); - } + if ($data && stristr($request->getContentType(), 'application/json')) { + $data = json_decode($data); + } - if ($data instanceof \stdClass) { - $data = get_object_vars($data); - } + if ($data instanceof \stdClass) { + $data = get_object_vars($data); + } - if (!class_exists($controllerClassName)) { - throw new NotFound("Controller '$controllerName' is not found"); - } + if (!class_exists($controllerClassName)) { + throw new NotFound("Controller '$controllerName' is not found"); + } - $controller = new $controllerClassName($this->container, $request->getMethod()); + $controller = new $controllerClassName($this->container, $request->getMethod()); - if ($actionName == 'index') { - $actionName = $controllerClassName::$defaultAction; - } + if ($actionName == 'index') { + $actionName = $controllerClassName::$defaultAction; + } - $actionNameUcfirst = ucfirst($actionName); + $actionNameUcfirst = ucfirst($actionName); - $beforeMethodName = 'before' . $actionNameUcfirst; - if (method_exists($controller, $beforeMethodName)) { - $controller->$beforeMethodName($params, $data, $request); - } - $actionMethodName = 'action' . $actionNameUcfirst; + $beforeMethodName = 'before' . $actionNameUcfirst; + if (method_exists($controller, $beforeMethodName)) { + $controller->$beforeMethodName($params, $data, $request); + } + $actionMethodName = 'action' . $actionNameUcfirst; - if (!method_exists($controller, $actionMethodName)) { - throw new NotFound("Action '$actionMethodName' does not exist in controller '$controller'"); - } + if (!method_exists($controller, $actionMethodName)) { + throw new NotFound("Action '$actionMethodName' does not exist in controller '$controller'"); + } - $result = $controller->$actionMethodName($params, $data, $request); + $result = $controller->$actionMethodName($params, $data, $request); - $afterMethodName = 'after' . $actionNameUcfirst; - if (method_exists($controller, $afterMethodName)) { - $controller->$afterMethodName($params, $data, $request); - } + $afterMethodName = 'after' . $actionNameUcfirst; + if (method_exists($controller, $afterMethodName)) { + $controller->$afterMethodName($params, $data, $request); + } - if (is_array($result) || is_bool($result)) { - return \Espo\Core\Utils\Json::encode($result); - } + if (is_array($result) || is_bool($result)) { + return \Espo\Core\Utils\Json::encode($result); + } - return $result; - } + return $result; + } } diff --git a/application/Espo/Core/Controllers/Base.php b/application/Espo/Core/Controllers/Base.php index cf8f1703fd..7c49730251 100644 --- a/application/Espo/Core/Controllers/Base.php +++ b/application/Espo/Core/Controllers/Base.php @@ -28,91 +28,91 @@ use \Espo\Core\Utils\Util; abstract class Base { - protected $name; + protected $name; - private $container; + private $container; - private $requestMethod; + private $requestMethod; - public static $defaultAction = 'index'; + public static $defaultAction = 'index'; - public function __construct(Container $container, $requestMethod = null) - { - $this->container = $container; + public function __construct(Container $container, $requestMethod = null) + { + $this->container = $container; - if (isset($requestMethod)) { - $this->setRequestMethod($requestMethod); - } + if (isset($requestMethod)) { + $this->setRequestMethod($requestMethod); + } - if (empty($this->name)) { - $name = get_class($this); - if (preg_match('@\\\\([\w]+)$@', $name, $matches)) { - $name = $matches[1]; - } - $this->name = $name; - } + if (empty($this->name)) { + $name = get_class($this); + if (preg_match('@\\\\([\w]+)$@', $name, $matches)) { + $name = $matches[1]; + } + $this->name = $name; + } - $this->checkControllerAccess(); - } + $this->checkControllerAccess(); + } - protected function checkControllerAccess() - { - return; - } + protected function checkControllerAccess() + { + return; + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - /** - * Get request method name (Uppercase) - * - * @return string - */ - protected function getRequestMethod() - { - return $this->requestMethod; - } + /** + * Get request method name (Uppercase) + * + * @return string + */ + protected function getRequestMethod() + { + return $this->requestMethod; + } - protected function setRequestMethod($requestMethod) - { - $this->requestMethod = strtoupper($requestMethod); - } + protected function setRequestMethod($requestMethod) + { + $this->requestMethod = strtoupper($requestMethod); + } - protected function getUser() - { - return $this->container->get('user'); - } + protected function getUser() + { + return $this->container->get('user'); + } - protected function getAcl() - { - return $this->container->get('acl'); - } + protected function getAcl() + { + return $this->container->get('acl'); + } - protected function getConfig() - { - return $this->container->get('config'); - } + protected function getConfig() + { + return $this->container->get('config'); + } - protected function getPreferences() - { - return $this->container->get('preferences'); - } + protected function getPreferences() + { + return $this->container->get('preferences'); + } - protected function getMetadata() - { - return $this->container->get('metadata'); - } + protected function getMetadata() + { + return $this->container->get('metadata'); + } - protected function getServiceFactory() - { - return $this->container->get('serviceFactory'); - } + protected function getServiceFactory() + { + return $this->container->get('serviceFactory'); + } - protected function getService($name) - { - return $this->getServiceFactory()->create($name); - } + protected function getService($name) + { + return $this->getServiceFactory()->create($name); + } } diff --git a/application/Espo/Core/Controllers/Record.php b/application/Espo/Core/Controllers/Record.php index 0f20ea26c6..25c3e5f914 100644 --- a/application/Espo/Core/Controllers/Record.php +++ b/application/Espo/Core/Controllers/Record.php @@ -29,277 +29,277 @@ use \Espo\Core\Utils\Util; class Record extends Base { - const MAX_SIZE_LIMIT = 200; - - public static $defaultAction = 'list'; - - protected function getEntityManager() - { - return $this->getContainer()->get('entityManager'); - } - - protected function getRecordService($name = null) - { - if (empty($name)) { - $name = $this->name; - } - - if ($this->getServiceFactory()->checkExists($name)) { - $service = $this->getServiceFactory()->create($name); - } else { - $service = $this->getServiceFactory()->create('Record'); - $service->setEntityName($name); - } - - return $service; - } + const MAX_SIZE_LIMIT = 200; + + public static $defaultAction = 'list'; + + protected function getEntityManager() + { + return $this->getContainer()->get('entityManager'); + } + + protected function getRecordService($name = null) + { + if (empty($name)) { + $name = $this->name; + } + + if ($this->getServiceFactory()->checkExists($name)) { + $service = $this->getServiceFactory()->create($name); + } else { + $service = $this->getServiceFactory()->create('Record'); + $service->setEntityName($name); + } + + return $service; + } - public function actionRead($params) - { - $id = $params['id']; - $entity = $this->getRecordService()->getEntity($id); - - if (empty($entity)) { - throw new NotFound(); - } + public function actionRead($params) + { + $id = $params['id']; + $entity = $this->getRecordService()->getEntity($id); + + if (empty($entity)) { + throw new NotFound(); + } - return $entity->toArray(); - } - - public function actionPatch($params, $data) - { - return $this->actionUpdate($params, $data); - } - - public function actionCreate($params, $data) - { - if (!$this->getAcl()->check($this->name, 'edit')) { - throw new Forbidden(); - } + return $entity->toArray(); + } + + public function actionPatch($params, $data) + { + return $this->actionUpdate($params, $data); + } + + public function actionCreate($params, $data) + { + if (!$this->getAcl()->check($this->name, 'edit')) { + throw new Forbidden(); + } - $service = $this->getRecordService(); - - if ($entity = $service->createEntity($data)) { - return $entity->toArray(); - } + $service = $this->getRecordService(); + + if ($entity = $service->createEntity($data)) { + return $entity->toArray(); + } - throw new Error(); - } + throw new Error(); + } - public function actionUpdate($params, $data) - { - if (!$this->getAcl()->check($this->name, 'edit')) { - throw new Forbidden(); - } - - $id = $params['id']; - - if ($entity = $this->getRecordService()->updateEntity($id, $data)) { - return $entity->toArray(); - } + public function actionUpdate($params, $data) + { + if (!$this->getAcl()->check($this->name, 'edit')) { + throw new Forbidden(); + } + + $id = $params['id']; + + if ($entity = $this->getRecordService()->updateEntity($id, $data)) { + return $entity->toArray(); + } - throw new Error(); - } + throw new Error(); + } - public function actionList($params, $data, $request) - { - if (!$this->getAcl()->check($this->name, 'read')) { - throw new Forbidden(); - } + public function actionList($params, $data, $request) + { + if (!$this->getAcl()->check($this->name, 'read')) { + throw new Forbidden(); + } - $where = $request->get('where'); - $offset = $request->get('offset'); - $maxSize = $request->get('maxSize'); - $asc = $request->get('asc') === 'true'; - $sortBy = $request->get('sortBy'); - $q = $request->get('q'); - - if (empty($maxSize)) { - $maxSize = self::MAX_SIZE_LIMIT; - } - if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) { - throw new Forbidden(); - } + $where = $request->get('where'); + $offset = $request->get('offset'); + $maxSize = $request->get('maxSize'); + $asc = $request->get('asc') === 'true'; + $sortBy = $request->get('sortBy'); + $q = $request->get('q'); + + if (empty($maxSize)) { + $maxSize = self::MAX_SIZE_LIMIT; + } + if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) { + throw new Forbidden(); + } - $result = $this->getRecordService()->findEntities(array( - 'where' => $where, - 'offset' => $offset, - 'maxSize' => $maxSize, - 'asc' => $asc, - 'sortBy' => $sortBy, - 'q' => $q, - )); - - return array( - 'total' => $result['total'], - 'list' => $result['collection']->toArray() - ); - } - - public function actionListLinked($params, $data, $request) - { - $id = $params['id']; - $link = $params['link']; + $result = $this->getRecordService()->findEntities(array( + 'where' => $where, + 'offset' => $offset, + 'maxSize' => $maxSize, + 'asc' => $asc, + 'sortBy' => $sortBy, + 'q' => $q, + )); + + return array( + 'total' => $result['total'], + 'list' => $result['collection']->toArray() + ); + } + + public function actionListLinked($params, $data, $request) + { + $id = $params['id']; + $link = $params['link']; - $where = $request->get('where'); - $offset = $request->get('offset'); - $maxSize = $request->get('maxSize'); - $asc = $request->get('asc') === 'true'; - $sortBy = $request->get('sortBy'); - $q = $request->get('q'); - - if (empty($maxSize)) { - $maxSize = self::MAX_SIZE_LIMIT; - } - if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) { - throw new Forbidden(); - } + $where = $request->get('where'); + $offset = $request->get('offset'); + $maxSize = $request->get('maxSize'); + $asc = $request->get('asc') === 'true'; + $sortBy = $request->get('sortBy'); + $q = $request->get('q'); + + if (empty($maxSize)) { + $maxSize = self::MAX_SIZE_LIMIT; + } + if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) { + throw new Forbidden(); + } - $result = $this->getRecordService()->findLinkedEntities($id, $link, array( - 'where' => $where, - 'offset' => $offset, - 'maxSize' => $maxSize, - 'asc' => $asc, - 'sortBy' => $sortBy, - 'q' => $q, - )); - - - return array( - 'total' => $result['total'], - 'list' => $result['collection']->toArray() - ); - } + $result = $this->getRecordService()->findLinkedEntities($id, $link, array( + 'where' => $where, + 'offset' => $offset, + 'maxSize' => $maxSize, + 'asc' => $asc, + 'sortBy' => $sortBy, + 'q' => $q, + )); + + + return array( + 'total' => $result['total'], + 'list' => $result['collection']->toArray() + ); + } - public function actionDelete($params) - { - $id = $params['id']; + public function actionDelete($params) + { + $id = $params['id']; - if ($this->getRecordService()->deleteEntity($id)) { - return true; - } - throw new Error(); - } - - public function actionExport($params, $data, $request) - { - if ($this->getConfig()->get('disableExport') && !$this->getUser()->isAdmin()) { - throw new Forbidden(); - } - - if (!$this->getAcl()->check($this->name, 'read')) { - throw new Forbidden(); - } - - $ids = $request->get('ids'); - $where = $request->get('where'); - - return array( - 'id' => $this->getRecordService()->export($ids, $where) - ); - } + if ($this->getRecordService()->deleteEntity($id)) { + return true; + } + throw new Error(); + } + + public function actionExport($params, $data, $request) + { + if ($this->getConfig()->get('disableExport') && !$this->getUser()->isAdmin()) { + throw new Forbidden(); + } + + if (!$this->getAcl()->check($this->name, 'read')) { + throw new Forbidden(); + } + + $ids = $request->get('ids'); + $where = $request->get('where'); + + return array( + 'id' => $this->getRecordService()->export($ids, $where) + ); + } - public function actionMassUpdate($params, $data) - { - if (!$this->getAcl()->check($this->name, 'edit')) { - throw new Forbidden(); - } + public function actionMassUpdate($params, $data) + { + if (!$this->getAcl()->check($this->name, 'edit')) { + throw new Forbidden(); + } - $ids = $data['ids']; - $where = $data['where']; - $attributes = $data['attributes']; + $ids = $data['ids']; + $where = $data['where']; + $attributes = $data['attributes']; - $idsUpdated = $this->getRecordService()->massUpdate($attributes, $ids, $where); + $idsUpdated = $this->getRecordService()->massUpdate($attributes, $ids, $where); - return $idsUpdated; - } + return $idsUpdated; + } - public function actionMassDelete($params, $data) - { - if (!$this->getAcl()->check($this->name, 'delete')) { - throw new Forbidden(); - } + public function actionMassDelete($params, $data) + { + if (!$this->getAcl()->check($this->name, 'delete')) { + throw new Forbidden(); + } - $ids = $data['ids']; - $where = $data['where']; + $ids = $data['ids']; + $where = $data['where']; - $idsDeleted = $this->getRecordService()->massDelete($ids, $where); + $idsDeleted = $this->getRecordService()->massDelete($ids, $where); - return $idsDeleted; - } + return $idsDeleted; + } - public function actionCreateLink($params, $data) - { - $id = $params['id']; - $link = $params['link']; - - $foreignIds = array(); - if (isset($data['id'])) { - $foreignIds[] = $data['id']; - } - if (isset($data['ids']) && is_array($data['ids'])) { - foreach ($data['ids'] as $foreignId) { - $foreignIds[] = $foreignId; - } - } - - $result = false; - foreach ($foreignIds as $foreignId) { - if ($this->getRecordService()->linkEntity($id, $link, $foreignId)) { - $result = $result || true; - } - } - if ($result) { - return true; - } - - throw new Error(); - } - - public function actionRemoveLink($params, $data) - { - $id = $params['id']; - $link = $params['link']; - - $foreignIds = array(); - if (isset($data['id'])) { - $foreignIds[] = $data['id']; - } - if (isset($data['ids']) && is_array($data['ids'])) { - foreach ($data['ids'] as $foreignId) { - $foreignIds[] = $foreignId; - } - } - - $result = false; - foreach ($foreignIds as $foreignId) { - if ($this->getRecordService()->unlinkEntity($id, $link, $foreignId)) { - $result = $result || true; - } - } - if ($result) { - return true; - } - - throw new Error(); - } - - public function actionFollow($params) - { - if (!$this->getAcl()->check($this->name, 'read')) { - throw new Forbidden(); - } - $id = $params['id']; - return $this->getRecordService()->follow($id); - } - - public function actionUnfollow($params) - { - if (!$this->getAcl()->check($this->name, 'read')) { - throw new Forbidden(); - } - $id = $params['id']; - return $this->getRecordService()->unfollow($id); - } + public function actionCreateLink($params, $data) + { + $id = $params['id']; + $link = $params['link']; + + $foreignIds = array(); + if (isset($data['id'])) { + $foreignIds[] = $data['id']; + } + if (isset($data['ids']) && is_array($data['ids'])) { + foreach ($data['ids'] as $foreignId) { + $foreignIds[] = $foreignId; + } + } + + $result = false; + foreach ($foreignIds as $foreignId) { + if ($this->getRecordService()->linkEntity($id, $link, $foreignId)) { + $result = $result || true; + } + } + if ($result) { + return true; + } + + throw new Error(); + } + + public function actionRemoveLink($params, $data) + { + $id = $params['id']; + $link = $params['link']; + + $foreignIds = array(); + if (isset($data['id'])) { + $foreignIds[] = $data['id']; + } + if (isset($data['ids']) && is_array($data['ids'])) { + foreach ($data['ids'] as $foreignId) { + $foreignIds[] = $foreignId; + } + } + + $result = false; + foreach ($foreignIds as $foreignId) { + if ($this->getRecordService()->unlinkEntity($id, $link, $foreignId)) { + $result = $result || true; + } + } + if ($result) { + return true; + } + + throw new Error(); + } + + public function actionFollow($params) + { + if (!$this->getAcl()->check($this->name, 'read')) { + throw new Forbidden(); + } + $id = $params['id']; + return $this->getRecordService()->follow($id); + } + + public function actionUnfollow($params) + { + if (!$this->getAcl()->check($this->name, 'read')) { + throw new Forbidden(); + } + $id = $params['id']; + return $this->getRecordService()->unfollow($id); + } } diff --git a/application/Espo/Core/Cron/ScheduledJob.php b/application/Espo/Core/Cron/ScheduledJob.php index 22fa69ad81..886dfd0b70 100644 --- a/application/Espo/Core/Cron/ScheduledJob.php +++ b/application/Espo/Core/Cron/ScheduledJob.php @@ -23,163 +23,163 @@ namespace Espo\Core\Cron; use Espo\Core\Exceptions\NotFound, - Espo\Core\Utils\Util; + Espo\Core\Utils\Util; class ScheduledJob { - private $container; - private $systemUtil; + private $container; + private $systemUtil; - protected $data = null; + protected $data = null; - protected $cacheFile = 'data/cache/application/jobs.php'; + protected $cacheFile = 'data/cache/application/jobs.php'; - protected $cronFile = 'cron.php'; + protected $cronFile = 'cron.php'; - protected $allowedMethod = 'run'; + protected $allowedMethod = 'run'; - /** - * @var array - path to cron job files - */ - private $paths = array( - 'corePath' => 'application/Espo/Jobs', - 'modulePath' => 'application/Espo/Modules/{*}/Jobs', - 'customPath' => 'custom/Espo/Custom/Jobs', - ); + /** + * @var array - path to cron job files + */ + private $paths = array( + 'corePath' => 'application/Espo/Jobs', + 'modulePath' => 'application/Espo/Modules/{*}/Jobs', + 'customPath' => 'custom/Espo/Custom/Jobs', + ); - protected $cronSetup = array( - 'linux' => '* * * * * {PHP-BIN-DIR} -f {CRON-FILE} > /dev/null 2>&1', - 'windows' => '{PHP-BIN-DIR}.exe -f {CRON-FILE}', - 'mac' => '* * * * * {PHP-BIN-DIR} -f {CRON-FILE} > /dev/null 2>&1', - 'default' => '* * * * * {PHP-BIN-DIR} -f {CRON-FILE}', - ); + protected $cronSetup = array( + 'linux' => '* * * * * {PHP-BIN-DIR} -f {CRON-FILE} > /dev/null 2>&1', + 'windows' => '{PHP-BIN-DIR}.exe -f {CRON-FILE}', + 'mac' => '* * * * * {PHP-BIN-DIR} -f {CRON-FILE} > /dev/null 2>&1', + 'default' => '* * * * * {PHP-BIN-DIR} -f {CRON-FILE}', + ); - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; - $this->systemUtil = new \Espo\Core\Utils\System(); - } + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; + $this->systemUtil = new \Espo\Core\Utils\System(); + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - protected function getEntityManager() - { - return $this->container->get('entityManager'); - } + protected function getEntityManager() + { + return $this->container->get('entityManager'); + } - protected function getSystemUtil() - { - return $this->systemUtil; - } + protected function getSystemUtil() + { + return $this->systemUtil; + } - public function run(array $job) - { - $jobName = $job['method']; + public function run(array $job) + { + $jobName = $job['method']; - $className = $this->getClassName($jobName); - if ($className === false) { - throw new NotFound(); - } + $className = $this->getClassName($jobName); + if ($className === false) { + throw new NotFound(); + } - $jobClass = new $className($this->container); - $method = $this->allowedMethod; + $jobClass = new $className($this->container); + $method = $this->allowedMethod; - $jobClass->$method(); - } + $jobClass->$method(); + } - /** - * Get list of all jobs - * - * @return array - */ - public function getAll() - { - if (!isset($this->data)) { - $this->init(); - } + /** + * Get list of all jobs + * + * @return array + */ + public function getAll() + { + if (!isset($this->data)) { + $this->init(); + } - return $this->data; - } + return $this->data; + } - /** - * Get class name of a job by name - * - * @param string $name - * @return string - */ - public function get($name) - { - return $this->getClassName($name); - } + /** + * Get class name of a job by name + * + * @param string $name + * @return string + */ + public function get($name) + { + return $this->getClassName($name); + } - /** - * Get list of all job names - * - * @return array - */ - public function getAllNamesOnly() - { - $data = $this->getAll(); + /** + * Get list of all job names + * + * @return array + */ + public function getAllNamesOnly() + { + $data = $this->getAll(); - $namesOnly = array_keys($data); + $namesOnly = array_keys($data); - return $namesOnly; - } + return $namesOnly; + } - /** - * Get class name of a job - * - * @param string $name - * @return string - */ - protected function getClassName($name) - { - $name = Util::normilizeClassName($name); + /** + * Get class name of a job + * + * @param string $name + * @return string + */ + protected function getClassName($name) + { + $name = Util::normilizeClassName($name); - $data = $this->getAll(); + $data = $this->getAll(); - $name = ucfirst($name); - if (isset($data[$name])) { - return $data[$name]; - } + $name = ucfirst($name); + if (isset($data[$name])) { + return $data[$name]; + } - return false; - } + return false; + } - /** - * Load scheduler classes. It loads from ...Jobs, ex. \Espo\Jobs - * @return null - */ - protected function init() - { - $classParser = $this->getContainer()->get('classParser'); - $classParser->setAllowedMethods( array($this->allowedMethod) ); - $this->data = $classParser->getData($this->paths, $this->cacheFile); - } + /** + * Load scheduler classes. It loads from ...Jobs, ex. \Espo\Jobs + * @return null + */ + protected function init() + { + $classParser = $this->getContainer()->get('classParser'); + $classParser->setAllowedMethods( array($this->allowedMethod) ); + $this->data = $classParser->getData($this->paths, $this->cacheFile); + } - public function getSetupMessage() - { - $language = $this->getContainer()->get('language'); + public function getSetupMessage() + { + $language = $this->getContainer()->get('language'); - $OS = $this->getSystemUtil()->getOS(); - $phpBin = $this->getSystemUtil()->getPhpBin(); - $cronFile = Util::concatPath($this->getSystemUtil()->getRootDir(), $this->cronFile); - $desc = $language->translate('cronSetup', 'options', 'ScheduledJob'); + $OS = $this->getSystemUtil()->getOS(); + $phpBin = $this->getSystemUtil()->getPhpBin(); + $cronFile = Util::concatPath($this->getSystemUtil()->getRootDir(), $this->cronFile); + $desc = $language->translate('cronSetup', 'options', 'ScheduledJob'); - $message = isset($desc[$OS]) ? $desc[$OS] : $desc['default']; + $message = isset($desc[$OS]) ? $desc[$OS] : $desc['default']; - $command = isset($this->cronSetup[$OS]) ? $this->cronSetup[$OS] : $this->cronSetup['default']; - $command = str_replace(array('{PHP-BIN-DIR}', '{CRON-FILE}'), array($phpBin, $cronFile), $command); + $command = isset($this->cronSetup[$OS]) ? $this->cronSetup[$OS] : $this->cronSetup['default']; + $command = str_replace(array('{PHP-BIN-DIR}', '{CRON-FILE}'), array($phpBin, $cronFile), $command); - return array( - 'message' => $message, - 'command' => $command, - ); - } + return array( + 'message' => $message, + 'command' => $command, + ); + } } diff --git a/application/Espo/Core/Cron/Service.php b/application/Espo/Core/Cron/Service.php index 7ffa3a2ca6..cb969e1b53 100644 --- a/application/Espo/Core/Cron/Service.php +++ b/application/Espo/Core/Cron/Service.php @@ -23,45 +23,45 @@ namespace Espo\Core\Cron; use Espo\Core\Utils\Json, - Espo\Core\Exceptions\NotFound; + Espo\Core\Exceptions\NotFound; class Service { - private $serviceFactory; + private $serviceFactory; - public function __construct(\Espo\Core\ServiceFactory $serviceFactory) - { - $this->serviceFactory = $serviceFactory; - } + public function __construct(\Espo\Core\ServiceFactory $serviceFactory) + { + $this->serviceFactory = $serviceFactory; + } - protected function getServiceFactory() - { - return $this->serviceFactory; - } + protected function getServiceFactory() + { + return $this->serviceFactory; + } - public function run($job) - { - $serviceName = $job['service_name']; + public function run($job) + { + $serviceName = $job['service_name']; - if (!$this->getServiceFactory()->checkExists($serviceName)) { - throw new NotFound(); - } + if (!$this->getServiceFactory()->checkExists($serviceName)) { + throw new NotFound(); + } - $service = $this->getServiceFactory()->create($serviceName); - $serviceMethod = $job['method']; + $service = $this->getServiceFactory()->create($serviceName); + $serviceMethod = $job['method']; - if (!method_exists($service, $serviceMethod)) { - throw new NotFound(); - } + if (!method_exists($service, $serviceMethod)) { + throw new NotFound(); + } - $data = $job['data']; - if (Json::isJSON($data)) { - $data = Json::decode($data, true); - } + $data = $job['data']; + if (Json::isJSON($data)) { + $data = Json::decode($data, true); + } - $service->$serviceMethod($data); - } + $service->$serviceMethod($data); + } } \ No newline at end of file diff --git a/application/Espo/Core/CronManager.php b/application/Espo/Core/CronManager.php index 6c5cb13063..059ec4d059 100644 --- a/application/Espo/Core/CronManager.php +++ b/application/Espo/Core/CronManager.php @@ -24,192 +24,192 @@ namespace Espo\Core; class CronManager { - private $container; - private $config; - private $fileManager; + private $container; + private $config; + private $fileManager; - private $scheduledJobCron; - private $serviceCron; + private $scheduledJobCron; + private $serviceCron; - private $jobService; - private $scheduledJobService; + private $jobService; + private $scheduledJobService; - const PENDING = 'Pending'; - const RUNNING = 'Running'; - const SUCCESS = 'Success'; - const FAILED = 'Failed'; + const PENDING = 'Pending'; + const RUNNING = 'Running'; + const SUCCESS = 'Success'; + const FAILED = 'Failed'; - protected $lastRunTime = 'data/cache/application/cronLastRunTime.php'; + protected $lastRunTime = 'data/cache/application/cronLastRunTime.php'; - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; - $this->config = $this->container->get('config'); - $this->fileManager = $this->container->get('fileManager'); + $this->config = $this->container->get('config'); + $this->fileManager = $this->container->get('fileManager'); - $this->scheduledJobCron = $this->container->get('scheduledJob'); - $this->serviceCron = new \Espo\Core\Cron\Service( $this->container->get('serviceFactory')); + $this->scheduledJobCron = $this->container->get('scheduledJob'); + $this->serviceCron = new \Espo\Core\Cron\Service( $this->container->get('serviceFactory')); - $this->jobService = $this->container->get('serviceFactory')->create('job'); - $this->scheduledJobService = $this->container->get('serviceFactory')->create('scheduledJob'); - } + $this->jobService = $this->container->get('serviceFactory')->create('job'); + $this->scheduledJobService = $this->container->get('serviceFactory')->create('scheduledJob'); + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - protected function getConfig() - { - return $this->config; - } + protected function getConfig() + { + return $this->config; + } - protected function getFileManager() - { - return $this->fileManager; - } + protected function getFileManager() + { + return $this->fileManager; + } - protected function getJobService() - { - return $this->jobService; - } + protected function getJobService() + { + return $this->jobService; + } - protected function getScheduledJobService() - { - return $this->scheduledJobService; - } + protected function getScheduledJobService() + { + return $this->scheduledJobService; + } - protected function getScheduledJobCron() - { - return $this->scheduledJobCron; - } + protected function getScheduledJobCron() + { + return $this->scheduledJobCron; + } - protected function getServiceCron() - { - return $this->serviceCron; - } + protected function getServiceCron() + { + return $this->serviceCron; + } - protected function getLastRunTime() - { - $lastRunTime = $this->getFileManager()->getContents($this->lastRunTime); - if (!is_int($lastRunTime)) { - $lastRunTime = time() - (intval($this->getConfig()->get('cron.minExecutionTime')) + 60); - } + protected function getLastRunTime() + { + $lastRunTime = $this->getFileManager()->getContents($this->lastRunTime); + if (!is_int($lastRunTime)) { + $lastRunTime = time() - (intval($this->getConfig()->get('cron.minExecutionTime')) + 60); + } - return $lastRunTime; - } + return $lastRunTime; + } - protected function setLastRunTime($time) - { - return $this->getFileManager()->putContentsPHP($this->lastRunTime, $time); - } + protected function setLastRunTime($time) + { + return $this->getFileManager()->putContentsPHP($this->lastRunTime, $time); + } - protected function checkLastRunTime() - { - $currentTime = time(); - $lastRunTime = $this->getLastRunTime(); - $minTime = $this->getConfig()->get('cron.minExecutionTime'); + protected function checkLastRunTime() + { + $currentTime = time(); + $lastRunTime = $this->getLastRunTime(); + $minTime = $this->getConfig()->get('cron.minExecutionTime'); - if ($currentTime > ($lastRunTime + $minTime) ) { - return true; - } + if ($currentTime > ($lastRunTime + $minTime) ) { + return true; + } - return false; - } + return false; + } - public function run() - { - if (!$this->checkLastRunTime()) { - $GLOBALS['log']->info('Cron Manager: Stop cron running, too frequency execution'); - return; //stop cron running, too frequency execution - } + public function run() + { + if (!$this->checkLastRunTime()) { + $GLOBALS['log']->info('Cron Manager: Stop cron running, too frequency execution'); + return; //stop cron running, too frequency execution + } - $this->setLastRunTime(time()); + $this->setLastRunTime(time()); - //Check scheduled jobs and create related jobs - $this->createJobsFromScheduledJobs(); + //Check scheduled jobs and create related jobs + $this->createJobsFromScheduledJobs(); - $pendingJobs = $this->getJobService()->getPendingJobs(); + $pendingJobs = $this->getJobService()->getPendingJobs(); - foreach ($pendingJobs as $job) { + foreach ($pendingJobs as $job) { - $this->getJobService()->updateEntity($job['id'], array( - 'status' => self::RUNNING, - )); + $this->getJobService()->updateEntity($job['id'], array( + 'status' => self::RUNNING, + )); - $isSuccess = true; + $isSuccess = true; - try { - if (!empty($job['scheduled_job_id'])) { - $this->getScheduledJobCron()->run($job); - } else { - $this->getServiceCron()->run($job); - } - } catch (\Exception $e) { - $isSuccess = false; - $GLOBALS['log']->error('Failed job running, job ['.$job['id'].']. Error Details: '.$e->getMessage()); - } + try { + if (!empty($job['scheduled_job_id'])) { + $this->getScheduledJobCron()->run($job); + } else { + $this->getServiceCron()->run($job); + } + } catch (\Exception $e) { + $isSuccess = false; + $GLOBALS['log']->error('Failed job running, job ['.$job['id'].']. Error Details: '.$e->getMessage()); + } - $status = $isSuccess ? self::SUCCESS : self::FAILED; + $status = $isSuccess ? self::SUCCESS : self::FAILED; - $this->getJobService()->updateEntity($job['id'], array( - 'status' => $status, - )); + $this->getJobService()->updateEntity($job['id'], array( + 'status' => $status, + )); - //set status in the schedulerJobLog - if (!empty($job['scheduled_job_id'])) { - $this->getScheduledJobService()->addLogRecord($job['scheduled_job_id'], $status); - } - } + //set status in the schedulerJobLog + if (!empty($job['scheduled_job_id'])) { + $this->getScheduledJobService()->addLogRecord($job['scheduled_job_id'], $status); + } + } - } + } - /** - * Check scheduled jobs and create related jobs - * @return array List of created Jobs - */ - protected function createJobsFromScheduledJobs() - { - $activeScheduledJobs = $this->getScheduledJobService()->getActiveJobs(); + /** + * Check scheduled jobs and create related jobs + * @return array List of created Jobs + */ + protected function createJobsFromScheduledJobs() + { + $activeScheduledJobs = $this->getScheduledJobService()->getActiveJobs(); - $createdJobs = array(); - foreach ($activeScheduledJobs as $scheduledJob) { + $createdJobs = array(); + foreach ($activeScheduledJobs as $scheduledJob) { - $scheduling = $scheduledJob['scheduling']; + $scheduling = $scheduledJob['scheduling']; - $cronExpression = \Cron\CronExpression::factory($scheduling); + $cronExpression = \Cron\CronExpression::factory($scheduling); - try { - $prevDate = $cronExpression->getPreviousRunDate()->format('Y-m-d H:i:s'); - } catch (\Exception $e) { - $GLOBALS['log']->error('ScheduledJob ['.$scheduledJob['id'].']: CronExpression - Impossible CRON expression ['.$scheduling.']'); - continue; - } + try { + $prevDate = $cronExpression->getPreviousRunDate()->format('Y-m-d H:i:s'); + } catch (\Exception $e) { + $GLOBALS['log']->error('ScheduledJob ['.$scheduledJob['id'].']: CronExpression - Impossible CRON expression ['.$scheduling.']'); + continue; + } - if ($cronExpression->isDue()) { - $prevDate = date('Y-m-d H:i:00'); - } + if ($cronExpression->isDue()) { + $prevDate = date('Y-m-d H:i:00'); + } - $existsJob = $this->getJobService()->getJobByScheduledJob($scheduledJob['id'], $prevDate); + $existsJob = $this->getJobService()->getJobByScheduledJob($scheduledJob['id'], $prevDate); - if (!isset($existsJob) || empty($existsJob)) { - //create a job - $data = array( - 'name' => $scheduledJob['name'], - 'status' => self::PENDING, - 'scheduledJobId' => $scheduledJob['id'], - 'executeTime' => $prevDate, - 'method' => $scheduledJob['job'], - ); - $createdJobs[] = $this->getJobService()->createEntity($data); - } - } + if (!isset($existsJob) || empty($existsJob)) { + //create a job + $data = array( + 'name' => $scheduledJob['name'], + 'status' => self::PENDING, + 'scheduledJobId' => $scheduledJob['id'], + 'executeTime' => $prevDate, + 'method' => $scheduledJob['job'], + ); + $createdJobs[] = $this->getJobService()->createEntity($data); + } + } - return $createdJobs; - } + return $createdJobs; + } } diff --git a/application/Espo/Core/DataManager.php b/application/Espo/Core/DataManager.php index 65ee595dd7..c71441bd24 100644 --- a/application/Espo/Core/DataManager.php +++ b/application/Espo/Core/DataManager.php @@ -24,106 +24,106 @@ namespace Espo\Core; class DataManager { - private $container; + private $container; - private $cachePath = 'data/cache'; + private $cachePath = 'data/cache'; - public function __construct(Container $container) - { - $this->container = $container; - } + public function __construct(Container $container) + { + $this->container = $container; + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - /** - * Rebuild the system with metadata, database and cache clearing - * - * @return bool - */ - public function rebuild($entityList = null) - { - $result = $this->clearCache(); + /** + * Rebuild the system with metadata, database and cache clearing + * + * @return bool + */ + public function rebuild($entityList = null) + { + $result = $this->clearCache(); - $result &= $this->rebuildMetadata(); + $result &= $this->rebuildMetadata(); - $result &= $this->rebuildDatabase($entityList); + $result &= $this->rebuildDatabase($entityList); - return $result; - } + return $result; + } - /** - * Clear a cache - * - * @return bool - */ - public function clearCache() - { - $result = $this->getContainer()->get('fileManager')->removeInDir($this->cachePath); + /** + * Clear a cache + * + * @return bool + */ + public function clearCache() + { + $result = $this->getContainer()->get('fileManager')->removeInDir($this->cachePath); - if ($result === false) { - throw new Exceptions\Error("Error while clearing cache"); - } + if ($result === false) { + throw new Exceptions\Error("Error while clearing cache"); + } - $this->updateCacheTimestamp(); + $this->updateCacheTimestamp(); - return $result; - } + return $result; + } - /** - * Rebuild database - * - * @return bool - */ - public function rebuildDatabase($entityList = null) - { - try { - $result = $this->getContainer()->get('schema')->rebuild($entityList); - } catch (\Exception $e) { - $result = false; - $GLOBALS['log']->error('Fault to rebuild database schema'.'. Details: '.$e->getMessage()); - } + /** + * Rebuild database + * + * @return bool + */ + public function rebuildDatabase($entityList = null) + { + try { + $result = $this->getContainer()->get('schema')->rebuild($entityList); + } catch (\Exception $e) { + $result = false; + $GLOBALS['log']->error('Fault to rebuild database schema'.'. Details: '.$e->getMessage()); + } - if ($result === false) { - throw new Exceptions\Error("Error while rebuilding database. See log file for details."); - } + if ($result === false) { + throw new Exceptions\Error("Error while rebuilding database. See log file for details."); + } - $this->updateCacheTimestamp(); + $this->updateCacheTimestamp(); - return $result; - } + return $result; + } - /** - * Rebuild metadata - * - * @return bool - */ - public function rebuildMetadata() - { - $metadata = $this->getContainer()->get('metadata'); + /** + * Rebuild metadata + * + * @return bool + */ + public function rebuildMetadata() + { + $metadata = $this->getContainer()->get('metadata'); - $metadata->init(true); + $metadata->init(true); - $ormMeta = $metadata->getOrmMetadata(true); + $ormMeta = $metadata->getOrmMetadata(true); - $this->updateCacheTimestamp(); + $this->updateCacheTimestamp(); - return empty($ormMeta) ? false : true; - } + return empty($ormMeta) ? false : true; + } - /** - * Update cache timestamp - * - * @return bool - */ - public function updateCacheTimestamp() - { - $this->getContainer()->get('config')->updateCacheTimestamp(); - $this->getContainer()->get('config')->save(); - return true; - } + /** + * Update cache timestamp + * + * @return bool + */ + public function updateCacheTimestamp() + { + $this->getContainer()->get('config')->updateCacheTimestamp(); + $this->getContainer()->get('config')->save(); + return true; + } } diff --git a/application/Espo/Core/Entities/Person.php b/application/Espo/Core/Entities/Person.php index 38de106a55..f1465162a8 100644 --- a/application/Espo/Core/Entities/Person.php +++ b/application/Espo/Core/Entities/Person.php @@ -24,30 +24,30 @@ namespace Espo\Core\Entities; class Person extends \Espo\Core\ORM\Entity { - public static $person = true; - - public function setLastName($value) - { - $this->_setValue('lastName', $value); - - $firstName = $this->get('firstName'); - if (empty($firstName)) { - $this->_setValue('name', $value); - } else { - $this->_setValue('name', $firstName . ' ' . $value); - } - } - - public function setFirstName($value) - { - $this->_setValue('firstName', $value); - - $lastName = $this->get('lastName'); - if (empty($lastName)) { - $this->_setValue('name', $value); - } else { - $this->_setValue('name', $value . ' ' . $lastName); - } - } + public static $person = true; + + public function setLastName($value) + { + $this->_setValue('lastName', $value); + + $firstName = $this->get('firstName'); + if (empty($firstName)) { + $this->_setValue('name', $value); + } else { + $this->_setValue('name', $firstName . ' ' . $value); + } + } + + public function setFirstName($value) + { + $this->_setValue('firstName', $value); + + $lastName = $this->get('lastName'); + if (empty($lastName)) { + $this->_setValue('name', $value); + } else { + $this->_setValue('name', $value . ' ' . $lastName); + } + } } diff --git a/application/Espo/Core/EntryPointManager.php b/application/Espo/Core/EntryPointManager.php index fa24a67fa5..271bcdabf3 100644 --- a/application/Espo/Core/EntryPointManager.php +++ b/application/Espo/Core/EntryPointManager.php @@ -23,93 +23,93 @@ namespace Espo\Core; use \Espo\Core\Exceptions\NotFound, - \Espo\Core\Utils\Util; + \Espo\Core\Utils\Util; class EntryPointManager { - private $container; - - private $fileManager; + private $container; + + private $fileManager; - protected $data = null; + protected $data = null; - protected $cacheFile = 'data/cache/application/entryPoints.php'; + protected $cacheFile = 'data/cache/application/entryPoints.php'; - protected $allowedMethods = array( - 'run', - ); + protected $allowedMethods = array( + 'run', + ); - /** + /** * @var array - path to entryPoint files */ - private $paths = array( - 'corePath' => 'application/Espo/EntryPoints', - 'modulePath' => 'application/Espo/Modules/{*}/EntryPoints', - 'customPath' => 'custom/Espo/Custom/EntryPoints', - ); + private $paths = array( + 'corePath' => 'application/Espo/EntryPoints', + 'modulePath' => 'application/Espo/Modules/{*}/EntryPoints', + 'customPath' => 'custom/Espo/Custom/EntryPoints', + ); - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; - $this->fileManager = $container->get('fileManager'); - } + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; + $this->fileManager = $container->get('fileManager'); + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - protected function getFileManager() - { - return $this->fileManager; - } + protected function getFileManager() + { + return $this->fileManager; + } - public function checkAuthRequired($name) - { - $className = $this->getClassName($name); - if ($className === false) { - throw new NotFound(); - } - return $className::$authRequired; - } + public function checkAuthRequired($name) + { + $className = $this->getClassName($name); + if ($className === false) { + throw new NotFound(); + } + return $className::$authRequired; + } - public function run($name) - { - $className = $this->getClassName($name); - if ($className === false) { - throw new NotFound(); - } - $entryPoint = new $className($this->container); + public function run($name) + { + $className = $this->getClassName($name); + if ($className === false) { + throw new NotFound(); + } + $entryPoint = new $className($this->container); - $entryPoint->run(); - } + $entryPoint->run(); + } - protected function getClassName($name) - { - $name = Util::normilizeClassName($name); - - if (!isset($this->data)) { - $this->init(); - } + protected function getClassName($name) + { + $name = Util::normilizeClassName($name); + + if (!isset($this->data)) { + $this->init(); + } - $name = ucfirst($name); - if (isset($this->data[$name])) { - return $this->data[$name]; - } - + $name = ucfirst($name); + if (isset($this->data[$name])) { + return $this->data[$name]; + } + return false; - } + } - protected function init() - { - $classParser = $this->getContainer()->get('classParser'); - $classParser->setAllowedMethods($this->allowedMethods); - $this->data = $classParser->getData($this->paths, $this->cacheFile); - } - + protected function init() + { + $classParser = $this->getContainer()->get('classParser'); + $classParser->setAllowedMethods($this->allowedMethods); + $this->data = $classParser->getData($this->paths, $this->cacheFile); + } + } diff --git a/application/Espo/Core/EntryPoints/Base.php b/application/Espo/Core/EntryPoints/Base.php index 52c668b8e7..d62598a66f 100644 --- a/application/Espo/Core/EntryPoints/Base.php +++ b/application/Espo/Core/EntryPoints/Base.php @@ -28,51 +28,51 @@ use \Espo\Core\Exceptions\Forbidden; abstract class Base { - private $container; - - public static $authRequired = true; - - protected function getContainer() - { - return $this->container; - } - - protected function getUser() - { - return $this->getContainer()->get('user'); - } - - protected function getAcl() - { - return $this->getContainer()->get('acl'); - } - - protected function getEntityManager() - { - return $this->getContainer()->get('entityManager'); - } - - protected function getServiceFactory() - { - return $this->getContainer()->get('serviceFactory'); - } - - protected function getConfig() - { - return $this->getContainer()->get('config'); - } - - protected function getMetadata() - { - return $this->getContainer()->get('metadata'); - } - - public function __construct(Container $container) - { - $this->container = $container; - } - - abstract public function run(); + private $container; + + public static $authRequired = true; + + protected function getContainer() + { + return $this->container; + } + + protected function getUser() + { + return $this->getContainer()->get('user'); + } + + protected function getAcl() + { + return $this->getContainer()->get('acl'); + } + + protected function getEntityManager() + { + return $this->getContainer()->get('entityManager'); + } + + protected function getServiceFactory() + { + return $this->getContainer()->get('serviceFactory'); + } + + protected function getConfig() + { + return $this->getContainer()->get('config'); + } + + protected function getMetadata() + { + return $this->getContainer()->get('metadata'); + } + + public function __construct(Container $container) + { + $this->container = $container; + } + + abstract public function run(); } diff --git a/application/Espo/Core/Exceptions/BadRequest.php b/application/Espo/Core/Exceptions/BadRequest.php index d12197cb01..e27d485b5f 100644 --- a/application/Espo/Core/Exceptions/BadRequest.php +++ b/application/Espo/Core/Exceptions/BadRequest.php @@ -24,7 +24,7 @@ namespace Espo\Core\Exceptions; class BadRequest extends \Exception { - protected $code = 400; + protected $code = 400; } diff --git a/application/Espo/Core/Exceptions/Conflict.php b/application/Espo/Core/Exceptions/Conflict.php index 0433a62160..d749eab336 100644 --- a/application/Espo/Core/Exceptions/Conflict.php +++ b/application/Espo/Core/Exceptions/Conflict.php @@ -24,7 +24,7 @@ namespace Espo\Core\Exceptions; class Conflict extends \Exception { - protected $code = 409; + protected $code = 409; } diff --git a/application/Espo/Core/Exceptions/Forbidden.php b/application/Espo/Core/Exceptions/Forbidden.php index 2fdf613a23..edf5350b55 100644 --- a/application/Espo/Core/Exceptions/Forbidden.php +++ b/application/Espo/Core/Exceptions/Forbidden.php @@ -24,7 +24,7 @@ namespace Espo\Core\Exceptions; class Forbidden extends \Exception { - protected $code = 403; + protected $code = 403; } diff --git a/application/Espo/Core/Exceptions/InternalServerError.php b/application/Espo/Core/Exceptions/InternalServerError.php index d3f0b80706..7a28a14b69 100644 --- a/application/Espo/Core/Exceptions/InternalServerError.php +++ b/application/Espo/Core/Exceptions/InternalServerError.php @@ -24,6 +24,6 @@ namespace Espo\Core\Exceptions; class InternalServerError extends \Exception { - protected $code = 500; + protected $code = 500; } diff --git a/application/Espo/Core/Exceptions/NotFound.php b/application/Espo/Core/Exceptions/NotFound.php index 4371ca19e6..836f774be9 100644 --- a/application/Espo/Core/Exceptions/NotFound.php +++ b/application/Espo/Core/Exceptions/NotFound.php @@ -24,7 +24,7 @@ namespace Espo\Core\Exceptions; class NotFound extends \Exception { - protected $code = 404; + protected $code = 404; } diff --git a/application/Espo/Core/Exceptions/Unauthorized.php b/application/Espo/Core/Exceptions/Unauthorized.php index 6c8b403ebc..99b784657c 100644 --- a/application/Espo/Core/Exceptions/Unauthorized.php +++ b/application/Espo/Core/Exceptions/Unauthorized.php @@ -24,7 +24,7 @@ namespace Espo\Core\Exceptions; class Unauthorized extends \Exception { - protected $code = 401; + protected $code = 401; } diff --git a/application/Espo/Core/ExtensionManager.php b/application/Espo/Core/ExtensionManager.php index d9b848c0ed..ce01895275 100644 --- a/application/Espo/Core/ExtensionManager.php +++ b/application/Espo/Core/ExtensionManager.php @@ -24,18 +24,18 @@ namespace Espo\Core; class ExtensionManager extends Upgrades\Base { - protected $name = 'Extension'; + protected $name = 'Extension'; - protected $params = array( - 'packagePath' => 'data/upload/extensions', + protected $params = array( + 'packagePath' => 'data/upload/extensions', - 'backupPath' => 'data/.backup/extensions', + 'backupPath' => 'data/.backup/extensions', - 'scriptNames' => array( - 'before' => 'BeforeInstall', - 'after' => 'AfterInstall', - 'beforeUninstall' => 'BeforeUninstall', - 'afterUninstall' => 'AfterUninstall', - ) - ); + 'scriptNames' => array( + 'before' => 'BeforeInstall', + 'after' => 'AfterInstall', + 'beforeUninstall' => 'BeforeUninstall', + 'afterUninstall' => 'AfterUninstall', + ) + ); } diff --git a/application/Espo/Core/ExternalAccount/ClientManager.php b/application/Espo/Core/ExternalAccount/ClientManager.php index 7d5dcd59bb..7f5ef2a55f 100644 --- a/application/Espo/Core/ExternalAccount/ClientManager.php +++ b/application/Espo/Core/ExternalAccount/ClientManager.php @@ -28,98 +28,98 @@ use \Espo\Core\Exceptions\NotFound; class ClientManager { - protected $entityManager; - - protected $metadata; - - protected $clientMap = array(); - - public function __construct($entityManager, $metadata, $config) - { - $this->entityManager = $entityManager; - $this->metadata = $metadata; - $this->config = $config; - } - - protected function getMetadata() - { - return $this->metadata; - } - - protected function getEntityManager() - { - return $this->entityManager; - } - - protected function getConfig() - { - return $this->config; - } - - public function storeAccessToken($hash, $data) - { - if (!empty($this->clientMap[$hash]) && !empty($this->clientMap[$hash]['externalAccountEntity'])) { - $externalAccountEntity = $this->clientMap[$hash]['externalAccountEntity']; - $externalAccountEntity->set('accessToken', $data['accessToken']); - $externalAccountEntity->set('tokenType', $data['tokenType']); - $this->getEntityManager()->saveEntity($externalAccountEntity); - } - } - - public function create($integration, $userId) - { - $authMethod = $this->getMetadata()->get("integrations.{$integration}.authMethod"); - $methodName = 'create' . ucfirst($authMethod); - return $this->$methodName($integration, $userId); - } - - protected function createOAuth2($integration, $userId) - { - $integrationEntity = $this->getEntityManager()->getEntity('Integration', $integration); - $externalAccountEntity = $this->getEntityManager()->getEntity('ExternalAccount', $integration . '__' . $userId); - - $className = $this->getMetadata()->get("integrations.{$integration}.clientClassName"); - - $redirectUri = $this->getConfig()->get('siteUrl') . '/oauthcallback'; // TODO move to client class - - if (!$externalAccountEntity) { - throw new Error("External Account {$integration} not found for {$userId}"); - } - - if (!$integrationEntity->get('enabled')) { - return null; - } - if (!$externalAccountEntity->get('enabled')) { - return null; - } - - $oauth2Client = new \Espo\Core\ExternalAccount\OAuth2\Client(); - - $client = new $className($oauth2Client, array( - 'endpoint' => $this->getMetadata()->get("integrations.{$integration}.params.endpoint"), - 'tokenEndpoint' => $this->getMetadata()->get("integrations.{$integration}.params.tokenEndpoint"), - 'clientId' => $integrationEntity->get('clientId'), - 'clientSecret' => $integrationEntity->get('clientSecret'), - 'redirectUri' => $redirectUri, - 'accessToken' => $externalAccountEntity->get('accessToken'), - 'refreshToken' => $externalAccountEntity->get('refreshToken'), - 'tokenType' => $externalAccountEntity->get('tokenType'), - ), $this); - - $this->addToClientMap($client, $integrationEntity, $externalAccountEntity, $userId); - - return $client; - } - - protected function addToClientMap($client, $integrationEntity, $externalAccountEntity, $userId) - { - $this->clientMap[spl_object_hash($client)] = array( - 'client' => $client, - 'userId' => $userId, - 'integration' => $integrationEntity->id, - 'integrationEntity' => $integrationEntity, - 'externalAccountEntity' => $externalAccountEntity, - ); - } + protected $entityManager; + + protected $metadata; + + protected $clientMap = array(); + + public function __construct($entityManager, $metadata, $config) + { + $this->entityManager = $entityManager; + $this->metadata = $metadata; + $this->config = $config; + } + + protected function getMetadata() + { + return $this->metadata; + } + + protected function getEntityManager() + { + return $this->entityManager; + } + + protected function getConfig() + { + return $this->config; + } + + public function storeAccessToken($hash, $data) + { + if (!empty($this->clientMap[$hash]) && !empty($this->clientMap[$hash]['externalAccountEntity'])) { + $externalAccountEntity = $this->clientMap[$hash]['externalAccountEntity']; + $externalAccountEntity->set('accessToken', $data['accessToken']); + $externalAccountEntity->set('tokenType', $data['tokenType']); + $this->getEntityManager()->saveEntity($externalAccountEntity); + } + } + + public function create($integration, $userId) + { + $authMethod = $this->getMetadata()->get("integrations.{$integration}.authMethod"); + $methodName = 'create' . ucfirst($authMethod); + return $this->$methodName($integration, $userId); + } + + protected function createOAuth2($integration, $userId) + { + $integrationEntity = $this->getEntityManager()->getEntity('Integration', $integration); + $externalAccountEntity = $this->getEntityManager()->getEntity('ExternalAccount', $integration . '__' . $userId); + + $className = $this->getMetadata()->get("integrations.{$integration}.clientClassName"); + + $redirectUri = $this->getConfig()->get('siteUrl') . '/oauthcallback'; // TODO move to client class + + if (!$externalAccountEntity) { + throw new Error("External Account {$integration} not found for {$userId}"); + } + + if (!$integrationEntity->get('enabled')) { + return null; + } + if (!$externalAccountEntity->get('enabled')) { + return null; + } + + $oauth2Client = new \Espo\Core\ExternalAccount\OAuth2\Client(); + + $client = new $className($oauth2Client, array( + 'endpoint' => $this->getMetadata()->get("integrations.{$integration}.params.endpoint"), + 'tokenEndpoint' => $this->getMetadata()->get("integrations.{$integration}.params.tokenEndpoint"), + 'clientId' => $integrationEntity->get('clientId'), + 'clientSecret' => $integrationEntity->get('clientSecret'), + 'redirectUri' => $redirectUri, + 'accessToken' => $externalAccountEntity->get('accessToken'), + 'refreshToken' => $externalAccountEntity->get('refreshToken'), + 'tokenType' => $externalAccountEntity->get('tokenType'), + ), $this); + + $this->addToClientMap($client, $integrationEntity, $externalAccountEntity, $userId); + + return $client; + } + + protected function addToClientMap($client, $integrationEntity, $externalAccountEntity, $userId) + { + $this->clientMap[spl_object_hash($client)] = array( + 'client' => $client, + 'userId' => $userId, + 'integration' => $integrationEntity->id, + 'integrationEntity' => $integrationEntity, + 'externalAccountEntity' => $externalAccountEntity, + ); + } } diff --git a/application/Espo/Core/ExternalAccount/Clients/Google.php b/application/Espo/Core/ExternalAccount/Clients/Google.php index 089b5f5e31..e6713a2767 100644 --- a/application/Espo/Core/ExternalAccount/Clients/Google.php +++ b/application/Espo/Core/ExternalAccount/Clients/Google.php @@ -26,9 +26,9 @@ use \Espo\Core\Exceptions\Error; class Google extends OAuth2Abstract { - protected function getPingUrl() - { - return 'https://www.googleapis.com/calendar/v3/users/me/calendarList'; - } + protected function getPingUrl() + { + return 'https://www.googleapis.com/calendar/v3/users/me/calendarList'; + } } diff --git a/application/Espo/Core/ExternalAccount/Clients/IClient.php b/application/Espo/Core/ExternalAccount/Clients/IClient.php index 978d9835a3..37e31a6673 100644 --- a/application/Espo/Core/ExternalAccount/Clients/IClient.php +++ b/application/Espo/Core/ExternalAccount/Clients/IClient.php @@ -24,12 +24,12 @@ namespace Espo\Core\ExternalAccount\Clients; interface IClient { - public function getParam($name); - - public function setParam($name, $value); - - public function setParams(array $params); + public function getParam($name); + + public function setParam($name, $value); + + public function setParams(array $params); - public function ping(); + public function ping(); } diff --git a/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php b/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php index de0a7e837e..76f79fceff 100644 --- a/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php +++ b/application/Espo/Core/ExternalAccount/Clients/OAuth2Abstract.php @@ -28,182 +28,182 @@ use \Espo\Core\ExternalAccount\OAuth2\Client; abstract class OAuth2Abstract implements IClient { - protected $client = null; - - protected $manager = null; - - protected $paramList = array( - 'endpoint', - 'tokenEndpoint', - 'clientId', - 'clientSecret', - 'tokenType', - 'accessToken', - 'refreshToken', - 'redirectUri', - ); - - protected $clientId = null; - - protected $clientSecret = null; - - protected $accessToken = null; - - protected $refreshToken = null; - - protected $redirectUri = null; - - public function __construct($client, array $params = array(), $manager = null) - { - $this->client = $client; + protected $client = null; + + protected $manager = null; + + protected $paramList = array( + 'endpoint', + 'tokenEndpoint', + 'clientId', + 'clientSecret', + 'tokenType', + 'accessToken', + 'refreshToken', + 'redirectUri', + ); + + protected $clientId = null; + + protected $clientSecret = null; + + protected $accessToken = null; + + protected $refreshToken = null; + + protected $redirectUri = null; + + public function __construct($client, array $params = array(), $manager = null) + { + $this->client = $client; - $this->setParams($params); - - $this->manager = $manager; - } - - public function getParam($name) - { - if (in_array($name, $this->paramList)) { - return $this->$name; - } - } - - public function setParam($name, $value) - { - if (in_array($name, $this->paramList)) { - $methodName = 'set' . ucfirst($name); - if (method_exists($this->client, $methodName)) { - $this->client->$methodName($value); - } - $this->$name = $value; - } - } - - public function setParams(array $params) - { - foreach ($this->paramList as $name) { - if (!empty($params[$name])) { - $this->setParam($name, $params[$name]); - } - } - } - - protected function afterTokenRefreshed($data) - { - if ($this->manager) { - $this->manager->storeAccessToken(spl_object_hash($this), $data); - } - } - - public function getAccessTokenFromAuthorizationCode($code) - { - $r = $this->client->getAccessToken($this->getParam('tokenEndpoint'), Client::GRANT_TYPE_AUTHORIZATION_CODE, array( - 'code' => $code, - 'redirect_uri' => $this->getParam('redirectUri') - )); - - - if ($r['code'] == 200) { - $data = array(); - if (!empty($r['result'])) { - $data['accessToken'] = $r['result']['access_token']; - $data['tokenType'] = $r['result']['token_type']; - $data['refreshToken'] = $r['result']['refresh_token']; - } - return $data; - } - return null; - } - - abstract protected function getPingUrl(); - - public function ping() - { - if (empty($this->accessToken) || empty($this->clientId) || empty($this->clientSecret)) { - return false; - } - - $url = $this->getPingUrl(); + $this->setParams($params); + + $this->manager = $manager; + } + + public function getParam($name) + { + if (in_array($name, $this->paramList)) { + return $this->$name; + } + } + + public function setParam($name, $value) + { + if (in_array($name, $this->paramList)) { + $methodName = 'set' . ucfirst($name); + if (method_exists($this->client, $methodName)) { + $this->client->$methodName($value); + } + $this->$name = $value; + } + } + + public function setParams(array $params) + { + foreach ($this->paramList as $name) { + if (!empty($params[$name])) { + $this->setParam($name, $params[$name]); + } + } + } + + protected function afterTokenRefreshed($data) + { + if ($this->manager) { + $this->manager->storeAccessToken(spl_object_hash($this), $data); + } + } + + public function getAccessTokenFromAuthorizationCode($code) + { + $r = $this->client->getAccessToken($this->getParam('tokenEndpoint'), Client::GRANT_TYPE_AUTHORIZATION_CODE, array( + 'code' => $code, + 'redirect_uri' => $this->getParam('redirectUri') + )); + + + if ($r['code'] == 200) { + $data = array(); + if (!empty($r['result'])) { + $data['accessToken'] = $r['result']['access_token']; + $data['tokenType'] = $r['result']['token_type']; + $data['refreshToken'] = $r['result']['refresh_token']; + } + return $data; + } + return null; + } + + abstract protected function getPingUrl(); + + public function ping() + { + if (empty($this->accessToken) || empty($this->clientId) || empty($this->clientSecret)) { + return false; + } + + $url = $this->getPingUrl(); - try { - $this->request($url); - return true; - } catch (\Exception $e) { - return false; - } - } - - public function request($url, $params = array(), $httpMethod = Client::HTTP_METHOD_GET, $allowRenew = true) - { - $r = $this->client->request($url, $params, $httpMethod); - - $code = null; - if (!empty($r['code'])) { - $code = $r['code']; - } - - if ($code == 200) { - return $r['result']; - } else { - $handledData = $this->handleErrorResponse($r); - - if ($allowRenew && is_array($handledData)) { - if ($handledData['action'] == 'refreshToken') { - if ($this->refreshToken()) { - return $this->request($url, $params, $httpMethod, false); - } - } else if ($handledData['action'] == 'renew') { - return $this->request($url, $params, $httpMethod, false); - } - } - } - - throw new Error("Error after requesting {$httpMethod} {$url}.", $code); - } - - protected function refreshToken() - { - if (!empty($this->refreshToken)) { - $r = $this->client->getAccessToken($this->getParam('tokenEndpoint'), Client::GRANT_TYPE_REFRESH_TOKEN, array( - 'refresh_token' => $this->refreshToken, - )); - if ($r['code'] == 200) { - if (is_array($r['result'])) { - if (!empty($r['result']['access_token'])) { - $data = array(); - $data['accessToken'] = $r['result']['access_token']; - $data['tokenType'] = $r['result']['token_type']; + try { + $this->request($url); + return true; + } catch (\Exception $e) { + return false; + } + } + + public function request($url, $params = array(), $httpMethod = Client::HTTP_METHOD_GET, $allowRenew = true) + { + $r = $this->client->request($url, $params, $httpMethod); + + $code = null; + if (!empty($r['code'])) { + $code = $r['code']; + } + + if ($code == 200) { + return $r['result']; + } else { + $handledData = $this->handleErrorResponse($r); + + if ($allowRenew && is_array($handledData)) { + if ($handledData['action'] == 'refreshToken') { + if ($this->refreshToken()) { + return $this->request($url, $params, $httpMethod, false); + } + } else if ($handledData['action'] == 'renew') { + return $this->request($url, $params, $httpMethod, false); + } + } + } + + throw new Error("Error after requesting {$httpMethod} {$url}.", $code); + } + + protected function refreshToken() + { + if (!empty($this->refreshToken)) { + $r = $this->client->getAccessToken($this->getParam('tokenEndpoint'), Client::GRANT_TYPE_REFRESH_TOKEN, array( + 'refresh_token' => $this->refreshToken, + )); + if ($r['code'] == 200) { + if (is_array($r['result'])) { + if (!empty($r['result']['access_token'])) { + $data = array(); + $data['accessToken'] = $r['result']['access_token']; + $data['tokenType'] = $r['result']['token_type']; - $this->setParams($data); - $this->afterTokenRefreshed($data); - return true; - } - } - } - } - } - - protected function handleErrorResponse($r) - { - if ($r['code'] == 401 && !empty($r['result'])) { - $result = $r['result']; - if (strpos($r['header'], 'error=invalid_token') !== false) { - return array( - 'action' => 'refreshToken' - ); - } else { - return array( - 'action' => 'renew' - ); - } - } else if ($r['code'] == 400 && !empty($r['result'])) { - if ($r['result']['error'] == 'invalid_token') { - return array( - 'action' => 'refreshToken' - ); - } - } - } + $this->setParams($data); + $this->afterTokenRefreshed($data); + return true; + } + } + } + } + } + + protected function handleErrorResponse($r) + { + if ($r['code'] == 401 && !empty($r['result'])) { + $result = $r['result']; + if (strpos($r['header'], 'error=invalid_token') !== false) { + return array( + 'action' => 'refreshToken' + ); + } else { + return array( + 'action' => 'renew' + ); + } + } else if ($r['code'] == 400 && !empty($r['result'])) { + if ($r['result']['error'] == 'invalid_token') { + return array( + 'action' => 'refreshToken' + ); + } + } + } } diff --git a/application/Espo/Core/ExternalAccount/OAuth2/Client.php b/application/Espo/Core/ExternalAccount/OAuth2/Client.php index dea4caf0a8..b96c2a42a0 100644 --- a/application/Espo/Core/ExternalAccount/OAuth2/Client.php +++ b/application/Espo/Core/ExternalAccount/OAuth2/Client.php @@ -24,225 +24,225 @@ namespace Espo\Core\ExternalAccount\OAuth2; class Client { - const AUTH_TYPE_URI = 0; - const AUTH_TYPE_AUTHORIZATION_BASIC = 1; - const AUTH_TYPE_FORM = 2; + const AUTH_TYPE_URI = 0; + const AUTH_TYPE_AUTHORIZATION_BASIC = 1; + const AUTH_TYPE_FORM = 2; - const TOKEN_TYPE_URI = 'Uri'; - const TOKEN_TYPE_BEARER = 'Bearer'; - const TOKEN_TYPE_OAUTH = 'OAuth'; + const TOKEN_TYPE_URI = 'Uri'; + const TOKEN_TYPE_BEARER = 'Bearer'; + const TOKEN_TYPE_OAUTH = 'OAuth'; - const CONTENT_TYPE_APPLICATION = 0; - const CONTENT_TYPE_MULTIPART = 1; + const CONTENT_TYPE_APPLICATION = 0; + const CONTENT_TYPE_MULTIPART = 1; - const HTTP_METHOD_GET = 'GET'; - const HTTP_METHOD_POST = 'POST'; - const HTTP_METHOD_PUT = 'PUT'; + const HTTP_METHOD_GET = 'GET'; + const HTTP_METHOD_POST = 'POST'; + const HTTP_METHOD_PUT = 'PUT'; - const HTTP_METHOD_DELETE = 'DELETE'; - const HTTP_METHOD_HEAD = 'HEAD'; - const HTTP_METHOD_PATCH = 'PATCH'; + const HTTP_METHOD_DELETE = 'DELETE'; + const HTTP_METHOD_HEAD = 'HEAD'; + const HTTP_METHOD_PATCH = 'PATCH'; - const GRANT_TYPE_AUTHORIZATION_CODE = 'authorization_code'; - const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token'; - const GRANT_TYPE_PASSWORD = 'password'; - const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials'; + const GRANT_TYPE_AUTHORIZATION_CODE = 'authorization_code'; + const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token'; + const GRANT_TYPE_PASSWORD = 'password'; + const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials'; - protected $clientId = null; + protected $clientId = null; - protected $clientSecret = null; + protected $clientSecret = null; - protected $accessToken = null; + protected $accessToken = null; - protected $authType = self::AUTH_TYPE_URI; + protected $authType = self::AUTH_TYPE_URI; - protected $tokenType = self::TOKEN_TYPE_URI; + protected $tokenType = self::TOKEN_TYPE_URI; - protected $accessTokenSecret = null; + protected $accessTokenSecret = null; - protected $accessTokenParamName = 'access_token'; + protected $accessTokenParamName = 'access_token'; - protected $certificateFile = null; + protected $certificateFile = null; - protected $curlOptions = array(); + protected $curlOptions = array(); - public function __construct(array $params = array()) - { - if (!extension_loaded('curl')) { - throw new \Exception('CURL extension not found.'); - } - } + public function __construct(array $params = array()) + { + if (!extension_loaded('curl')) { + throw new \Exception('CURL extension not found.'); + } + } - public function setClientId($clientId) - { - $this->clientId = $clientId; - } + public function setClientId($clientId) + { + $this->clientId = $clientId; + } - public function setClientSecret($clientSecret) - { - $this->clientSecret = $clientSecret; - } + public function setClientSecret($clientSecret) + { + $this->clientSecret = $clientSecret; + } - public function setAccessToken($accessToken) - { - $this->accessToken = $accessToken; - } + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + } - public function setAuthType($authType) - { - $this->authType = $authType; - } + public function setAuthType($authType) + { + $this->authType = $authType; + } - public function setCertificateFile($certificateFile) - { - $this->certificateFile = $certificateFile; - } + public function setCertificateFile($certificateFile) + { + $this->certificateFile = $certificateFile; + } - public function setCurlOption($option, $value) - { - $this->curlOptions[$option] = $value; - } + public function setCurlOption($option, $value) + { + $this->curlOptions[$option] = $value; + } - public function setCurlOptions($options) - { - $this->curlOptions = array_merge($this->curlOptions, $options); - } + public function setCurlOptions($options) + { + $this->curlOptions = array_merge($this->curlOptions, $options); + } - public function setTokenType($tokenType) - { - $this->tokenType = $tokenType; - } + public function setTokenType($tokenType) + { + $this->tokenType = $tokenType; + } - public function setAccessTokenSecret($accessTokenSecret) - { - $this->accessTokenSecret = $accessTokenSecret; - } + public function setAccessTokenSecret($accessTokenSecret) + { + $this->accessTokenSecret = $accessTokenSecret; + } - public function request($url, $params = array(), $httpMethod = self::HTTP_METHOD_GET, array $httpHeaders = array(), $contentType = self::CONTENT_TYPE_MULTIPART) - { - if ($this->accessToken) { - switch ($this->tokenType) { - case self::TOKEN_TYPE_URI: - $params[$this->accessTokenParamName] = $this->accessToken; - break; - case self::TOKEN_TYPE_BEARER: - $httpHeaders['Authorization'] = 'Bearer ' . $this->accessToken; - break; - case self::TOKEN_TYPE_OAUTH: - $httpHeaders['Authorization'] = 'OAuth ' . $this->accessToken; - break; - default: - throw new \Exception('Unknown access token type.'); + public function request($url, $params = array(), $httpMethod = self::HTTP_METHOD_GET, array $httpHeaders = array(), $contentType = self::CONTENT_TYPE_MULTIPART) + { + if ($this->accessToken) { + switch ($this->tokenType) { + case self::TOKEN_TYPE_URI: + $params[$this->accessTokenParamName] = $this->accessToken; + break; + case self::TOKEN_TYPE_BEARER: + $httpHeaders['Authorization'] = 'Bearer ' . $this->accessToken; + break; + case self::TOKEN_TYPE_OAUTH: + $httpHeaders['Authorization'] = 'OAuth ' . $this->accessToken; + break; + default: + throw new \Exception('Unknown access token type.'); - } - } + } + } - return $this->execute($url, $params, $httpMethod, $httpHeaders, $contentType); - } + return $this->execute($url, $params, $httpMethod, $httpHeaders, $contentType); + } - private function execute($url, $params = array(), $httpMethod, array $httpHeaders = array(), $contentType = self::CONTENT_TYPE_MULTIPART) - { - $curlOptions = array( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_SSL_VERIFYPEER => true, - CURLOPT_CUSTOMREQUEST => $httpMethod - ); + private function execute($url, $params = array(), $httpMethod, array $httpHeaders = array(), $contentType = self::CONTENT_TYPE_MULTIPART) + { + $curlOptions = array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => true, + CURLOPT_CUSTOMREQUEST => $httpMethod + ); - switch ($httpMethod) { - case self::HTTP_METHOD_POST: - $curlOptions[CURLOPT_POST] = true; - case self::HTTP_METHOD_PUT: - case self::HTTP_METHOD_PATCH: - if (self::CONTENT_TYPE_APPLICATION === $contentType) { - $postFields = http_build_query($params, null, '&'); - } - $curlOptions[CURLOPT_POSTFIELDS] = $postFields; - break; - case self::HTTP_METHOD_HEAD: - $curlOptions[CURLOPT_NOBODY] = true; - case self::HTTP_METHOD_DELETE: - case self::HTTP_METHOD_GET: - if (strpos($url, '?') === false) { - $url .= '?'; - } - $url .= http_build_query($params, null, '&'); - break; - default: - break; - } + switch ($httpMethod) { + case self::HTTP_METHOD_POST: + $curlOptions[CURLOPT_POST] = true; + case self::HTTP_METHOD_PUT: + case self::HTTP_METHOD_PATCH: + if (self::CONTENT_TYPE_APPLICATION === $contentType) { + $postFields = http_build_query($params, null, '&'); + } + $curlOptions[CURLOPT_POSTFIELDS] = $postFields; + break; + case self::HTTP_METHOD_HEAD: + $curlOptions[CURLOPT_NOBODY] = true; + case self::HTTP_METHOD_DELETE: + case self::HTTP_METHOD_GET: + if (strpos($url, '?') === false) { + $url .= '?'; + } + $url .= http_build_query($params, null, '&'); + break; + default: + break; + } - $curlOptions[CURLOPT_URL] = $url; + $curlOptions[CURLOPT_URL] = $url; - $curlOptHttpHeader = array(); - foreach ($httpHeaders as $key => $value) { - $curlOptHttpHeader[] = "{$key}: {$value}"; - } - $curlOptions[CURLOPT_HTTPHEADER] = $curlOptHttpHeader; + $curlOptHttpHeader = array(); + foreach ($httpHeaders as $key => $value) { + $curlOptHttpHeader[] = "{$key}: {$value}"; + } + $curlOptions[CURLOPT_HTTPHEADER] = $curlOptHttpHeader; - $ch = curl_init(); - curl_setopt_array($ch, $curlOptions); + $ch = curl_init(); + curl_setopt_array($ch, $curlOptions); - curl_setopt($ch, CURLOPT_HEADER, 1); + curl_setopt($ch, CURLOPT_HEADER, 1); - if (!empty($this->certificateFile)) { - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_CAINFO, $this->certificateFile); - } else { - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - } + if (!empty($this->certificateFile)) { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($ch, CURLOPT_CAINFO, $this->certificateFile); + } else { + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + } - if (!empty($this->curlOptions)) { - curl_setopt_array($ch, $this->curlOptions); - } + if (!empty($this->curlOptions)) { + curl_setopt_array($ch, $this->curlOptions); + } - $response = curl_exec($ch); + $response = curl_exec($ch); - $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); - $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); + $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); - $responceHeader = substr($response, 0, $headerSize); - $responceBody = substr($response, $headerSize); + $responceHeader = substr($response, 0, $headerSize); + $responceBody = substr($response, $headerSize); - $resultArray = null; + $resultArray = null; - if ($curlError = curl_error($ch)) { - throw new \Exception($curlError); - } else { - $resultArray = json_decode($responceBody, true); - } - curl_close($ch); + if ($curlError = curl_error($ch)) { + throw new \Exception($curlError); + } else { + $resultArray = json_decode($responceBody, true); + } + curl_close($ch); - return array( - 'result' => (null !== $resultArray) ? $resultArray: $responceBody, - 'code' => intval($httpCode), - 'contentType' => $contentType, - 'header' => $responceHeader, - ); - } + return array( + 'result' => (null !== $resultArray) ? $resultArray: $responceBody, + 'code' => intval($httpCode), + 'contentType' => $contentType, + 'header' => $responceHeader, + ); + } - public function getAccessToken($url, $grantType, array $params) - { - $params['grant_type'] = $grantType; + public function getAccessToken($url, $grantType, array $params) + { + $params['grant_type'] = $grantType; - $httpHeaders = array(); - switch ($this->clientAuth) { - case self::AUTH_TYPE_URI: - case self::AUTH_TYPE_FORM: - $params['client_id'] = $this->clientId; - $params['client_secret'] = $this->clientSecret; - break; - case self::AUTH_TYPE_AUTHORIZATION_BASIC: - $params['client_id'] = $this->clientId; - $httpHeaders['Authorization'] = 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret); - break; - default: - throw new \Exception(); - } + $httpHeaders = array(); + switch ($this->clientAuth) { + case self::AUTH_TYPE_URI: + case self::AUTH_TYPE_FORM: + $params['client_id'] = $this->clientId; + $params['client_secret'] = $this->clientSecret; + break; + case self::AUTH_TYPE_AUTHORIZATION_BASIC: + $params['client_id'] = $this->clientId; + $httpHeaders['Authorization'] = 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret); + break; + default: + throw new \Exception(); + } - return $this->execute($url, $params, self::HTTP_METHOD_POST, $httpHeaders, self::CONTENT_TYPE_APPLICATION); - } + return $this->execute($url, $params, self::HTTP_METHOD_POST, $httpHeaders, self::CONTENT_TYPE_APPLICATION); + } } diff --git a/application/Espo/Core/HookManager.php b/application/Espo/Core/HookManager.php index 2e1073376d..f7c6c65dc4 100644 --- a/application/Espo/Core/HookManager.php +++ b/application/Espo/Core/HookManager.php @@ -23,162 +23,162 @@ namespace Espo\Core; use \Espo\Core\Exceptions\Error, - \Espo\Core\Utils\Util; + \Espo\Core\Utils\Util; class HookManager { - private $container; + private $container; - private $data; + private $data; - private $hooks; + private $hooks; - protected $cacheFile = 'data/cache/application/hooks.php'; + protected $cacheFile = 'data/cache/application/hooks.php'; - /** + /** * List of defined hooks * * @var array */ - protected $hookList = array( - 'beforeSave', - 'afterSave', - 'beforeRemove', - 'afterRemove', - ); + protected $hookList = array( + 'beforeSave', + 'afterSave', + 'beforeRemove', + 'afterRemove', + ); - protected $paths = array( - 'corePath' => 'application/Espo/Hooks', - 'modulePath' => 'application/Espo/Modules/{*}/Hooks', - 'customPath' => 'custom/Espo/Custom/Hooks', - ); + protected $paths = array( + 'corePath' => 'application/Espo/Hooks', + 'modulePath' => 'application/Espo/Modules/{*}/Hooks', + 'customPath' => 'custom/Espo/Custom/Hooks', + ); public function __construct(Container $container) { - $this->container = $container; - $this->loadHooks(); + $this->container = $container; + $this->loadHooks(); } protected function getConfig() { - return $this->container->get('config'); + return $this->container->get('config'); } - protected function getFileManager() - { - return $this->container->get('fileManager'); - } + protected function getFileManager() + { + return $this->container->get('fileManager'); + } protected function loadHooks() { - if ($this->getConfig()->get('useCache') && file_exists($this->cacheFile)) { - $this->data = $this->getFileManager()->getContents($this->cacheFile); - return; - } + if ($this->getConfig()->get('useCache') && file_exists($this->cacheFile)) { + $this->data = $this->getFileManager()->getContents($this->cacheFile); + return; + } - $metadata = $this->container->get('metadata'); + $metadata = $this->container->get('metadata'); - $this->data = $this->getHookData($this->paths['corePath']); + $this->data = $this->getHookData($this->paths['corePath']); - foreach ($metadata->getModuleList() as $moduleName) { - $modulePath = str_replace('{*}', $moduleName, $this->paths['modulePath']); - $this->data = array_merge($this->data, $this->getHookData($modulePath)); - } + foreach ($metadata->getModuleList() as $moduleName) { + $modulePath = str_replace('{*}', $moduleName, $this->paths['modulePath']); + $this->data = array_merge($this->data, $this->getHookData($modulePath)); + } - $this->data = array_merge($this->data, $this->getHookData($this->paths['customPath'])); + $this->data = array_merge($this->data, $this->getHookData($this->paths['customPath'])); - if ($this->getConfig()->get('useCache')) { - $this->getFileManager()->putContentsPHP($this->cacheFile, $this->data); - } + if ($this->getConfig()->get('useCache')) { + $this->getFileManager()->putContentsPHP($this->cacheFile, $this->data); + } } public function process($scope, $hookName, $injection = null) { - if ($scope != 'Common') { - $this->process('Common', $hookName, $injection); - } + if ($scope != 'Common') { + $this->process('Common', $hookName, $injection); + } - if (!empty($this->data[$scope])) { - if (!empty($this->data[$scope][$hookName])) { - foreach ($this->data[$scope][$hookName] as $className) { - if (empty($this->hooks[$className])) { - $this->hooks[$className] = $this->createHookByClassName($className); - } - $hook = $this->hooks[$className]; - $hook->$hookName($injection); - } - } - } + if (!empty($this->data[$scope])) { + if (!empty($this->data[$scope][$hookName])) { + foreach ($this->data[$scope][$hookName] as $className) { + if (empty($this->hooks[$className])) { + $this->hooks[$className] = $this->createHookByClassName($className); + } + $hook = $this->hooks[$className]; + $hook->$hookName($injection); + } + } + } } - public function createHookByClassName($className) - { - if (class_exists($className)) { - $hook = new $className(); - $dependencies = $hook->getDependencyList(); - foreach ($dependencies as $name) { - $hook->inject($name, $this->container->get($name)); - } - return $hook; - } - throw new Error("Class '$className' does not exist"); - } + public function createHookByClassName($className) + { + if (class_exists($className)) { + $hook = new $className(); + $dependencies = $hook->getDependencyList(); + foreach ($dependencies as $name) { + $hook->inject($name, $this->container->get($name)); + } + return $hook; + } + throw new Error("Class '$className' does not exist"); + } /** * Get and merge hook data by checking the files exist in $hookDirs - * - * @param array $hookDirs - it can be an array('Espo/Hooks', 'Espo/Custom/Hooks', 'Espo/Modules/Crm/Hooks') - * - * @return array - */ - protected function getHookData($hookDirs) - { - if (is_string($hookDirs)) { - $hookDirs = (array) $hookDirs; - } + * + * @param array $hookDirs - it can be an array('Espo/Hooks', 'Espo/Custom/Hooks', 'Espo/Modules/Crm/Hooks') + * + * @return array + */ + protected function getHookData($hookDirs) + { + if (is_string($hookDirs)) { + $hookDirs = (array) $hookDirs; + } - $hooks = array(); + $hooks = array(); - foreach ($hookDirs as $hookDir) { + foreach ($hookDirs as $hookDir) { - if (file_exists($hookDir)) { - $fileList = $this->getFileManager()->getFileList($hookDir, 1, '\.php$', 'file'); + if (file_exists($hookDir)) { + $fileList = $this->getFileManager()->getFileList($hookDir, 1, '\.php$', 'file'); - foreach ($fileList as $scopeName => $hookFiles) { + foreach ($fileList as $scopeName => $hookFiles) { - $hookScopeDirPath = Util::concatPath($hookDir, $scopeName); + $hookScopeDirPath = Util::concatPath($hookDir, $scopeName); - $scopeHooks = array(); - foreach($hookFiles as $hookFile) { - $hookFilePath = Util::concatPath($hookScopeDirPath, $hookFile); - $className = Util::getClassName($hookFilePath); + $scopeHooks = array(); + foreach($hookFiles as $hookFile) { + $hookFilePath = Util::concatPath($hookScopeDirPath, $hookFile); + $className = Util::getClassName($hookFilePath); - foreach($this->hookList as $hookName) { - if (method_exists($className, $hookName)) { - $scopeHooks[$hookName][$className::$order][] = $className; - } - } - } + foreach($this->hookList as $hookName) { + if (method_exists($className, $hookName)) { + $scopeHooks[$hookName][$className::$order][] = $className; + } + } + } - //sort hooks by order - foreach ($scopeHooks as $hookName => $hookList) { - ksort($hookList); + //sort hooks by order + foreach ($scopeHooks as $hookName => $hookList) { + ksort($hookList); - $sortedHookList = array(); - foreach($hookList as $hookDetails) { - $sortedHookList = array_merge($sortedHookList, $hookDetails); - } + $sortedHookList = array(); + foreach($hookList as $hookDetails) { + $sortedHookList = array_merge($sortedHookList, $hookDetails); + } $hooks[$scopeName][$hookName] = isset($hooks[$scopeName][$hookName]) ? array_merge($hooks[$scopeName][$hookName], $sortedHookList) : $sortedHookList; - } - } - } + } + } + } - } + } - return $hooks; - } + return $hooks; + } } diff --git a/application/Espo/Core/Hooks/Base.php b/application/Espo/Core/Hooks/Base.php index e3627788be..ae6baeb3c4 100644 --- a/application/Espo/Core/Hooks/Base.php +++ b/application/Espo/Core/Hooks/Base.php @@ -26,70 +26,70 @@ use \Espo\Core\Interfaces\Injectable; class Base implements Injectable { - protected $dependencies = array( - 'entityManager', - 'config', - 'metadata', - 'acl', - 'user', - ); + protected $dependencies = array( + 'entityManager', + 'config', + 'metadata', + 'acl', + 'user', + ); - protected $injections = array(); + protected $injections = array(); - public static $order = 9; + public static $order = 9; - public function __construct() - { - $this->init(); - } + public function __construct() + { + $this->init(); + } - protected function init() - { - } + protected function init() + { + } - public function getDependencyList() - { - return $this->dependencies; - } + public function getDependencyList() + { + return $this->dependencies; + } - protected function getInjection($name) - { - return $this->injections[$name]; - } + protected function getInjection($name) + { + return $this->injections[$name]; + } - public function inject($name, $object) - { - $this->injections[$name] = $object; - } + public function inject($name, $object) + { + $this->injections[$name] = $object; + } - protected function getEntityManager() - { - return $this->injections['entityManager']; - } + protected function getEntityManager() + { + return $this->injections['entityManager']; + } - protected function getUser() - { - return $this->injections['user']; - } + protected function getUser() + { + return $this->injections['user']; + } - protected function getAcl() - { - return $this->injections['acl']; - } + protected function getAcl() + { + return $this->injections['acl']; + } - protected function getConfig() - { - return $this->injections['config']; - } + protected function getConfig() + { + return $this->injections['config']; + } - protected function getMetadata() - { - return $this->injections['metadata']; - } + protected function getMetadata() + { + return $this->injections['metadata']; + } - protected function getRepository() - { - return $this->getEntityManager()->getRepository($this->entityName); - } + protected function getRepository() + { + return $this->getEntityManager()->getRepository($this->entityName); + } } diff --git a/application/Espo/Core/Interfaces/Injectable.php b/application/Espo/Core/Interfaces/Injectable.php index 9185de91d8..7ccae942e1 100644 --- a/application/Espo/Core/Interfaces/Injectable.php +++ b/application/Espo/Core/Interfaces/Injectable.php @@ -24,8 +24,8 @@ namespace Espo\Core\Interfaces; interface Injectable { - public function getDependencyList(); - - public function inject($name, $object); + public function getDependencyList(); + + public function inject($name, $object); } diff --git a/application/Espo/Core/Jobs/Base.php b/application/Espo/Core/Jobs/Base.php index 975dd5fa1d..9256cd997b 100644 --- a/application/Espo/Core/Jobs/Base.php +++ b/application/Espo/Core/Jobs/Base.php @@ -27,44 +27,44 @@ use \Espo\Core\Container; abstract class Base { - private $container; + private $container; - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - protected function getEntityManager() - { - return $this->getContainer()->get('entityManager'); - } + protected function getEntityManager() + { + return $this->getContainer()->get('entityManager'); + } - protected function getServiceFactory() - { - return $this->getContainer()->get('serviceFactory'); - } + protected function getServiceFactory() + { + return $this->getContainer()->get('serviceFactory'); + } - protected function getConfig() - { - return $this->getContainer()->get('config'); - } + protected function getConfig() + { + return $this->getContainer()->get('config'); + } - protected function getMetadata() - { - return $this->getContainer()->get('metadata'); - } + protected function getMetadata() + { + return $this->getContainer()->get('metadata'); + } - protected function getUser() - { - return $this->getContainer()->get('user'); - } + protected function getUser() + { + return $this->getContainer()->get('user'); + } - public function __construct(Container $container) - { - $this->container = $container; - } + public function __construct(Container $container) + { + $this->container = $container; + } - abstract public function run(); + abstract public function run(); } diff --git a/application/Espo/Core/Loaders/EntityManager.php b/application/Espo/Core/Loaders/EntityManager.php index 66e05872f0..e9ac2a7dab 100644 --- a/application/Espo/Core/Loaders/EntityManager.php +++ b/application/Espo/Core/Loaders/EntityManager.php @@ -27,38 +27,38 @@ use Doctrine\ORM\Tools\Setup, class EntityManager implements Loader { - private $container; + private $container; - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; - } + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - public function load() - { - $config = $this->getContainer()->get('config'); + public function load() + { + $config = $this->getContainer()->get('config'); - $params = array( - 'host' => $config->get('database.host'), - 'port' => $config->get('database.port'), - 'dbname' => $config->get('database.dbname'), - 'user' => $config->get('database.user'), - 'password' => $config->get('database.password'), - 'metadata' => $this->getContainer()->get('metadata')->getOrmMetadata(), - 'repositoryFactoryClassName' => '\\Espo\\Core\\ORM\\RepositoryFactory', - ); + $params = array( + 'host' => $config->get('database.host'), + 'port' => $config->get('database.port'), + 'dbname' => $config->get('database.dbname'), + 'user' => $config->get('database.user'), + 'password' => $config->get('database.password'), + 'metadata' => $this->getContainer()->get('metadata')->getOrmMetadata(), + 'repositoryFactoryClassName' => '\\Espo\\Core\\ORM\\RepositoryFactory', + ); - $entityManager = new \Espo\Core\ORM\EntityManager($params); - $entityManager->setEspoMetadata($this->getContainer()->get('metadata')); - $entityManager->setHookManager($this->getContainer()->get('hookManager')); - $entityManager->setContainer($this->getContainer()); + $entityManager = new \Espo\Core\ORM\EntityManager($params); + $entityManager->setEspoMetadata($this->getContainer()->get('metadata')); + $entityManager->setHookManager($this->getContainer()->get('hookManager')); + $entityManager->setContainer($this->getContainer()); - return $entityManager; - } + return $entityManager; + } } diff --git a/application/Espo/Core/Loaders/Loader.php b/application/Espo/Core/Loaders/Loader.php index 971290c6a0..545defa809 100644 --- a/application/Espo/Core/Loaders/Loader.php +++ b/application/Espo/Core/Loaders/Loader.php @@ -25,7 +25,7 @@ namespace Espo\Core\Loaders; interface Loader { - public function load(); + public function load(); } diff --git a/application/Espo/Core/Loaders/Log.php b/application/Espo/Core/Loaders/Log.php index 764eaad4ce..99ce5c08af 100644 --- a/application/Espo/Core/Loaders/Log.php +++ b/application/Espo/Core/Loaders/Log.php @@ -23,42 +23,42 @@ namespace Espo\Core\Loaders; use Espo\Core\Utils, - Espo\Core\Utils\Log\Monolog\Handler; + Espo\Core\Utils\Log\Monolog\Handler; class Log implements Loader { - private $container; + private $container; - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; - } + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - public function load() - { - $logConfig = $this->getContainer()->get('config')->get('logger'); + public function load() + { + $logConfig = $this->getContainer()->get('config')->get('logger'); - $log = new Utils\Log('Espo'); + $log = new Utils\Log('Espo'); - $levelCode = $log->getLevelCode($logConfig['level']); + $levelCode = $log->getLevelCode($logConfig['level']); - if ($logConfig['isRotate']) { - $handler = new Handler\RotatingFileHandler($logConfig['path'], $logConfig['maxRotateFiles'], $levelCode); - } else { - $handler = new Handler\StreamHandler($logConfig['path'], $levelCode); - } - $log->pushHandler($handler); + if ($logConfig['isRotate']) { + $handler = new Handler\RotatingFileHandler($logConfig['path'], $logConfig['maxRotateFiles'], $levelCode); + } else { + $handler = new Handler\StreamHandler($logConfig['path'], $levelCode); + } + $log->pushHandler($handler); - $errorHandler = new \Monolog\ErrorHandler($log); - $errorHandler->registerExceptionHandler(null, false); - $errorHandler->registerErrorHandler(array(), false); + $errorHandler = new \Monolog\ErrorHandler($log); + $errorHandler->registerExceptionHandler(null, false); + $errorHandler->registerErrorHandler(array(), false); - return $log; - } + return $log; + } } diff --git a/application/Espo/Core/Mail/Importer.php b/application/Espo/Core/Mail/Importer.php index c8aa318ff2..ed338f9484 100644 --- a/application/Espo/Core/Mail/Importer.php +++ b/application/Espo/Core/Mail/Importer.php @@ -5,245 +5,245 @@ namespace Espo\Core\Mail; use \Zend\Mime\Mime as Mime; class Importer -{ - private $entityManager; - - private $fileManager; - - public function __construct($entityManager, $fileManager) - { - $this->entityManager = $entityManager; - $this->fileManager = $fileManager; - } - - protected function getEntityManager() - { - return $this->entityManager; - } - - protected function getFileManager() - { - return $this->fileManager; - } - - public function importMessage($message, $userId, $teamsIds = array()) - { - try { - $email = $this->getEntityManager()->getEntity('Email'); - - $subject = $message->subject; - if ($subject !== '0' && empty($subject)) { - $subject = '--empty--'; - } - - $email->set('isHtml', false); - $email->set('name', $subject); - $email->set('status', 'Archived'); - $email->set('attachmentsIds', array()); - $email->set('assignedUserId', $userId); - $email->set('teamsIds', $teamsIds); - - $fromArr = $this->getAddressListFromMessage($message, 'from'); - if (isset($message->from)) { - $email->set('fromName', $message->from); - } - $email->set('from', $fromArr[0]); - $email->set('to', implode(';', $this->getAddressListFromMessage($message, 'to'))); - $email->set('cc', implode(';', $this->getAddressListFromMessage($message, 'cc'))); - - if (isset($message->messageId) && !empty($message->messageId)) { - $email->set('messageId', $message->messageId); - if (isset($message->deliveredTo)) { - $email->set('messageIdInternal', $message->messageId . '-' . $message->deliveredTo); - } - } - - if ($this->checkIsDuplicate($email)) { - return false; - } +{ + private $entityManager; + + private $fileManager; + + public function __construct($entityManager, $fileManager) + { + $this->entityManager = $entityManager; + $this->fileManager = $fileManager; + } + + protected function getEntityManager() + { + return $this->entityManager; + } + + protected function getFileManager() + { + return $this->fileManager; + } + + public function importMessage($message, $userId, $teamsIds = array()) + { + try { + $email = $this->getEntityManager()->getEntity('Email'); + + $subject = $message->subject; + if ($subject !== '0' && empty($subject)) { + $subject = '--empty--'; + } + + $email->set('isHtml', false); + $email->set('name', $subject); + $email->set('status', 'Archived'); + $email->set('attachmentsIds', array()); + $email->set('assignedUserId', $userId); + $email->set('teamsIds', $teamsIds); + + $fromArr = $this->getAddressListFromMessage($message, 'from'); + if (isset($message->from)) { + $email->set('fromName', $message->from); + } + $email->set('from', $fromArr[0]); + $email->set('to', implode(';', $this->getAddressListFromMessage($message, 'to'))); + $email->set('cc', implode(';', $this->getAddressListFromMessage($message, 'cc'))); + + if (isset($message->messageId) && !empty($message->messageId)) { + $email->set('messageId', $message->messageId); + if (isset($message->deliveredTo)) { + $email->set('messageIdInternal', $message->messageId . '-' . $message->deliveredTo); + } + } + + if ($this->checkIsDuplicate($email)) { + return false; + } - if (isset($message->date)) { - $dt = new \DateTime($message->date); - if ($dt) { - $dateSent = $dt->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s'); - $email->set('dateSent', $dateSent); - } - } - if (isset($message->deliveryDate)) { - $dt = new \DateTime($message->deliveryDate); - if ($dt) { - $deliveryDate = $dt->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s'); - $email->set('deliveryDate', $deliveryDate); - } - } - - $inlineIds = array(); - - if ($message->isMultipart()) { - foreach (new \RecursiveIteratorIterator($message) as $part) { - $this->importPartDataToEmail($email, $part, $inlineIds); - } - } else { - $this->importPartDataToEmail($email, $message, $inlineIds); - } - - $body = $email->get('body'); - if (!empty($body)) { - foreach ($inlineIds as $cid => $attachmentId) { - $body = str_replace('cid:' . $cid, '?entryPoint=attachment&id=' . $attachmentId, $body); - } - $email->set('body', $body); - } + if (isset($message->date)) { + $dt = new \DateTime($message->date); + if ($dt) { + $dateSent = $dt->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s'); + $email->set('dateSent', $dateSent); + } + } + if (isset($message->deliveryDate)) { + $dt = new \DateTime($message->deliveryDate); + if ($dt) { + $deliveryDate = $dt->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s'); + $email->set('deliveryDate', $deliveryDate); + } + } + + $inlineIds = array(); + + if ($message->isMultipart()) { + foreach (new \RecursiveIteratorIterator($message) as $part) { + $this->importPartDataToEmail($email, $part, $inlineIds); + } + } else { + $this->importPartDataToEmail($email, $message, $inlineIds); + } + + $body = $email->get('body'); + if (!empty($body)) { + foreach ($inlineIds as $cid => $attachmentId) { + $body = str_replace('cid:' . $cid, '?entryPoint=attachment&id=' . $attachmentId, $body); + } + $email->set('body', $body); + } - $this->getEntityManager()->saveEntity($email); - - return $email; - - } catch (\Exception $e) {} - } - - protected function checkIsDuplicate($email) - { - if ($email->get('messageIdInternal')) { - $duplicate = $this->getEntityManager()->getRepository('Email')->where(array( - 'messageIdInternal' => $email->get('messageIdInternal') - ))->findOne(); - if ($duplicate) { - return true; - } - } - } - - protected function getAddressListFromMessage($message, $type) - { - $addressList = array(); - if (isset($message->$type)) { - - $list = $message->getHeader($type)->getAddressList(); - foreach ($list as $address) { - $addressList[] = $address->getEmail(); - } - } - return $addressList; - } - - protected function importPartDataToEmail(\Espo\Entities\Email $email, $part, &$inlineIds = array()) - { - try { - $type = strtok($part->contentType, ';'); - $encoding = null; - - switch ($type) { - case 'text/plain': - $content = $this->getContentFromPart($part); - if (!$email->get('body')) { - $email->set('body', $content); - } - $email->set('bodyPlain', $content); - break; - case 'text/html': - $content = $this->getContentFromPart($part); - $email->set('body', $content); - $email->set('isHtml', true); - break; - default: - $content = $part->getContent(); - $disposition = null; - - $fileName = null; - $contentId = null; - - if (isset($part->ContentDisposition)) { - if (strpos($part->ContentDisposition, 'attachment') === 0) { - if (preg_match('/filename="?([^"]+)"?/i', $part->ContentDisposition, $m)) { - $fileName = $m[1]; - $disposition = 'attachment'; - } - } else if (strpos($part->ContentDisposition, 'inline') === 0) { - $contentId = trim($part->contentID, '<>'); - $fileName = $contentId; - $disposition = 'inline'; - } - } - - if (isset($part->contentTransferEncoding)) { - $encoding = strtolower($part->getHeader('Content-Transfer-Encoding')->getTransferEncoding()); - } - - $attachment = $this->getEntityManager()->getEntity('Attachment'); - $attachment->set('name', $fileName); - $attachment->set('type', $type); - - if ($disposition == 'inline') { - $attachment->set('role', 'Inline Attachment'); - } else { - $attachment->set('role', 'Attachment'); - } - - if ($encoding == 'base64') { - $content = base64_decode($content); - } - - $attachment->set('size', strlen($content)); - - $this->getEntityManager()->saveEntity($attachment); - - $path = 'data/upload/' . $attachment->id; - $this->getFileManager()->putContents($path, $content); - - if ($disposition == 'attachment') { - $attachmentsIds = $email->get('attachmentsIds'); - $attachmentsIds[] = $attachment->id; - $email->set('attachmentsIds', $attachmentsIds); - } else if ($disposition == 'inline') { - $inlineIds[$contentId] = $attachment->id; - } - } - } catch (\Exception $e) {} - } - - protected function getContentFromPart($part) - { - if ($part instanceof \Zend\Mime\Part) { - $content = $part->getRawContent(); - if (strtolower($part->charset) != 'utf-8') { - $content = mb_convert_encoding($content, 'UTF-8', $part->charset); - } - } else { - $content = $part->getContent(); - - $encoding = null; - - if (isset($part->contentTransferEncoding)) { - $cteHeader = $part->getHeader('Content-Transfer-Encoding'); - $encoding = strtolower($cteHeader->getTransferEncoding()); - } - - if ($encoding == 'base64') { - $content = base64_decode($content); - } - - $charset = 'UTF-8'; - - if (isset($part->contentType)) { - $ctHeader = $part->getHeader('Content-Type'); - $charsetParamValue = $ctHeader->getParameter('charset'); - if (!empty($charsetParamValue)) { - $charset = strtoupper($charsetParamValue); - } - } - - if ($charset !== 'UTF-8') { - $content = mb_convert_encoding($content, 'UTF-8', $charset); - } - - if (isset($part->contentTransferEncoding)) { - $cteHeader = $part->getHeader('Content-Transfer-Encoding'); - if ($cteHeader->getTransferEncoding() == 'quoted-printable') { - $content = quoted_printable_decode($content); - } - } - } - return $content; - } + $this->getEntityManager()->saveEntity($email); + + return $email; + + } catch (\Exception $e) {} + } + + protected function checkIsDuplicate($email) + { + if ($email->get('messageIdInternal')) { + $duplicate = $this->getEntityManager()->getRepository('Email')->where(array( + 'messageIdInternal' => $email->get('messageIdInternal') + ))->findOne(); + if ($duplicate) { + return true; + } + } + } + + protected function getAddressListFromMessage($message, $type) + { + $addressList = array(); + if (isset($message->$type)) { + + $list = $message->getHeader($type)->getAddressList(); + foreach ($list as $address) { + $addressList[] = $address->getEmail(); + } + } + return $addressList; + } + + protected function importPartDataToEmail(\Espo\Entities\Email $email, $part, &$inlineIds = array()) + { + try { + $type = strtok($part->contentType, ';'); + $encoding = null; + + switch ($type) { + case 'text/plain': + $content = $this->getContentFromPart($part); + if (!$email->get('body')) { + $email->set('body', $content); + } + $email->set('bodyPlain', $content); + break; + case 'text/html': + $content = $this->getContentFromPart($part); + $email->set('body', $content); + $email->set('isHtml', true); + break; + default: + $content = $part->getContent(); + $disposition = null; + + $fileName = null; + $contentId = null; + + if (isset($part->ContentDisposition)) { + if (strpos($part->ContentDisposition, 'attachment') === 0) { + if (preg_match('/filename="?([^"]+)"?/i', $part->ContentDisposition, $m)) { + $fileName = $m[1]; + $disposition = 'attachment'; + } + } else if (strpos($part->ContentDisposition, 'inline') === 0) { + $contentId = trim($part->contentID, '<>'); + $fileName = $contentId; + $disposition = 'inline'; + } + } + + if (isset($part->contentTransferEncoding)) { + $encoding = strtolower($part->getHeader('Content-Transfer-Encoding')->getTransferEncoding()); + } + + $attachment = $this->getEntityManager()->getEntity('Attachment'); + $attachment->set('name', $fileName); + $attachment->set('type', $type); + + if ($disposition == 'inline') { + $attachment->set('role', 'Inline Attachment'); + } else { + $attachment->set('role', 'Attachment'); + } + + if ($encoding == 'base64') { + $content = base64_decode($content); + } + + $attachment->set('size', strlen($content)); + + $this->getEntityManager()->saveEntity($attachment); + + $path = 'data/upload/' . $attachment->id; + $this->getFileManager()->putContents($path, $content); + + if ($disposition == 'attachment') { + $attachmentsIds = $email->get('attachmentsIds'); + $attachmentsIds[] = $attachment->id; + $email->set('attachmentsIds', $attachmentsIds); + } else if ($disposition == 'inline') { + $inlineIds[$contentId] = $attachment->id; + } + } + } catch (\Exception $e) {} + } + + protected function getContentFromPart($part) + { + if ($part instanceof \Zend\Mime\Part) { + $content = $part->getRawContent(); + if (strtolower($part->charset) != 'utf-8') { + $content = mb_convert_encoding($content, 'UTF-8', $part->charset); + } + } else { + $content = $part->getContent(); + + $encoding = null; + + if (isset($part->contentTransferEncoding)) { + $cteHeader = $part->getHeader('Content-Transfer-Encoding'); + $encoding = strtolower($cteHeader->getTransferEncoding()); + } + + if ($encoding == 'base64') { + $content = base64_decode($content); + } + + $charset = 'UTF-8'; + + if (isset($part->contentType)) { + $ctHeader = $part->getHeader('Content-Type'); + $charsetParamValue = $ctHeader->getParameter('charset'); + if (!empty($charsetParamValue)) { + $charset = strtoupper($charsetParamValue); + } + } + + if ($charset !== 'UTF-8') { + $content = mb_convert_encoding($content, 'UTF-8', $charset); + } + + if (isset($part->contentTransferEncoding)) { + $cteHeader = $part->getHeader('Content-Transfer-Encoding'); + if ($cteHeader->getTransferEncoding() == 'quoted-printable') { + $content = quoted_printable_decode($content); + } + } + } + return $content; + } } diff --git a/application/Espo/Core/Mail/Sender.php b/application/Espo/Core/Mail/Sender.php index 777c97a595..0f110c90ad 100644 --- a/application/Espo/Core/Mail/Sender.php +++ b/application/Espo/Core/Mail/Sender.php @@ -36,239 +36,239 @@ use \Espo\Core\Exceptions\Error; class Sender { - protected $config; + protected $config; - protected $transport; + protected $transport; - protected $isGlobal = false; + protected $isGlobal = false; - protected $params = array(); + protected $params = array(); - public function __construct($config) - { - $this->config = $config; - $this->useGlobal(); - } + public function __construct($config) + { + $this->config = $config; + $this->useGlobal(); + } - public function resetParams() - { - $this->params = array(); - return $this; - } + public function resetParams() + { + $this->params = array(); + return $this; + } - public function setParams(array $params = array()) - { - $this->params = array_merge($this->params, $params); - return $this; - } + public function setParams(array $params = array()) + { + $this->params = array_merge($this->params, $params); + return $this; + } - public function useSmtp(array $params = array()) - { - $this->isGlobal = false; - $this->params = $params; + public function useSmtp(array $params = array()) + { + $this->isGlobal = false; + $this->params = $params; - $this->transport = new SmtpTransport(); + $this->transport = new SmtpTransport(); - $opts = array( - 'name' => 'admin', - 'host' => $params['server'], - 'port' => $params['port'], - 'connection_config' => array() - ); - if ($params['auth']) { - $opts['connection_class'] = 'login'; - $opts['connection_config']['username'] = $params['username']; - $opts['connection_config']['password'] = $params['password']; - } - if ($params['security']) { - $opts['connection_config']['ssl'] = strtolower($params['security']); - } + $opts = array( + 'name' => 'admin', + 'host' => $params['server'], + 'port' => $params['port'], + 'connection_config' => array() + ); + if ($params['auth']) { + $opts['connection_class'] = 'login'; + $opts['connection_config']['username'] = $params['username']; + $opts['connection_config']['password'] = $params['password']; + } + if ($params['security']) { + $opts['connection_config']['ssl'] = strtolower($params['security']); + } - $options = new SmtpOptions($opts); - $this->transport->setOptions($options); + $options = new SmtpOptions($opts); + $this->transport->setOptions($options); - return $this; - } + return $this; + } - public function useGlobal() - { - $this->params = array(); - if ($this->isGlobal) { - return $this; - } + public function useGlobal() + { + $this->params = array(); + if ($this->isGlobal) { + return $this; + } - $this->transport = new SmtpTransport(); + $this->transport = new SmtpTransport(); - $config = $this->config; + $config = $this->config; - $opts = array( - 'name' => 'admin', - 'host' => $config->get('smtpServer'), - 'port' => $config->get('smtpPort'), - 'connection_config' => array() - ); - if ($config->get('smtpAuth')) { - $opts['connection_class'] = 'login'; - $opts['connection_config']['username'] = $config->get('smtpUsername'); - $opts['connection_config']['password'] = $config->get('smtpPassword'); - } - if ($config->get('smtpSecurity')) { - $opts['connection_config']['ssl'] = strtolower($config->get('smtpSecurity')); - } + $opts = array( + 'name' => 'admin', + 'host' => $config->get('smtpServer'), + 'port' => $config->get('smtpPort'), + 'connection_config' => array() + ); + if ($config->get('smtpAuth')) { + $opts['connection_class'] = 'login'; + $opts['connection_config']['username'] = $config->get('smtpUsername'); + $opts['connection_config']['password'] = $config->get('smtpPassword'); + } + if ($config->get('smtpSecurity')) { + $opts['connection_config']['ssl'] = strtolower($config->get('smtpSecurity')); + } - $options = new SmtpOptions($opts); - $this->transport->setOptions($options); + $options = new SmtpOptions($opts); + $this->transport->setOptions($options); - $this->isGlobal = true; + $this->isGlobal = true; - return $this; - } + return $this; + } - public function send(Email $email, $params = array()) - { - $message = new Message(); + public function send(Email $email, $params = array()) + { + $message = new Message(); - $config = $this->config; - - $params = $this->params + $params; + $config = $this->config; + + $params = $this->params + $params; - if ($email->get('from')) { - $fromName = null; - if (!empty($params['fromName'])) { - $fromName = $params['fromName']; - } else { - $fromName = $config->get('outboundEmailFromName'); - } - $message->addFrom(trim($email->get('from')), $fromName); - } else { - if (!empty($params['fromAddress'])) { - $fromAddress = $params['fromAddress']; - } else { - if (!$config->get('outboundEmailFromAddress')) { - throw new Error('outboundEmailFromAddress is not specified in config.'); - } - $fromAddress = $config->get('outboundEmailFromAddress'); - } + if ($email->get('from')) { + $fromName = null; + if (!empty($params['fromName'])) { + $fromName = $params['fromName']; + } else { + $fromName = $config->get('outboundEmailFromName'); + } + $message->addFrom(trim($email->get('from')), $fromName); + } else { + if (!empty($params['fromAddress'])) { + $fromAddress = $params['fromAddress']; + } else { + if (!$config->get('outboundEmailFromAddress')) { + throw new Error('outboundEmailFromAddress is not specified in config.'); + } + $fromAddress = $config->get('outboundEmailFromAddress'); + } - if (!empty($params['fromName'])) { - $fromName = $params['fromName']; - } else { - $fromName = $config->get('outboundEmailFromName'); - } + if (!empty($params['fromName'])) { + $fromName = $params['fromName']; + } else { + $fromName = $config->get('outboundEmailFromName'); + } - $message->addFrom($fromAddress, $fromName); - } - - if (!empty($params['replyToAddress'])) { - $replyToName = null; - if (!empty($params['replyToName'])) { - $replyToName = $params['replyToName']; - } - $message->setReplyTo($params['replyToAddress'], $replyToName); - } + $message->addFrom($fromAddress, $fromName); + } + + if (!empty($params['replyToAddress'])) { + $replyToName = null; + if (!empty($params['replyToName'])) { + $replyToName = $params['replyToName']; + } + $message->setReplyTo($params['replyToAddress'], $replyToName); + } - $value = $email->get('to'); - if ($value) { - $arr = explode(';', $value); - if (is_array($arr)) { - foreach ($arr as $address) { - $message->addTo(trim($address)); - } - } - } + $value = $email->get('to'); + if ($value) { + $arr = explode(';', $value); + if (is_array($arr)) { + foreach ($arr as $address) { + $message->addTo(trim($address)); + } + } + } - $value = $email->get('cc'); - if ($value) { - $arr = explode(';', $value); - if (is_array($arr)) { - foreach ($arr as $address) { - $message->addCC(trim($address)); - } - } - } + $value = $email->get('cc'); + if ($value) { + $arr = explode(';', $value); + if (is_array($arr)) { + foreach ($arr as $address) { + $message->addCC(trim($address)); + } + } + } - $value = $email->get('bcc'); - if ($value) { - $arr = explode(';', $value); - if (is_array($arr)) { - foreach ($arr as $address) { - $message->addBCC(trim($address)); - } - } - } + $value = $email->get('bcc'); + if ($value) { + $arr = explode(';', $value); + if (is_array($arr)) { + foreach ($arr as $address) { + $message->addBCC(trim($address)); + } + } + } - $message->setSubject($email->get('name')); + $message->setSubject($email->get('name')); - $body = new MimeMessage; - $parts = array(); - + $body = new MimeMessage; + $parts = array(); + - $bodyPart = new MimePart($email->getBodyPlainForSending()); - $bodyPart->type = 'text/plain'; - $bodyPart->charset = 'utf-8'; - $parts[] = $bodyPart; + $bodyPart = new MimePart($email->getBodyPlainForSending()); + $bodyPart->type = 'text/plain'; + $bodyPart->charset = 'utf-8'; + $parts[] = $bodyPart; - - if ($email->get('isHtml')) { - $bodyPart = new MimePart($email->getBodyForSending()); - $bodyPart->type = 'text/html'; - $bodyPart->charset = 'utf-8'; - $parts[] = $bodyPart; - } - + + if ($email->get('isHtml')) { + $bodyPart = new MimePart($email->getBodyForSending()); + $bodyPart->type = 'text/html'; + $bodyPart->charset = 'utf-8'; + $parts[] = $bodyPart; + } + - $aCollection = $email->get('attachments'); - if (!empty($aCollection)) { - foreach ($aCollection as $a) { - $fileName = 'data/upload/' . $a->id; - $attachment = new MimePart(file_get_contents($fileName)); - $attachment->disposition = Mime::DISPOSITION_ATTACHMENT; - $attachment->encoding = Mime::ENCODING_BASE64; - $attachment->filename = $a->get('name'); - if ($a->get('type')) { - $attachment->type = $a->get('type'); - } - $parts[] = $attachment; - } - } - - $aCollection = $email->getInlineAttachments(); - if (!empty($aCollection)) { - foreach ($aCollection as $a) { - $fileName = 'data/upload/' . $a->id; - $attachment = new MimePart(file_get_contents($fileName)); - $attachment->disposition = Mime::DISPOSITION_INLINE; - $attachment->encoding = Mime::ENCODING_BASE64; - $attachment->id = $a->id; - if ($a->get('type')) { - $attachment->type = $a->get('type'); - } - $parts[] = $attachment; - } - } + $aCollection = $email->get('attachments'); + if (!empty($aCollection)) { + foreach ($aCollection as $a) { + $fileName = 'data/upload/' . $a->id; + $attachment = new MimePart(file_get_contents($fileName)); + $attachment->disposition = Mime::DISPOSITION_ATTACHMENT; + $attachment->encoding = Mime::ENCODING_BASE64; + $attachment->filename = $a->get('name'); + if ($a->get('type')) { + $attachment->type = $a->get('type'); + } + $parts[] = $attachment; + } + } + + $aCollection = $email->getInlineAttachments(); + if (!empty($aCollection)) { + foreach ($aCollection as $a) { + $fileName = 'data/upload/' . $a->id; + $attachment = new MimePart(file_get_contents($fileName)); + $attachment->disposition = Mime::DISPOSITION_INLINE; + $attachment->encoding = Mime::ENCODING_BASE64; + $attachment->id = $a->id; + if ($a->get('type')) { + $attachment->type = $a->get('type'); + } + $parts[] = $attachment; + } + } - $body->setParts($parts); - $message->setBody($body); - - if ($email->get('isHtml')) { - $message->getHeaders()->get('content-type')->setType('multipart/alternative'); - } + $body->setParts($parts); + $message->setBody($body); + + if ($email->get('isHtml')) { + $message->getHeaders()->get('content-type')->setType('multipart/alternative'); + } - try { - $this->transport->send($message); - - $headers = $message->getHeaders(); - if ($headers->has('messageId')) { - $email->set('messageId', $headers->get('messageId')->getId()); - } + try { + $this->transport->send($message); + + $headers = $message->getHeaders(); + if ($headers->has('messageId')) { + $email->set('messageId', $headers->get('messageId')->getId()); + } - $email->set('status', 'Sent'); - $email->set('dateSent', date("Y-m-d H:i:s")); - } catch (\Exception $e) { - throw new Error($e->getMessage(), 500); - } + $email->set('status', 'Sent'); + $email->set('dateSent', date("Y-m-d H:i:s")); + } catch (\Exception $e) { + throw new Error($e->getMessage(), 500); + } - $this->useGlobal(); - } + $this->useGlobal(); + } } diff --git a/application/Espo/Core/Mail/Storage/Imap.php b/application/Espo/Core/Mail/Storage/Imap.php index 65a9ded66b..494ad94e6a 100644 --- a/application/Espo/Core/Mail/Storage/Imap.php +++ b/application/Espo/Core/Mail/Storage/Imap.php @@ -3,17 +3,17 @@ namespace Espo\Core\Mail\Storage; class Imap extends \Zend\Mail\Storage\Imap -{ - public function getIdsFromUID($uid) - { - $uid = intval($uid) + 1; - return $this->protocol->search(array('UID ' . $uid . ':*')); - } - - public function getIdsFromDate($date) - { - return $this->protocol->search(array('SINCE "' . $date . '"')); - } - +{ + public function getIdsFromUID($uid) + { + $uid = intval($uid) + 1; + return $this->protocol->search(array('UID ' . $uid . ':*')); + } + + public function getIdsFromDate($date) + { + return $this->protocol->search(array('SINCE "' . $date . '"')); + } + } diff --git a/application/Espo/Core/ORM/DB/MysqlMapper.php b/application/Espo/Core/ORM/DB/MysqlMapper.php index 78ef574046..b1de6bc5ba 100644 --- a/application/Espo/Core/ORM/DB/MysqlMapper.php +++ b/application/Espo/Core/ORM/DB/MysqlMapper.php @@ -24,6 +24,6 @@ namespace Espo\Core\ORM\DB; class MysqlMapper extends \Espo\ORM\DB\MysqlMapper { - protected $returnCollection = false; + protected $returnCollection = false; } diff --git a/application/Espo/Core/ORM/Entity.php b/application/Espo/Core/ORM/Entity.php index e279f94be9..997e0420c3 100644 --- a/application/Espo/Core/ORM/Entity.php +++ b/application/Espo/Core/ORM/Entity.php @@ -24,40 +24,40 @@ namespace Espo\Core\ORM; class Entity extends \Espo\ORM\Entity { - public function loadLinkMultipleField($field, $columns = null) - { - if ($this->hasRelation($field) && $this->hasField($field . 'Ids')) { - - $defs = array(); - if (!empty($columns)) { - $defs['additionalColumns'] = $columns; - } - - $collection = $this->get($field, $defs); - $ids = array(); - $names = new \stdClass(); - if (!empty($columns)) { - $columnsData = new \stdClass(); - } - - foreach ($collection as $e) { - $id = $e->id; - $ids[] = $id; - $names->$id = $e->get('name'); - if (!empty($columns)) { - $columnsData->$id = new \stdClass(); - foreach ($columns as $column => $f) { - $columnsData->$id->$column = $e->get($f); - } - } - } - $this->set($field . 'Ids', $ids); - $this->set($field . 'Names', $names); - if (!empty($columns)) { - $this->set($field . 'Columns', $columnsData); - } - - } - } + public function loadLinkMultipleField($field, $columns = null) + { + if ($this->hasRelation($field) && $this->hasField($field . 'Ids')) { + + $defs = array(); + if (!empty($columns)) { + $defs['additionalColumns'] = $columns; + } + + $collection = $this->get($field, $defs); + $ids = array(); + $names = new \stdClass(); + if (!empty($columns)) { + $columnsData = new \stdClass(); + } + + foreach ($collection as $e) { + $id = $e->id; + $ids[] = $id; + $names->$id = $e->get('name'); + if (!empty($columns)) { + $columnsData->$id = new \stdClass(); + foreach ($columns as $column => $f) { + $columnsData->$id->$column = $e->get($f); + } + } + } + $this->set($field . 'Ids', $ids); + $this->set($field . 'Names', $names); + if (!empty($columns)) { + $this->set($field . 'Columns', $columnsData); + } + + } + } } diff --git a/application/Espo/Core/ORM/EntityManager.php b/application/Espo/Core/ORM/EntityManager.php index 555e6875b8..3b49cff4c7 100644 --- a/application/Espo/Core/ORM/EntityManager.php +++ b/application/Espo/Core/ORM/EntityManager.php @@ -26,80 +26,80 @@ use \Espo\Core\Utils\Util; class EntityManager extends \Espo\ORM\EntityManager { - protected $espoMetadata; - - private $hookManager; - - protected $user; - - protected $container; - - private $repositoryClassNameHash = array(); - - private $entityClassNameHash = array(); - - public function setContainer(\Espo\Core\Container $container) - { - $this->container = $container; - } - - public function getContainer() - { - return $this->container; - } - - public function setUser($user) - { - $this->user = $user; - } - - public function getUser() - { - return $this->user; - } - - public function getEspoMetadata() - { - return $this->espoMetadata; - } + protected $espoMetadata; + + private $hookManager; + + protected $user; + + protected $container; + + private $repositoryClassNameHash = array(); + + private $entityClassNameHash = array(); + + public function setContainer(\Espo\Core\Container $container) + { + $this->container = $container; + } + + public function getContainer() + { + return $this->container; + } + + public function setUser($user) + { + $this->user = $user; + } + + public function getUser() + { + return $this->user; + } + + public function getEspoMetadata() + { + return $this->espoMetadata; + } - public function setEspoMetadata($espoMetadata) - { - $this->espoMetadata = $espoMetadata; - } - - public function setHookManager(\Espo\Core\HookManager $hookManager) - { - $this->hookManager = $hookManager; - } - - public function getHookManager() - { - return $this->hookManager; - } + public function setEspoMetadata($espoMetadata) + { + $this->espoMetadata = $espoMetadata; + } + + public function setHookManager(\Espo\Core\HookManager $hookManager) + { + $this->hookManager = $hookManager; + } + + public function getHookManager() + { + return $this->hookManager; + } - public function normalizeRepositoryName($name) - { - if (empty($this->repositoryClassNameHash[$name])) { - $className = '\\Espo\\Custom\\Repositories\\' . Util::normilizeClassName($name); - if (!class_exists($className)) { - $className = $this->espoMetadata->getRepositoryPath($name); - } - $this->repositoryClassNameHash[$name] = $className; - } - return $this->repositoryClassNameHash[$name]; - } - - public function normalizeEntityName($name) - { - if (empty($this->entityClassNameHash[$name])) { - $className = '\\Espo\\Custom\\Entities\\' . Util::normilizeClassName($name); - if (!class_exists($className)) { - $className = $this->espoMetadata->getEntityPath($name); - } - $this->entityClassNameHash[$name] = $className; - } - return $this->entityClassNameHash[$name]; - } + public function normalizeRepositoryName($name) + { + if (empty($this->repositoryClassNameHash[$name])) { + $className = '\\Espo\\Custom\\Repositories\\' . Util::normilizeClassName($name); + if (!class_exists($className)) { + $className = $this->espoMetadata->getRepositoryPath($name); + } + $this->repositoryClassNameHash[$name] = $className; + } + return $this->repositoryClassNameHash[$name]; + } + + public function normalizeEntityName($name) + { + if (empty($this->entityClassNameHash[$name])) { + $className = '\\Espo\\Custom\\Entities\\' . Util::normilizeClassName($name); + if (!class_exists($className)) { + $className = $this->espoMetadata->getEntityPath($name); + } + $this->entityClassNameHash[$name] = $className; + } + return $this->entityClassNameHash[$name]; + } } diff --git a/application/Espo/Core/ORM/Repositories/RDB.php b/application/Espo/Core/ORM/Repositories/RDB.php index 0023ee6f9b..23f5cb5d5d 100644 --- a/application/Espo/Core/ORM/Repositories/RDB.php +++ b/application/Espo/Core/ORM/Repositories/RDB.php @@ -32,282 +32,282 @@ use \Espo\Core\Interfaces\Injectable; class RDB extends \Espo\ORM\Repositories\RDB implements Injectable { - public static $mapperClassName = '\\Espo\\Core\\ORM\\DB\\MysqlMapper'; + public static $mapperClassName = '\\Espo\\Core\\ORM\\DB\\MysqlMapper'; - protected $dependencies = array( - 'metadata' - ); + protected $dependencies = array( + 'metadata' + ); - protected $injections = array(); + protected $injections = array(); - public function inject($name, $object) - { - $this->injections[$name] = $object; - } + public function inject($name, $object) + { + $this->injections[$name] = $object; + } - protected function getInjection($name) - { - return $this->injections[$name]; - } + protected function getInjection($name) + { + return $this->injections[$name]; + } - public function getDependencyList() - { - return $this->dependencies; - } + public function getDependencyList() + { + return $this->dependencies; + } - protected function getMetadata() - { - return $this->getInjection('metadata'); - } + protected function getMetadata() + { + return $this->getInjection('metadata'); + } - public function handleSelectParams(&$params) - { - $this->handleEmailAddressParams($params); - $this->handlePhoneNumberParams($params); - $this->handleCurrencyParams($params); - } - - protected function handleCurrencyParams(&$params) - { - $entityName = $this->entityName; - - $metadata = $this->getMetadata(); - - if (!$metadata) { - return; - } - - $defs = $metadata->get('entityDefs.' . $entityName); + public function handleSelectParams(&$params) + { + $this->handleEmailAddressParams($params); + $this->handlePhoneNumberParams($params); + $this->handleCurrencyParams($params); + } + + protected function handleCurrencyParams(&$params) + { + $entityName = $this->entityName; + + $metadata = $this->getMetadata(); + + if (!$metadata) { + return; + } + + $defs = $metadata->get('entityDefs.' . $entityName); - foreach ($defs['fields'] as $field => $d) { - if (isset($d['type']) && $d['type'] == 'currency') { - if (empty($params['customJoin'])) { - $params['customJoin'] = ''; - } - $alias = Util::toUnderScore($field) . "_currency_alias"; - $params['customJoin'] .= " - LEFT JOIN currency AS `{$alias}` ON {$alias}.id = ".Util::toUnderScore($entityName).".".Util::toUnderScore($field)."_currency - "; - } - } + foreach ($defs['fields'] as $field => $d) { + if (isset($d['type']) && $d['type'] == 'currency') { + if (empty($params['customJoin'])) { + $params['customJoin'] = ''; + } + $alias = Util::toUnderScore($field) . "_currency_alias"; + $params['customJoin'] .= " + LEFT JOIN currency AS `{$alias}` ON {$alias}.id = ".Util::toUnderScore($entityName).".".Util::toUnderScore($field)."_currency + "; + } + } - } + } - protected function handleEmailAddressParams(&$params) - { - $entityName = $this->entityName; + protected function handleEmailAddressParams(&$params) + { + $entityName = $this->entityName; - $defs = $this->getEntityManager()->getMetadata()->get($entityName); - if (!empty($defs['relations']) && array_key_exists('emailAddresses', $defs['relations'])) { - if (empty($params['leftJoins'])) { - $params['leftJoins'] = array(); - } - if (empty($params['whereClause'])) { - $params['whereClause'] = array(); - } - if (empty($params['joinConditions'])) { - $params['joinConditions'] = array(); - } - $params['leftJoins'][] = 'emailAddresses'; - $params['joinConditions']['emailAddresses'] = array( - 'primary' => 1 - ); - } - } - - protected function handlePhoneNumberParams(&$params) - { - $entityName = $this->entityName; + $defs = $this->getEntityManager()->getMetadata()->get($entityName); + if (!empty($defs['relations']) && array_key_exists('emailAddresses', $defs['relations'])) { + if (empty($params['leftJoins'])) { + $params['leftJoins'] = array(); + } + if (empty($params['whereClause'])) { + $params['whereClause'] = array(); + } + if (empty($params['joinConditions'])) { + $params['joinConditions'] = array(); + } + $params['leftJoins'][] = 'emailAddresses'; + $params['joinConditions']['emailAddresses'] = array( + 'primary' => 1 + ); + } + } + + protected function handlePhoneNumberParams(&$params) + { + $entityName = $this->entityName; - $defs = $this->getEntityManager()->getMetadata()->get($entityName); - if (!empty($defs['relations']) && array_key_exists('phoneNumbers', $defs['relations'])) { - if (empty($params['leftJoins'])) { - $params['leftJoins'] = array(); - } - if (empty($params['whereClause'])) { - $params['whereClause'] = array(); - } - if (empty($params['joinConditions'])) { - $params['joinConditions'] = array(); - } - $params['leftJoins'][] = 'phoneNumbers'; - $params['joinConditions']['phoneNumbers'] = array( - 'primary' => 1 - ); - } - } + $defs = $this->getEntityManager()->getMetadata()->get($entityName); + if (!empty($defs['relations']) && array_key_exists('phoneNumbers', $defs['relations'])) { + if (empty($params['leftJoins'])) { + $params['leftJoins'] = array(); + } + if (empty($params['whereClause'])) { + $params['whereClause'] = array(); + } + if (empty($params['joinConditions'])) { + $params['joinConditions'] = array(); + } + $params['leftJoins'][] = 'phoneNumbers'; + $params['joinConditions']['phoneNumbers'] = array( + 'primary' => 1 + ); + } + } - protected function beforeRemove(Entity $entity) - { - parent::beforeRemove($entity); - $this->getEntityManager()->getHookManager()->process($this->entityName, 'beforeRemove', $entity); - } + protected function beforeRemove(Entity $entity) + { + parent::beforeRemove($entity); + $this->getEntityManager()->getHookManager()->process($this->entityName, 'beforeRemove', $entity); + } - protected function afterRemove(Entity $entity) - { - parent::afterRemove($entity); - $this->getEntityManager()->getHookManager()->process($this->entityName, 'afterRemove', $entity); - } + protected function afterRemove(Entity $entity) + { + parent::afterRemove($entity); + $this->getEntityManager()->getHookManager()->process($this->entityName, 'afterRemove', $entity); + } - public function remove(Entity $entity) - { - $this->getEntityManager()->getHookManager()->process($this->entityName, 'beforeRemove', $entity); + public function remove(Entity $entity) + { + $this->getEntityManager()->getHookManager()->process($this->entityName, 'beforeRemove', $entity); - $result = parent::remove($entity); - if ($result) { - $this->getEntityManager()->getHookManager()->process($this->entityName, 'afterRemove', $entity); - } - return $result; - } + $result = parent::remove($entity); + if ($result) { + $this->getEntityManager()->getHookManager()->process($this->entityName, 'afterRemove', $entity); + } + return $result; + } - protected function beforeSave(Entity $entity) - { - parent::beforeSave($entity); - $this->getEntityManager()->getHookManager()->process($this->entityName, 'beforeSave', $entity); - } + protected function beforeSave(Entity $entity) + { + parent::beforeSave($entity); + $this->getEntityManager()->getHookManager()->process($this->entityName, 'beforeSave', $entity); + } - protected function afterSave(Entity $entity) - { - parent::afterSave($entity); - $this->getEntityManager()->getHookManager()->process($this->entityName, 'afterSave', $entity); - } + protected function afterSave(Entity $entity) + { + parent::afterSave($entity); + $this->getEntityManager()->getHookManager()->process($this->entityName, 'afterSave', $entity); + } - public function save(Entity $entity) - { - $nowString = date('Y-m-d H:i:s', time()); - $restoreData = array(); + public function save(Entity $entity) + { + $nowString = date('Y-m-d H:i:s', time()); + $restoreData = array(); - if ($entity->isNew()) { - if (!$entity->has('id')) { - $entity->set('id', uniqid()); - } + if ($entity->isNew()) { + if (!$entity->has('id')) { + $entity->set('id', uniqid()); + } - if ($entity->hasField('createdAt')) { - $entity->set('createdAt', $nowString); - } - if ($entity->hasField('createdById')) { - $entity->set('createdById', $this->entityManager->getUser()->id); - } + if ($entity->hasField('createdAt')) { + $entity->set('createdAt', $nowString); + } + if ($entity->hasField('createdById')) { + $entity->set('createdById', $this->entityManager->getUser()->id); + } - if ($entity->has('modifiedById')) { - $restoreData['modifiedById'] = $entity->get('modifiedById'); - } - if ($entity->has('modifiedAt')) { - $restoreData['modifiedAt'] = $entity->get('modifiedAt'); - } - $entity->clear('modifiedById'); - $entity->clear('modifiedAt'); - } else { - if ($entity->hasField('modifiedAt')) { - $entity->set('modifiedAt', $nowString); - } - if ($entity->hasField('modifiedById')) { - $entity->set('modifiedById', $this->entityManager->getUser()->id); - } + if ($entity->has('modifiedById')) { + $restoreData['modifiedById'] = $entity->get('modifiedById'); + } + if ($entity->has('modifiedAt')) { + $restoreData['modifiedAt'] = $entity->get('modifiedAt'); + } + $entity->clear('modifiedById'); + $entity->clear('modifiedAt'); + } else { + if ($entity->hasField('modifiedAt')) { + $entity->set('modifiedAt', $nowString); + } + if ($entity->hasField('modifiedById')) { + $entity->set('modifiedById', $this->entityManager->getUser()->id); + } - if ($entity->has('createdById')) { - $restoreData['createdById'] = $entity->get('createdById'); - } - if ($entity->has('createdAt')) { - $restoreData['createdAt'] = $entity->get('createdAt'); - } - $entity->clear('createdById'); - $entity->clear('createdAt'); - } - $result = parent::save($entity); + if ($entity->has('createdById')) { + $restoreData['createdById'] = $entity->get('createdById'); + } + if ($entity->has('createdAt')) { + $restoreData['createdAt'] = $entity->get('createdAt'); + } + $entity->clear('createdById'); + $entity->clear('createdAt'); + } + $result = parent::save($entity); - $entity->set($restoreData); + $entity->set($restoreData); - $this->handleEmailAddressSave($entity); - $this->handlePhoneNumberSave($entity); - $this->handleSpecifiedRelations($entity); + $this->handleEmailAddressSave($entity); + $this->handlePhoneNumberSave($entity); + $this->handleSpecifiedRelations($entity); - return $result; - } + return $result; + } - protected function handleEmailAddressSave(Entity $entity) - { - if ($entity->hasRelation('emailAddresses') && $entity->hasField('emailAddress')) { - $emailAddressRepository = $this->getEntityManager()->getRepository('EmailAddress')->storeEntityEmailAddress($entity); - } - } - - protected function handlePhoneNumberSave(Entity $entity) - { - if ($entity->hasRelation('phoneNumbers') && $entity->hasField('phoneNumber')) { - $emailAddressRepository = $this->getEntityManager()->getRepository('PhoneNumber')->storeEntityPhoneNumber($entity); - } - } + protected function handleEmailAddressSave(Entity $entity) + { + if ($entity->hasRelation('emailAddresses') && $entity->hasField('emailAddress')) { + $emailAddressRepository = $this->getEntityManager()->getRepository('EmailAddress')->storeEntityEmailAddress($entity); + } + } + + protected function handlePhoneNumberSave(Entity $entity) + { + if ($entity->hasRelation('phoneNumbers') && $entity->hasField('phoneNumber')) { + $emailAddressRepository = $this->getEntityManager()->getRepository('PhoneNumber')->storeEntityPhoneNumber($entity); + } + } - protected function handleSpecifiedRelations(Entity $entity) - { - $relationTypes = array($entity::HAS_MANY, $entity::MANY_MANY, $entity::HAS_CHILDREN); - foreach ($entity->getRelations() as $name => $defs) { - if (in_array($defs['type'], $relationTypes)) { - $fieldName = $name . 'Ids'; - if ($entity->has($fieldName)) { - $specifiedIds = $entity->get($fieldName); - if (is_array($specifiedIds)) { - $toRemoveIds = array(); - $existingIds = array(); - $toUpdateIds = array(); - $existingColumnsData = new \stdClass(); - - $defs = array(); - $columns = $this->getMetadata()->get("entityDefs." . $entity->getEntityName() . ".fields.{$name}.columns"); - if (!empty($columns)) { - $columnData = $entity->get($name . 'Columns'); - $defs['additionalColumns'] = $columns; + protected function handleSpecifiedRelations(Entity $entity) + { + $relationTypes = array($entity::HAS_MANY, $entity::MANY_MANY, $entity::HAS_CHILDREN); + foreach ($entity->getRelations() as $name => $defs) { + if (in_array($defs['type'], $relationTypes)) { + $fieldName = $name . 'Ids'; + if ($entity->has($fieldName)) { + $specifiedIds = $entity->get($fieldName); + if (is_array($specifiedIds)) { + $toRemoveIds = array(); + $existingIds = array(); + $toUpdateIds = array(); + $existingColumnsData = new \stdClass(); + + $defs = array(); + $columns = $this->getMetadata()->get("entityDefs." . $entity->getEntityName() . ".fields.{$name}.columns"); + if (!empty($columns)) { + $columnData = $entity->get($name . 'Columns'); + $defs['additionalColumns'] = $columns; - } - - foreach ($entity->get($name, $defs) as $foreignEntity) { - $existingIds[] = $foreignEntity->id; - if (!empty($columns)) { - $data = new \stdClass(); - foreach ($columns as $columnName => $columnField) { - $foreignId = $foreignEntity->id; - $data->$columnName = $foreignEntity->get($columnField); - } - $existingColumnsData->$foreignId = $data; - } - - } - foreach ($existingIds as $id) { - if (!in_array($id, $specifiedIds)) { - $toRemoveIds[] = $id; - } else { - if (!empty($columns)) { - foreach ($columns as $columnName => $columnField) { - if ($columnData->$id->$columnName != $existingColumnsData->$id->$columnName) { - $toUpdateIds[] = $id; - } - } - } - } - } - foreach ($specifiedIds as $id) { - if (!in_array($id, $existingIds)) { - $data = null; - if (!empty($columns)) { - $data = $columnData->$id; - } - $this->relate($entity, $name, $id, $data); - } - } - foreach ($toRemoveIds as $id) { - $this->unrelate($entity, $name, $id); - } - if (!empty($columns)) { - foreach ($toUpdateIds as $id) { - $data = $columnData->$id; - $this->updateRelation($entity, $name, $id, $data); - } - } - } - } - } - } - } + } + + foreach ($entity->get($name, $defs) as $foreignEntity) { + $existingIds[] = $foreignEntity->id; + if (!empty($columns)) { + $data = new \stdClass(); + foreach ($columns as $columnName => $columnField) { + $foreignId = $foreignEntity->id; + $data->$columnName = $foreignEntity->get($columnField); + } + $existingColumnsData->$foreignId = $data; + } + + } + foreach ($existingIds as $id) { + if (!in_array($id, $specifiedIds)) { + $toRemoveIds[] = $id; + } else { + if (!empty($columns)) { + foreach ($columns as $columnName => $columnField) { + if ($columnData->$id->$columnName != $existingColumnsData->$id->$columnName) { + $toUpdateIds[] = $id; + } + } + } + } + } + foreach ($specifiedIds as $id) { + if (!in_array($id, $existingIds)) { + $data = null; + if (!empty($columns)) { + $data = $columnData->$id; + } + $this->relate($entity, $name, $id, $data); + } + } + foreach ($toRemoveIds as $id) { + $this->unrelate($entity, $name, $id); + } + if (!empty($columns)) { + foreach ($toUpdateIds as $id) { + $data = $columnData->$id; + $this->updateRelation($entity, $name, $id, $data); + } + } + } + } + } + } + } } diff --git a/application/Espo/Core/ORM/Repository.php b/application/Espo/Core/ORM/Repository.php index a6386eae43..0c54abd89c 100644 --- a/application/Espo/Core/ORM/Repository.php +++ b/application/Espo/Core/ORM/Repository.php @@ -26,23 +26,23 @@ use \Espo\Core\Interfaces\Injectable; abstract class Repository extends \Espo\ORM\Repository implements Injectable { - protected $dependencies = array(); - - protected $injections = array(); - - public function inject($name, $object) - { - $this->injections[$name] = $object; - } - - protected function getInjection($name) - { - return $this->injections[$name]; - } - - public function getDependencyList() - { - return $this->dependencies; - } + protected $dependencies = array(); + + protected $injections = array(); + + public function inject($name, $object) + { + $this->injections[$name] = $object; + } + + protected function getInjection($name) + { + return $this->injections[$name]; + } + + public function getDependencyList() + { + return $this->dependencies; + } } diff --git a/application/Espo/Core/ORM/RepositoryFactory.php b/application/Espo/Core/ORM/RepositoryFactory.php index 6975192db8..6107565483 100644 --- a/application/Espo/Core/ORM/RepositoryFactory.php +++ b/application/Espo/Core/ORM/RepositoryFactory.php @@ -23,18 +23,18 @@ namespace Espo\Core\ORM; class RepositoryFactory extends \Espo\ORM\RepositoryFactory -{ - protected $defaultRepositoryClassName = '\\Espo\\Core\\ORM\\Repositories\\RDB'; +{ + protected $defaultRepositoryClassName = '\\Espo\\Core\\ORM\\Repositories\\RDB'; - public function create($name) - { - $repository = parent::create($name); - - $dependencies = $repository->getDependencyList(); - foreach ($dependencies as $name) { - $repository->inject($name, $this->entityManager->getContainer()->get($name)); - } - return $repository; - } + public function create($name) + { + $repository = parent::create($name); + + $dependencies = $repository->getDependencyList(); + foreach ($dependencies as $name) { + $repository->inject($name, $this->entityManager->getContainer()->get($name)); + } + return $repository; + } } diff --git a/application/Espo/Core/SelectManagerFactory.php b/application/Espo/Core/SelectManagerFactory.php index dd035fe8b8..333023ee73 100644 --- a/application/Espo/Core/SelectManagerFactory.php +++ b/application/Espo/Core/SelectManagerFactory.php @@ -28,41 +28,41 @@ use \Espo\Core\Utils\Util; class SelectManagerFactory { - private $entityManager; - - private $user; - - private $acl; - - private $metadata; + private $entityManager; + + private $user; + + private $acl; + + private $metadata; public function __construct($entityManager, \Espo\Entities\User $user, Acl $acl, $metadata) { - $this->entityManager = $entityManager; - $this->user = $user; - $this->acl = $acl; - $this->metadata = $metadata; + $this->entityManager = $entityManager; + $this->user = $user; + $this->acl = $acl; + $this->metadata = $metadata; } - public function create($entityName) - { - $className = '\\Espo\\Custom\\SelectManagers\\' . Util::normilizeClassName($entityName); - if (!class_exists($className)) { - $moduleName = $this->metadata->getScopeModuleName($entityName); - if ($moduleName) { - $className = '\\Espo\\Modules\\' . $moduleName . '\\SelectManagers\\' . Util::normilizeClassName($entityName); - } else { - $className = '\\Espo\\SelectManagers\\' . Util::normilizeClassName($entityName); - } - if (!class_exists($className)) { - $className = '\\Espo\\Core\\SelectManagers\\Base'; - } - } - - $selectManager = new $className($this->entityManager, $this->user, $this->acl, $this->metadata); - $selectManager->setEntityName($entityName); - - return $selectManager; - } + public function create($entityName) + { + $className = '\\Espo\\Custom\\SelectManagers\\' . Util::normilizeClassName($entityName); + if (!class_exists($className)) { + $moduleName = $this->metadata->getScopeModuleName($entityName); + if ($moduleName) { + $className = '\\Espo\\Modules\\' . $moduleName . '\\SelectManagers\\' . Util::normilizeClassName($entityName); + } else { + $className = '\\Espo\\SelectManagers\\' . Util::normilizeClassName($entityName); + } + if (!class_exists($className)) { + $className = '\\Espo\\Core\\SelectManagers\\Base'; + } + } + + $selectManager = new $className($this->entityManager, $this->user, $this->acl, $this->metadata); + $selectManager->setEntityName($entityName); + + return $selectManager; + } } diff --git a/application/Espo/Core/SelectManagers/Base.php b/application/Espo/Core/SelectManagers/Base.php index b32890dfd0..a017defb3a 100644 --- a/application/Espo/Core/SelectManagers/Base.php +++ b/application/Espo/Core/SelectManagers/Base.php @@ -28,374 +28,374 @@ use \Espo\Core\Acl; class Base { - protected $container; + protected $container; - protected $user; + protected $user; - protected $acl; + protected $acl; - protected $entityManager; + protected $entityManager; - protected $entityName; + protected $entityName; - protected $metadata; + protected $metadata; - const MIN_LENGTH_FOR_CONTENT_SEARCH = 4; + const MIN_LENGTH_FOR_CONTENT_SEARCH = 4; public function __construct($entityManager, \Espo\Entities\User $user, Acl $acl, $metadata) { - $this->entityManager = $entityManager; - $this->user = $user; - $this->acl = $acl; - $this->metadata = $metadata; + $this->entityManager = $entityManager; + $this->user = $user; + $this->acl = $acl; + $this->metadata = $metadata; } public function setEntityName($entityName) { - $this->entityName = $entityName; + $this->entityName = $entityName; } protected function limit($params, &$result) { - if (isset($params['offset']) && !is_null($params['offset'])) { - $result['offset'] = $params['offset']; - } - if (isset($params['maxSize']) && !is_null($params['maxSize'])) { - $result['limit'] = $params['maxSize']; - } + if (isset($params['offset']) && !is_null($params['offset'])) { + $result['offset'] = $params['offset']; + } + if (isset($params['maxSize']) && !is_null($params['maxSize'])) { + $result['limit'] = $params['maxSize']; + } } protected function order($params, &$result) { - if (!empty($params['sortBy'])) { - $result['orderBy'] = $params['sortBy']; - $type = $this->metadata->get("entityDefs.{$this->entityName}.fields." . $result['orderBy'] . ".type"); - if ($type == 'link') { - $result['orderBy'] .= 'Name'; - } else if ($type == 'linkParent') { - $result['orderBy'] .= 'Type'; - } - } - if (isset($params['asc'])) { - if ($params['asc']) { - $result['order'] = 'ASC'; - } else { - $result['order'] = 'DESC'; - } - } + if (!empty($params['sortBy'])) { + $result['orderBy'] = $params['sortBy']; + $type = $this->metadata->get("entityDefs.{$this->entityName}.fields." . $result['orderBy'] . ".type"); + if ($type == 'link') { + $result['orderBy'] .= 'Name'; + } else if ($type == 'linkParent') { + $result['orderBy'] .= 'Type'; + } + } + if (isset($params['asc'])) { + if ($params['asc']) { + $result['order'] = 'ASC'; + } else { + $result['order'] = 'DESC'; + } + } } protected function getTextFilterFields() { - return $this->metadata->get("entityDefs.{$this->entityName}.collection.textFilterFields", array('name')); + return $this->metadata->get("entityDefs.{$this->entityName}.collection.textFilterFields", array('name')); } protected function where($params, &$result) { - if (!empty($params['where']) && is_array($params['where'])) { - $where = array(); + if (!empty($params['where']) && is_array($params['where'])) { + $where = array(); - foreach ($params['where'] as $item) { - if ($item['type'] == 'boolFilters' && !empty($item['value']) && is_array($item['value'])) { - foreach ($item['value'] as $filter) { - $p = $this->getBoolFilterWhere($filter); - if (!empty($p)) { - $params['where'][] = $p; - } - } - } else if ($item['type'] == 'textFilter' && !empty($item['value'])) { - if (!empty($item['value'])) { - if (empty($result['whereClause'])) { - $result['whereClause'] = array(); - } - $fieldDefs = $this->entityManager->getEntity($this->entityName)->getFields(); - $fieldList = $this->getTextFilterFields(); - $d = array(); - foreach ($fieldList as $field) { - if ( - strlen($item['value']) >= self::MIN_LENGTH_FOR_CONTENT_SEARCH - && - !empty($fieldDefs[$field]['type']) && $fieldDefs[$field]['type'] == 'text' - ) { - $d[$field . '*'] = '%' . $item['value'] . '%'; - } else { - $d[$field . '*'] = $item['value'] . '%'; - } - } - $where['OR'] = $d; - } - } - } + foreach ($params['where'] as $item) { + if ($item['type'] == 'boolFilters' && !empty($item['value']) && is_array($item['value'])) { + foreach ($item['value'] as $filter) { + $p = $this->getBoolFilterWhere($filter); + if (!empty($p)) { + $params['where'][] = $p; + } + } + } else if ($item['type'] == 'textFilter' && !empty($item['value'])) { + if (!empty($item['value'])) { + if (empty($result['whereClause'])) { + $result['whereClause'] = array(); + } + $fieldDefs = $this->entityManager->getEntity($this->entityName)->getFields(); + $fieldList = $this->getTextFilterFields(); + $d = array(); + foreach ($fieldList as $field) { + if ( + strlen($item['value']) >= self::MIN_LENGTH_FOR_CONTENT_SEARCH + && + !empty($fieldDefs[$field]['type']) && $fieldDefs[$field]['type'] == 'text' + ) { + $d[$field . '*'] = '%' . $item['value'] . '%'; + } else { + $d[$field . '*'] = $item['value'] . '%'; + } + } + $where['OR'] = $d; + } + } + } - $linkedWith = array(); - $ignoreList = array('linkedWith', 'boolFilters'); - foreach ($params['where'] as $item) { - if (!in_array($item['type'], $ignoreList)) { - $part = $this->getWherePart($item); - if (!empty($part)) { - $where[] = $part; - } - } else { - if ($item['type'] == 'linkedWith' && !empty($item['value'])) { - $linkedWith[$item['field']] = $item['value']; - } - } - } + $linkedWith = array(); + $ignoreList = array('linkedWith', 'boolFilters'); + foreach ($params['where'] as $item) { + if (!in_array($item['type'], $ignoreList)) { + $part = $this->getWherePart($item); + if (!empty($part)) { + $where[] = $part; + } + } else { + if ($item['type'] == 'linkedWith' && !empty($item['value'])) { + $linkedWith[$item['field']] = $item['value']; + } + } + } - if (!empty($linkedWith)) { - $joins = array(); + if (!empty($linkedWith)) { + $joins = array(); - $part = array(); - foreach ($linkedWith as $link => $ids) { - $joins[] = $link; - $defs = $this->entityManager->getMetadata()->get($this->entityName); + $part = array(); + foreach ($linkedWith as $link => $ids) { + $joins[] = $link; + $defs = $this->entityManager->getMetadata()->get($this->entityName); - $entityName = $defs['relations'][$link]['entity']; - if ($entityName) { - $part[$entityName . '.id'] = $ids; - } - } + $entityName = $defs['relations'][$link]['entity']; + if ($entityName) { + $part[$entityName . '.id'] = $ids; + } + } - if (!empty($part)) { - $where[] = $part; - } - $result['joins'] = $joins; - $result['distinct'] = true; + if (!empty($part)) { + $where[] = $part; + } + $result['joins'] = $joins; + $result['distinct'] = true; - } + } - $result['whereClause'] = $where; - } + $result['whereClause'] = $where; + } } protected function q($params, &$result) { - if (!empty($params['q'])) { - if (empty($result['whereClause'])) { - $result['whereClause'] = array(); - } - - $fieldDefs = $this->entityManager->getEntity($this->entityName)->getFields(); + if (!empty($params['q'])) { + if (empty($result['whereClause'])) { + $result['whereClause'] = array(); + } + + $fieldDefs = $this->entityManager->getEntity($this->entityName)->getFields(); - $value = $params['q']; + $value = $params['q']; - $fieldList = $this->getTextFilterFields(); - $d = array(); - foreach ($fieldList as $field) { - if ( - strlen($item['value']) >= self::MIN_LENGTH_FOR_CONTENT_SEARCH - && - !empty($fieldDefs[$field]['type']) && $fieldDefs[$field]['type'] == 'text' - ) { - $d[$field . '*'] = '%' . $value . '%'; - } else { - $d[$field . '*'] = $value . '%'; - } - } + $fieldList = $this->getTextFilterFields(); + $d = array(); + foreach ($fieldList as $field) { + if ( + strlen($item['value']) >= self::MIN_LENGTH_FOR_CONTENT_SEARCH + && + !empty($fieldDefs[$field]['type']) && $fieldDefs[$field]['type'] == 'text' + ) { + $d[$field . '*'] = '%' . $value . '%'; + } else { + $d[$field . '*'] = $value . '%'; + } + } - $result['whereClause']['OR'] = $d; - } - } + $result['whereClause']['OR'] = $d; + } + } protected function access(&$result) { - if ($this->acl->checkReadOnlyOwn($this->entityName)) { + if ($this->acl->checkReadOnlyOwn($this->entityName)) { - if (!array_key_exists('whereClause', $result)) { - $result['whereClause'] = array(); - } - $result['whereClause']['assignedUserId'] = $this->user->id; - } - if (!$this->user->isAdmin() && $this->acl->checkReadOnlyTeam($this->entityName)) { - if (!array_key_exists('whereClause', $result)) { - $result['whereClause'] = array(); - } - $result['distinct'] = true; - if (!array_key_exists('joins', $result)) { - $result['joins'] = array(); - } - if (!in_array('teams', $result['joins'])) { - $result['leftJoins'][] = 'teams'; - } + if (!array_key_exists('whereClause', $result)) { + $result['whereClause'] = array(); + } + $result['whereClause']['assignedUserId'] = $this->user->id; + } + if (!$this->user->isAdmin() && $this->acl->checkReadOnlyTeam($this->entityName)) { + if (!array_key_exists('whereClause', $result)) { + $result['whereClause'] = array(); + } + $result['distinct'] = true; + if (!array_key_exists('joins', $result)) { + $result['joins'] = array(); + } + if (!in_array('teams', $result['joins'])) { + $result['leftJoins'][] = 'teams'; + } - $result['whereClause']['OR'] = array( - 'Team.id' => $this->user->get('teamsIds'), - 'assignedUserId' => $this->user->id - ); - //$result['whereClause']['Team.id'] = $this->user->get('teamsIds'); - } + $result['whereClause']['OR'] = array( + 'Team.id' => $this->user->get('teamsIds'), + 'assignedUserId' => $this->user->id + ); + //$result['whereClause']['Team.id'] = $this->user->get('teamsIds'); + } } public function getAclParams() { - $result = array(); - $this->access($result); - return $result; + $result = array(); + $this->access($result); + return $result; } - public function getSelectParams(array $params, $withAcl = false) - { - $result = array(); + public function getSelectParams(array $params, $withAcl = false) + { + $result = array(); - $this->order($params, $result); - $this->limit($params, $result); - $this->where($params, $result); - $this->q($params, $result); + $this->order($params, $result); + $this->limit($params, $result); + $this->where($params, $result); + $this->q($params, $result); - if ($withAcl) { - $this->access($result); - } + if ($withAcl) { + $this->access($result); + } - return $result; - } + return $result; + } - protected function getWherePart($item) - { - $part = array(); + protected function getWherePart($item) + { + $part = array(); - if (!empty($item['type'])) { - switch ($item['type']) { - case 'or': - case 'and': - if (is_array($item['value'])) { - $arr = array(); - foreach ($item['value'] as $i) { - $a = $this->getWherePart($i); - foreach ($a as $left => $right) { - if (!empty($right)) { - $arr[$left] = $right; - } - } - } - $part[strtoupper($item['type'])] = $arr; - } - break; - case 'like': - $part[$item['field'] . '*'] = $item['value']; - break; - case 'equals': - case 'on': - $part[$item['field'] . '='] = $item['value']; - break; - case 'notEquals': - case 'notOn': - $part[$item['field'] . '!='] = $item['value']; - break; - case 'greaterThan': - case 'after': - $part[$item['field'] . '>'] = $item['value']; - break; - case 'lessThan': - case 'before': - $part[$item['field'] . '<'] = $item['value']; - break; - case 'greaterThanOrEquals': - $part[$item['field'] . '>='] = $item['value']; - break; - case 'lessThanOrEquals': - $part[$item['field'] . '<'] = $item['value']; - break; - case 'in': - $part[$item['field'] . '='] = $item['value']; - break; - case 'notIn': - $part[$item['field'] . '!='] = $item['value']; - break; - case 'isTrue': - $part[$item['field'] . '='] = true; - break; - case 'isFalse': - $part[$item['field'] . '='] = false; - break; - case 'today': - $part[$item['field'] . '='] = date('Y-m-d'); - break; - case 'past': - $part[$item['field'] . '<'] = date('Y-m-d'); - break; - case 'future': - $part[$item['field'] . '>'] = date('Y-m-d'); - break; - case 'currentMonth': - $dt = new \DateTime(); - $part['AND'] = array( - $item['field'] . '>=' => $dt->modify('first day of this month')->format('Y-m-d'), - $item['field'] . '<' => $dt->add(new \DateInterval('P1M'))->format('Y-m-d'), - ); - break; - case 'lastMonth': - $dt = new \DateTime(); - $part['AND'] = array( - $item['field'] . '>=' => $dt->modify('first day of last month')->format('Y-m-d'), - $item['field'] . '<' => $dt->add(new \DateInterval('P1M'))->format('Y-m-d'), - ); - break; - case 'currentQuarter': - $dt = new \DateTime(); - $quarter = ceil($dt->format('m') / 3); - $dt->modify('first day of January this year'); - $part['AND'] = array( - $item['field'] . '>=' => $dt->add(new \DateInterval('P'.(($quarter - 1) * 3).'M'))->format('Y-m-d'), - $item['field'] . '<' => $dt->add(new \DateInterval('P3M'))->format('Y-m-d'), - ); - break; - case 'lastQuarter': - $dt = new \DateTime(); - $quarter = ceil($dt->format('m') / 3); - $dt->modify('first day of January this year'); - $quarter--; - if ($quarter == 0) { - $quarter = 4; - $dt->sub('P1Y'); - } - $part['AND'] = array( - $item['field'] . '>=' => $dt->add(new \DateInterval('P'.(($quarter - 1) * 3).'M'))->format('Y-m-d'), - $item['field'] . '<' => $dt->add(new \DateInterval('P3M'))->format('Y-m-d'), - ); - break; - case 'currentYear': - $dt = new \DateTime(); - $part['AND'] = array( - $item['field'] . '>=' => $dt->modify('first day of January this year')->format('Y-m-d'), - $item['field'] . '<' => $dt->add(new \DateInterval('P1Y'))->format('Y-m-d'), - ); - break; - case 'lastYear': - $dt = new \DateTime(); - $part['AND'] = array( - $item['field'] . '>=' => $dt->modify('first day of January last year')->format('Y-m-d'), - $item['field'] . '<' => $dt->add(new \DateInterval('P1Y'))->format('Y-m-d'), - ); - break; - case 'between': - if (is_array($item['value'])) { - $part['AND'] = array( - $item['field'] . '>=' => $item['value'][0], - $item['field'] . '<=' => $item['value'][1], - ); - } - break; - } - } + if (!empty($item['type'])) { + switch ($item['type']) { + case 'or': + case 'and': + if (is_array($item['value'])) { + $arr = array(); + foreach ($item['value'] as $i) { + $a = $this->getWherePart($i); + foreach ($a as $left => $right) { + if (!empty($right)) { + $arr[$left] = $right; + } + } + } + $part[strtoupper($item['type'])] = $arr; + } + break; + case 'like': + $part[$item['field'] . '*'] = $item['value']; + break; + case 'equals': + case 'on': + $part[$item['field'] . '='] = $item['value']; + break; + case 'notEquals': + case 'notOn': + $part[$item['field'] . '!='] = $item['value']; + break; + case 'greaterThan': + case 'after': + $part[$item['field'] . '>'] = $item['value']; + break; + case 'lessThan': + case 'before': + $part[$item['field'] . '<'] = $item['value']; + break; + case 'greaterThanOrEquals': + $part[$item['field'] . '>='] = $item['value']; + break; + case 'lessThanOrEquals': + $part[$item['field'] . '<'] = $item['value']; + break; + case 'in': + $part[$item['field'] . '='] = $item['value']; + break; + case 'notIn': + $part[$item['field'] . '!='] = $item['value']; + break; + case 'isTrue': + $part[$item['field'] . '='] = true; + break; + case 'isFalse': + $part[$item['field'] . '='] = false; + break; + case 'today': + $part[$item['field'] . '='] = date('Y-m-d'); + break; + case 'past': + $part[$item['field'] . '<'] = date('Y-m-d'); + break; + case 'future': + $part[$item['field'] . '>'] = date('Y-m-d'); + break; + case 'currentMonth': + $dt = new \DateTime(); + $part['AND'] = array( + $item['field'] . '>=' => $dt->modify('first day of this month')->format('Y-m-d'), + $item['field'] . '<' => $dt->add(new \DateInterval('P1M'))->format('Y-m-d'), + ); + break; + case 'lastMonth': + $dt = new \DateTime(); + $part['AND'] = array( + $item['field'] . '>=' => $dt->modify('first day of last month')->format('Y-m-d'), + $item['field'] . '<' => $dt->add(new \DateInterval('P1M'))->format('Y-m-d'), + ); + break; + case 'currentQuarter': + $dt = new \DateTime(); + $quarter = ceil($dt->format('m') / 3); + $dt->modify('first day of January this year'); + $part['AND'] = array( + $item['field'] . '>=' => $dt->add(new \DateInterval('P'.(($quarter - 1) * 3).'M'))->format('Y-m-d'), + $item['field'] . '<' => $dt->add(new \DateInterval('P3M'))->format('Y-m-d'), + ); + break; + case 'lastQuarter': + $dt = new \DateTime(); + $quarter = ceil($dt->format('m') / 3); + $dt->modify('first day of January this year'); + $quarter--; + if ($quarter == 0) { + $quarter = 4; + $dt->sub('P1Y'); + } + $part['AND'] = array( + $item['field'] . '>=' => $dt->add(new \DateInterval('P'.(($quarter - 1) * 3).'M'))->format('Y-m-d'), + $item['field'] . '<' => $dt->add(new \DateInterval('P3M'))->format('Y-m-d'), + ); + break; + case 'currentYear': + $dt = new \DateTime(); + $part['AND'] = array( + $item['field'] . '>=' => $dt->modify('first day of January this year')->format('Y-m-d'), + $item['field'] . '<' => $dt->add(new \DateInterval('P1Y'))->format('Y-m-d'), + ); + break; + case 'lastYear': + $dt = new \DateTime(); + $part['AND'] = array( + $item['field'] . '>=' => $dt->modify('first day of January last year')->format('Y-m-d'), + $item['field'] . '<' => $dt->add(new \DateInterval('P1Y'))->format('Y-m-d'), + ); + break; + case 'between': + if (is_array($item['value'])) { + $part['AND'] = array( + $item['field'] . '>=' => $item['value'][0], + $item['field'] . '<=' => $item['value'][1], + ); + } + break; + } + } - return $part; - } + return $part; + } - protected function getBoolFilterWhere($filterName) - { - $method = 'getBoolFilterWhere' . ucfirst($filterName); - if (method_exists($this, $method)) { - return $this->$method(); - } - } + protected function getBoolFilterWhere($filterName) + { + $method = 'getBoolFilterWhere' . ucfirst($filterName); + if (method_exists($this, $method)) { + return $this->$method(); + } + } - protected function getBoolFilterWhereOnlyMy() - { - return array( - 'type' => 'equals', - 'field' => 'assignedUserId', - 'value' => $this->user->id, - ); - } + protected function getBoolFilterWhereOnlyMy() + { + return array( + 'type' => 'equals', + 'field' => 'assignedUserId', + 'value' => $this->user->id, + ); + } } diff --git a/application/Espo/Core/ServiceFactory.php b/application/Espo/Core/ServiceFactory.php index b55d69b22b..b23c2cce3f 100644 --- a/application/Espo/Core/ServiceFactory.php +++ b/application/Espo/Core/ServiceFactory.php @@ -28,127 +28,127 @@ use \Espo\Core\Utils\Util; class ServiceFactory { - private $container; + private $container; - protected $cacheFile = 'data/cache/application/services.php'; + protected $cacheFile = 'data/cache/application/services.php'; - /** + /** * @var array - path to Service files */ - protected $paths = array( - 'corePath' => 'application/Espo/Services', - 'modulePath' => 'application/Espo/Modules/{*}/Services', - 'customPath' => 'custom/Espo/Custom/Services', - ); + protected $paths = array( + 'corePath' => 'application/Espo/Services', + 'modulePath' => 'application/Espo/Modules/{*}/Services', + 'customPath' => 'custom/Espo/Custom/Services', + ); - protected $data; + protected $data; public function __construct(Container $container) { - $this->container = $container; + $this->container = $container; } - protected function init() - { - $config = $this->getContainer()->get('config'); + protected function init() + { + $config = $this->getContainer()->get('config'); - if (file_exists($this->cacheFile) && $config->get('useCache')) { - $this->data = $this->getFileManager()->getContents($this->cacheFile); - } else { - $this->data = $this->getClassNameHash($this->paths['corePath']); + if (file_exists($this->cacheFile) && $config->get('useCache')) { + $this->data = $this->getFileManager()->getContents($this->cacheFile); + } else { + $this->data = $this->getClassNameHash($this->paths['corePath']); - foreach ($this->getContainer()->get('metadata')->getModuleList() as $moduleName) { - $path = str_replace('{*}', $moduleName, $this->paths['modulePath']); - $this->data = array_merge($this->data, $this->getClassNameHash($path)); - } + foreach ($this->getContainer()->get('metadata')->getModuleList() as $moduleName) { + $path = str_replace('{*}', $moduleName, $this->paths['modulePath']); + $this->data = array_merge($this->data, $this->getClassNameHash($path)); + } - $this->data = array_merge($this->data, $this->getClassNameHash($this->paths['customPath'])); + $this->data = array_merge($this->data, $this->getClassNameHash($this->paths['customPath'])); - if ($config->get('useCache')) { - $result = $this->getFileManager()->putContentsPHP($this->cacheFile, $this->data); - if ($result == false) { - throw new \Espo\Core\Exceptions\Error(); - } - } - } - } + if ($config->get('useCache')) { + $result = $this->getFileManager()->putContentsPHP($this->cacheFile, $this->data); + if ($result == false) { + throw new \Espo\Core\Exceptions\Error(); + } + } + } + } - protected function getFileManager() - { - return $this->container->get('fileManager'); - } + protected function getFileManager() + { + return $this->container->get('fileManager'); + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - protected function getClassName($name) - { - $name = Util::normilizeClassName($name); + protected function getClassName($name) + { + $name = Util::normilizeClassName($name); - if (!isset($this->data)) { - $this->init(); - } + if (!isset($this->data)) { + $this->init(); + } - $name = ucfirst($name); - if (isset($this->data[$name])) { - return $this->data[$name]; - } + $name = ucfirst($name); + if (isset($this->data[$name])) { + return $this->data[$name]; + } return false; - } + } - public function checkExists($name) { - $className = $this->getClassName($name); - if (!empty($className)) { - return true; - } - } + public function checkExists($name) { + $className = $this->getClassName($name); + if (!empty($className)) { + return true; + } + } public function create($name) { - $className = $this->getClassName($name); - if (empty($className)) { - throw new Error(); - } - return $this->createByClassName($className); + $className = $this->getClassName($name); + if (empty($className)) { + throw new Error(); + } + return $this->createByClassName($className); } - protected function createByClassName($className) - { - if (class_exists($className)) { - $service = new $className(); - $dependencies = $service->getDependencyList(); - foreach ($dependencies as $name) { - $service->inject($name, $this->container->get($name)); - } - return $service; - } - throw new Error("Class '$className' does not exist"); - } + protected function createByClassName($className) + { + if (class_exists($className)) { + $service = new $className(); + $dependencies = $service->getDependencyList(); + foreach ($dependencies as $name) { + $service->inject($name, $this->container->get($name)); + } + return $service; + } + throw new Error("Class '$className' does not exist"); + } - // TODO delegate to another class - protected function getClassNameHash($dirs) - { - if (is_string($dirs)) { - $dirs = (array) $dirs; - } + // TODO delegate to another class + protected function getClassNameHash($dirs) + { + if (is_string($dirs)) { + $dirs = (array) $dirs; + } - $data = array(); + $data = array(); - foreach ($dirs as $dir) { - if (file_exists($dir)) { - $fileList = $this->getFileManager()->getFileList($dir, false, '\.php$', 'file'); - foreach ($fileList as $file) { - $filePath = Util::concatPath($dir, $file); - $className = Util::getClassName($filePath); - $fileName = $this->getFileManager()->getFileName($filePath); - $data[$fileName] = $className; - } - } - } - return $data; - } + foreach ($dirs as $dir) { + if (file_exists($dir)) { + $fileList = $this->getFileManager()->getFileList($dir, false, '\.php$', 'file'); + foreach ($fileList as $file) { + $filePath = Util::concatPath($dir, $file); + $className = Util::getClassName($filePath); + $fileName = $this->getFileManager()->getFileName($filePath); + $data[$fileName] = $className; + } + } + } + return $data; + } } diff --git a/application/Espo/Core/Services/Base.php b/application/Espo/Core/Services/Base.php index d28a8afb23..95f11034f2 100644 --- a/application/Espo/Core/Services/Base.php +++ b/application/Espo/Core/Services/Base.php @@ -26,51 +26,51 @@ use \Espo\Core\Interfaces\Injectable; abstract class Base implements Injectable { - protected $dependencies = array( - 'config', - 'entityManager', - 'user', - ); - - protected $injections = array(); - - public function inject($name, $object) - { - $this->injections[$name] = $object; - } - - public function __construct() - { - $this->init(); - } - - protected function init() - { - } - - protected function getInjection($name) - { - return $this->injections[$name]; - } - - public function getDependencyList() - { - return $this->dependencies; - } - - protected function getEntityManager() - { - return $this->getInjection('entityManager'); - } - - protected function getConfig() - { - return $this->getInjection('config'); - } + protected $dependencies = array( + 'config', + 'entityManager', + 'user', + ); + + protected $injections = array(); + + public function inject($name, $object) + { + $this->injections[$name] = $object; + } + + public function __construct() + { + $this->init(); + } + + protected function init() + { + } + + protected function getInjection($name) + { + return $this->injections[$name]; + } + + public function getDependencyList() + { + return $this->dependencies; + } + + protected function getEntityManager() + { + return $this->getInjection('entityManager'); + } + + protected function getConfig() + { + return $this->getInjection('config'); + } - protected function getUser() - { - return $this->getInjection('user'); - } + protected function getUser() + { + return $this->getInjection('user'); + } } diff --git a/application/Espo/Core/UpgradeManager.php b/application/Espo/Core/UpgradeManager.php index 5d42afe3d7..e6e62bdd18 100644 --- a/application/Espo/Core/UpgradeManager.php +++ b/application/Espo/Core/UpgradeManager.php @@ -26,14 +26,14 @@ use Espo\Core\Exceptions\Error; class UpgradeManager extends Upgrades\Base { - protected $name = 'Upgrade'; + protected $name = 'Upgrade'; - protected $params = array( - 'packagePath' => 'data/upload/upgrades', + protected $params = array( + 'packagePath' => 'data/upload/upgrades', - 'scriptNames' => array( - 'before' => 'BeforeUpgrade', - 'after' => 'AfterUpgrade', - ) - ); + 'scriptNames' => array( + 'before' => 'BeforeUpgrade', + 'after' => 'AfterUpgrade', + ) + ); } \ No newline at end of file diff --git a/application/Espo/Core/Upgrades/ActionManager.php b/application/Espo/Core/Upgrades/ActionManager.php index 44a0fc7b8a..7b176230b4 100644 --- a/application/Espo/Core/Upgrades/ActionManager.php +++ b/application/Espo/Core/Upgrades/ActionManager.php @@ -26,77 +26,77 @@ use Espo\Core\Exceptions\Error; class ActionManager { - private $managerName; + private $managerName; - private $container; + private $container; - private $objects; + private $objects; - protected $currentAction; + protected $currentAction; - protected $params; + protected $params; - public function __construct($managerName, $container, $params) - { - $this->managerName = $managerName; - $this->container = $container; + public function __construct($managerName, $container, $params) + { + $this->managerName = $managerName; + $this->container = $container; - $params['name'] = $managerName; - $this->params = $params; - } + $params['name'] = $managerName; + $this->params = $params; + } - protected function getManagerName() - { - return $this->managerName; - } + protected function getManagerName() + { + return $this->managerName; + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - public function setAction($action) - { - $this->currentAction = $action; - } + public function setAction($action) + { + $this->currentAction = $action; + } - public function getAction() - { - return $this->currentAction; - } + public function getAction() + { + return $this->currentAction; + } - public function getParams() - { - return $this->params; - } + public function getParams() + { + return $this->params; + } - public function run($data) - { - $object = $this->getObject(); + public function run($data) + { + $object = $this->getObject(); - return $object->run($data); - } + return $object->run($data); + } - public function getManifest() - { - return $this->getObject()->getManifest(); - } + public function getManifest() + { + return $this->getObject()->getManifest(); + } - protected function getObject() - { - $managerName = $this->getManagerName(); - $actionName = $this->getAction(); + protected function getObject() + { + $managerName = $this->getManagerName(); + $actionName = $this->getAction(); - if (!isset($this->objects[$managerName][$actionName])) { - $class = '\Espo\Core\Upgrades\Actions\\' . ucfirst($managerName) . '\\' . ucfirst($actionName); + if (!isset($this->objects[$managerName][$actionName])) { + $class = '\Espo\Core\Upgrades\Actions\\' . ucfirst($managerName) . '\\' . ucfirst($actionName); - if (!class_exists($class)) { - throw new Error('Could not find an action ['.ucfirst($actionName).'], class ['.$class.'].'); - } + if (!class_exists($class)) { + throw new Error('Could not find an action ['.ucfirst($actionName).'], class ['.$class.'].'); + } - $this->objects[$managerName][$actionName] = new $class($this->container, $this); - } + $this->objects[$managerName][$actionName] = new $class($this->container, $this); + } - return $this->objects[$managerName][$actionName]; - } + return $this->objects[$managerName][$actionName]; + } } \ No newline at end of file diff --git a/application/Espo/Core/Upgrades/Actions/Base.php b/application/Espo/Core/Upgrades/Actions/Base.php index fb270cf0b9..be12914e85 100644 --- a/application/Espo/Core/Upgrades/Actions/Base.php +++ b/application/Espo/Core/Upgrades/Actions/Base.php @@ -23,466 +23,466 @@ namespace Espo\Core\Upgrades\Actions; use Espo\Core\Utils\Util, - Espo\Core\Utils\Json, - Espo\Core\Exceptions\Error; + Espo\Core\Utils\Json, + Espo\Core\Exceptions\Error; abstract class Base { - private $container; + private $container; - private $actionManager; + private $actionManager; - private $zipUtil; + private $zipUtil; - private $fileManager; - - private $config; + private $fileManager; + + private $config; - private $entityManager; - - protected $data; - - protected $params = null; - - protected $processId = null; + private $entityManager; + + protected $data; + + protected $params = null; + + protected $processId = null; - protected $manifestName = 'manifest.json'; - - protected $packagePostfix = 'z'; - - /** - * Directory name of files in a package - */ - const FILES = 'files'; + protected $manifestName = 'manifest.json'; + + protected $packagePostfix = 'z'; + + /** + * Directory name of files in a package + */ + const FILES = 'files'; - /** - * Directory name of scripts in a package - */ - const SCRIPTS = 'scripts'; - - /** - * Package types - */ - protected $packageTypes = array( - 'upgrade' => 'upgrade', - 'extension' => 'extension', - ); - - /** - * Default package type - */ - protected $defaultPackageType = 'extension'; - - - public function __construct(\Espo\Core\Container $container, \Espo\Core\Upgrades\ActionManager $actionManager) - { - $this->container = $container; - $this->actionManager = $actionManager; - $this->params = $actionManager->getParams(); - - $this->zipUtil = new \Espo\Core\Utils\File\ZipArchive($container->get('fileManager')); - } - - public function __destruct() - { - $this->processId = null; - $this->data = null; - } - - protected function getContainer() - { - return $this->container; - } - - protected function getActionManager() - { - return $this->actionManager; - } - - protected function getParams($name = null) - { - if (isset($this->params[$name])) { - return $this->params[$name]; - } - - return $this->params; - } - - protected function getZipUtil() - { - return $this->zipUtil; - } - - protected function getFileManager() - { - if (!isset($this->fileManager)) { - $this->fileManager = $this->getContainer()->get('fileManager'); - } - return $this->fileManager; - } - - protected function getConfig() - { - if (!isset($this->config)) { - $this->config = $this->getContainer()->get('config'); - } - return $this->config; - } - - protected function getEntityManager() - { - if (!isset($this->entityManager)) { - $this->entityManager = $this->getContainer()->get('entityManager'); - } - return $this->entityManager; - } - - protected function throwErrorAndRemovePackage($errorMessage = '') - { - $this->deletePackageFiles(); - $this->deletePackageArchive(); - throw new Error($errorMessage); - } - - abstract public function run($data); - - protected function createProcessId() - { - if (isset($this->processId)) { - throw new Error('Another installation process is currently running.'); - } - - $this->processId = uniqid(); - - return $this->processId; - } - - protected function getProcessId() - { - if (!isset($this->processId)) { - throw new Error('Installation ID was not specified.'); - } - - return $this->processId; - } - - protected function setProcessId($processId) - { - $this->processId = $processId; - } - - /** - * Check if version of upgrade/extension is acceptable to current version of EspoCRM - * - * @param string $version - * @return boolean - */ - protected function isAcceptable() - { - $res = $this->checkPackageType(); - $res &= $this->checkVersions(); - - return (bool) $res; - } - - protected function checkVersions() - { - $manifest = $this->getManifest(); - - /** check acceptable versions */ - $version = $manifest['acceptableVersions']; - if (empty($version)) { - return true; - } - - $currentVersion = $this->getConfig()->get('version'); - - if (is_string($version)) { - $version = (array) $version; - } - - foreach ($version as $strVersion) { - - $strVersion = trim($strVersion); - - if ($strVersion == $currentVersion) { - return true; - } - - $strVersion = str_replace('\\', '', $strVersion); - $strVersion = preg_quote($strVersion); - $strVersion = str_replace('\\*', '+', $strVersion); - - if (preg_match('/^'.$strVersion.'/', $currentVersion)) { - return true; - } - } - - $this->throwErrorAndRemovePackage('Your EspoCRM version doesn\'t match for this installation package.'); - } - - protected function checkPackageType() - { - $manifest = $this->getManifest(); - - /** check package type */ - $type = strtolower( $this->getParams('name') ); - $manifestType = isset($manifest['type']) ? strtolower($manifest['type']) : $this->defaultPackageType; - - if (!in_array($manifestType, $this->packageTypes)) { - $this->throwErrorAndRemovePackage('Unknown package type.'); - } - - if ($type != $manifestType) { - $this->throwErrorAndRemovePackage('Wrong package type. You cannot install '.$manifestType.' package via '.ucfirst($type).' Manager.'); - } - - return true; - } - - /** - * Run scripts by type - * @param string $type Ex. "before", "after" - * @return void - */ - protected function runScript($type) - { - $packagePath = $this->getPackagePath(); - $scriptNames = $this->getParams('scriptNames'); - - $scriptName = $scriptNames[$type]; - if (!isset($scriptName)) { - return; - } - - $beforeInstallScript = Util::concatPath( array($packagePath, self::SCRIPTS, $scriptName) ) . '.php'; - - if (file_exists($beforeInstallScript)) { - require_once($beforeInstallScript); - $script = new $scriptName(); - - try { - $script->run($this->getContainer()); - } catch (\Exception $e) { - $this->throwErrorAndRemovePackage($e->getMessage()); - } - } - } - - /** - * Get package path - * - * @param string $processId - * @return string - */ - protected function getPath($name = 'packagePath', $isPackage = false) - { - $postfix = $isPackage ? $this->packagePostfix : ''; - - $processId = $this->getProcessId(); - $path = Util::concatPath($this->getParams($name), $processId); - - return $path . $postfix; - } - - protected function getPackagePath($isPackage = false) - { - return $this->getPath('packagePath', $isPackage); - } - - /** - * Get a list of files defined in manifest.json - * - * @return [type] [description] - */ - protected function getDeleteFileList() - { - $manifest = $this->getManifest(); - - if (!empty($manifest['delete'])) { - return $manifest['delete']; - } - - return array(); - } - - /** - * Delete files defined in a manifest - * - * @return boolen - */ - protected function deleteFiles() - { - $deleteFileList = $this->getDeleteFileList(); - - if (!empty($deleteFileList)) { - return $this->getFileManager()->remove($deleteFileList); - } - - return true; - } - - protected function getCopyFileList() - { - if (!isset($this->data['fileList'])) { - $packagePath = $this->getPackagePath(); - $filesPath = Util::concatPath($packagePath, self::FILES); - - $this->data['fileList'] = $this->getFileManager()->getFileList($filesPath, true, '', 'all', true); - } - - return $this->data['fileList']; - } - - protected function copy($sourcePath, $destPath, $recursively = false, array $fileList = null, $copyOnlyFiles = false) - { - try { - $res = $this->getFileManager()->copy($sourcePath, $destPath, $recursively, $fileList, $copyOnlyFiles); - } catch (\Exception $e) { - $this->throwErrorAndRemovePackage($e->getMessage()); - } - - return $res; - } - - /** - * Copy files from upgrade/extension package - * - * @param string $processId - * @return boolean - */ - protected function copyFiles() - { - $packagePath = $this->getPackagePath(); - $filesPath = Util::concatPath($packagePath, self::FILES); - - return $this->copy($filesPath, '', true); - } - - public function getManifest() - { - if (!isset($this->data['manifest'])) { - $packagePath = $this->getPackagePath(); - - $manifestPath = Util::concatPath($packagePath, $this->manifestName); - if (!file_exists($manifestPath)) { - $this->throwErrorAndRemovePackage('It\'s not an Installation package.'); - } - - $manifestJson = $this->getFileManager()->getContents($manifestPath); - $this->data['manifest'] = Json::decode($manifestJson, true); - - if (!$this->data['manifest']) { - $this->throwErrorAndRemovePackage('Syntax error in manifest.json.'); - } - - if (!$this->checkManifest($this->data['manifest'])) { - $this->throwErrorAndRemovePackage('Unsupported package.'); - } - } - - return $this->data['manifest']; - } - - /** - * Check if the manifest is correct - * - * @param array $manifest - * @return boolean - */ - protected function checkManifest(array $manifest) - { - $requiredFields = array( - 'name', - 'version', - ); - - foreach ($requiredFields as $fieldName) { - if (empty($manifest[$fieldName])) { - return false; - } - } - - return true; - } - - /** - * Unzip a package archieve - * - * @return void - */ - protected function unzipArchive($packagePath = null) - { - $packagePath = isset($packagePath) ? $packagePath : $this->getPackagePath(); - $packageArchivePath = $this->getPackagePath(true); - - if (!file_exists($packageArchivePath)) { - throw new Error('Package Archive doesn\'t exist.'); - } - - $res = $this->getZipUtil()->unzip($packageArchivePath, $packagePath); - if ($res === false) { - throw new Error('Unnable to unzip the file - '.$packagePath.'.'); - } - } - - /** - * Delete temporary package files - * - * @return boolean - */ - protected function deletePackageFiles() - { - $packagePath = $this->getPackagePath(); - $res = $this->getFileManager()->removeInDir($packagePath, true); - - return $res; - } - - /** - * Delete temporary package archive - * - * @return boolean - */ - protected function deletePackageArchive() - { - $packageArchive = $this->getPackagePath(true); - $res = $this->getFileManager()->removeFile($packageArchive); - - return $res; - } - - protected function systemRebuild() - { - return $this->getContainer()->get('dataManager')->rebuild(); - } - - /** - * Execute an action. For ex., execute uninstall action in install - * - * @param [type] $actionName [description] - * @param [type] $data [description] - * @return [type] [description] - */ - protected function executeAction($actionName, $data) - { - $currentAction = $this->getActionManager()->getAction(); - - $this->getActionManager()->setAction($actionName); - $this->getActionManager()->run($data); - - $this->getActionManager()->setAction($currentAction); - } - - protected function beforeRunAction() - { - - } - - protected function afterRunAction() - { - - } + /** + * Directory name of scripts in a package + */ + const SCRIPTS = 'scripts'; + + /** + * Package types + */ + protected $packageTypes = array( + 'upgrade' => 'upgrade', + 'extension' => 'extension', + ); + + /** + * Default package type + */ + protected $defaultPackageType = 'extension'; + + + public function __construct(\Espo\Core\Container $container, \Espo\Core\Upgrades\ActionManager $actionManager) + { + $this->container = $container; + $this->actionManager = $actionManager; + $this->params = $actionManager->getParams(); + + $this->zipUtil = new \Espo\Core\Utils\File\ZipArchive($container->get('fileManager')); + } + + public function __destruct() + { + $this->processId = null; + $this->data = null; + } + + protected function getContainer() + { + return $this->container; + } + + protected function getActionManager() + { + return $this->actionManager; + } + + protected function getParams($name = null) + { + if (isset($this->params[$name])) { + return $this->params[$name]; + } + + return $this->params; + } + + protected function getZipUtil() + { + return $this->zipUtil; + } + + protected function getFileManager() + { + if (!isset($this->fileManager)) { + $this->fileManager = $this->getContainer()->get('fileManager'); + } + return $this->fileManager; + } + + protected function getConfig() + { + if (!isset($this->config)) { + $this->config = $this->getContainer()->get('config'); + } + return $this->config; + } + + protected function getEntityManager() + { + if (!isset($this->entityManager)) { + $this->entityManager = $this->getContainer()->get('entityManager'); + } + return $this->entityManager; + } + + protected function throwErrorAndRemovePackage($errorMessage = '') + { + $this->deletePackageFiles(); + $this->deletePackageArchive(); + throw new Error($errorMessage); + } + + abstract public function run($data); + + protected function createProcessId() + { + if (isset($this->processId)) { + throw new Error('Another installation process is currently running.'); + } + + $this->processId = uniqid(); + + return $this->processId; + } + + protected function getProcessId() + { + if (!isset($this->processId)) { + throw new Error('Installation ID was not specified.'); + } + + return $this->processId; + } + + protected function setProcessId($processId) + { + $this->processId = $processId; + } + + /** + * Check if version of upgrade/extension is acceptable to current version of EspoCRM + * + * @param string $version + * @return boolean + */ + protected function isAcceptable() + { + $res = $this->checkPackageType(); + $res &= $this->checkVersions(); + + return (bool) $res; + } + + protected function checkVersions() + { + $manifest = $this->getManifest(); + + /** check acceptable versions */ + $version = $manifest['acceptableVersions']; + if (empty($version)) { + return true; + } + + $currentVersion = $this->getConfig()->get('version'); + + if (is_string($version)) { + $version = (array) $version; + } + + foreach ($version as $strVersion) { + + $strVersion = trim($strVersion); + + if ($strVersion == $currentVersion) { + return true; + } + + $strVersion = str_replace('\\', '', $strVersion); + $strVersion = preg_quote($strVersion); + $strVersion = str_replace('\\*', '+', $strVersion); + + if (preg_match('/^'.$strVersion.'/', $currentVersion)) { + return true; + } + } + + $this->throwErrorAndRemovePackage('Your EspoCRM version doesn\'t match for this installation package.'); + } + + protected function checkPackageType() + { + $manifest = $this->getManifest(); + + /** check package type */ + $type = strtolower( $this->getParams('name') ); + $manifestType = isset($manifest['type']) ? strtolower($manifest['type']) : $this->defaultPackageType; + + if (!in_array($manifestType, $this->packageTypes)) { + $this->throwErrorAndRemovePackage('Unknown package type.'); + } + + if ($type != $manifestType) { + $this->throwErrorAndRemovePackage('Wrong package type. You cannot install '.$manifestType.' package via '.ucfirst($type).' Manager.'); + } + + return true; + } + + /** + * Run scripts by type + * @param string $type Ex. "before", "after" + * @return void + */ + protected function runScript($type) + { + $packagePath = $this->getPackagePath(); + $scriptNames = $this->getParams('scriptNames'); + + $scriptName = $scriptNames[$type]; + if (!isset($scriptName)) { + return; + } + + $beforeInstallScript = Util::concatPath( array($packagePath, self::SCRIPTS, $scriptName) ) . '.php'; + + if (file_exists($beforeInstallScript)) { + require_once($beforeInstallScript); + $script = new $scriptName(); + + try { + $script->run($this->getContainer()); + } catch (\Exception $e) { + $this->throwErrorAndRemovePackage($e->getMessage()); + } + } + } + + /** + * Get package path + * + * @param string $processId + * @return string + */ + protected function getPath($name = 'packagePath', $isPackage = false) + { + $postfix = $isPackage ? $this->packagePostfix : ''; + + $processId = $this->getProcessId(); + $path = Util::concatPath($this->getParams($name), $processId); + + return $path . $postfix; + } + + protected function getPackagePath($isPackage = false) + { + return $this->getPath('packagePath', $isPackage); + } + + /** + * Get a list of files defined in manifest.json + * + * @return [type] [description] + */ + protected function getDeleteFileList() + { + $manifest = $this->getManifest(); + + if (!empty($manifest['delete'])) { + return $manifest['delete']; + } + + return array(); + } + + /** + * Delete files defined in a manifest + * + * @return boolen + */ + protected function deleteFiles() + { + $deleteFileList = $this->getDeleteFileList(); + + if (!empty($deleteFileList)) { + return $this->getFileManager()->remove($deleteFileList); + } + + return true; + } + + protected function getCopyFileList() + { + if (!isset($this->data['fileList'])) { + $packagePath = $this->getPackagePath(); + $filesPath = Util::concatPath($packagePath, self::FILES); + + $this->data['fileList'] = $this->getFileManager()->getFileList($filesPath, true, '', 'all', true); + } + + return $this->data['fileList']; + } + + protected function copy($sourcePath, $destPath, $recursively = false, array $fileList = null, $copyOnlyFiles = false) + { + try { + $res = $this->getFileManager()->copy($sourcePath, $destPath, $recursively, $fileList, $copyOnlyFiles); + } catch (\Exception $e) { + $this->throwErrorAndRemovePackage($e->getMessage()); + } + + return $res; + } + + /** + * Copy files from upgrade/extension package + * + * @param string $processId + * @return boolean + */ + protected function copyFiles() + { + $packagePath = $this->getPackagePath(); + $filesPath = Util::concatPath($packagePath, self::FILES); + + return $this->copy($filesPath, '', true); + } + + public function getManifest() + { + if (!isset($this->data['manifest'])) { + $packagePath = $this->getPackagePath(); + + $manifestPath = Util::concatPath($packagePath, $this->manifestName); + if (!file_exists($manifestPath)) { + $this->throwErrorAndRemovePackage('It\'s not an Installation package.'); + } + + $manifestJson = $this->getFileManager()->getContents($manifestPath); + $this->data['manifest'] = Json::decode($manifestJson, true); + + if (!$this->data['manifest']) { + $this->throwErrorAndRemovePackage('Syntax error in manifest.json.'); + } + + if (!$this->checkManifest($this->data['manifest'])) { + $this->throwErrorAndRemovePackage('Unsupported package.'); + } + } + + return $this->data['manifest']; + } + + /** + * Check if the manifest is correct + * + * @param array $manifest + * @return boolean + */ + protected function checkManifest(array $manifest) + { + $requiredFields = array( + 'name', + 'version', + ); + + foreach ($requiredFields as $fieldName) { + if (empty($manifest[$fieldName])) { + return false; + } + } + + return true; + } + + /** + * Unzip a package archieve + * + * @return void + */ + protected function unzipArchive($packagePath = null) + { + $packagePath = isset($packagePath) ? $packagePath : $this->getPackagePath(); + $packageArchivePath = $this->getPackagePath(true); + + if (!file_exists($packageArchivePath)) { + throw new Error('Package Archive doesn\'t exist.'); + } + + $res = $this->getZipUtil()->unzip($packageArchivePath, $packagePath); + if ($res === false) { + throw new Error('Unnable to unzip the file - '.$packagePath.'.'); + } + } + + /** + * Delete temporary package files + * + * @return boolean + */ + protected function deletePackageFiles() + { + $packagePath = $this->getPackagePath(); + $res = $this->getFileManager()->removeInDir($packagePath, true); + + return $res; + } + + /** + * Delete temporary package archive + * + * @return boolean + */ + protected function deletePackageArchive() + { + $packageArchive = $this->getPackagePath(true); + $res = $this->getFileManager()->removeFile($packageArchive); + + return $res; + } + + protected function systemRebuild() + { + return $this->getContainer()->get('dataManager')->rebuild(); + } + + /** + * Execute an action. For ex., execute uninstall action in install + * + * @param [type] $actionName [description] + * @param [type] $data [description] + * @return [type] [description] + */ + protected function executeAction($actionName, $data) + { + $currentAction = $this->getActionManager()->getAction(); + + $this->getActionManager()->setAction($actionName); + $this->getActionManager()->run($data); + + $this->getActionManager()->setAction($currentAction); + } + + protected function beforeRunAction() + { + + } + + protected function afterRunAction() + { + + } } diff --git a/application/Espo/Core/Upgrades/Actions/Base/Delete.php b/application/Espo/Core/Upgrades/Actions/Base/Delete.php index 210dceb73d..445f6b7209 100644 --- a/application/Espo/Core/Upgrades/Actions/Base/Delete.php +++ b/application/Espo/Core/Upgrades/Actions/Base/Delete.php @@ -24,32 +24,32 @@ namespace Espo\Core\Upgrades\Actions\Base; class Delete extends \Espo\Core\Upgrades\Actions\Base { - public function run($processId) - { - $GLOBALS['log']->debug('Delete package process ['.$processId.']: start run.'); + public function run($processId) + { + $GLOBALS['log']->debug('Delete package process ['.$processId.']: start run.'); - if (empty($processId)) { - throw new Error('Delete package package ID was not specified.'); - } + if (empty($processId)) { + throw new Error('Delete package package ID was not specified.'); + } - $this->setProcessId($processId); + $this->setProcessId($processId); - $this->beforeRunAction(); + $this->beforeRunAction(); - /* delete a package */ - $this->deletePackage(); + /* delete a package */ + $this->deletePackage(); - $this->afterRunAction(); + $this->afterRunAction(); - $GLOBALS['log']->debug('Delete package process ['.$processId.']: end run.'); - } + $GLOBALS['log']->debug('Delete package process ['.$processId.']: end run.'); + } - protected function deletePackage() - { - $packageArchivePath = $this->getPackagePath(true); - $res = $this->getFileManager()->removeFile($packageArchivePath); + protected function deletePackage() + { + $packageArchivePath = $this->getPackagePath(true); + $res = $this->getFileManager()->removeFile($packageArchivePath); - return $res; - } + return $res; + } } \ No newline at end of file diff --git a/application/Espo/Core/Upgrades/Actions/Base/Install.php b/application/Espo/Core/Upgrades/Actions/Base/Install.php index 4eb235165d..c1e0c83080 100644 --- a/application/Espo/Core/Upgrades/Actions/Base/Install.php +++ b/application/Espo/Core/Upgrades/Actions/Base/Install.php @@ -26,87 +26,87 @@ use Espo\Core\Exceptions\Error; class Install extends \Espo\Core\Upgrades\Actions\Base { - /** - * Is copied extension files to Espo - * - * @var [type] - */ - protected $isCopied = null; + /** + * Is copied extension files to Espo + * + * @var [type] + */ + protected $isCopied = null; - /** - * Main installation process - * - * @param string $processId Upgrade/Extension ID, gotten in upload stage - * @return bool - */ - public function run($processId) - { - $GLOBALS['log']->debug('Installation process ['.$processId.']: start run.'); + /** + * Main installation process + * + * @param string $processId Upgrade/Extension ID, gotten in upload stage + * @return bool + */ + public function run($processId) + { + $GLOBALS['log']->debug('Installation process ['.$processId.']: start run.'); - if (empty($processId)) { - throw new Error('Installation package ID was not specified.'); - } + if (empty($processId)) { + throw new Error('Installation package ID was not specified.'); + } - $this->setProcessId($processId); + $this->setProcessId($processId); - $this->isCopied = false; + $this->isCopied = false; - /** check if an archive is unzipped, if no then unzip */ - $packagePath = $this->getPackagePath(); - if (!file_exists($packagePath)) { - $this->unzipArchive(); - $this->isAcceptable(); - } + /** check if an archive is unzipped, if no then unzip */ + $packagePath = $this->getPackagePath(); + if (!file_exists($packagePath)) { + $this->unzipArchive(); + $this->isAcceptable(); + } - $this->beforeRunAction(); + $this->beforeRunAction(); - /* run before install script */ - $this->runScript('before'); + /* run before install script */ + $this->runScript('before'); - /* remove files defined in a manifest */ - if (!$this->deleteFiles()) { - $this->throwErrorAndRemovePackage('Permission denied to delete files.'); - } + /* remove files defined in a manifest */ + if (!$this->deleteFiles()) { + $this->throwErrorAndRemovePackage('Permission denied to delete files.'); + } - /* copy files from directory "Files" to EspoCRM files */ - if (!$this->copyFiles()) { - $this->throwErrorAndRemovePackage('Cannot copy files.'); - } - $this->isCopied = true; + /* copy files from directory "Files" to EspoCRM files */ + if (!$this->copyFiles()) { + $this->throwErrorAndRemovePackage('Cannot copy files.'); + } + $this->isCopied = true; - if (!$this->systemRebuild()) { - $this->throwErrorAndRemovePackage('Error occurred while EspoCRM rebuild.'); - } + if (!$this->systemRebuild()) { + $this->throwErrorAndRemovePackage('Error occurred while EspoCRM rebuild.'); + } - /* run before install script */ - $this->runScript('after'); + /* run before install script */ + $this->runScript('after'); - $this->afterRunAction(); + $this->afterRunAction(); - /* delete unziped files */ - $this->deletePackageFiles(); + /* delete unziped files */ + $this->deletePackageFiles(); - $GLOBALS['log']->debug('Installation process ['.$processId.']: end run.'); - } + $GLOBALS['log']->debug('Installation process ['.$processId.']: end run.'); + } - protected function restoreFiles() - { - $backupPath = $this->getPath('backupPath'); + protected function restoreFiles() + { + $backupPath = $this->getPath('backupPath'); - $res = true; - if ($this->isCopied) { - $res &= $this->copy(array($backupPath, self::FILES), '', true); - $GLOBALS['log']->info('Restore: copy back'); - } + $res = true; + if ($this->isCopied) { + $res &= $this->copy(array($backupPath, self::FILES), '', true); + $GLOBALS['log']->info('Restore: copy back'); + } - $res &= $this->getFileManager()->removeInDir($backupPath, true); + $res &= $this->getFileManager()->removeInDir($backupPath, true); - return $res; - } + return $res; + } - protected function throwErrorAndRemovePackage($errorMessage = '') - { - $this->restoreFiles(); - parent::throwErrorAndRemovePackage($errorMessage); - } + protected function throwErrorAndRemovePackage($errorMessage = '') + { + $this->restoreFiles(); + parent::throwErrorAndRemovePackage($errorMessage); + } } diff --git a/application/Espo/Core/Upgrades/Actions/Base/Uninstall.php b/application/Espo/Core/Upgrades/Actions/Base/Uninstall.php index 68528b50bd..717a98ca50 100644 --- a/application/Espo/Core/Upgrades/Actions/Base/Uninstall.php +++ b/application/Espo/Core/Upgrades/Actions/Base/Uninstall.php @@ -23,110 +23,110 @@ namespace Espo\Core\Upgrades\Actions\Base; use Espo\Core\Exceptions\Error, - Espo\Core\Utils\Util; + Espo\Core\Utils\Util; class Uninstall extends \Espo\Core\Upgrades\Actions\Base { - public function run($processId) - { - $GLOBALS['log']->debug('Uninstallation process ['.$processId.']: start run.'); + public function run($processId) + { + $GLOBALS['log']->debug('Uninstallation process ['.$processId.']: start run.'); - if (empty($processId)) { - throw new Error('Uninstallation package ID was not specified.'); - } + if (empty($processId)) { + throw new Error('Uninstallation package ID was not specified.'); + } - $this->setProcessId($processId); + $this->setProcessId($processId); - $this->beforeRunAction(); + $this->beforeRunAction(); - /* run before install script */ - $this->runScript('beforeUninstall'); + /* run before install script */ + $this->runScript('beforeUninstall'); - $backupPath = $this->getPath('backupPath'); - if (file_exists($backupPath)) { + $backupPath = $this->getPath('backupPath'); + if (file_exists($backupPath)) { - /* remove extension files, saved in fileList */ - if (!$this->deleteFiles()) { - throw new Error('Permission denied to delete files.'); - } + /* remove extension files, saved in fileList */ + if (!$this->deleteFiles()) { + throw new Error('Permission denied to delete files.'); + } - /* copy core files */ - if (!$this->copyFiles()) { - throw new Error('Cannot copy files.'); - } - } + /* copy core files */ + if (!$this->copyFiles()) { + throw new Error('Cannot copy files.'); + } + } - if (!$this->systemRebuild()) { - throw new Error('Error occurred while EspoCRM rebuild.'); - } + if (!$this->systemRebuild()) { + throw new Error('Error occurred while EspoCRM rebuild.'); + } - /* run before install script */ - $this->runScript('afterUninstall'); + /* run before install script */ + $this->runScript('afterUninstall'); - $this->afterRunAction(); + $this->afterRunAction(); - /* delete backup files */ - $this->deletePackageFiles(); + /* delete backup files */ + $this->deletePackageFiles(); - $GLOBALS['log']->debug('Uninstallation process ['.$processId.']: end run.'); - } + $GLOBALS['log']->debug('Uninstallation process ['.$processId.']: end run.'); + } - protected function getDeleteFileList() - { - $extensionEntity = $this->getExtensionEntity(); - return $extensionEntity->get('fileList'); - } + protected function getDeleteFileList() + { + $extensionEntity = $this->getExtensionEntity(); + return $extensionEntity->get('fileList'); + } - protected function restoreFiles() - { - $packagePath = $this->getPath('packagePath'); - $filesPath = Util::concatPath($packagePath, self::FILES); + protected function restoreFiles() + { + $packagePath = $this->getPath('packagePath'); + $filesPath = Util::concatPath($packagePath, self::FILES); - if (!file_exists($filesPath)) { - $this->unzipArchive($packagePath); - } + if (!file_exists($filesPath)) { + $this->unzipArchive($packagePath); + } - $res = $this->copy($filesPath, '', true); - $res &= $this->getFileManager()->removeInDir($packagePath, true); + $res = $this->copy($filesPath, '', true); + $res &= $this->getFileManager()->removeInDir($packagePath, true); - return $res; - } + return $res; + } - protected function copyFiles() - { - $backupPath = $this->getPath('backupPath'); - $res = $this->copy(array($backupPath, self::FILES), '', true); + protected function copyFiles() + { + $backupPath = $this->getPath('backupPath'); + $res = $this->copy(array($backupPath, self::FILES), '', true); - return $res; - } + return $res; + } - /** - * Get backup path - * - * @param string $processId - * @return string - */ - protected function getPackagePath($isPackage = false) - { - if ($isPackage) { - return $this->getPath('packagePath', $isPackage); - } + /** + * Get backup path + * + * @param string $processId + * @return string + */ + protected function getPackagePath($isPackage = false) + { + if ($isPackage) { + return $this->getPath('packagePath', $isPackage); + } - return $this->getPath('backupPath'); - } + return $this->getPath('backupPath'); + } - protected function deletePackageFiles() - { - $backupPath = $this->getPath('backupPath'); - $res = $this->getFileManager()->removeInDir($backupPath, true); + protected function deletePackageFiles() + { + $backupPath = $this->getPath('backupPath'); + $res = $this->getFileManager()->removeInDir($backupPath, true); - return $res; - } + return $res; + } - protected function throwErrorAndRemovePackage($errorMessage = '') - { - $this->restoreFiles(); - throw new Error($errorMessage); - } + protected function throwErrorAndRemovePackage($errorMessage = '') + { + $this->restoreFiles(); + throw new Error($errorMessage); + } } diff --git a/application/Espo/Core/Upgrades/Actions/Base/Upload.php b/application/Espo/Core/Upgrades/Actions/Base/Upload.php index aff8d61a84..9a4d7bfd3a 100644 --- a/application/Espo/Core/Upgrades/Actions/Base/Upload.php +++ b/application/Espo/Core/Upgrades/Actions/Base/Upload.php @@ -26,37 +26,37 @@ use Espo\Core\Exceptions\Error; class Upload extends \Espo\Core\Upgrades\Actions\Base { - /** - * Upload an upgrade/extension package - * - * @param [type] $contents - * @return string ID of upgrade/extension process - */ - public function run($data) - { - $processId = $this->createProcessId(); + /** + * Upload an upgrade/extension package + * + * @param [type] $contents + * @return string ID of upgrade/extension process + */ + public function run($data) + { + $processId = $this->createProcessId(); - $GLOBALS['log']->debug('Installation process ['.$processId.']: start upload the package.'); + $GLOBALS['log']->debug('Installation process ['.$processId.']: start upload the package.'); - $packagePath = $this->getPackagePath(); - $packageArchivePath = $this->getPackagePath(true); + $packagePath = $this->getPackagePath(); + $packageArchivePath = $this->getPackagePath(true); - if (!empty($data)) { - list($prefix, $contents) = explode(',', $data); - $contents = base64_decode($contents); - } + if (!empty($data)) { + list($prefix, $contents) = explode(',', $data); + $contents = base64_decode($contents); + } - $res = $this->getFileManager()->putContents($packageArchivePath, $contents); - if ($res === false) { - throw new Error('Could not upload the package.'); - } + $res = $this->getFileManager()->putContents($packageArchivePath, $contents); + if ($res === false) { + throw new Error('Could not upload the package.'); + } - $this->unzipArchive(); + $this->unzipArchive(); - $this->isAcceptable(); + $this->isAcceptable(); - $GLOBALS['log']->debug('Installation process ['.$processId.']: end upload the package.'); + $GLOBALS['log']->debug('Installation process ['.$processId.']: end upload the package.'); - return $processId; - } + return $processId; + } } \ No newline at end of file diff --git a/application/Espo/Core/Upgrades/Actions/Extension/Delete.php b/application/Espo/Core/Upgrades/Actions/Extension/Delete.php index 4edc165261..cc8ad25a32 100644 --- a/application/Espo/Core/Upgrades/Actions/Extension/Delete.php +++ b/application/Espo/Core/Upgrades/Actions/Extension/Delete.php @@ -26,44 +26,44 @@ use Espo\Core\Exceptions\Error; class Delete extends \Espo\Core\Upgrades\Actions\Base\Delete { - protected $extensionEntity; + protected $extensionEntity; - /** - * Get entity of this extension - * - * @return \Espo\Entities\Extension - */ - protected function getExtensionEntity() - { - return $this->extensionEntity; - } + /** + * Get entity of this extension + * + * @return \Espo\Entities\Extension + */ + protected function getExtensionEntity() + { + return $this->extensionEntity; + } - /** - * Set Extension Entity - * - * @param \Espo\Entities\Extension $extensionEntity - */ - protected function setExtensionEntity(\Espo\Entities\Extension $extensionEntity) - { - $this->extensionEntity = $extensionEntity; - } + /** + * Set Extension Entity + * + * @param \Espo\Entities\Extension $extensionEntity + */ + protected function setExtensionEntity(\Espo\Entities\Extension $extensionEntity) + { + $this->extensionEntity = $extensionEntity; + } - protected function beforeRunAction() - { - $processId = $this->getProcessId(); + protected function beforeRunAction() + { + $processId = $this->getProcessId(); - /** get extension entity */ - $extensionEntity = $this->getEntityManager()->getEntity('Extension', $processId); - if (!isset($extensionEntity)) { - throw new Error('Extension Entity not found.'); - } - $this->setExtensionEntity($extensionEntity); - } + /** get extension entity */ + $extensionEntity = $this->getEntityManager()->getEntity('Extension', $processId); + if (!isset($extensionEntity)) { + throw new Error('Extension Entity not found.'); + } + $this->setExtensionEntity($extensionEntity); + } - protected function afterRunAction() - { - /** Delete extension entity */ - $extensionEntity = $this->getExtensionEntity(); - $this->getEntityManager()->removeEntity($extensionEntity); - } + protected function afterRunAction() + { + /** Delete extension entity */ + $extensionEntity = $this->getExtensionEntity(); + $this->getEntityManager()->removeEntity($extensionEntity); + } } \ No newline at end of file diff --git a/application/Espo/Core/Upgrades/Actions/Extension/Install.php b/application/Espo/Core/Upgrades/Actions/Extension/Install.php index b5425c41b3..0221a7b7f0 100644 --- a/application/Espo/Core/Upgrades/Actions/Extension/Install.php +++ b/application/Espo/Core/Upgrades/Actions/Extension/Install.php @@ -23,205 +23,205 @@ namespace Espo\Core\Upgrades\Actions\Extension; use Espo\Core\Exceptions\Error, - Espo\Core\ExtensionManager; + Espo\Core\ExtensionManager; class Install extends \Espo\Core\Upgrades\Actions\Base\Install { - protected $extensionEntity = null; + protected $extensionEntity = null; - protected function beforeRunAction() - { - $this->findExtension(); - if (!$this->isNew()) { - $this->compareVersion(); - $this->uninstallExtension(); - $this->deleteExtension(); - } + protected function beforeRunAction() + { + $this->findExtension(); + if (!$this->isNew()) { + $this->compareVersion(); + $this->uninstallExtension(); + $this->deleteExtension(); + } - $this->copyExistingFiles(); - } + $this->copyExistingFiles(); + } - protected function afterRunAction() - { - $this->storeExtension(); - } + protected function afterRunAction() + { + $this->storeExtension(); + } - /** - * Copy Existing files to backup directory - * - * @return bool - */ - protected function copyExistingFiles() - { - $fileList = $this->getCopyFileList(); - $backupPath = $this->getPath('backupPath'); + /** + * Copy Existing files to backup directory + * + * @return bool + */ + protected function copyExistingFiles() + { + $fileList = $this->getCopyFileList(); + $backupPath = $this->getPath('backupPath'); - $res = $this->copy('', array($backupPath, self::FILES), false, $fileList); + $res = $this->copy('', array($backupPath, self::FILES), false, $fileList); - /** copy scripts files */ - $packagePath = $this->getPackagePath(); - $res &= $this->copy(array($packagePath, self::SCRIPTS), array($backupPath, self::SCRIPTS), true); + /** copy scripts files */ + $packagePath = $this->getPackagePath(); + $res &= $this->copy(array($packagePath, self::SCRIPTS), array($backupPath, self::SCRIPTS), true); - return $res; - } + return $res; + } - protected function restoreFiles() - { - $res = true; - if ($this->isCopied) { - $extensionFileList = $this->getCopyFileList(); - $res &= $this->getFileManager()->remove($extensionFileList); - } + protected function restoreFiles() + { + $res = true; + if ($this->isCopied) { + $extensionFileList = $this->getCopyFileList(); + $res &= $this->getFileManager()->remove($extensionFileList); + } - $res &= parent::restoreFiles(); + $res &= parent::restoreFiles(); - return $res; - } + return $res; + } - protected function isNew() - { - $extensionEntity = $this->getExtensionEntity(); + protected function isNew() + { + $extensionEntity = $this->getExtensionEntity(); - if (isset($extensionEntity)) { - $id = $this->getExtensionEntity()->get('id'); - } + if (isset($extensionEntity)) { + $id = $this->getExtensionEntity()->get('id'); + } - return isset($id) ? false : true; - } + return isset($id) ? false : true; + } - /** - * Get extension ID. It's an ID of existing entity (if available) or Installation ID - * - * @return string - */ - protected function getExtensionId() - { - $extensionEntity = $this->getExtensionEntity(); - if (isset($extensionEntity)) { - $extensionEntityId = $extensionEntity->get('id'); - } + /** + * Get extension ID. It's an ID of existing entity (if available) or Installation ID + * + * @return string + */ + protected function getExtensionId() + { + $extensionEntity = $this->getExtensionEntity(); + if (isset($extensionEntity)) { + $extensionEntityId = $extensionEntity->get('id'); + } - if (!isset($extensionEntityId)) { - return $this->getProcessId(); - } + if (!isset($extensionEntityId)) { + return $this->getProcessId(); + } - return $extensionEntityId; - } + return $extensionEntityId; + } - /** - * Get entity of this extension - * - * @return \Espo\Entities\Extension - */ - protected function getExtensionEntity() - { - return $this->extensionEntity; - } + /** + * Get entity of this extension + * + * @return \Espo\Entities\Extension + */ + protected function getExtensionEntity() + { + return $this->extensionEntity; + } - /** - * Find Extension entity - * - * @return \Espo\Entities\Extension - */ - protected function findExtension() - { - $manifest = $this->getManifest(); + /** + * Find Extension entity + * + * @return \Espo\Entities\Extension + */ + protected function findExtension() + { + $manifest = $this->getManifest(); - $this->extensionEntity = $this->getEntityManager()->getRepository('Extension')->where(array( - 'name' => $manifest['name'], - 'isInstalled' => true, - ))->findOne(); + $this->extensionEntity = $this->getEntityManager()->getRepository('Extension')->where(array( + 'name' => $manifest['name'], + 'isInstalled' => true, + ))->findOne(); - return $this->extensionEntity; - } + return $this->extensionEntity; + } - /** - * Create a record of Extension Entity - * - * @return bool - */ - protected function storeExtension() - { - $entityManager = $this->getEntityManager(); + /** + * Create a record of Extension Entity + * + * @return bool + */ + protected function storeExtension() + { + $entityManager = $this->getEntityManager(); - $extensionEntity = $entityManager->getEntity('Extension', $this->getProcessId()); - if (!isset($extensionEntity)) { - $extensionEntity = $entityManager->getEntity('Extension'); - } + $extensionEntity = $entityManager->getEntity('Extension', $this->getProcessId()); + if (!isset($extensionEntity)) { + $extensionEntity = $entityManager->getEntity('Extension'); + } - $manifest = $this->getManifest(); - $fileList = $this->getCopyFileList(); + $manifest = $this->getManifest(); + $fileList = $this->getCopyFileList(); - $data = array( - 'id' => $this->getProcessId(), - 'name' => $manifest['name'], - 'isInstalled' => true, - 'version' => $manifest['version'], - 'fileList' => $fileList, - 'description' => $manifest['description'], - ); - $extensionEntity->set($data); + $data = array( + 'id' => $this->getProcessId(), + 'name' => $manifest['name'], + 'isInstalled' => true, + 'version' => $manifest['version'], + 'fileList' => $fileList, + 'description' => $manifest['description'], + ); + $extensionEntity->set($data); - return $entityManager->saveEntity($extensionEntity); - } + return $entityManager->saveEntity($extensionEntity); + } - /** - * Compare version between installed and a new extensions - * - * @return void - */ - protected function compareVersion() - { - $manifest = $this->getManifest(); - $extensionEntity = $this->getExtensionEntity(); + /** + * Compare version between installed and a new extensions + * + * @return void + */ + protected function compareVersion() + { + $manifest = $this->getManifest(); + $extensionEntity = $this->getExtensionEntity(); - if (isset($extensionEntity)) { - $comparedVersion = version_compare($manifest['version'], $extensionEntity->get('version')); - if ($comparedVersion <= 0) { - $this->throwErrorAndRemovePackage('You cannot install an older version of this extension.'); - } - } - } + if (isset($extensionEntity)) { + $comparedVersion = version_compare($manifest['version'], $extensionEntity->get('version')); + if ($comparedVersion <= 0) { + $this->throwErrorAndRemovePackage('You cannot install an older version of this extension.'); + } + } + } - /** - * Throw an exception and remove package files. - * Redeclared to prevent of deleting a package of installed extension. - * - * @param string $errorMessage [description] - * @return [type] [description] - */ - protected function throwErrorAndRemovePackage($errorMessage = '') - { - if (!$this->isNew()) { - throw new Error($errorMessage); - } + /** + * Throw an exception and remove package files. + * Redeclared to prevent of deleting a package of installed extension. + * + * @param string $errorMessage [description] + * @return [type] [description] + */ + protected function throwErrorAndRemovePackage($errorMessage = '') + { + if (!$this->isNew()) { + throw new Error($errorMessage); + } - return parent::throwErrorAndRemovePackage($errorMessage); - } + return parent::throwErrorAndRemovePackage($errorMessage); + } - /** - * If extension already installed, uninstall an old version - * - * @return void - */ - protected function uninstallExtension() - { - $extensionEntity = $this->getExtensionEntity(); + /** + * If extension already installed, uninstall an old version + * + * @return void + */ + protected function uninstallExtension() + { + $extensionEntity = $this->getExtensionEntity(); - $this->executeAction(ExtensionManager::UNINSTALL, $extensionEntity->get('id')); - } + $this->executeAction(ExtensionManager::UNINSTALL, $extensionEntity->get('id')); + } - /** - * Delete extension package - * - * @return void - */ - protected function deleteExtension() - { - $extensionEntity = $this->getExtensionEntity(); + /** + * Delete extension package + * + * @return void + */ + protected function deleteExtension() + { + $extensionEntity = $this->getExtensionEntity(); - $this->executeAction(ExtensionManager::DELETE, $extensionEntity->get('id')); - } + $this->executeAction(ExtensionManager::DELETE, $extensionEntity->get('id')); + } diff --git a/application/Espo/Core/Upgrades/Actions/Extension/Uninstall.php b/application/Espo/Core/Upgrades/Actions/Extension/Uninstall.php index a405e6beea..bc8a4ded94 100644 --- a/application/Espo/Core/Upgrades/Actions/Extension/Uninstall.php +++ b/application/Espo/Core/Upgrades/Actions/Extension/Uninstall.php @@ -26,46 +26,46 @@ use Espo\Core\Exceptions\Error; class Uninstall extends \Espo\Core\Upgrades\Actions\Base\Uninstall { - protected $extensionEntity; + protected $extensionEntity; - /** - * Get entity of this extension - * - * @return \Espo\Entities\Extension - */ - protected function getExtensionEntity() - { - return $this->extensionEntity; - } + /** + * Get entity of this extension + * + * @return \Espo\Entities\Extension + */ + protected function getExtensionEntity() + { + return $this->extensionEntity; + } - /** - * Set Extension Entity - * - * @param \Espo\Entities\Extension $extensionEntity [description] - */ - protected function setExtensionEntity(\Espo\Entities\Extension $extensionEntity) - { - $this->extensionEntity = $extensionEntity; - } + /** + * Set Extension Entity + * + * @param \Espo\Entities\Extension $extensionEntity [description] + */ + protected function setExtensionEntity(\Espo\Entities\Extension $extensionEntity) + { + $this->extensionEntity = $extensionEntity; + } - protected function beforeRunAction() - { - $processId = $this->getProcessId(); + protected function beforeRunAction() + { + $processId = $this->getProcessId(); - /** get extension entity */ - $extensionEntity = $this->getEntityManager()->getEntity('Extension', $processId); - if (!isset($extensionEntity)) { - throw new Error('Extension Entity not found.'); - } - $this->setExtensionEntity($extensionEntity); - } + /** get extension entity */ + $extensionEntity = $this->getEntityManager()->getEntity('Extension', $processId); + if (!isset($extensionEntity)) { + throw new Error('Extension Entity not found.'); + } + $this->setExtensionEntity($extensionEntity); + } - protected function afterRunAction() - { - /** Set extension entity, isInstalled = false */ - $extensionEntity = $this->getExtensionEntity(); + protected function afterRunAction() + { + /** Set extension entity, isInstalled = false */ + $extensionEntity = $this->getExtensionEntity(); - $extensionEntity->set('isInstalled', false); - $this->getEntityManager()->saveEntity($extensionEntity); - } + $extensionEntity->set('isInstalled', false); + $this->getEntityManager()->saveEntity($extensionEntity); + } } \ No newline at end of file diff --git a/application/Espo/Core/Upgrades/Actions/Upgrade/Install.php b/application/Espo/Core/Upgrades/Actions/Upgrade/Install.php index bff4a69052..ec3b787293 100644 --- a/application/Espo/Core/Upgrades/Actions/Upgrade/Install.php +++ b/application/Espo/Core/Upgrades/Actions/Upgrade/Install.php @@ -24,29 +24,29 @@ namespace Espo\Core\Upgrades\Actions\Upgrade; class Install extends \Espo\Core\Upgrades\Actions\Base\Install { - protected function systemRebuild() - { - $manifest = $this->getManifest(); + protected function systemRebuild() + { + $manifest = $this->getManifest(); - $res = $this->getConfig()->set('version', $manifest['version']); - if (method_exists($this->getConfig(), 'save')) { - $res = $this->getConfig()->save(); - } - $res &= parent::systemRebuild(); + $res = $this->getConfig()->set('version', $manifest['version']); + if (method_exists($this->getConfig(), 'save')) { + $res = $this->getConfig()->save(); + } + $res &= parent::systemRebuild(); - return $res; - } + return $res; + } - /** - * Delete temporary package files - * - * @return boolean - */ - protected function deletePackageFiles() - { - $res = parent::deletePackageFiles(); - $res &= $this->deletePackageArchive(); + /** + * Delete temporary package files + * + * @return boolean + */ + protected function deletePackageFiles() + { + $res = parent::deletePackageFiles(); + $res &= $this->deletePackageArchive(); - return $res; - } + return $res; + } } diff --git a/application/Espo/Core/Upgrades/Base.php b/application/Espo/Core/Upgrades/Base.php index 66129556a3..ff351f4485 100644 --- a/application/Espo/Core/Upgrades/Base.php +++ b/application/Espo/Core/Upgrades/Base.php @@ -23,72 +23,72 @@ namespace Espo\Core\Upgrades; use Espo\Core\Utils\Util, - Espo\Core\Utils\Json, - Espo\Core\Exceptions\Error; + Espo\Core\Utils\Json, + Espo\Core\Exceptions\Error; abstract class Base { - private $container; + private $container; - protected $name = null; + protected $name = null; - protected $params = array(); + protected $params = array(); - const UPLOAD = 'upload'; + const UPLOAD = 'upload'; - const INSTALL = 'install'; + const INSTALL = 'install'; - const UNINSTALL = 'uninstall'; + const UNINSTALL = 'uninstall'; - const DELETE = 'delete'; + const DELETE = 'delete'; - public function __construct($container) - { - $this->container = $container; + public function __construct($container) + { + $this->container = $container; - $this->actionManager = new ActionManager($this->name, $container, $this->params); - } + $this->actionManager = new ActionManager($this->name, $container, $this->params); + } - protected function getContainer() - { - return $this->container; - } + protected function getContainer() + { + return $this->container; + } - protected function getActionManager() - { - return $this->actionManager; - } + protected function getActionManager() + { + return $this->actionManager; + } - public function getManifest() - { - return $this->getActionManager()->getManifest(); - } + public function getManifest() + { + return $this->getActionManager()->getManifest(); + } - public function upload($data) - { - $this->getActionManager()->setAction(self::UPLOAD); + public function upload($data) + { + $this->getActionManager()->setAction(self::UPLOAD); - return $this->getActionManager()->run($data); - } + return $this->getActionManager()->run($data); + } - public function install($processId) - { - $this->getActionManager()->setAction(self::INSTALL); + public function install($processId) + { + $this->getActionManager()->setAction(self::INSTALL); - return $this->getActionManager()->run($processId); - } + return $this->getActionManager()->run($processId); + } - public function uninstall($processId) - { - $this->getActionManager()->setAction(self::UNINSTALL); + public function uninstall($processId) + { + $this->getActionManager()->setAction(self::UNINSTALL); - return $this->getActionManager()->run($processId); - } + return $this->getActionManager()->run($processId); + } - public function delete($processId) - { - $this->getActionManager()->setAction(self::DELETE); + public function delete($processId) + { + $this->getActionManager()->setAction(self::DELETE); - return $this->getActionManager()->run($processId); - } + return $this->getActionManager()->run($processId); + } } diff --git a/application/Espo/Core/Utils/Api/Auth.php b/application/Espo/Core/Utils/Api/Auth.php index 5394fa16f1..d9ec0b96e7 100644 --- a/application/Espo/Core/Utils/Api/Auth.php +++ b/application/Espo/Core/Utils/Api/Auth.php @@ -26,108 +26,108 @@ use \Espo\Core\Utils\Api\Slim; class Auth extends \Slim\Middleware { - protected $auth; + protected $auth; - protected $authRequired = null; + protected $authRequired = null; - protected $showDialog = false; + protected $showDialog = false; - public function __construct(\Espo\Core\Utils\Auth $auth, $authRequired = null, $showDialog = false) - { - $this->auth = $auth; - $this->authRequired = $authRequired; - $this->showDialog = $showDialog; - } + public function __construct(\Espo\Core\Utils\Auth $auth, $authRequired = null, $showDialog = false) + { + $this->auth = $auth; + $this->authRequired = $authRequired; + $this->showDialog = $showDialog; + } - function call() - { - $req = $this->app->request(); + function call() + { + $req = $this->app->request(); - $uri = $req->getResourceUri(); - $httpMethod = $req->getMethod(); + $uri = $req->getResourceUri(); + $httpMethod = $req->getMethod(); - $authUsername = $req->headers('PHP_AUTH_USER'); - $authPassword = $req->headers('PHP_AUTH_PW'); + $authUsername = $req->headers('PHP_AUTH_USER'); + $authPassword = $req->headers('PHP_AUTH_PW'); - $espoAuth = $req->headers('HTTP_ESPO_AUTHORIZATION'); - if (isset($espoAuth)) { - list($authUsername, $authPassword) = explode(':', base64_decode($espoAuth)); - } + $espoAuth = $req->headers('HTTP_ESPO_AUTHORIZATION'); + if (isset($espoAuth)) { + list($authUsername, $authPassword) = explode(':', base64_decode($espoAuth)); + } - $espoCgiAuth = $req->headers('HTTP_ESPO_CGI_AUTH'); - if ( !isset($authUsername) && !isset($authPassword) && isset($espoCgiAuth) ) { - list($authUsername, $authPassword) = explode(':' , base64_decode(substr($espoCgiAuth, 6))); - } + $espoCgiAuth = $req->headers('HTTP_ESPO_CGI_AUTH'); + if ( !isset($authUsername) && !isset($authPassword) && isset($espoCgiAuth) ) { + list($authUsername, $authPassword) = explode(':' , base64_decode(substr($espoCgiAuth, 6))); + } - if (is_null($this->authRequired)) { - $routes = $this->app->router()->getMatchedRoutes($httpMethod, $uri); + if (is_null($this->authRequired)) { + $routes = $this->app->router()->getMatchedRoutes($httpMethod, $uri); - if (!empty($routes[0])) { - $routeConditions = $routes[0]->getConditions(); - if (isset($routeConditions['auth']) && $routeConditions['auth'] === false) { + if (!empty($routes[0])) { + $routeConditions = $routes[0]->getConditions(); + if (isset($routeConditions['auth']) && $routeConditions['auth'] === false) { - if ($authUsername && $authPassword) { - $isAuthenticated = $this->auth->login($authUsername, $authPassword); - if ($isAuthenticated) { - $this->next->call(); - return; - } - } + if ($authUsername && $authPassword) { + $isAuthenticated = $this->auth->login($authUsername, $authPassword); + if ($isAuthenticated) { + $this->next->call(); + return; + } + } - $this->auth->useNoAuth(); - $this->next->call(); - return; - } - } - } else { - if (!$this->authRequired) { - $this->auth->useNoAuth(); - $this->next->call(); - return; - } - } + $this->auth->useNoAuth(); + $this->next->call(); + return; + } + } + } else { + if (!$this->authRequired) { + $this->auth->useNoAuth(); + $this->next->call(); + return; + } + } - if ($authUsername && $authPassword) { + if ($authUsername && $authPassword) { - $isAuthenticated = $this->auth->login($authUsername, $authPassword); + $isAuthenticated = $this->auth->login($authUsername, $authPassword); - if ($isAuthenticated) { - $this->next->call(); - } else { - $this->processUnauthorized(); - } - } else { - if (!$this->isXMLHttpRequest()) { - $this->showDialog = true; - } - $this->processUnauthorized(); - } - } + if ($isAuthenticated) { + $this->next->call(); + } else { + $this->processUnauthorized(); + } + } else { + if (!$this->isXMLHttpRequest()) { + $this->showDialog = true; + } + $this->processUnauthorized(); + } + } - protected function processUnauthorized() - { - $res = $this->app->response(); + protected function processUnauthorized() + { + $res = $this->app->response(); - if ($this->showDialog) { - $res->header('WWW-Authenticate', 'Basic realm=""'); - } else { - $res->header('WWW-Authenticate'); - } - $res->status(401); - } + if ($this->showDialog) { + $res->header('WWW-Authenticate', 'Basic realm=""'); + } else { + $res->header('WWW-Authenticate'); + } + $res->status(401); + } - protected function isXMLHttpRequest() - { - $req = $this->app->request(); + protected function isXMLHttpRequest() + { + $req = $this->app->request(); - $httpXRequestedWith = $req->headers('HTTP_X_REQUESTED_WITH'); + $httpXRequestedWith = $req->headers('HTTP_X_REQUESTED_WITH'); - if (isset($httpXRequestedWith) && strtolower($httpXRequestedWith) == 'xmlhttprequest') { - return true; - } + if (isset($httpXRequestedWith) && strtolower($httpXRequestedWith) == 'xmlhttprequest') { + return true; + } - return false; - } + return false; + } } diff --git a/application/Espo/Core/Utils/Api/Output.php b/application/Espo/Core/Utils/Api/Output.php index 8955f25f62..e1791ec1c2 100644 --- a/application/Espo/Core/Utils/Api/Output.php +++ b/application/Espo/Core/Utils/Api/Output.php @@ -24,94 +24,94 @@ namespace Espo\Core\Utils\Api; class Output { - private $slim; + private $slim; - protected $errorDesc = array( - 400 => 'Bad Request', - 401 => 'Unauthorized', - 403 => 'Forbidden', - 404 => 'Page Not Found', - 409 => 'Conflict', - 500 => 'Internal Server Error', - ); + protected $errorDesc = array( + 400 => 'Bad Request', + 401 => 'Unauthorized', + 403 => 'Forbidden', + 404 => 'Page Not Found', + 409 => 'Conflict', + 500 => 'Internal Server Error', + ); - public function __construct(\Espo\Core\Utils\Api\Slim $slim) - { - $this->slim = $slim; - } + public function __construct(\Espo\Core\Utils\Api\Slim $slim) + { + $this->slim = $slim; + } - protected function getSlim() - { - return $this->slim; - } + protected function getSlim() + { + return $this->slim; + } - /** - * Output the result - * - * @param mixed $data - JSON - */ - public function render($data = null) - { - if (is_array($data)) { - $dataArr = array_values($data); - $data = empty($dataArr[0]) ? false : $dataArr[0]; - } + /** + * Output the result + * + * @param mixed $data - JSON + */ + public function render($data = null) + { + if (is_array($data)) { + $dataArr = array_values($data); + $data = empty($dataArr[0]) ? false : $dataArr[0]; + } - ob_clean(); - echo $data; - } + ob_clean(); + echo $data; + } - public function processError($message = 'Error', $code = 500, $isPrint = false) - { - $GLOBALS['log']->error('API ['.$this->getSlim()->request()->getMethod().']:'.$this->getSlim()->router()->getCurrentRoute()->getPattern().', Params:'.print_r($this->getSlim()->router()->getCurrentRoute()->getParams(), true).', InputData: '.$this->getSlim()->request()->getBody().' - '.$message); - $this->displayError($message, $code, $isPrint); - } + public function processError($message = 'Error', $code = 500, $isPrint = false) + { + $GLOBALS['log']->error('API ['.$this->getSlim()->request()->getMethod().']:'.$this->getSlim()->router()->getCurrentRoute()->getPattern().', Params:'.print_r($this->getSlim()->router()->getCurrentRoute()->getParams(), true).', InputData: '.$this->getSlim()->request()->getBody().' - '.$message); + $this->displayError($message, $code, $isPrint); + } - /** - * Output the error and stop app execution - * - * @param string $text - * @param int $statusCode - * - * @return void - */ - public function displayError($text, $statusCode = 500, $isPrint = false) - { - $GLOBALS['log']->error('Display Error: '.$text.', Code: '.$statusCode.' URL: '.$_SERVER['REQUEST_URI']); + /** + * Output the error and stop app execution + * + * @param string $text + * @param int $statusCode + * + * @return void + */ + public function displayError($text, $statusCode = 500, $isPrint = false) + { + $GLOBALS['log']->error('Display Error: '.$text.', Code: '.$statusCode.' URL: '.$_SERVER['REQUEST_URI']); - if (!empty( $this->slim)) { - $this->getSlim()->response()->status($statusCode); - $this->getSlim()->response()->header('X-Status-Reason', $text); + if (!empty( $this->slim)) { + $this->getSlim()->response()->status($statusCode); + $this->getSlim()->response()->header('X-Status-Reason', $text); - if ($isPrint) { - $status = $this->getCodeDesc($statusCode); - $status = isset($status) ? $statusCode.' '.$status : 'HTTP '.$statusCode; - $this->getSlim()->printError($text, $status); - } + if ($isPrint) { + $status = $this->getCodeDesc($statusCode); + $status = isset($status) ? $statusCode.' '.$status : 'HTTP '.$statusCode; + $this->getSlim()->printError($text, $status); + } - $this->getSlim()->stop(); - } - else { - $GLOBALS['log']->info('Could not get Slim instance. It looks like a direct call (bypass API). URL: '.$_SERVER['REQUEST_URI']); - die($text); - } - } + $this->getSlim()->stop(); + } + else { + $GLOBALS['log']->info('Could not get Slim instance. It looks like a direct call (bypass API). URL: '.$_SERVER['REQUEST_URI']); + die($text); + } + } - /** - * Get status code desription - * - * @param int $statusCode - * @return string | null - */ - protected function getCodeDesc($statusCode) - { - if (isset($this->errorDesc[$statusCode])) { - return $this->errorDesc[$statusCode]; - } + /** + * Get status code desription + * + * @param int $statusCode + * @return string | null + */ + protected function getCodeDesc($statusCode) + { + if (isset($this->errorDesc[$statusCode])) { + return $this->errorDesc[$statusCode]; + } - return null; - } + return null; + } diff --git a/application/Espo/Core/Utils/Api/Slim.php b/application/Espo/Core/Utils/Api/Slim.php index b91d4acda8..e03e55fb6f 100644 --- a/application/Espo/Core/Utils/Api/Slim.php +++ b/application/Espo/Core/Utils/Api/Slim.php @@ -26,60 +26,60 @@ namespace Espo\Core\Utils\Api; class Slim extends \Slim\Slim { - /** - * Redefine the run method - * - * We no need to use a Slim handler - */ - public function run() - { - //set_error_handler(array('\Slim\Slim', 'handleErrors')); //Espo: no needs to use this handler + /** + * Redefine the run method + * + * We no need to use a Slim handler + */ + public function run() + { + //set_error_handler(array('\Slim\Slim', 'handleErrors')); //Espo: no needs to use this handler - //Apply final outer middleware layers - if ($this->config('debug')) { - //Apply pretty exceptions only in debug to avoid accidental information leakage in production - //$this->add(new \Slim\Middleware\PrettyExceptions()); //Espo: no needs to use this handler - } + //Apply final outer middleware layers + if ($this->config('debug')) { + //Apply pretty exceptions only in debug to avoid accidental information leakage in production + //$this->add(new \Slim\Middleware\PrettyExceptions()); //Espo: no needs to use this handler + } - //Invoke middleware and application stack - $this->middleware[0]->call(); + //Invoke middleware and application stack + $this->middleware[0]->call(); - //Fetch status, header, and body - list($status, $headers, $body) = $this->response->finalize(); + //Fetch status, header, and body + list($status, $headers, $body) = $this->response->finalize(); - // Serialize cookies (with optional encryption) - \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings); + // Serialize cookies (with optional encryption) + \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings); - //Send headers - if (headers_sent() === false) { - //Send status - if (strpos(PHP_SAPI, 'cgi') === 0) { - header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status))); - } else { - header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status))); - } + //Send headers + if (headers_sent() === false) { + //Send status + if (strpos(PHP_SAPI, 'cgi') === 0) { + header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status))); + } else { + header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status))); + } - //Send headers - foreach ($headers as $name => $value) { - $hValues = explode("\n", $value); - foreach ($hValues as $hVal) { - header("$name: $hVal", false); - } - } - } + //Send headers + foreach ($headers as $name => $value) { + $hValues = explode("\n", $value); + foreach ($hValues as $hVal) { + header("$name: $hVal", false); + } + } + } - //Send body, but only if it isn't a HEAD request - if (!$this->request->isHead()) { - echo $body; - } + //Send body, but only if it isn't a HEAD request + if (!$this->request->isHead()) { + echo $body; + } - //restore_error_handler(); //Espo: no needs to use this handler - } + //restore_error_handler(); //Espo: no needs to use this handler + } - public function printError($error, $status) - { - echo static::generateTemplateMarkup($status, '
'.$error.'
Visit the Home Page'); - } + public function printError($error, $status) + { + echo static::generateTemplateMarkup($status, ''.$error.'
Visit the Home Page'); + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Auth.php b/application/Espo/Core/Utils/Auth.php index f8d56b0530..b35bafb358 100644 --- a/application/Espo/Core/Utils/Auth.php +++ b/application/Espo/Core/Utils/Auth.php @@ -26,88 +26,88 @@ use \Espo\Core\Exceptions\Error; class Auth { - protected $container; + protected $container; - protected $authentication; + protected $authentication; - protected $config; + protected $config; - protected $entityManager; + protected $entityManager; - public function __construct(\Espo\Core\Container $container) - { - $this->container = $container; + public function __construct(\Espo\Core\Container $container) + { + $this->container = $container; - $this->entityManager = $this->container->get('entityManager'); - $this->config = $this->container->get('config'); + $this->entityManager = $this->container->get('entityManager'); + $this->config = $this->container->get('config'); - $authenticationMethod = $this->config->get('authenticationMethod', 'Espo'); - $authenticationClassName = "\\Espo\\Core\\Utils\\Authentication\\" . $authenticationMethod; - $this->authentication = new $authenticationClassName($this->config, $this->entityManager, $this); - } + $authenticationMethod = $this->config->get('authenticationMethod', 'Espo'); + $authenticationClassName = "\\Espo\\Core\\Utils\\Authentication\\" . $authenticationMethod; + $this->authentication = new $authenticationClassName($this->config, $this->entityManager, $this); + } - public function useNoAuth($isAdmin = false) - { - $entityManager = $this->container->get('entityManager'); + public function useNoAuth($isAdmin = false) + { + $entityManager = $this->container->get('entityManager'); - $user = $entityManager->getRepository('User')->get('system'); - if (!$user) { - throw new Error('System user is not found'); - } + $user = $entityManager->getRepository('User')->get('system'); + if (!$user) { + throw new Error('System user is not found'); + } - $user->set('isAdmin', $isAdmin); + $user->set('isAdmin', $isAdmin); - $entityManager->setUser($user); - $this->container->setUser($user); - } + $entityManager->setUser($user); + $this->container->setUser($user); + } - public function login($username, $password) - { - $GLOBALS['log']->debug('AUTH: Try to authenticate'); + public function login($username, $password) + { + $GLOBALS['log']->debug('AUTH: Try to authenticate'); - $entityManager = $this->entityManager; + $entityManager = $this->entityManager; - $authToken = $entityManager->getRepository('AuthToken')->where(array('token' => $password))->findOne(); + $authToken = $entityManager->getRepository('AuthToken')->where(array('token' => $password))->findOne(); - $user = $this->authentication->login($username, $password, $authToken); + $user = $this->authentication->login($username, $password, $authToken); - if ($user) { - $entityManager->setUser($user); - $this->container->setUser($user); - $GLOBALS['log']->debug('AUTH: Result of authenticate is [true]'); + if ($user) { + $entityManager->setUser($user); + $this->container->setUser($user); + $GLOBALS['log']->debug('AUTH: Result of authenticate is [true]'); - if (!$authToken) { - $authToken = $entityManager->getEntity('AuthToken'); - $token = $this->createToken($user); - $authToken->set('token', $token); - $authToken->set('hash', $user->get('password')); - $authToken->set('ipAddress', $_SERVER['REMOTE_ADDR']); - $authToken->set('userId', $user->id); - } + if (!$authToken) { + $authToken = $entityManager->getEntity('AuthToken'); + $token = $this->createToken($user); + $authToken->set('token', $token); + $authToken->set('hash', $user->get('password')); + $authToken->set('ipAddress', $_SERVER['REMOTE_ADDR']); + $authToken->set('userId', $user->id); + } - $authToken->set('lastAccess', date('Y-m-d H:i:s')); + $authToken->set('lastAccess', date('Y-m-d H:i:s')); - $entityManager->saveEntity($authToken); - $user->set('token', $authToken->get('token')); + $entityManager->saveEntity($authToken); + $user->set('token', $authToken->get('token')); - return true; - } - } + return true; + } + } - protected function createToken($user) - { - return md5(uniqid($user->get('id'))); - } + protected function createToken($user) + { + return md5(uniqid($user->get('id'))); + } - public function destroyAuthToken($token) - { - $entityManager = $this->container->get('entityManager'); + public function destroyAuthToken($token) + { + $entityManager = $this->container->get('entityManager'); - $authToken = $entityManager->getRepository('AuthToken')->where(array('token' => $token))->findOne(); - if ($authToken) { - $entityManager->removeEntity($authToken); - return true; - } - } + $authToken = $entityManager->getRepository('AuthToken')->where(array('token' => $token))->findOne(); + if ($authToken) { + $entityManager->removeEntity($authToken); + return true; + } + } } diff --git a/application/Espo/Core/Utils/Authentication/Base.php b/application/Espo/Core/Utils/Authentication/Base.php index 144d108686..e196cd2156 100644 --- a/application/Espo/Core/Utils/Authentication/Base.php +++ b/application/Espo/Core/Utils/Authentication/Base.php @@ -28,44 +28,44 @@ use \Espo\Core\Utils\Auth; abstract class Base { - private $config; + private $config; - private $entityManager; + private $entityManager; - private $auth; + private $auth; - private $passwordHash; + private $passwordHash; - public function __construct(Config $config, EntityManager $entityManager, Auth $auth) - { - $this->config = $config; - $this->entityManager = $entityManager; - $this->auth = $auth; - } + public function __construct(Config $config, EntityManager $entityManager, Auth $auth) + { + $this->config = $config; + $this->entityManager = $entityManager; + $this->auth = $auth; + } - protected function getConfig() - { - return $this->config; - } + protected function getConfig() + { + return $this->config; + } - protected function getEntityManager() - { - return $this->entityManager; - } + protected function getEntityManager() + { + return $this->entityManager; + } - protected function getAuth() - { - return $this->auth; - } + protected function getAuth() + { + return $this->auth; + } - protected function getPasswordHash() - { - if (!isset($this->passwordHash)) { - $this->passwordHash = new \Espo\Core\Utils\PasswordHash($this->config); - } + protected function getPasswordHash() + { + if (!isset($this->passwordHash)) { + $this->passwordHash = new \Espo\Core\Utils\PasswordHash($this->config); + } - return $this->passwordHash; - } + return $this->passwordHash; + } } diff --git a/application/Espo/Core/Utils/Authentication/Espo.php b/application/Espo/Core/Utils/Authentication/Espo.php index 42735b76d7..ba220e1d35 100644 --- a/application/Espo/Core/Utils/Authentication/Espo.php +++ b/application/Espo/Core/Utils/Authentication/Espo.php @@ -26,22 +26,22 @@ use \Espo\Core\Exceptions\Error; class Espo extends Base { - public function login($username, $password, \Espo\Entities\AuthToken $authToken = null) - { - if ($authToken) { - $hash = $authToken->get('hash'); - } else { - $hash = $this->getPasswordHash()->hash($password); - } + public function login($username, $password, \Espo\Entities\AuthToken $authToken = null) + { + if ($authToken) { + $hash = $authToken->get('hash'); + } else { + $hash = $this->getPasswordHash()->hash($password); + } - $user = $this->getEntityManager()->getRepository('User')->findOne(array( - 'whereClause' => array( - 'userName' => $username, - 'password' => $hash - ), - )); + $user = $this->getEntityManager()->getRepository('User')->findOne(array( + 'whereClause' => array( + 'userName' => $username, + 'password' => $hash + ), + )); - return $user; - } + return $user; + } } diff --git a/application/Espo/Core/Utils/Authentication/LDAP.php b/application/Espo/Core/Utils/Authentication/LDAP.php index 8b53c9bbe7..8bbb90ad7b 100644 --- a/application/Espo/Core/Utils/Authentication/LDAP.php +++ b/application/Espo/Core/Utils/Authentication/LDAP.php @@ -23,177 +23,177 @@ namespace Espo\Core\Utils\Authentication; use Espo\Core\Exceptions\Error, - Espo\Core\Utils\Config, - Espo\Core\ORM\EntityManager, - Espo\Core\Utils\Auth; + Espo\Core\Utils\Config, + Espo\Core\ORM\EntityManager, + Espo\Core\Utils\Auth; class LDAP extends Base { - private $utils; + private $utils; - private $zendLdap; + private $zendLdap; - /** - * Espo => LDAP name - * - * @var array - */ - private $fields = array( - 'userName' => 'cn', - 'firstName' => 'givenname', - 'lastName' => 'sn', - 'title' => 'title', - 'emailAddress' => 'mail', - 'phoneNumber' => 'telephonenumber', - ); + /** + * Espo => LDAP name + * + * @var array + */ + private $fields = array( + 'userName' => 'cn', + 'firstName' => 'givenname', + 'lastName' => 'sn', + 'title' => 'title', + 'emailAddress' => 'mail', + 'phoneNumber' => 'telephonenumber', + ); - public function __construct(Config $config, EntityManager $entityManager, Auth $auth) - { - parent::__construct($config, $entityManager, $auth); + public function __construct(Config $config, EntityManager $entityManager, Auth $auth) + { + parent::__construct($config, $entityManager, $auth); - $this->zendLdap = new LDAP\LDAP(); - $this->utils = new LDAP\Utils($config); - } + $this->zendLdap = new LDAP\LDAP(); + $this->utils = new LDAP\Utils($config); + } - protected function getZendLdap() - { - return $this->zendLdap; - } + protected function getZendLdap() + { + return $this->zendLdap; + } - protected function getUtils() - { - return $this->utils; - } + protected function getUtils() + { + return $this->utils; + } - /** - * LDAP login - * - * @param string $username - * @param string $password - * @param \Espo\Entities\AuthToken $authToken - * @return \Espo\Entities\User | null - */ - public function login($username, $password, \Espo\Entities\AuthToken $authToken = null) - { - if ($authToken) { - return $this->loginByToken($username, $authToken); - } + /** + * LDAP login + * + * @param string $username + * @param string $password + * @param \Espo\Entities\AuthToken $authToken + * @return \Espo\Entities\User | null + */ + public function login($username, $password, \Espo\Entities\AuthToken $authToken = null) + { + if ($authToken) { + return $this->loginByToken($username, $authToken); + } - $options = $this->getUtils()->getZendOptions(); + $options = $this->getUtils()->getZendOptions(); - $ldap = $this->getZendLdap(); - $ldap = $ldap->setOptions($options); + $ldap = $this->getZendLdap(); + $ldap = $ldap->setOptions($options); - try { - $ldap->bind($username, $password); + try { + $ldap->bind($username, $password); - $dn = $ldap->getDn($username); + $dn = $ldap->getDn($username); - $loginFilter = $this->getUtils()->getOption('userLoginFilter'); - $userData = $ldap->searchByLoginFilter($loginFilter, $dn, 3); + $loginFilter = $this->getUtils()->getOption('userLoginFilter'); + $userData = $ldap->searchByLoginFilter($loginFilter, $dn, 3); - } catch (\Zend\Ldap\Exception\LdapException $zle) { + } catch (\Zend\Ldap\Exception\LdapException $zle) { - $admin = $this->adminLogin($username, $password); - if (!isset($admin)) { - $GLOBALS['log']->info('LDAP Authentication: ' . $zle->getMessage()); - return null; - } + $admin = $this->adminLogin($username, $password); + if (!isset($admin)) { + $GLOBALS['log']->info('LDAP Authentication: ' . $zle->getMessage()); + return null; + } - $GLOBALS['log']->info('LDAP Authentication: Administrator login by username ['.$username.']'); - } + $GLOBALS['log']->info('LDAP Authentication: Administrator login by username ['.$username.']'); + } - $user = $this->getEntityManager()->getRepository('User')->findOne(array( - 'whereClause' => array( - 'userName' => $username, - ), - )); + $user = $this->getEntityManager()->getRepository('User')->findOne(array( + 'whereClause' => array( + 'userName' => $username, + ), + )); - $isCreateUser = $this->getUtils()->getOption('createEspoUser'); - if (!isset($user) && $isCreateUser) { - $this->getAuth()->useNoAuth(); /** Required to fix Acl "isFetched()" error */ - $user = $this->createUser($userData); - } + $isCreateUser = $this->getUtils()->getOption('createEspoUser'); + if (!isset($user) && $isCreateUser) { + $this->getAuth()->useNoAuth(); /** Required to fix Acl "isFetched()" error */ + $user = $this->createUser($userData); + } - return $user; - } + return $user; + } - /** - * Login by authorization token - * - * @param string $username - * @param \Espo\Entities\AuthToken $authToken - * @return \Espo\Entities\User | null - */ - protected function loginByToken($username, \Espo\Entities\AuthToken $authToken = null) - { - if (!isset($authToken)) { - return null; - } + /** + * Login by authorization token + * + * @param string $username + * @param \Espo\Entities\AuthToken $authToken + * @return \Espo\Entities\User | null + */ + protected function loginByToken($username, \Espo\Entities\AuthToken $authToken = null) + { + if (!isset($authToken)) { + return null; + } - $userId = $authToken->get('userId'); - $user = $this->getEntityManager()->getEntity('User', $userId); + $userId = $authToken->get('userId'); + $user = $this->getEntityManager()->getEntity('User', $userId); - $tokenUsername = $user->get('userName'); - if ($username != $tokenUsername) { - $GLOBALS['log']->alert('Unauthorized access attempt for user ['.$username.'] from IP ['.$_SERVER['REMOTE_ADDR'].']'); - return null; - } + $tokenUsername = $user->get('userName'); + if ($username != $tokenUsername) { + $GLOBALS['log']->alert('Unauthorized access attempt for user ['.$username.'] from IP ['.$_SERVER['REMOTE_ADDR'].']'); + return null; + } - $user = $this->getEntityManager()->getRepository('User')->findOne(array( - 'whereClause' => array( - 'userName' => $username, - ), - )); + $user = $this->getEntityManager()->getRepository('User')->findOne(array( + 'whereClause' => array( + 'userName' => $username, + ), + )); - return $user; - } + return $user; + } - /** - * Login user with administrator rights - * - * @param string $username - * @param string $password - * @return \Espo\Entities\User | null - */ - protected function adminLogin($username, $password) - { - $hash = $this->getPasswordHash()->hash($password); + /** + * Login user with administrator rights + * + * @param string $username + * @param string $password + * @return \Espo\Entities\User | null + */ + protected function adminLogin($username, $password) + { + $hash = $this->getPasswordHash()->hash($password); - $user = $this->getEntityManager()->getRepository('User')->findOne(array( - 'whereClause' => array( - 'userName' => $username, - 'password' => $hash, - 'isAdmin' => 1 - ), - )); + $user = $this->getEntityManager()->getRepository('User')->findOne(array( + 'whereClause' => array( + 'userName' => $username, + 'password' => $hash, + 'isAdmin' => 1 + ), + )); - return $user; - } + return $user; + } - /** - * Create Espo user with data gets from LDAP server - * - * @param array $userData LDAP entity data - * @return \Espo\Entities\User - */ - protected function createUser(array $userData) - { - $data = array(); - foreach ($this->fields as $espo => $ldap) { - if (isset($userData[$ldap][0])) { - $data[$espo] = $userData[$ldap][0]; - } - } + /** + * Create Espo user with data gets from LDAP server + * + * @param array $userData LDAP entity data + * @return \Espo\Entities\User + */ + protected function createUser(array $userData) + { + $data = array(); + foreach ($this->fields as $espo => $ldap) { + if (isset($userData[$ldap][0])) { + $data[$espo] = $userData[$ldap][0]; + } + } - $user = $this->getEntityManager()->getEntity('User'); - $user->set($data); + $user = $this->getEntityManager()->getEntity('User'); + $user->set($data); - $this->getEntityManager()->saveEntity($user); + $this->getEntityManager()->saveEntity($user); - return $user; - } + return $user; + } diff --git a/application/Espo/Core/Utils/Authentication/LDAP/LDAP.php b/application/Espo/Core/Utils/Authentication/LDAP/LDAP.php index 0361d617e0..eda42a9b16 100644 --- a/application/Espo/Core/Utils/Authentication/LDAP/LDAP.php +++ b/application/Espo/Core/Utils/Authentication/LDAP/LDAP.php @@ -24,100 +24,100 @@ namespace Espo\Core\Utils\Authentication\LDAP; class LDAP extends \Zend\Ldap\Ldap { - protected $usernameAttribute = 'cn'; + protected $usernameAttribute = 'cn'; - /** - * Get DN depends on options, ex. "cn=test,ou=People,dc=maxcrc,dc=com" - * - * @return string DN format - */ - public function getDn($acctname) - { - return $this->getAccountDn($acctname, \Zend\Ldap\Ldap::ACCTNAME_FORM_DN); - } + /** + * Get DN depends on options, ex. "cn=test,ou=People,dc=maxcrc,dc=com" + * + * @return string DN format + */ + public function getDn($acctname) + { + return $this->getAccountDn($acctname, \Zend\Ldap\Ldap::ACCTNAME_FORM_DN); + } - /** - * Fix a bug, ex. CN=Alice Baker,CN=Users,DC=example,DC=com - * - * @param string $acctname - * @return string - Account DN - */ - protected function getAccountDn($acctname) - { - $baseDn = $this->getBaseDn(); + /** + * Fix a bug, ex. CN=Alice Baker,CN=Users,DC=example,DC=com + * + * @param string $acctname + * @return string - Account DN + */ + protected function getAccountDn($acctname) + { + $baseDn = $this->getBaseDn(); - if ($this->getBindRequiresDn() && isset($baseDn)) { - try { - return parent::getAccountDn($acctname); - } catch (\Zend\Ldap\Exception\LdapException $zle) { - if ($zle->getCode() != \Zend\Ldap\Exception\LdapException::LDAP_NO_SUCH_OBJECT) { - throw $zle; - } - } + if ($this->getBindRequiresDn() && isset($baseDn)) { + try { + return parent::getAccountDn($acctname); + } catch (\Zend\Ldap\Exception\LdapException $zle) { + if ($zle->getCode() != \Zend\Ldap\Exception\LdapException::LDAP_NO_SUCH_OBJECT) { + throw $zle; + } + } - $acctname = $this->usernameAttribute . '=' . \Zend\Ldap\Filter\AbstractFilter::escapeValue($acctname) . ',' . $baseDn; - } + $acctname = $this->usernameAttribute . '=' . \Zend\Ldap\Filter\AbstractFilter::escapeValue($acctname) . ',' . $baseDn; + } - return parent::getAccountDn($acctname); - } + return parent::getAccountDn($acctname); + } - /** - * Search a user using userLoginFilter - * - * @param string $filter - * @param string $basedn - * @param int $scope - * @param array $attributes - * @return array - */ - public function searchByLoginFilter($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array()) - { - $filter = $this->getLoginFilter($filter); + /** + * Search a user using userLoginFilter + * + * @param string $filter + * @param string $basedn + * @param int $scope + * @param array $attributes + * @return array + */ + public function searchByLoginFilter($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array()) + { + $filter = $this->getLoginFilter($filter); - $result = $this->search($filter, $basedn, $scope, $attributes); + $result = $this->search($filter, $basedn, $scope, $attributes); - if ($result->count() > 0) { - return $result->getFirst(); - } + if ($result->count() > 0) { + return $result->getFirst(); + } - throw new \Zend\Ldap\Exception\LdapException($this, 'searching: ' . $filter); - } + throw new \Zend\Ldap\Exception\LdapException($this, 'searching: ' . $filter); + } - /** - * Get login filter in LDAP format - * - * @param string $filter - * @return string - */ - protected function getLoginFilter($filter) - { - $baseFilter = '(objectClass=*)'; + /** + * Get login filter in LDAP format + * + * @param string $filter + * @return string + */ + protected function getLoginFilter($filter) + { + $baseFilter = '(objectClass=*)'; - if (!empty($filter)) { - $baseFilter = '(&' . $baseFilter . $this->convertToFilterFormat($filter). ')'; - } + if (!empty($filter)) { + $baseFilter = '(&' . $baseFilter . $this->convertToFilterFormat($filter). ')'; + } - return $baseFilter; - } + return $baseFilter; + } - /** - * Check and convert filter item in LDAP format - * - * @param string $filter [description] - * @return string - */ - protected function convertToFilterFormat($filter) - { - $filter = trim($filter); - if (substr($filter, 0, 1) != '(') { - $filter = '(' . $filter; - } + /** + * Check and convert filter item in LDAP format + * + * @param string $filter [description] + * @return string + */ + protected function convertToFilterFormat($filter) + { + $filter = trim($filter); + if (substr($filter, 0, 1) != '(') { + $filter = '(' . $filter; + } - if (substr($filter, -1) != ')') { - $filter = $filter . ')'; - } + if (substr($filter, -1) != ')') { + $filter = $filter . ')'; + } - return $filter; - } + return $filter; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Authentication/LDAP/Utils.php b/application/Espo/Core/Utils/Authentication/LDAP/Utils.php index 35da2e3917..25ee732b06 100644 --- a/application/Espo/Core/Utils/Authentication/LDAP/Utils.php +++ b/application/Espo/Core/Utils/Authentication/LDAP/Utils.php @@ -26,130 +26,130 @@ use \Espo\Core\Utils\Config; class Utils { - private $config; + private $config; - protected $options = null; + protected $options = null; - /** - * Association between LDAP and Espo fields - * @var array - */ - protected $fieldMap = array( - 'host' => 'ldapHost', - 'port' => 'ldapPort', - 'useSsl' => 'ldapSecurity', - 'useStartTls' => 'ldapSecurity', - 'username' => 'ldapUsername', - 'password' => 'ldapPassword', - 'bindRequiresDn' => 'ldapBindRequiresDn', - 'baseDn' => 'ldapBaseDn', - 'accountCanonicalForm' => 'ldapAccountCanonicalForm', - 'accountDomainName' => 'ldapAccountDomainName', - 'accountDomainNameShort' => 'ldapAccountDomainNameShort', - 'accountFilterFormat' => 'ldapAccountFilterFormat', - 'optReferrals' => 'ldapOptReferrals', - 'tryUsernameSplit' => 'ldapTryUsernameSplit', - 'networkTimeout' => 'ldapNetworkTimeout', - 'createEspoUser' => 'ldapCreateEspoUser', - 'userLoginFilter' => 'ldapUserLoginFilter', - ); + /** + * Association between LDAP and Espo fields + * @var array + */ + protected $fieldMap = array( + 'host' => 'ldapHost', + 'port' => 'ldapPort', + 'useSsl' => 'ldapSecurity', + 'useStartTls' => 'ldapSecurity', + 'username' => 'ldapUsername', + 'password' => 'ldapPassword', + 'bindRequiresDn' => 'ldapBindRequiresDn', + 'baseDn' => 'ldapBaseDn', + 'accountCanonicalForm' => 'ldapAccountCanonicalForm', + 'accountDomainName' => 'ldapAccountDomainName', + 'accountDomainNameShort' => 'ldapAccountDomainNameShort', + 'accountFilterFormat' => 'ldapAccountFilterFormat', + 'optReferrals' => 'ldapOptReferrals', + 'tryUsernameSplit' => 'ldapTryUsernameSplit', + 'networkTimeout' => 'ldapNetworkTimeout', + 'createEspoUser' => 'ldapCreateEspoUser', + 'userLoginFilter' => 'ldapUserLoginFilter', + ); - /** - * Permitted Espo Options - * - * @var array - */ - protected $permittedEspoOptions = array( - 'createEspoUser' => false, - 'userLoginFilter' => null, - ); + /** + * Permitted Espo Options + * + * @var array + */ + protected $permittedEspoOptions = array( + 'createEspoUser' => false, + 'userLoginFilter' => null, + ); - /** - * accountCanonicalForm Map between Espo and Zend value - * - * @var array - */ - protected $accountCanonicalFormMap = array( - 'Dn' => 1, - 'Username' => 2, - 'Backslash' => 3, - 'Principal' => 4, - ); + /** + * accountCanonicalForm Map between Espo and Zend value + * + * @var array + */ + protected $accountCanonicalFormMap = array( + 'Dn' => 1, + 'Username' => 2, + 'Backslash' => 3, + 'Principal' => 4, + ); - public function __construct(Config $config) - { - $this->config = $config; - } + public function __construct(Config $config) + { + $this->config = $config; + } - protected function getConfig() - { - return $this->config; - } + protected function getConfig() + { + return $this->config; + } - /** - * Get Options from espo config according to $this->fieldMap - * - * @return array - */ - public function getOptions() - { - if (isset($this->options)) { - return $this->options; - } + /** + * Get Options from espo config according to $this->fieldMap + * + * @return array + */ + public function getOptions() + { + if (isset($this->options)) { + return $this->options; + } - $options = array(); - foreach ($this->fieldMap as $ldapName => $espoName) { + $options = array(); + foreach ($this->fieldMap as $ldapName => $espoName) { - $option = $this->getConfig()->get($espoName); - if (isset($option)) { - $options[$ldapName] = $option; - } - } + $option = $this->getConfig()->get($espoName); + if (isset($option)) { + $options[$ldapName] = $option; + } + } - /** peculiar fields */ - $options['useSsl'] = (bool) ($options['useSsl'] == 'SSL'); - $options['useStartTls'] = (bool) ($options['useStartTls'] == 'TLS'); - $options['accountCanonicalForm'] = $this->accountCanonicalFormMap[ $options['accountCanonicalForm'] ]; + /** peculiar fields */ + $options['useSsl'] = (bool) ($options['useSsl'] == 'SSL'); + $options['useStartTls'] = (bool) ($options['useStartTls'] == 'TLS'); + $options['accountCanonicalForm'] = $this->accountCanonicalFormMap[ $options['accountCanonicalForm'] ]; - $this->options = $options; + $this->options = $options; - return $this->options; - } + return $this->options; + } - /** - * Get an ldap option - * - * @param string $name - * @param mixed $returns Return value - * @return mixed - */ - public function getOption($name, $returns = null) - { - if (isset($this->options)) { - $this->getOptions(); - } + /** + * Get an ldap option + * + * @param string $name + * @param mixed $returns Return value + * @return mixed + */ + public function getOption($name, $returns = null) + { + if (isset($this->options)) { + $this->getOptions(); + } - if (isset($this->options[$name])) { - return $this->options[$name]; - } + if (isset($this->options[$name])) { + return $this->options[$name]; + } - return $returns; - } + return $returns; + } - /** - * Get Zend options for using Zend\Ldap - * - * @return array - */ - public function getZendOptions() - { - $options = $this->getOptions(); - $espoOptions = array_keys($this->permittedEspoOptions); + /** + * Get Zend options for using Zend\Ldap + * + * @return array + */ + public function getZendOptions() + { + $options = $this->getOptions(); + $espoOptions = array_keys($this->permittedEspoOptions); - $zendOptions = array_diff_key($options, array_flip($espoOptions)); + $zendOptions = array_diff_key($options, array_flip($espoOptions)); - return $zendOptions; - } + return $zendOptions; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Config.php b/application/Espo/Core/Utils/Config.php index 09cde9ef46..9d1a18b727 100644 --- a/application/Espo/Core/Utils/Config.php +++ b/application/Espo/Core/Utils/Config.php @@ -24,265 +24,265 @@ namespace Espo\Core\Utils; class Config { - /** - * Path of default config file - * - * @access private - * @var string - */ - private $defaultConfigPath = 'application/Espo/Core/defaults/config.php'; + /** + * Path of default config file + * + * @access private + * @var string + */ + private $defaultConfigPath = 'application/Espo/Core/defaults/config.php'; - private $systemConfigPath = 'application/Espo/Core/defaults/systemConfig.php'; + private $systemConfigPath = 'application/Espo/Core/defaults/systemConfig.php'; - protected $configPath = 'data/config.php'; + protected $configPath = 'data/config.php'; - private $cacheTimestamp = 'cacheTimestamp'; + private $cacheTimestamp = 'cacheTimestamp'; - /** - * Array of admin items - * - * @access protected - * @var array - */ - protected $adminItems = array(); + /** + * Array of admin items + * + * @access protected + * @var array + */ + protected $adminItems = array(); - /** - * Contains content of config - * - * @access private - * @var array - */ - private $data; + /** + * Contains content of config + * + * @access private + * @var array + */ + private $data; - private $changedData = array(); - private $removeData = array(); + private $changedData = array(); + private $removeData = array(); - private $fileManager; + private $fileManager; - public function __construct(\Espo\Core\Utils\File\Manager $fileManager) //TODO - { - $this->fileManager = $fileManager; - } + public function __construct(\Espo\Core\Utils\File\Manager $fileManager) //TODO + { + $this->fileManager = $fileManager; + } - protected function getFileManager() - { - return $this->fileManager; - } + protected function getFileManager() + { + return $this->fileManager; + } - public function getConfigPath() - { - return $this->configPath; - } + public function getConfigPath() + { + return $this->configPath; + } - /** - * Get an option from config - * - * @param string $name - * @param string $default - * @return string | array - */ - public function get($name, $default = null) - { - $keys = explode('.', $name); + /** + * Get an option from config + * + * @param string $name + * @param string $default + * @return string | array + */ + public function get($name, $default = null) + { + $keys = explode('.', $name); - $lastBranch = $this->loadConfig(); - foreach ($keys as $keyName) { - if (isset($lastBranch[$keyName]) && is_array($lastBranch)) { - $lastBranch = $lastBranch[$keyName]; - } else { - return $default; - } - } + $lastBranch = $this->loadConfig(); + foreach ($keys as $keyName) { + if (isset($lastBranch[$keyName]) && is_array($lastBranch)) { + $lastBranch = $lastBranch[$keyName]; + } else { + return $default; + } + } - return $lastBranch; - } + return $lastBranch; + } - /** - * Set an option to the config - * - * @param string $name - * @param string $value - * @return bool - */ - public function set($name, $value = '') - { - if (!is_array($name)) { - $name = array($name => $value); - } + /** + * Set an option to the config + * + * @param string $name + * @param string $value + * @return bool + */ + public function set($name, $value = '') + { + if (!is_array($name)) { + $name = array($name => $value); + } - foreach ($name as $key => $value) { + foreach ($name as $key => $value) { - if (is_object($value)) { - $value = (array) $value; - } + if (is_object($value)) { + $value = (array) $value; + } - $this->data[$key] = $value; - $this->changedData[$key] = $value; - } - } + $this->data[$key] = $value; + $this->changedData[$key] = $value; + } + } - /** - * Remove an option in config - * - * @param string $name - * @return bool | null - null if an option doesn't exist - */ - public function remove($name) - { - if (array_key_exists($name, $this->data)) { - unset($this->data[$name]); - $this->removeData[] = $name; - return true; - } + /** + * Remove an option in config + * + * @param string $name + * @return bool | null - null if an option doesn't exist + */ + public function remove($name) + { + if (array_key_exists($name, $this->data)) { + unset($this->data[$name]); + $this->removeData[] = $name; + return true; + } - return null; - } + return null; + } - public function save() - { - $values = $this->changedData; + public function save() + { + $values = $this->changedData; - if (!isset($values[$this->cacheTimestamp])) { - $values = array_merge($this->updateCacheTimestamp(true), $values); - } + if (!isset($values[$this->cacheTimestamp])) { + $values = array_merge($this->updateCacheTimestamp(true), $values); + } - $removeData = empty($this->removeData) ? null : $this->removeData; + $removeData = empty($this->removeData) ? null : $this->removeData; - $result = $this->getFileManager()->mergeContentsPHP($this->configPath, $values, $removeData); - if ($result) { - $this->changedData = array(); - $this->removeData = array(); - $this->loadConfig(true); - } + $result = $this->getFileManager()->mergeContentsPHP($this->configPath, $values, $removeData); + if ($result) { + $this->changedData = array(); + $this->removeData = array(); + $this->loadConfig(true); + } - return $result; - } + return $result; + } - public function getDefaults() - { - return $this->getFileManager()->getContents($this->defaultConfigPath); - } + public function getDefaults() + { + return $this->getFileManager()->getContents($this->defaultConfigPath); + } - /** - * Return an Object of all configs - * @param boolean $reload - * @return array() - */ - protected function loadConfig($reload = false) - { - if (!$reload && isset($this->data) && !empty($this->data)) { - return $this->data; - } + /** + * Return an Object of all configs + * @param boolean $reload + * @return array() + */ + protected function loadConfig($reload = false) + { + if (!$reload && isset($this->data) && !empty($this->data)) { + return $this->data; + } - $configPath = file_exists($this->configPath) ? $this->configPath : $this->defaultConfigPath; + $configPath = file_exists($this->configPath) ? $this->configPath : $this->defaultConfigPath; - $this->data = $this->getFileManager()->getContents($configPath); + $this->data = $this->getFileManager()->getContents($configPath); - $systemConfig = $this->getFileManager()->getContents($this->systemConfigPath); - $this->data = Util::merge($systemConfig, $this->data); + $systemConfig = $this->getFileManager()->getContents($this->systemConfigPath); + $this->data = Util::merge($systemConfig, $this->data); - return $this->data; - } + return $this->data; + } - /** - * Get config acording to restrictions for a user - * - * @param $isAdmin - * @return array - */ - public function getData($isAdmin = false) - { - $data = $this->loadConfig(); + /** + * Get config acording to restrictions for a user + * + * @param $isAdmin + * @return array + */ + public function getData($isAdmin = false) + { + $data = $this->loadConfig(); - $restrictedConfig = $data; - foreach($this->getRestrictItems($isAdmin) as $name) { - if (isset($restrictedConfig[$name])) { - unset($restrictedConfig[$name]); - } - } + $restrictedConfig = $data; + foreach($this->getRestrictItems($isAdmin) as $name) { + if (isset($restrictedConfig[$name])) { + unset($restrictedConfig[$name]); + } + } - return $restrictedConfig; - } + return $restrictedConfig; + } - /** - * Set JSON data acording to restrictions for a user - * - * @param $isAdmin - * @return bool - */ - public function setData($data, $isAdmin = false) - { - $restrictItems = $this->getRestrictItems($isAdmin); + /** + * Set JSON data acording to restrictions for a user + * + * @param $isAdmin + * @return bool + */ + public function setData($data, $isAdmin = false) + { + $restrictItems = $this->getRestrictItems($isAdmin); - $values = array(); - foreach($data as $key => $item) { - if (!in_array($key, $restrictItems)) { - $values[$key]= $item; - } - } + $values = array(); + foreach($data as $key => $item) { + if (!in_array($key, $restrictItems)) { + $values[$key]= $item; + } + } - return $this->set($values); - } + return $this->set($values); + } - /** - * Update cache timestamp - * - * @param $onlyValue - If need to return just timestamp array - * @return bool | array - */ - public function updateCacheTimestamp($onlyValue = false) - { - $timestamp = array( - $this->cacheTimestamp => time(), - ); + /** + * Update cache timestamp + * + * @param $onlyValue - If need to return just timestamp array + * @return bool | array + */ + public function updateCacheTimestamp($onlyValue = false) + { + $timestamp = array( + $this->cacheTimestamp => time(), + ); - if ($onlyValue) { - return $timestamp; - } + if ($onlyValue) { + return $timestamp; + } - return $this->set($timestamp); - } + return $this->set($timestamp); + } - /** - * Get admin items - * - * @return object - */ - protected function getRestrictItems($onlySystemItems = false) - { - $data = $this->loadConfig(); + /** + * Get admin items + * + * @return object + */ + protected function getRestrictItems($onlySystemItems = false) + { + $data = $this->loadConfig(); - if ($onlySystemItems) { - return $data['systemItems']; - } + if ($onlySystemItems) { + return $data['systemItems']; + } - if (empty($this->adminItems)) { - $this->adminItems= Util::merge($data['systemItems'], $data['adminItems']); - } + if (empty($this->adminItems)) { + $this->adminItems= Util::merge($data['systemItems'], $data['adminItems']); + } - return $this->adminItems; - } + return $this->adminItems; + } - /** - * Check if an item is allowed to get and save - * - * @param $name - * @param $isAdmin - * @return bool - */ - protected function isAllowed($name, $isAdmin = false) - { - if (in_array($name, $this->getRestrictItems($isAdmin))) { - return false; - } + /** + * Check if an item is allowed to get and save + * + * @param $name + * @param $isAdmin + * @return bool + */ + protected function isAllowed($name, $isAdmin = false) + { + if (in_array($name, $this->getRestrictItems($isAdmin))) { + return false; + } - return true; - } + return true; + } } ?> diff --git a/application/Espo/Core/Utils/Crypt.php b/application/Espo/Core/Utils/Crypt.php index f6e070666b..8d4e591232 100644 --- a/application/Espo/Core/Utils/Crypt.php +++ b/application/Espo/Core/Utils/Crypt.php @@ -24,39 +24,39 @@ namespace Espo\Core\Utils; class Crypt { - private $config; - - private $key = null; - - private $cryptKey = null; - - public function __construct($config) - { - $this->config = $config; - $this->cryptKey = $config->get('cryptKey', ''); - } - - protected function getKey() - { - if (empty($this->key)) { - $this->key = hash('sha256', $this->cryptKey, true); - } - return $this->key; - } - - public function encrypt($string) - { - return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->getKey(), $string, MCRYPT_MODE_CBC)); - } - - public function decrypt($encryptedString) - { - return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->getKey(), base64_decode($encryptedString), MCRYPT_MODE_CBC)); - } - - public function generateKey() - { - return md5(uniqid()); - } + private $config; + + private $key = null; + + private $cryptKey = null; + + public function __construct($config) + { + $this->config = $config; + $this->cryptKey = $config->get('cryptKey', ''); + } + + protected function getKey() + { + if (empty($this->key)) { + $this->key = hash('sha256', $this->cryptKey, true); + } + return $this->key; + } + + public function encrypt($string) + { + return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->getKey(), $string, MCRYPT_MODE_CBC)); + } + + public function decrypt($encryptedString) + { + return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->getKey(), base64_decode($encryptedString), MCRYPT_MODE_CBC)); + } + + public function generateKey() + { + return md5(uniqid()); + } } diff --git a/application/Espo/Core/Utils/Database/Converter.php b/application/Espo/Core/Utils/Database/Converter.php index 570ca66d43..a0704d9372 100644 --- a/application/Espo/Core/Utils/Database/Converter.php +++ b/application/Espo/Core/Utils/Database/Converter.php @@ -23,81 +23,81 @@ namespace Espo\Core\Utils\Database; use Espo\Core\Utils\Util, - Espo\ORM\Entity; + Espo\ORM\Entity; class Converter { - private $metadata; + private $metadata; - private $fileManager; + private $fileManager; - private $schemaConverter; + private $schemaConverter; - private $schemaFromMetadata = null; + private $schemaFromMetadata = null; - /** - * @var array $meta - metadata array - */ - //private $meta; + /** + * @var array $meta - metadata array + */ + //private $meta; - public function __construct(\Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\File\Manager $fileManager) - { - $this->metadata = $metadata; - $this->fileManager = $fileManager; + public function __construct(\Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\File\Manager $fileManager) + { + $this->metadata = $metadata; + $this->fileManager = $fileManager; - $this->ormConverter = new Orm\Converter($this->metadata, $this->fileManager); + $this->ormConverter = new Orm\Converter($this->metadata, $this->fileManager); - $this->schemaConverter = new Schema\Converter($this->fileManager); - } + $this->schemaConverter = new Schema\Converter($this->fileManager); + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - protected function getOrmConverter() - { - return $this->ormConverter; - } + protected function getOrmConverter() + { + return $this->ormConverter; + } - protected function getSchemaConverter() - { - return $this->schemaConverter; - } + protected function getSchemaConverter() + { + return $this->schemaConverter; + } - public function getSchemaFromMetadata($entityList = null) - { - $ormMeta = $this->getMetadata()->getOrmMetadata(); - $entityDefs = $this->getMetadata()->get('entityDefs'); + public function getSchemaFromMetadata($entityList = null) + { + $ormMeta = $this->getMetadata()->getOrmMetadata(); + $entityDefs = $this->getMetadata()->get('entityDefs'); - $this->schemaFromMetadata = $this->getSchemaConverter()->process($ormMeta, $entityDefs, $entityList); + $this->schemaFromMetadata = $this->getSchemaConverter()->process($ormMeta, $entityDefs, $entityList); - return $this->schemaFromMetadata; - } + return $this->schemaFromMetadata; + } - /** - * Main method of convertation from metadata to orm metadata and database schema - * - * @return bool - */ - public function process() - { - $GLOBALS['log']->debug('Orm\Converter - Start: orm convertation'); + /** + * Main method of convertation from metadata to orm metadata and database schema + * + * @return bool + */ + public function process() + { + $GLOBALS['log']->debug('Orm\Converter - Start: orm convertation'); - $ormMeta = $this->getOrmConverter()->process(); + $ormMeta = $this->getOrmConverter()->process(); - //save database meta to a file espoMetadata.php - $result = $this->getMetadata()->setOrmMetadata($ormMeta); + //save database meta to a file espoMetadata.php + $result = $this->getMetadata()->setOrmMetadata($ormMeta); - $GLOBALS['log']->debug('Orm\Converter - End: orm convertation, result=['.$result.']'); + $GLOBALS['log']->debug('Orm\Converter - End: orm convertation, result=['.$result.']'); - return $result; - } + return $result; + } diff --git a/application/Espo/Core/Utils/Database/DBAL/Driver/Mysqli/Driver.php b/application/Espo/Core/Utils/Database/DBAL/Driver/Mysqli/Driver.php index f7be7e83c8..15a66152b5 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Driver/Mysqli/Driver.php +++ b/application/Espo/Core/Utils/Database/DBAL/Driver/Mysqli/Driver.php @@ -25,7 +25,7 @@ namespace Espo\Core\Utils\Database\DBAL\Driver\Mysqli; class Driver extends \Doctrine\DBAL\Driver\Mysqli\Driver { - public function getDatabasePlatform() + public function getDatabasePlatform() { return new \Espo\Core\Utils\Database\DBAL\Platforms\MySqlPlatform(); } diff --git a/application/Espo/Core/Utils/Database/DBAL/Driver/PDOMySql/Driver.php b/application/Espo/Core/Utils/Database/DBAL/Driver/PDOMySql/Driver.php index db6f43b00b..11e5887e7b 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Driver/PDOMySql/Driver.php +++ b/application/Espo/Core/Utils/Database/DBAL/Driver/PDOMySql/Driver.php @@ -25,7 +25,7 @@ namespace Espo\Core\Utils\Database\DBAL\Driver\PDOMySql; class Driver extends \Doctrine\DBAL\Driver\PDOMySql\Driver { - public function getDatabasePlatform() + public function getDatabasePlatform() { return new \Espo\Core\Utils\Database\DBAL\Platforms\MySqlPlatform(); } diff --git a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Bool.php b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Bool.php index c6dce4d685..d43063b9c2 100644 --- a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Bool.php +++ b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Bool.php @@ -26,15 +26,15 @@ use Doctrine\DBAL\Types\BooleanType; class Bool extends BooleanType { - const BOOL = 'bool'; + const BOOL = 'bool'; - public function getName() + public function getName() { return self::BOOL; } - public static function getDbTypeName() - { - return 'TINYINT'; - } + public static function getDbTypeName() + { + return 'TINYINT'; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Int.php b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Int.php index 0c0c688af0..5f3c06a03e 100644 --- a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Int.php +++ b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Int.php @@ -26,7 +26,7 @@ use Doctrine\DBAL\Types\IntegerType; class Int extends IntegerType { - const INTtype = 'int'; + const INTtype = 'int'; public function getName() { diff --git a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonArray.php b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonArray.php index cd822e27a0..2651398edc 100644 --- a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonArray.php +++ b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonArray.php @@ -24,16 +24,16 @@ namespace Espo\Core\Utils\Database\DBAL\FieldTypes; class JsonArray extends \Doctrine\DBAL\Types\JsonArrayType { - const JSON_ARRAY = 'jsonArray'; + const JSON_ARRAY = 'jsonArray'; - public function getName() - { - return self::JSON_ARRAY; - } + public function getName() + { + return self::JSON_ARRAY; + } - public static function getDbTypeName() - { - return 'TEXT'; - } + public static function getDbTypeName() + { + return 'TEXT'; + } } diff --git a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonObject.php b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonObject.php index f2f4f756ff..5d6382aef1 100644 --- a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonObject.php +++ b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/JsonObject.php @@ -24,16 +24,16 @@ namespace Espo\Core\Utils\Database\DBAL\FieldTypes; class JsonObject extends \Doctrine\DBAL\Types\ObjectType { - const JSON_OBJECT = 'jsonObject'; + const JSON_OBJECT = 'jsonObject'; - public function getName() - { - return self::JSON_OBJECT; - } + public function getName() + { + return self::JSON_OBJECT; + } - public static function getDbTypeName() - { - return 'TEXT'; - } + public static function getDbTypeName() + { + return 'TEXT'; + } } diff --git a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Password.php b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Password.php index 5d408dfec6..aaf6fcbfeb 100644 --- a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Password.php +++ b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Password.php @@ -28,14 +28,14 @@ class Password extends StringType { const PASSWORD = 'password'; - public function getName() + public function getName() { return self::PASSWORD; } - public static function getDbTypeName() - { - return 'VARCHAR'; - } + public static function getDbTypeName() + { + return 'VARCHAR'; + } } diff --git a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Varchar.php b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Varchar.php index 77910cc1e3..e3ed0f7ff2 100644 --- a/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Varchar.php +++ b/application/Espo/Core/Utils/Database/DBAL/FieldTypes/Varchar.php @@ -26,9 +26,9 @@ use Doctrine\DBAL\Types\StringType; class Varchar extends StringType { - const VARCHAR = 'varchar'; + const VARCHAR = 'varchar'; - public function getName() + public function getName() { return self::VARCHAR; } diff --git a/application/Espo/Core/Utils/Database/DBAL/Platforms/MySqlPlatform.php b/application/Espo/Core/Utils/Database/DBAL/Platforms/MySqlPlatform.php index 8b2947825f..0c92c2beb2 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Platforms/MySqlPlatform.php +++ b/application/Espo/Core/Utils/Database/DBAL/Platforms/MySqlPlatform.php @@ -23,252 +23,252 @@ namespace Espo\Core\Utils\Database\DBAL\Platforms; use Doctrine\DBAL\Schema\TableDiff, - Doctrine\DBAL\Schema\Index, - Doctrine\DBAL\Schema\Table, - Doctrine\DBAL\Schema\Constraint, - Doctrine\DBAL\Schema\ForeignKeyConstraint; + Doctrine\DBAL\Schema\Index, + Doctrine\DBAL\Schema\Table, + Doctrine\DBAL\Schema\Constraint, + Doctrine\DBAL\Schema\ForeignKeyConstraint; class MySqlPlatform extends \Doctrine\DBAL\Platforms\MySqlPlatform { - public function getAlterTableSQL(TableDiff $diff) - { - $columnSql = array(); - $queryParts = array(); - if ($diff->newName !== false) { - $queryParts[] = 'RENAME TO ' . $diff->newName; - } + public function getAlterTableSQL(TableDiff $diff) + { + $columnSql = array(); + $queryParts = array(); + if ($diff->newName !== false) { + $queryParts[] = 'RENAME TO ' . $diff->newName; + } - foreach ($diff->addedColumns as $column) { - if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { - continue; - } + foreach ($diff->addedColumns as $column) { + if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { + continue; + } - $columnArray = $column->toArray(); - $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); - } + $columnArray = $column->toArray(); + $columnArray['comment'] = $this->getColumnComment($column); + $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); + } - foreach ($diff->removedColumns as $column) { - if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) { - continue; - } + foreach ($diff->removedColumns as $column) { + if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) { + continue; + } - //$queryParts[] = 'DROP ' . $column->getQuotedName($this); //espo: no needs to remove columns - } + //$queryParts[] = 'DROP ' . $column->getQuotedName($this); //espo: no needs to remove columns + } - foreach ($diff->changedColumns as $columnDiff) { - if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) { - continue; - } + foreach ($diff->changedColumns as $columnDiff) { + if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) { + continue; + } - /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ - $column = $columnDiff->column; - $columnArray = $column->toArray(); - $columnArray['comment'] = $this->getColumnComment($column); + /* @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ + $column = $columnDiff->column; + $columnArray = $column->toArray(); + $columnArray['comment'] = $this->getColumnComment($column); - $queryParts[] = 'CHANGE ' . $this->espoQuote($columnDiff->oldColumnName) . ' ' - . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); - } + $queryParts[] = 'CHANGE ' . $this->espoQuote($columnDiff->oldColumnName) . ' ' + . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); + } - //espo: It works not correctly. It can rename some existing fields - foreach ($diff->renamedColumns as $oldColumnName => $column) { - if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) { - continue; - } + //espo: It works not correctly. It can rename some existing fields + foreach ($diff->renamedColumns as $oldColumnName => $column) { + if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) { + continue; + } - $columnArray = $column->toArray(); - $columnArray['comment'] = $this->getColumnComment($column); - /*$queryParts[] = 'CHANGE ' . $oldColumnName . ' ' - . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); */ - $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); //espo: fixed the problem - } //espo: END + $columnArray = $column->toArray(); + $columnArray['comment'] = $this->getColumnComment($column); + /*$queryParts[] = 'CHANGE ' . $oldColumnName . ' ' + . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); */ + $queryParts[] = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray); //espo: fixed the problem + } //espo: END - $sql = array(); - $tableSql = array(); + $sql = array(); + $tableSql = array(); - if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { - if (count($queryParts) > 0) { - $sql[] = 'ALTER TABLE ' . $this->espoQuote($diff->name) . ' ' . implode(", ", $queryParts); - } - $sql = array_merge( - $this->getPreAlterTableIndexForeignKeySQL($diff), - $sql, - $this->getPostAlterTableIndexForeignKeySQL($diff) - ); - } + if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { + if (count($queryParts) > 0) { + $sql[] = 'ALTER TABLE ' . $this->espoQuote($diff->name) . ' ' . implode(", ", $queryParts); + } + $sql = array_merge( + $this->getPreAlterTableIndexForeignKeySQL($diff), + $sql, + $this->getPostAlterTableIndexForeignKeySQL($diff) + ); + } - return array_merge($sql, $tableSql, $columnSql); - } + return array_merge($sql, $tableSql, $columnSql); + } - protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) - { - $sql = array(); - $table = $diff->name; + protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) + { + $sql = array(); + $table = $diff->name; - foreach ($diff->removedIndexes as $remKey => $remIndex) { + foreach ($diff->removedIndexes as $remKey => $remIndex) { - foreach ($diff->addedIndexes as $addKey => $addIndex) { - if ($remIndex->getColumns() == $addIndex->getColumns()) { + foreach ($diff->addedIndexes as $addKey => $addIndex) { + if ($remIndex->getColumns() == $addIndex->getColumns()) { - $type = ''; - if ($addIndex->isUnique()) { - $type = 'UNIQUE '; - } + $type = ''; + if ($addIndex->isUnique()) { + $type = 'UNIQUE '; + } - $query = 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP INDEX ' . $remIndex->getName() . ', '; - $query .= 'ADD ' . $type . 'INDEX ' . $addIndex->getName(); - $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')'; + $query = 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP INDEX ' . $remIndex->getName() . ', '; + $query .= 'ADD ' . $type . 'INDEX ' . $addIndex->getName(); + $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex->getQuotedColumns($this)) . ')'; - $sql[] = $query; + $sql[] = $query; - unset($diff->removedIndexes[$remKey]); - unset($diff->addedIndexes[$addKey]); + unset($diff->removedIndexes[$remKey]); + unset($diff->addedIndexes[$addKey]); - break; - } - } - } + break; + } + } + } - $sql = array_merge($sql, parent::getPreAlterTableIndexForeignKeySQL($diff)); + $sql = array_merge($sql, parent::getPreAlterTableIndexForeignKeySQL($diff)); - return $sql; - } + return $sql; + } - public function getDropIndexSQL($index, $table=null) - { - if ($index instanceof Index) { - $indexName = $index->getQuotedName($this); - } else if(is_string($index)) { - $indexName = $index; - } else { - throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); - } + public function getDropIndexSQL($index, $table=null) + { + if ($index instanceof Index) { + $indexName = $index->getQuotedName($this); + } else if(is_string($index)) { + $indexName = $index; + } else { + throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.'); + } - if ($table instanceof Table) { - $table = $table->getQuotedName($this); - } else if(!is_string($table)) { - throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); - } + if ($table instanceof Table) { + $table = $table->getQuotedName($this); + } else if(!is_string($table)) { + throw new \InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } - if ($index instanceof Index && $index->isPrimary()) { - // mysql primary keys are always named "PRIMARY", - // so we cannot use them in statements because of them being keyword. - return $this->getDropPrimaryKeySQL($table); - } + if ($index instanceof Index && $index->isPrimary()) { + // mysql primary keys are always named "PRIMARY", + // so we cannot use them in statements because of them being keyword. + return $this->getDropPrimaryKeySQL($table); + } - return 'DROP INDEX ' . $indexName . ' ON ' . $this->espoQuote($table); - } + return 'DROP INDEX ' . $indexName . ' ON ' . $this->espoQuote($table); + } - protected function getDropPrimaryKeySQL($table) - { - return 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP PRIMARY KEY'; - } + protected function getDropPrimaryKeySQL($table) + { + return 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP PRIMARY KEY'; + } - public function getDropTemporaryTableSQL($table) - { - if ($table instanceof Table) { - $table = $table->getQuotedName($this); - } else if(!is_string($table)) { - throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); - } + public function getDropTemporaryTableSQL($table) + { + if ($table instanceof Table) { + $table = $table->getQuotedName($this); + } else if(!is_string($table)) { + throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.'); + } - return 'DROP TEMPORARY TABLE ' . $this->espoQuote($table); - } + return 'DROP TEMPORARY TABLE ' . $this->espoQuote($table); + } - //ESPO: fix problem with quoting table name - public function espoQuote($name) - { - if ($name instanceof Table) { - $name = $name->getQuotedName($this); - } + //ESPO: fix problem with quoting table name + public function espoQuote($name) + { + if ($name instanceof Table) { + $name = $name->getQuotedName($this); + } - if (isset($name[0]) && $name[0] != '`') { - $name = $this->quoteIdentifier($name); - } - return $name; - } + if (isset($name[0]) && $name[0] != '`') { + $name = $this->quoteIdentifier($name); + } + return $name; + } - public function getCreateForeignKeySQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey, $table) - { - $query = 'ALTER TABLE ' . $this->espoQuote($table) . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey); + public function getCreateForeignKeySQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey, $table) + { + $query = 'ALTER TABLE ' . $this->espoQuote($table) . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey); - return $query; - } + return $query; + } - public function getIndexDeclarationSQL($name, Index $index) - { - $columns = $index->getQuotedColumns($this); + public function getIndexDeclarationSQL($name, Index $index) + { + $columns = $index->getQuotedColumns($this); - if (count($columns) === 0) { - throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); - } + if (count($columns) === 0) { + throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); + } - return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $this->espoQuote($name) . ' (' - . $this->getIndexFieldDeclarationListSQL($columns) - . ')'; - } + return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $this->espoQuote($name) . ' (' + . $this->getIndexFieldDeclarationListSQL($columns) + . ')'; + } - public function getCreateIndexSQL(Index $index, $table) - { - if ($table instanceof Table) { - $table = $table->getQuotedName($this); - } - $name = $index->getQuotedName($this); - $columns = $index->getQuotedColumns($this); + public function getCreateIndexSQL(Index $index, $table) + { + if ($table instanceof Table) { + $table = $table->getQuotedName($this); + } + $name = $index->getQuotedName($this); + $columns = $index->getQuotedColumns($this); - if (count($columns) == 0) { - throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); - } + if (count($columns) == 0) { + throw new \InvalidArgumentException("Incomplete definition. 'columns' required."); + } - if ($index->isPrimary()) { - return $this->getCreatePrimaryKeySQL($index, $table); - } + if ($index->isPrimary()) { + return $this->getCreatePrimaryKeySQL($index, $table); + } - $query = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $this->espoQuote($table); - $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')'; + $query = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $this->espoQuote($table); + $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')'; - return $query; - } + return $query; + } - public function getDropConstraintSQL($constraint, $table) - { - if ($constraint instanceof Constraint) { - $constraint = $constraint->getQuotedName($this); - } + public function getDropConstraintSQL($constraint, $table) + { + if ($constraint instanceof Constraint) { + $constraint = $constraint->getQuotedName($this); + } - if ($table instanceof Table) { - $table = $table->getQuotedName($this); - } + if ($table instanceof Table) { + $table = $table->getQuotedName($this); + } - return 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP CONSTRAINT ' . $constraint; - } + return 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP CONSTRAINT ' . $constraint; + } - public function getDropForeignKeySQL($foreignKey, $table) - { - if ($foreignKey instanceof ForeignKeyConstraint) { - $foreignKey = $foreignKey->getQuotedName($this); - } + public function getDropForeignKeySQL($foreignKey, $table) + { + if ($foreignKey instanceof ForeignKeyConstraint) { + $foreignKey = $foreignKey->getQuotedName($this); + } - if ($table instanceof Table) { - $table = $table->getQuotedName($this); - } + if ($table instanceof Table) { + $table = $table->getQuotedName($this); + } - return 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP FOREIGN KEY ' . $foreignKey; - } + return 'ALTER TABLE ' . $this->espoQuote($table) . ' DROP FOREIGN KEY ' . $foreignKey; + } - public function getCreatePrimaryKeySQL(Index $index, $table) - { - if ($table instanceof Table) { - $table = $table->getQuotedName($this); - } + public function getCreatePrimaryKeySQL(Index $index, $table) + { + if ($table instanceof Table) { + $table = $table->getQuotedName($this); + } - return 'ALTER TABLE ' . $this->espoQuote($table) . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')'; - } - //end: ESPO + return 'ALTER TABLE ' . $this->espoQuote($table) . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index->getQuotedColumns($this)) . ')'; + } + //end: ESPO } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/DBAL/Schema/Column.php b/application/Espo/Core/Utils/Database/DBAL/Schema/Column.php index ceb0e9aa97..afabc89dbd 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Schema/Column.php +++ b/application/Espo/Core/Utils/Database/DBAL/Schema/Column.php @@ -26,57 +26,57 @@ namespace Espo\Core\Utils\Database\DBAL\Schema; class Column extends \Doctrine\DBAL\Schema\Column { - /** - * @var boolean - */ - protected $_notnull = false; + /** + * @var boolean + */ + protected $_notnull = false; - /** - * @var boolean - */ - protected $_unique = false; + /** + * @var boolean + */ + protected $_unique = false; - /** - * @param boolean $unique - * - * @return \Doctrine\DBAL\Schema\Column - */ - public function setUnique($unique) - { - $this->_unique = (bool)$unique; + /** + * @param boolean $unique + * + * @return \Doctrine\DBAL\Schema\Column + */ + public function setUnique($unique) + { + $this->_unique = (bool)$unique; - return $this; - } + return $this; + } - /** - * @return boolean - */ - public function getUnique() - { - return $this->_unique; - } + /** + * @return boolean + */ + public function getUnique() + { + return $this->_unique; + } - /** - * @return array - */ - public function toArray() - { - return array_merge(array( - 'name' => $this->_name, - 'type' => $this->_type, - 'default' => $this->_default, - 'notnull' => $this->_notnull, - 'length' => $this->_length, - 'precision' => $this->_precision, - 'scale' => $this->_scale, - 'fixed' => $this->_fixed, - 'unsigned' => $this->_unsigned, - 'autoincrement' => $this->_autoincrement, - 'unique' => $this->_unique, - 'columnDefinition' => $this->_columnDefinition, - 'comment' => $this->_comment, - ), $this->_platformOptions, $this->_customSchemaOptions); - } + /** + * @return array + */ + public function toArray() + { + return array_merge(array( + 'name' => $this->_name, + 'type' => $this->_type, + 'default' => $this->_default, + 'notnull' => $this->_notnull, + 'length' => $this->_length, + 'precision' => $this->_precision, + 'scale' => $this->_scale, + 'fixed' => $this->_fixed, + 'unsigned' => $this->_unsigned, + 'autoincrement' => $this->_autoincrement, + 'unique' => $this->_unique, + 'columnDefinition' => $this->_columnDefinition, + 'comment' => $this->_comment, + ), $this->_platformOptions, $this->_customSchemaOptions); + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/DBAL/Schema/Comparator.php b/application/Espo/Core/Utils/Database/DBAL/Schema/Comparator.php index 4e9ee27a37..407901aac6 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Schema/Comparator.php +++ b/application/Espo/Core/Utils/Database/DBAL/Schema/Comparator.php @@ -28,86 +28,86 @@ use Doctrine\DBAL\Schema\Column; class Comparator extends \Doctrine\DBAL\Schema\Comparator { - public function diffColumn(Column $column1, Column $column2) - { - $changedProperties = array(); - if ( $column1->getType() != $column2->getType() ) { + public function diffColumn(Column $column1, Column $column2) + { + $changedProperties = array(); + if ( $column1->getType() != $column2->getType() ) { - //espo: fix problem with executing query for custom types - $column1DbTypeName = method_exists($column1->getType(), 'getDbTypeName') ? $column1->getType()->getDbTypeName() : $column1->getType()->getName(); - $column2DbTypeName = method_exists($column2->getType(), 'getDbTypeName') ? $column2->getType()->getDbTypeName() : $column2->getType()->getName(); + //espo: fix problem with executing query for custom types + $column1DbTypeName = method_exists($column1->getType(), 'getDbTypeName') ? $column1->getType()->getDbTypeName() : $column1->getType()->getName(); + $column2DbTypeName = method_exists($column2->getType(), 'getDbTypeName') ? $column2->getType()->getDbTypeName() : $column2->getType()->getName(); - if (strtolower($column1DbTypeName) != strtolower($column2DbTypeName)) { - $changedProperties[] = 'type'; - } - //END: espo - } + if (strtolower($column1DbTypeName) != strtolower($column2DbTypeName)) { + $changedProperties[] = 'type'; + } + //END: espo + } - if ($column1->getNotnull() != $column2->getNotnull()) { - $changedProperties[] = 'notnull'; - } + if ($column1->getNotnull() != $column2->getNotnull()) { + $changedProperties[] = 'notnull'; + } - if ($column1->getDefault() != $column2->getDefault()) { - $changedProperties[] = 'default'; - } + if ($column1->getDefault() != $column2->getDefault()) { + $changedProperties[] = 'default'; + } - if ($column1->getUnsigned() != $column2->getUnsigned()) { - $changedProperties[] = 'unsigned'; - } + if ($column1->getUnsigned() != $column2->getUnsigned()) { + $changedProperties[] = 'unsigned'; + } - if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) { - // check if value of length is set at all, default value assumed otherwise. - $length1 = $column1->getLength() ?: 255; - $length2 = $column2->getLength() ?: 255; + if ($column1->getType() instanceof \Doctrine\DBAL\Types\StringType) { + // check if value of length is set at all, default value assumed otherwise. + $length1 = $column1->getLength() ?: 255; + $length2 = $column2->getLength() ?: 255; - /** Espo: column length can be increased only */ - /*if ($length1 != $length2) { - $changedProperties[] = 'length'; - }*/ - if ($length2 > $length1) { - $changedProperties[] = 'length'; - } - /** Espo: end */ + /** Espo: column length can be increased only */ + /*if ($length1 != $length2) { + $changedProperties[] = 'length'; + }*/ + if ($length2 > $length1) { + $changedProperties[] = 'length'; + } + /** Espo: end */ - if ($column1->getFixed() != $column2->getFixed()) { - $changedProperties[] = 'fixed'; - } - } + if ($column1->getFixed() != $column2->getFixed()) { + $changedProperties[] = 'fixed'; + } + } - if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) { - if (($column1->getPrecision()?:10) != ($column2->getPrecision()?:10)) { - $changedProperties[] = 'precision'; - } - if ($column1->getScale() != $column2->getScale()) { - $changedProperties[] = 'scale'; - } - } + if ($column1->getType() instanceof \Doctrine\DBAL\Types\DecimalType) { + if (($column1->getPrecision()?:10) != ($column2->getPrecision()?:10)) { + $changedProperties[] = 'precision'; + } + if ($column1->getScale() != $column2->getScale()) { + $changedProperties[] = 'scale'; + } + } - if ($column1->getAutoincrement() != $column2->getAutoincrement()) { - $changedProperties[] = 'autoincrement'; - } + if ($column1->getAutoincrement() != $column2->getAutoincrement()) { + $changedProperties[] = 'autoincrement'; + } - // only allow to delete comment if its set to '' not to null. - if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) { - $changedProperties[] = 'comment'; - } + // only allow to delete comment if its set to '' not to null. + if ($column1->getComment() !== null && $column1->getComment() != $column2->getComment()) { + $changedProperties[] = 'comment'; + } - $options1 = $column1->getCustomSchemaOptions(); - $options2 = $column2->getCustomSchemaOptions(); + $options1 = $column1->getCustomSchemaOptions(); + $options2 = $column2->getCustomSchemaOptions(); - $commonKeys = array_keys(array_intersect_key($options1, $options2)); + $commonKeys = array_keys(array_intersect_key($options1, $options2)); - foreach ($commonKeys as $key) { - if ($options1[$key] !== $options2[$key]) { - $changedProperties[] = $key; - } - } + foreach ($commonKeys as $key) { + if ($options1[$key] !== $options2[$key]) { + $changedProperties[] = $key; + } + } - $diffKeys = array_keys(array_diff_key($options1, $options2) + array_diff_key($options2, $options1)); + $diffKeys = array_keys(array_diff_key($options1, $options2) + array_diff_key($options2, $options1)); - $changedProperties = array_merge($changedProperties, $diffKeys); + $changedProperties = array_merge($changedProperties, $diffKeys); - return $changedProperties; - } + return $changedProperties; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/DBAL/Schema/Schema.php b/application/Espo/Core/Utils/Database/DBAL/Schema/Schema.php index 6cde05516d..d370412579 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Schema/Schema.php +++ b/application/Espo/Core/Utils/Database/DBAL/Schema/Schema.php @@ -25,23 +25,23 @@ namespace Espo\Core\Utils\Database\DBAL\Schema; class Schema extends \Doctrine\DBAL\Schema\Schema { - /** - * Creates a new table. - * - * @param string $tableName - * - * @return \Doctrine\DBAL\Schema\Table - */ - public function createTable($tableName) - { - $table = new Table($tableName); - $this->_addTable($table); + /** + * Creates a new table. + * + * @param string $tableName + * + * @return \Doctrine\DBAL\Schema\Table + */ + public function createTable($tableName) + { + $table = new Table($tableName); + $this->_addTable($table); - foreach ($this->_schemaConfig->getDefaultTableOptions() as $name => $value) { - $table->addOption($name, $value); - } + foreach ($this->_schemaConfig->getDefaultTableOptions() as $name => $value) { + $table->addOption($name, $value); + } - return $table; - } + return $table; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/DBAL/Schema/Table.php b/application/Espo/Core/Utils/Database/DBAL/Schema/Table.php index c6c82b1a93..d9b28b5a0b 100644 --- a/application/Espo/Core/Utils/Database/DBAL/Schema/Table.php +++ b/application/Espo/Core/Utils/Database/DBAL/Schema/Table.php @@ -27,20 +27,20 @@ use Doctrine\DBAL\Types\Type; class Table extends \Doctrine\DBAL\Schema\Table { - /** - * @param string $columnName - * @param string $typeName - * @param array $options - * - * @return \Doctrine\DBAL\Schema\Column - */ - public function addColumn($columnName, $typeName, array $options=array()) - { - $column = new Column($columnName, Type::getType($typeName), $options); + /** + * @param string $columnName + * @param string $typeName + * @param array $options + * + * @return \Doctrine\DBAL\Schema\Column + */ + public function addColumn($columnName, $typeName, array $options=array()) + { + $column = new Column($columnName, Type::getType($typeName), $options); - $this->_addColumn($column); + $this->_addColumn($column); - return $column; - } + return $column; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Base.php b/application/Espo/Core/Utils/Database/Orm/Base.php index fae05139fe..5733e75360 100644 --- a/application/Espo/Core/Utils/Database/Orm/Base.php +++ b/application/Espo/Core/Utils/Database/Orm/Base.php @@ -26,245 +26,245 @@ use Espo\Core\Utils\Util; class Base { - private $itemName = null; + private $itemName = null; - private $entityName = null; + private $entityName = null; - private $metadata; + private $metadata; - private $ormEntityDefs; + private $ormEntityDefs; - private $entityDefs; + private $entityDefs; - public function __construct(\Espo\Core\Utils\Metadata $metadata, array $ormEntityDefs, array $entityDefs) - { - $this->metadata = $metadata; - $this->ormEntityDefs = $ormEntityDefs; - $this->entityDefs = $entityDefs; - } + public function __construct(\Espo\Core\Utils\Metadata $metadata, array $ormEntityDefs, array $entityDefs) + { + $this->metadata = $metadata; + $this->ormEntityDefs = $ormEntityDefs; + $this->entityDefs = $entityDefs; + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - protected function getOrmEntityDefs() - { - return $this->ormEntityDefs; - } + protected function getOrmEntityDefs() + { + return $this->ormEntityDefs; + } - protected function getEntityDefs() - { - return $this->entityDefs; - } + protected function getEntityDefs() + { + return $this->entityDefs; + } - /** - * Set current Field name OR Link name - * - * @param void - */ - protected function setItemName($itemName) - { - $this->itemName = $itemName; - } + /** + * Set current Field name OR Link name + * + * @param void + */ + protected function setItemName($itemName) + { + $this->itemName = $itemName; + } - /** - * Get current Field name - * - * @return string - */ - protected function getFieldName() - { - return $this->itemName; - } + /** + * Get current Field name + * + * @return string + */ + protected function getFieldName() + { + return $this->itemName; + } - /** - * Get current Link name - * - * @return string - */ - protected function getLinkName() - { - return $this->itemName; - } + /** + * Get current Link name + * + * @return string + */ + protected function getLinkName() + { + return $this->itemName; + } - /** - * Set current Entity Name - * - * @param void - */ - protected function setEntityName($entityName) - { - $this->entityName = $entityName; - } + /** + * Set current Entity Name + * + * @param void + */ + protected function setEntityName($entityName) + { + $this->entityName = $entityName; + } - /** - * Get current Entity Name - * - * @return string - */ - protected function getEntityName() - { - return $this->entityName; - } + /** + * Get current Entity Name + * + * @return string + */ + protected function getEntityName() + { + return $this->entityName; + } - protected function setMethods(array $keyValueList) - { - foreach ($keyValueList as $key => $value) { - $methodName = 'set' . ucfirst($key); - if (method_exists($this, $methodName)) { - $this->$methodName($value); - } - } - } + protected function setMethods(array $keyValueList) + { + foreach ($keyValueList as $key => $value) { + $methodName = 'set' . ucfirst($key); + if (method_exists($this, $methodName)) { + $this->$methodName($value); + } + } + } - /** - * Start process Orm converting for fields/relations - * - * @param string $itemName Field name OR Link name - * @param string $entityName - * @return array - */ - public function process($itemName, $entityName) - { - $inputs = array( - 'itemName' => $itemName, - 'entityName' => $entityName, - ); - $this->setMethods($inputs); + /** + * Start process Orm converting for fields/relations + * + * @param string $itemName Field name OR Link name + * @param string $entityName + * @return array + */ + public function process($itemName, $entityName) + { + $inputs = array( + 'itemName' => $itemName, + 'entityName' => $entityName, + ); + $this->setMethods($inputs); - $convertedDefs = $this->load($itemName, $entityName); + $convertedDefs = $this->load($itemName, $entityName); - $inputs = $this->setArrayValue(null, $inputs); - $this->setMethods($inputs); + $inputs = $this->setArrayValue(null, $inputs); + $this->setMethods($inputs); - return $convertedDefs; - } + return $convertedDefs; + } - /** - * Get Entity Defs by type (entity/orm) - * - * @param boolean $isOrmEntityDefs - * @return array - */ - protected function getDefs($isOrmEntityDefs = false) - { - $entityDefs = $isOrmEntityDefs ? $this->getOrmEntityDefs() : $this->getEntityDefs(); + /** + * Get Entity Defs by type (entity/orm) + * + * @param boolean $isOrmEntityDefs + * @return array + */ + protected function getDefs($isOrmEntityDefs = false) + { + $entityDefs = $isOrmEntityDefs ? $this->getOrmEntityDefs() : $this->getEntityDefs(); - return $entityDefs; - } + return $entityDefs; + } - /** - * Get entity params by name - * - * @param string $entityName - * @param bool $isOrmEntityDefs - * @param mixed $returns - * @return mixed - */ - protected function getEntityParams($entityName = null, $isOrmEntityDefs = false, $returns = null) - { - if (!isset($entityName)) { - $entityName = $this->getEntityName(); - } + /** + * Get entity params by name + * + * @param string $entityName + * @param bool $isOrmEntityDefs + * @param mixed $returns + * @return mixed + */ + protected function getEntityParams($entityName = null, $isOrmEntityDefs = false, $returns = null) + { + if (!isset($entityName)) { + $entityName = $this->getEntityName(); + } - $entityDefs = $this->getDefs($isOrmEntityDefs); + $entityDefs = $this->getDefs($isOrmEntityDefs); - if (isset($entityDefs[$entityName])) { - return $entityDefs[$entityName]; - } + if (isset($entityDefs[$entityName])) { + return $entityDefs[$entityName]; + } - return $returns; - } + return $returns; + } - /** - * Get field params by name for a specified entity - * - * @param string $fieldName - * @param string $entityName - * @param bool $isOrmEntityDefs - * @param mixed $returns - * @return mixed - */ - protected function getFieldParams($fieldName = null, $entityName = null, $isOrmEntityDefs = false, $returns = null) - { - if (!isset($fieldName)) { - $fieldName = $this->getFieldName(); - } - if (!isset($entityName)) { - $entityName = $this->getEntityName(); - } + /** + * Get field params by name for a specified entity + * + * @param string $fieldName + * @param string $entityName + * @param bool $isOrmEntityDefs + * @param mixed $returns + * @return mixed + */ + protected function getFieldParams($fieldName = null, $entityName = null, $isOrmEntityDefs = false, $returns = null) + { + if (!isset($fieldName)) { + $fieldName = $this->getFieldName(); + } + if (!isset($entityName)) { + $entityName = $this->getEntityName(); + } - $entityDefs = $this->getDefs($isOrmEntityDefs); + $entityDefs = $this->getDefs($isOrmEntityDefs); - if (isset($entityDefs[$entityName]) && isset($entityDefs[$entityName]['fields'][$fieldName])) { - return $entityDefs[$entityName]['fields'][$fieldName]; - } + if (isset($entityDefs[$entityName]) && isset($entityDefs[$entityName]['fields'][$fieldName])) { + return $entityDefs[$entityName]['fields'][$fieldName]; + } - return $returns; - } + return $returns; + } - /** - * Get relation params by name for a specified entity - * - * @param string $linkName - * @param string $entityName - * @param bool $isOrmEntityDefs - * @param mixed $returns - * @return mixed - */ - protected function getLinkParams($linkName = null, $entityName = null, $isOrmEntityDefs = false, $returns = null) - { - if (!isset($linkName)) { - $linkName = $this->getLinkName(); - } - if (!isset($entityName)) { - $entityName = $this->getEntityName(); - } + /** + * Get relation params by name for a specified entity + * + * @param string $linkName + * @param string $entityName + * @param bool $isOrmEntityDefs + * @param mixed $returns + * @return mixed + */ + protected function getLinkParams($linkName = null, $entityName = null, $isOrmEntityDefs = false, $returns = null) + { + if (!isset($linkName)) { + $linkName = $this->getLinkName(); + } + if (!isset($entityName)) { + $entityName = $this->getEntityName(); + } - $entityDefs = $this->getDefs($isOrmEntityDefs); - $relationKeyName = $isOrmEntityDefs ? 'relations' : 'links'; + $entityDefs = $this->getDefs($isOrmEntityDefs); + $relationKeyName = $isOrmEntityDefs ? 'relations' : 'links'; - if (isset($entityDefs[$entityName]) && isset($entityDefs[$entityName][$relationKeyName][$linkName])) { - return $entityDefs[$entityName][$relationKeyName][$linkName]; - } + if (isset($entityDefs[$entityName]) && isset($entityDefs[$entityName][$relationKeyName][$linkName])) { + return $entityDefs[$entityName][$relationKeyName][$linkName]; + } - return $returns; - } + return $returns; + } - /** - * Get Foreign field - * - * @param string $name - * @param string $entityName - * @return string - */ - protected function getForeignField($name, $entityName) - { - $foreignField = $this->getMetadata()->get('entityDefs.'.$entityName.'.fields.'.$name); + /** + * Get Foreign field + * + * @param string $name + * @param string $entityName + * @return string + */ + protected function getForeignField($name, $entityName) + { + $foreignField = $this->getMetadata()->get('entityDefs.'.$entityName.'.fields.'.$name); - if ($foreignField['type'] != 'varchar') { - if ($foreignField['type'] == 'personName') { - return array('first' . ucfirst($name), ' ', 'last' . ucfirst($name)); - } - } + if ($foreignField['type'] != 'varchar') { + if ($foreignField['type'] == 'personName') { + return array('first' . ucfirst($name), ' ', 'last' . ucfirst($name)); + } + } - return $name; - } + return $name; + } - /** - * Set a value for all elements of array. So, in result all elements will have the same values - * - * @param string $value - * @param array $array - */ - protected function setArrayValue($inputValue, array $array) - { - foreach ($array as &$value) { - $value = $inputValue; - } + /** + * Set a value for all elements of array. So, in result all elements will have the same values + * + * @param string $value + * @param array $array + */ + protected function setArrayValue($inputValue, array $array) + { + foreach ($array as &$value) { + $value = $inputValue; + } - return $array; - } + return $array; + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Converter.php b/application/Espo/Core/Utils/Database/Orm/Converter.php index 5527ad3e09..07c9ac09df 100644 --- a/application/Espo/Core/Utils/Database/Orm/Converter.php +++ b/application/Espo/Core/Utils/Database/Orm/Converter.php @@ -23,402 +23,402 @@ namespace Espo\Core\Utils\Database\Orm; use Espo\Core\Utils\Util, - Espo\ORM\Entity; + Espo\ORM\Entity; class Converter { - private $metadata; - private $fileManager; - private $metadataUtils; - - private $relationManager; - - private $entityDefs; - - protected $defaultFieldType = 'varchar'; - protected $defaultNaming = 'postfix'; - - protected $defaultLength = array( - 'varchar' => 255, - 'int' => 11, - ); - - protected $defaultValue = array( - 'bool' => false, - ); - - /* - * //pair Espo => ORM - */ - protected $fieldAccordances = array( - 'type' => 'type', - 'dbType' => 'dbType', - 'maxLength' => 'len', - 'len' => 'len', - 'notNull' => 'notNull', - 'autoincrement' => 'autoincrement', - 'entity' => 'entity', - 'notStorable' => 'notStorable', - 'link' => 'relation', - 'field' => 'foreign', //todo change "foreign" to "field" - 'unique' => 'unique', - 'index' => 'index', - /*'conditions' => 'conditions', - 'additionalColumns' => 'additionalColumns', */ - 'default' => array( - 'condition' => '^javascript:', - 'conditionEquals' => false, - 'value' => array( - 'default' => '{0}', - ), - ), - 'select' => 'select', - 'orderBy' => 'orderBy', - 'where' => 'where', - ); - - protected $idParams = array( - 'dbType' => 'varchar', - 'len' => '24', - ); - - - public function __construct(\Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\File\Manager $fileManager) - { - $this->metadata = $metadata; - $this->fileManager = $fileManager; //need to featue with ormHooks. Ex. isFollowed field - - $this->relationManager = new RelationManager($this->metadata); - - $this->metadataUtils = new \Espo\Core\Utils\Metadata\Utils($this->metadata); - - $this->entityDefs = $this->getMetadata()->get('entityDefs'); - } - - - protected function getMetadata() - { - return $this->metadata; - } - - protected function getEntityDefs() - { - return $this->entityDefs; - } - - protected function getFileManager() - { - return $this->fileManager; - } - - protected function getRelationManager() - { - return $this->relationManager; - } - - protected function getMetadataUtils() - { - return $this->metadataUtils; - } - - public function process() - { - $entityDefs = $this->getEntityDefs(); - - $ormMeta = array(); - foreach($entityDefs as $entityName => $entityMeta) { - - if (empty($entityMeta)) { - $GLOBALS['log']->critical('Orm\Converter:process(), Entity:'.$entityName.' - metadata cannot be converted into ORM format'); - continue; - } - - $ormMeta = Util::merge($ormMeta, $this->convertEntity($entityName, $entityMeta)); - } - - $ormMeta = $this->afterProcess($ormMeta); - - return $ormMeta; - } - - protected function convertEntity($entityName, $entityMeta) - { - $ormMeta = array(); - $ormMeta[$entityName] = array( - 'fields' => array( - ), - 'relations' => array( - ), - ); - - $ormMeta[$entityName]['fields'] = $this->convertFields($entityName, $entityMeta); - - $convertedLinks = $this->convertLinks($entityName, $entityMeta, $ormMeta); - - $ormMeta = Util::merge($ormMeta, $convertedLinks); - - return $ormMeta; - } - - public function afterProcess(array $ormMeta) - { - $entityDefs = $this->getEntityDefs(); - - $currentOrmMeta = $ormMeta; - //load custom field definitions and customCodes - foreach($currentOrmMeta as $entityName => $entityParams) { - foreach($entityParams['fields'] as $fieldName => $fieldParams) { - - //load custom field definitions - $fieldType = ucfirst($fieldParams['type']); - $className = '\Espo\Custom\Core\Utils\Database\Orm\Fields\\'.$fieldType; - if (!class_exists($className)) { - $className = '\Espo\Core\Utils\Database\Orm\Fields\\'.$fieldType; - } - - if (class_exists($className) && method_exists($className, 'load')) { - $helperClass = new $className($this->metadata, $ormMeta, $entityDefs); - $fieldResult = $helperClass->process( $fieldName, $entityName ); - if (isset($fieldResult['unset'])) { - $ormMeta = Util::unsetInArray($ormMeta, $fieldResult['unset']); - unset($fieldResult['unset']); - } - - $ormMeta = Util::merge($ormMeta, $fieldResult); - - } //END: load custom field definitions - - //todo move to separate file - //add a field 'isFollowed' for scopes with 'stream => true' - $scopeDefs = $this->getMetadata()->get('scopes.'.$entityName); - if (isset($scopeDefs['stream']) && $scopeDefs['stream']) { - if (!isset($entityParams['fields']['isFollowed'])) { - $ormMeta[$entityName]['fields']['isFollowed'] = array( - 'type' => 'varchar', - 'notStorable' => true, - ); - } - } //END: add a field 'isFollowed' for stream => true - - } - } - - foreach($ormMeta as $entityName => &$entityParams) { - foreach($entityParams['fields'] as $fieldName => &$fieldParams) { - - switch ($fieldParams['type']) { - case 'id': - if ($fieldParams['dbType'] != 'int') { - $fieldParams = array_merge($fieldParams, $this->idParams); - } - break; - - case 'foreignId': - $fieldParams = array_merge($fieldParams, $this->idParams); - $fieldParams['notNull'] = false; - break; - - case 'foreignType': - $fieldParams['dbType'] = Entity::VARCHAR; - $fieldParams['len'] = $this->defaultLength['varchar']; - break; - - case 'bool': - $fieldParams['default'] = isset($fieldParams['default']) ? (bool) $fieldParams['default'] : $this->defaultValue['bool']; - break; - } - } - - } - - return $ormMeta; - } - - /** - * Metadata conversion from Espo format into Doctrine - * - * @param string $entityName - * @param array $entityMeta - * - * @return array - */ - protected function convertFields($entityName, &$entityMeta) - { - $outputMeta = array( - 'id' => array( - 'type' => Entity::ID, - 'dbType' => 'varchar', - ), - 'name' => array( - 'type' => isset($entityMeta['fields']['name']['type']) ? $entityMeta['fields']['name']['type'] : Entity::VARCHAR, - 'notStorable' => true, - ), - ); - - foreach($entityMeta['fields'] as $fieldName => $fieldParams) { - - /** check if "fields" option exists in $fieldMeta */ - $fieldTypeMeta = $this->getMetadataUtils()->getFieldDefsByType($fieldParams); - - if (isset($fieldTypeMeta['fields']) && is_array($fieldTypeMeta['fields'])) { - - foreach($fieldTypeMeta['actualFields'] as $subFieldName) { - - $subField = $this->convertActualFields($entityName, $fieldName, $fieldParams, $subFieldName, $fieldTypeMeta); - - if (!isset($outputMeta[ $subField['naming'] ])) { - $subFieldDefs = $this->convertField($entityName, $subField['name'], $subField['params']); - if ($subFieldDefs !== false) { - $outputMeta[ $subField['naming'] ] = $subFieldDefs; //push fieldDefs to the main array - } - } - } - } else { - $fieldDefs = $this->convertField($entityName, $fieldName, $fieldParams, $fieldTypeMeta); - if ($fieldDefs !== false) { - $outputMeta[$fieldName] = $fieldDefs; //push fieldDefs to the main array - } - } - - /** check and set the linkDefs from 'fields' metadata */ - if (isset($fieldTypeMeta['linkDefs'])) { - $linkDefs = $this->getMetadataUtils()->getLinkDefsInFieldMeta($entityName, $fieldParams, $fieldTypeMeta['linkDefs']); - if (isset($linkDefs)) { - $entityMeta['links'] = Util::merge( array($fieldName => $linkDefs), $entityMeta['links'] ); - } - } - } - - if (!isset($outputMeta['deleted'])) { - $outputMeta['deleted'] = array( - 'type' => Entity::BOOL, - 'default' => false, - ); - } - - return $outputMeta; - } - - protected function convertField($entityName, $fieldName, array $fieldParams, $fieldTypeMeta = null) - { - /** set default type if exists */ - if (!isset($fieldParams['type']) || empty($fieldParams['type'])) { - $GLOBALS['log']->debug('Field type does not exist for '.$entityName.':'.$fieldName.'. Use default type ['.$this->defaultFieldType.']'); - $fieldParams['type'] = $this->defaultFieldType; - } /** END: set default type if exists */ - - /** merge fieldDefs option from field definition */ - if (!isset($fieldTypeMeta)) { - $fieldTypeMeta = $this->getMetadataUtils()->getFieldDefsByType($fieldParams); - } - - if (isset($fieldTypeMeta['fieldDefs'])) { - $fieldParams = Util::merge($fieldParams, $fieldTypeMeta['fieldDefs']); - } - - /** check if need to skip this field in ORM metadata */ - if (isset($fieldParams['skip']) && $fieldParams['skip'] === true) { - return false; - } - - /** if defined 'notNull => false' and 'required => true', then remove 'notNull' */ - if (isset($fieldParams['notNull']) && !$fieldParams['notNull'] && isset($fieldParams['required']) && $fieldParams['required']) { - unset($fieldParams['notNull']); - } - - $fieldDefs = $this->getInitValues($fieldParams); - - /** check if the field need to be saved in database */ - if ( (isset($fieldParams['db']) && $fieldParams['db'] === false) ) { - $fieldDefs['notStorable'] = true; - } - - /** check and set the field length */ - if (!isset($fieldDefs['len']) && in_array($fieldDefs['type'], array_keys($this->defaultLength))) { - $fieldDefs['len'] = $this->defaultLength[$fieldDefs['type']]; - } - - return $fieldDefs; - } - - protected function convertActualFields($entityName, $fieldName, $fieldParams, $subFieldName, $fieldTypeMeta) - { - $subField = array(); - - $subField['params'] = $this->getInitValues($fieldParams); - - if (isset($fieldTypeMeta['fieldDefs'])) { - $subField['params'] = Util::merge($subField['params'], $fieldTypeMeta['fieldDefs']); - } - - //if empty field name, then use the main field - if (trim($subFieldName) == '') { + private $metadata; + private $fileManager; + private $metadataUtils; + + private $relationManager; + + private $entityDefs; + + protected $defaultFieldType = 'varchar'; + protected $defaultNaming = 'postfix'; + + protected $defaultLength = array( + 'varchar' => 255, + 'int' => 11, + ); + + protected $defaultValue = array( + 'bool' => false, + ); + + /* + * //pair Espo => ORM + */ + protected $fieldAccordances = array( + 'type' => 'type', + 'dbType' => 'dbType', + 'maxLength' => 'len', + 'len' => 'len', + 'notNull' => 'notNull', + 'autoincrement' => 'autoincrement', + 'entity' => 'entity', + 'notStorable' => 'notStorable', + 'link' => 'relation', + 'field' => 'foreign', //todo change "foreign" to "field" + 'unique' => 'unique', + 'index' => 'index', + /*'conditions' => 'conditions', + 'additionalColumns' => 'additionalColumns', */ + 'default' => array( + 'condition' => '^javascript:', + 'conditionEquals' => false, + 'value' => array( + 'default' => '{0}', + ), + ), + 'select' => 'select', + 'orderBy' => 'orderBy', + 'where' => 'where', + ); + + protected $idParams = array( + 'dbType' => 'varchar', + 'len' => '24', + ); + + + public function __construct(\Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\File\Manager $fileManager) + { + $this->metadata = $metadata; + $this->fileManager = $fileManager; //need to featue with ormHooks. Ex. isFollowed field + + $this->relationManager = new RelationManager($this->metadata); + + $this->metadataUtils = new \Espo\Core\Utils\Metadata\Utils($this->metadata); + + $this->entityDefs = $this->getMetadata()->get('entityDefs'); + } + + + protected function getMetadata() + { + return $this->metadata; + } + + protected function getEntityDefs() + { + return $this->entityDefs; + } + + protected function getFileManager() + { + return $this->fileManager; + } + + protected function getRelationManager() + { + return $this->relationManager; + } + + protected function getMetadataUtils() + { + return $this->metadataUtils; + } + + public function process() + { + $entityDefs = $this->getEntityDefs(); + + $ormMeta = array(); + foreach($entityDefs as $entityName => $entityMeta) { + + if (empty($entityMeta)) { + $GLOBALS['log']->critical('Orm\Converter:process(), Entity:'.$entityName.' - metadata cannot be converted into ORM format'); + continue; + } + + $ormMeta = Util::merge($ormMeta, $this->convertEntity($entityName, $entityMeta)); + } + + $ormMeta = $this->afterProcess($ormMeta); + + return $ormMeta; + } + + protected function convertEntity($entityName, $entityMeta) + { + $ormMeta = array(); + $ormMeta[$entityName] = array( + 'fields' => array( + ), + 'relations' => array( + ), + ); + + $ormMeta[$entityName]['fields'] = $this->convertFields($entityName, $entityMeta); + + $convertedLinks = $this->convertLinks($entityName, $entityMeta, $ormMeta); + + $ormMeta = Util::merge($ormMeta, $convertedLinks); + + return $ormMeta; + } + + public function afterProcess(array $ormMeta) + { + $entityDefs = $this->getEntityDefs(); + + $currentOrmMeta = $ormMeta; + //load custom field definitions and customCodes + foreach($currentOrmMeta as $entityName => $entityParams) { + foreach($entityParams['fields'] as $fieldName => $fieldParams) { + + //load custom field definitions + $fieldType = ucfirst($fieldParams['type']); + $className = '\Espo\Custom\Core\Utils\Database\Orm\Fields\\'.$fieldType; + if (!class_exists($className)) { + $className = '\Espo\Core\Utils\Database\Orm\Fields\\'.$fieldType; + } + + if (class_exists($className) && method_exists($className, 'load')) { + $helperClass = new $className($this->metadata, $ormMeta, $entityDefs); + $fieldResult = $helperClass->process( $fieldName, $entityName ); + if (isset($fieldResult['unset'])) { + $ormMeta = Util::unsetInArray($ormMeta, $fieldResult['unset']); + unset($fieldResult['unset']); + } + + $ormMeta = Util::merge($ormMeta, $fieldResult); + + } //END: load custom field definitions + + //todo move to separate file + //add a field 'isFollowed' for scopes with 'stream => true' + $scopeDefs = $this->getMetadata()->get('scopes.'.$entityName); + if (isset($scopeDefs['stream']) && $scopeDefs['stream']) { + if (!isset($entityParams['fields']['isFollowed'])) { + $ormMeta[$entityName]['fields']['isFollowed'] = array( + 'type' => 'varchar', + 'notStorable' => true, + ); + } + } //END: add a field 'isFollowed' for stream => true + + } + } + + foreach($ormMeta as $entityName => &$entityParams) { + foreach($entityParams['fields'] as $fieldName => &$fieldParams) { + + switch ($fieldParams['type']) { + case 'id': + if ($fieldParams['dbType'] != 'int') { + $fieldParams = array_merge($fieldParams, $this->idParams); + } + break; + + case 'foreignId': + $fieldParams = array_merge($fieldParams, $this->idParams); + $fieldParams['notNull'] = false; + break; + + case 'foreignType': + $fieldParams['dbType'] = Entity::VARCHAR; + $fieldParams['len'] = $this->defaultLength['varchar']; + break; + + case 'bool': + $fieldParams['default'] = isset($fieldParams['default']) ? (bool) $fieldParams['default'] : $this->defaultValue['bool']; + break; + } + } + + } + + return $ormMeta; + } + + /** + * Metadata conversion from Espo format into Doctrine + * + * @param string $entityName + * @param array $entityMeta + * + * @return array + */ + protected function convertFields($entityName, &$entityMeta) + { + $outputMeta = array( + 'id' => array( + 'type' => Entity::ID, + 'dbType' => 'varchar', + ), + 'name' => array( + 'type' => isset($entityMeta['fields']['name']['type']) ? $entityMeta['fields']['name']['type'] : Entity::VARCHAR, + 'notStorable' => true, + ), + ); + + foreach($entityMeta['fields'] as $fieldName => $fieldParams) { + + /** check if "fields" option exists in $fieldMeta */ + $fieldTypeMeta = $this->getMetadataUtils()->getFieldDefsByType($fieldParams); + + if (isset($fieldTypeMeta['fields']) && is_array($fieldTypeMeta['fields'])) { + + foreach($fieldTypeMeta['actualFields'] as $subFieldName) { + + $subField = $this->convertActualFields($entityName, $fieldName, $fieldParams, $subFieldName, $fieldTypeMeta); + + if (!isset($outputMeta[ $subField['naming'] ])) { + $subFieldDefs = $this->convertField($entityName, $subField['name'], $subField['params']); + if ($subFieldDefs !== false) { + $outputMeta[ $subField['naming'] ] = $subFieldDefs; //push fieldDefs to the main array + } + } + } + } else { + $fieldDefs = $this->convertField($entityName, $fieldName, $fieldParams, $fieldTypeMeta); + if ($fieldDefs !== false) { + $outputMeta[$fieldName] = $fieldDefs; //push fieldDefs to the main array + } + } + + /** check and set the linkDefs from 'fields' metadata */ + if (isset($fieldTypeMeta['linkDefs'])) { + $linkDefs = $this->getMetadataUtils()->getLinkDefsInFieldMeta($entityName, $fieldParams, $fieldTypeMeta['linkDefs']); + if (isset($linkDefs)) { + $entityMeta['links'] = Util::merge( array($fieldName => $linkDefs), $entityMeta['links'] ); + } + } + } + + if (!isset($outputMeta['deleted'])) { + $outputMeta['deleted'] = array( + 'type' => Entity::BOOL, + 'default' => false, + ); + } + + return $outputMeta; + } + + protected function convertField($entityName, $fieldName, array $fieldParams, $fieldTypeMeta = null) + { + /** set default type if exists */ + if (!isset($fieldParams['type']) || empty($fieldParams['type'])) { + $GLOBALS['log']->debug('Field type does not exist for '.$entityName.':'.$fieldName.'. Use default type ['.$this->defaultFieldType.']'); + $fieldParams['type'] = $this->defaultFieldType; + } /** END: set default type if exists */ + + /** merge fieldDefs option from field definition */ + if (!isset($fieldTypeMeta)) { + $fieldTypeMeta = $this->getMetadataUtils()->getFieldDefsByType($fieldParams); + } + + if (isset($fieldTypeMeta['fieldDefs'])) { + $fieldParams = Util::merge($fieldParams, $fieldTypeMeta['fieldDefs']); + } + + /** check if need to skip this field in ORM metadata */ + if (isset($fieldParams['skip']) && $fieldParams['skip'] === true) { + return false; + } + + /** if defined 'notNull => false' and 'required => true', then remove 'notNull' */ + if (isset($fieldParams['notNull']) && !$fieldParams['notNull'] && isset($fieldParams['required']) && $fieldParams['required']) { + unset($fieldParams['notNull']); + } + + $fieldDefs = $this->getInitValues($fieldParams); + + /** check if the field need to be saved in database */ + if ( (isset($fieldParams['db']) && $fieldParams['db'] === false) ) { + $fieldDefs['notStorable'] = true; + } + + /** check and set the field length */ + if (!isset($fieldDefs['len']) && in_array($fieldDefs['type'], array_keys($this->defaultLength))) { + $fieldDefs['len'] = $this->defaultLength[$fieldDefs['type']]; + } + + return $fieldDefs; + } + + protected function convertActualFields($entityName, $fieldName, $fieldParams, $subFieldName, $fieldTypeMeta) + { + $subField = array(); + + $subField['params'] = $this->getInitValues($fieldParams); + + if (isset($fieldTypeMeta['fieldDefs'])) { + $subField['params'] = Util::merge($subField['params'], $fieldTypeMeta['fieldDefs']); + } + + //if empty field name, then use the main field + if (trim($subFieldName) == '') { - $subField['name'] = $fieldName; - $subField['naming'] = $fieldName; - - } else { - - $namingType = isset($fieldTypeMeta['naming']) ? $fieldTypeMeta['naming'] : $this->defaultNaming; - - $subField['name'] = $subFieldName; - $subField['naming'] = Util::getNaming($fieldName, $subFieldName, $namingType); - if (isset($fieldTypeMeta['fields'][$subFieldName])) { - $subField['params'] = Util::merge($subField['params'], $fieldTypeMeta['fields'][$subFieldName]); - } - - } - - return $subField; - } - - protected function convertLinks($entityName, $entityMeta, $ormMeta) - { - if (!isset($entityMeta['links'])) { - return array(); - } + $subField['name'] = $fieldName; + $subField['naming'] = $fieldName; + + } else { + + $namingType = isset($fieldTypeMeta['naming']) ? $fieldTypeMeta['naming'] : $this->defaultNaming; + + $subField['name'] = $subFieldName; + $subField['naming'] = Util::getNaming($fieldName, $subFieldName, $namingType); + if (isset($fieldTypeMeta['fields'][$subFieldName])) { + $subField['params'] = Util::merge($subField['params'], $fieldTypeMeta['fields'][$subFieldName]); + } + + } + + return $subField; + } + + protected function convertLinks($entityName, $entityMeta, $ormMeta) + { + if (!isset($entityMeta['links'])) { + return array(); + } - $entityDefs = $this->getEntityDefs(); + $entityDefs = $this->getEntityDefs(); - $relationships = array(); - foreach($entityMeta['links'] as $linkName => $linkParams) { + $relationships = array(); + foreach($entityMeta['links'] as $linkName => $linkParams) { - $convertedLink = $this->getRelationManager()->convert($linkName, $linkParams, $entityName, $ormMeta); + $convertedLink = $this->getRelationManager()->convert($linkName, $linkParams, $entityName, $ormMeta); - if (isset($convertedLink)) { - $relationships = Util::merge($convertedLink, $relationships); - } - } + if (isset($convertedLink)) { + $relationships = Util::merge($convertedLink, $relationships); + } + } - return $relationships; - } + return $relationships; + } - protected function getInitValues(array $fieldParams) - { - $values = array(); - foreach($this->fieldAccordances as $espoType => $ormType) { + protected function getInitValues(array $fieldParams) + { + $values = array(); + foreach($this->fieldAccordances as $espoType => $ormType) { - if (isset($fieldParams[$espoType])) { + if (isset($fieldParams[$espoType])) { - if (is_array($ormType)) { + if (is_array($ormType)) { - $conditionRes = false; - if (!is_array($fieldParams[$espoType])) { - $conditionRes = preg_match('/'.$ormType['condition'].'/i', $fieldParams[$espoType]); - } + $conditionRes = false; + if (!is_array($fieldParams[$espoType])) { + $conditionRes = preg_match('/'.$ormType['condition'].'/i', $fieldParams[$espoType]); + } - if (!$conditionRes || ($conditionRes && $conditionRes === $ormType['conditionEquals']) ) { - $value = is_array($fieldParams[$espoType]) ? json_encode($fieldParams[$espoType]) : $fieldParams[$espoType]; - $values = Util::merge( $values, Util::replaceInArray('{0}', $value, $ormType['value']) ); - } - } else { - $values[$ormType] = $fieldParams[$espoType]; - } + if (!$conditionRes || ($conditionRes && $conditionRes === $ormType['conditionEquals']) ) { + $value = is_array($fieldParams[$espoType]) ? json_encode($fieldParams[$espoType]) : $fieldParams[$espoType]; + $values = Util::merge( $values, Util::replaceInArray('{0}', $value, $ormType['value']) ); + } + } else { + $values[$ormType] = $fieldParams[$espoType]; + } - } - } + } + } - return $values; - } + return $values; + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Fields/Currency.php b/application/Espo/Core/Utils/Database/Orm/Fields/Currency.php index f3d56094a2..12013e34b1 100644 --- a/application/Espo/Core/Utils/Database/Orm/Fields/Currency.php +++ b/application/Espo/Core/Utils/Database/Orm/Fields/Currency.php @@ -26,39 +26,39 @@ use Espo\Core\Utils\Util; class Currency extends \Espo\Core\Utils\Database\Orm\Base { - protected function load($fieldName, $entityName) - { - $converedFieldName = $fieldName . 'Converted'; - - $currencyColumnName = Util::toUnderScore($fieldName); - - $alias = Util::toUnderScore($fieldName) . "_currency_alias"; - - return array( - $entityName => array( - 'fields' => array( - $fieldName => array( - "type" => "float", - "orderBy" => $converedFieldName . " {direction}" - ), - $fieldName . 'Converted' => array( - 'type' => 'float', - 'select' => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate" , - 'where' => - array ( - "=" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate = {value}", - ">" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate > {value}", - "<" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate < {value}", - ">=" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate >= {value}", - "<=" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate <= {value}", - "<>" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate <> {value}" - ), - 'notStorable' => true, - 'orderBy' => $converedFieldName . " {direction}" - ), - ), - ), - ); - } + protected function load($fieldName, $entityName) + { + $converedFieldName = $fieldName . 'Converted'; + + $currencyColumnName = Util::toUnderScore($fieldName); + + $alias = Util::toUnderScore($fieldName) . "_currency_alias"; + + return array( + $entityName => array( + 'fields' => array( + $fieldName => array( + "type" => "float", + "orderBy" => $converedFieldName . " {direction}" + ), + $fieldName . 'Converted' => array( + 'type' => 'float', + 'select' => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate" , + 'where' => + array ( + "=" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate = {value}", + ">" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate > {value}", + "<" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate < {value}", + ">=" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate >= {value}", + "<=" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate <= {value}", + "<>" => Util::toUnderScore($entityName) . "." . $currencyColumnName . " * {$alias}.rate <> {value}" + ), + 'notStorable' => true, + 'orderBy' => $converedFieldName . " {direction}" + ), + ), + ), + ); + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Fields/Email.php b/application/Espo/Core/Utils/Database/Orm/Fields/Email.php index 0ecfc60968..422e34557b 100644 --- a/application/Espo/Core/Utils/Database/Orm/Fields/Email.php +++ b/application/Espo/Core/Utils/Database/Orm/Fields/Email.php @@ -24,74 +24,74 @@ namespace Espo\Core\Utils\Database\Orm\Fields; class Email extends \Espo\Core\Utils\Database\Orm\Base { - protected function load($fieldName, $entityName) - { - return array( - $entityName => array( - 'fields' => array( - $fieldName => array( - 'select' => 'email_address.name', - 'where' => - array ( - 'LIKE' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( - SELECT entity_id - FROM entity_email_address - JOIN email_address ON email_address.id = entity_email_address.email_address_id - WHERE - entity_email_address.deleted = 0 AND entity_email_address.entity_type = '{$entityName}' AND - email_address.deleted = 0 AND email_address.name LIKE {value} - )", - '=' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( - SELECT entity_id - FROM entity_email_address - JOIN email_address ON email_address.id = entity_email_address.email_address_id - WHERE - entity_email_address.deleted = 0 AND entity_email_address.entity_type = '{$entityName}' AND - email_address.deleted = 0 AND email_address.name = {value} - )", - '<>' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( - SELECT entity_id - FROM entity_email_address - JOIN email_address ON email_address.id = entity_email_address.email_address_id - WHERE - entity_email_address.deleted = 0 AND entity_email_address.entity_type = '{$entityName}' AND - email_address.deleted = 0 AND email_address.name <> {value} - )" - ), - 'orderBy' => 'email_address.name {direction}', - ), - $fieldName .'Data' => array( - 'type' => 'text', - 'notStorable' => true - ), - ), - 'relations' => array( - $fieldName.'es' => array( - 'type' => 'manyMany', - 'entity' => 'EmailAddress', - 'relationName' => 'entityEmailAddress', - 'midKeys' => array( - 'entity_id', - 'email_address_id', - ), - 'conditions' => array( - 'entityType' => $entityName, - ), - 'additionalColumns' => array( - 'entityType' => array( - 'type' => 'varchar', - 'len' => 100, - ), - 'primary' => array( - 'type' => 'bool', - 'default' => false, - ), - ), - ), - ), - ), - ); - } + protected function load($fieldName, $entityName) + { + return array( + $entityName => array( + 'fields' => array( + $fieldName => array( + 'select' => 'email_address.name', + 'where' => + array ( + 'LIKE' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( + SELECT entity_id + FROM entity_email_address + JOIN email_address ON email_address.id = entity_email_address.email_address_id + WHERE + entity_email_address.deleted = 0 AND entity_email_address.entity_type = '{$entityName}' AND + email_address.deleted = 0 AND email_address.name LIKE {value} + )", + '=' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( + SELECT entity_id + FROM entity_email_address + JOIN email_address ON email_address.id = entity_email_address.email_address_id + WHERE + entity_email_address.deleted = 0 AND entity_email_address.entity_type = '{$entityName}' AND + email_address.deleted = 0 AND email_address.name = {value} + )", + '<>' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( + SELECT entity_id + FROM entity_email_address + JOIN email_address ON email_address.id = entity_email_address.email_address_id + WHERE + entity_email_address.deleted = 0 AND entity_email_address.entity_type = '{$entityName}' AND + email_address.deleted = 0 AND email_address.name <> {value} + )" + ), + 'orderBy' => 'email_address.name {direction}', + ), + $fieldName .'Data' => array( + 'type' => 'text', + 'notStorable' => true + ), + ), + 'relations' => array( + $fieldName.'es' => array( + 'type' => 'manyMany', + 'entity' => 'EmailAddress', + 'relationName' => 'entityEmailAddress', + 'midKeys' => array( + 'entity_id', + 'email_address_id', + ), + 'conditions' => array( + 'entityType' => $entityName, + ), + 'additionalColumns' => array( + 'entityType' => array( + 'type' => 'varchar', + 'len' => 100, + ), + 'primary' => array( + 'type' => 'bool', + 'default' => false, + ), + ), + ), + ), + ), + ); + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Fields/LinkMultiple.php b/application/Espo/Core/Utils/Database/Orm/Fields/LinkMultiple.php index fba8cfce4b..62e42b261e 100644 --- a/application/Espo/Core/Utils/Database/Orm/Fields/LinkMultiple.php +++ b/application/Espo/Core/Utils/Database/Orm/Fields/LinkMultiple.php @@ -24,38 +24,38 @@ namespace Espo\Core\Utils\Database\Orm\Fields; class LinkMultiple extends \Espo\Core\Utils\Database\Orm\Base { - protected function load($fieldName, $entityName) - { - $data = array( - $entityName => array ( - 'fields' => array( - $fieldName.'Ids' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - $fieldName.'Names' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - ), - ), - 'unset' => array( - $entityName => array( - 'fields.'.$fieldName, - ), - ), - ); + protected function load($fieldName, $entityName) + { + $data = array( + $entityName => array ( + 'fields' => array( + $fieldName.'Ids' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + $fieldName.'Names' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + ), + ), + 'unset' => array( + $entityName => array( + 'fields.'.$fieldName, + ), + ), + ); - $columns = $this->getMetadata()->get("entityDefs.{$entityName}.fields.{$fieldName}.columns"); - if (!empty($columns)) { - $data[$entityName]['fields'][$fieldName . 'Columns'] = array( - 'type' => 'varchar', - 'notStorable' => true, - ); - } + $columns = $this->getMetadata()->get("entityDefs.{$entityName}.fields.{$fieldName}.columns"); + if (!empty($columns)) { + $data[$entityName]['fields'][$fieldName . 'Columns'] = array( + 'type' => 'varchar', + 'notStorable' => true, + ); + } - return $data; - } + return $data; + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Fields/LinkParent.php b/application/Espo/Core/Utils/Database/Orm/Fields/LinkParent.php index 34998bbd61..4006275eb0 100644 --- a/application/Espo/Core/Utils/Database/Orm/Fields/LinkParent.php +++ b/application/Espo/Core/Utils/Database/Orm/Fields/LinkParent.php @@ -24,28 +24,28 @@ namespace Espo\Core\Utils\Database\Orm\Fields; class LinkParent extends \Espo\Core\Utils\Database\Orm\Base { - protected function load($fieldName, $entityName) - { - return array( - $entityName => array ( - 'fields' => array( - $fieldName.'Id' => array( - 'type' => 'foreignId', - 'index' => $fieldName, - ), - $fieldName.'Type' => array( - 'type' => 'foreignType', - 'notNull' => false, - 'index' => $fieldName, - ), - $fieldName.'Name' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - ), - ), - ); - } + protected function load($fieldName, $entityName) + { + return array( + $entityName => array ( + 'fields' => array( + $fieldName.'Id' => array( + 'type' => 'foreignId', + 'index' => $fieldName, + ), + $fieldName.'Type' => array( + 'type' => 'foreignType', + 'notNull' => false, + 'index' => $fieldName, + ), + $fieldName.'Name' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + ), + ), + ); + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Fields/PersonName.php b/application/Espo/Core/Utils/Database/Orm/Fields/PersonName.php index b1bb17c231..b924a73aad 100644 --- a/application/Espo/Core/Utils/Database/Orm/Fields/PersonName.php +++ b/application/Espo/Core/Utils/Database/Orm/Fields/PersonName.php @@ -26,65 +26,65 @@ use Espo\Core\Utils\Util; class PersonName extends \Espo\Core\Utils\Database\Orm\Base { - protected function load($fieldName, $entityName) - { - $foreignField = array('first' . ucfirst($fieldName), ' ', 'last' . ucfirst($fieldName)); - - $tableName = Util::toUnderScore($entityName); + protected function load($fieldName, $entityName) + { + $foreignField = array('first' . ucfirst($fieldName), ' ', 'last' . ucfirst($fieldName)); + + $tableName = Util::toUnderScore($entityName); - $fullList = array(); //contains empty string (" ") like delimiter - $fullListReverse = array(); //reverse of $fullList - $fieldList = array(); //doesn't contain empty string (" ") like delimiter - $like = array(); - $equal = array(); + $fullList = array(); //contains empty string (" ") like delimiter + $fullListReverse = array(); //reverse of $fullList + $fieldList = array(); //doesn't contain empty string (" ") like delimiter + $like = array(); + $equal = array(); - foreach($foreignField as $foreignFieldName) { + foreach($foreignField as $foreignFieldName) { - $fieldNameTrimmed = trim($foreignFieldName); - if (!empty($fieldNameTrimmed)) { - $columnName = $tableName.'.'.Util::toUnderScore($fieldNameTrimmed); + $fieldNameTrimmed = trim($foreignFieldName); + if (!empty($fieldNameTrimmed)) { + $columnName = $tableName.'.'.Util::toUnderScore($fieldNameTrimmed); - $fullList[] = $fieldList[] = $columnName; - $like[] = $columnName." LIKE {value}"; - $equal[] = $columnName." = {value}"; - } else { - $fullList[] = "'".$foreignFieldName."'"; - } - } + $fullList[] = $fieldList[] = $columnName; + $like[] = $columnName." LIKE {value}"; + $equal[] = $columnName." = {value}"; + } else { + $fullList[] = "'".$foreignFieldName."'"; + } + } - $fullListReverse = array_reverse($fullList); + $fullListReverse = array_reverse($fullList); - return array( - $entityName => array ( - 'fields' => array( - $fieldName => array( - 'type' => 'varchar', - 'select' => $this->getSelect($fullList), - 'where' => array( - 'LIKE' => "(".implode(" OR ", $like)." OR CONCAT(".implode(", ", $fullList).") LIKE {value} OR CONCAT(".implode(", ", $fullListReverse).") LIKE {value})", - '=' => "(".implode(" OR ", $equal)." OR CONCAT(".implode(", ", $fullList).") = {value} OR CONCAT(".implode(", ", $fullListReverse).") = {value})", - ), - 'orderBy' => implode(", ", array_map(function ($item) {return $item . ' {direction}';}, $fieldList)), - ), - ), - ), - ); - } + return array( + $entityName => array ( + 'fields' => array( + $fieldName => array( + 'type' => 'varchar', + 'select' => $this->getSelect($fullList), + 'where' => array( + 'LIKE' => "(".implode(" OR ", $like)." OR CONCAT(".implode(", ", $fullList).") LIKE {value} OR CONCAT(".implode(", ", $fullListReverse).") LIKE {value})", + '=' => "(".implode(" OR ", $equal)." OR CONCAT(".implode(", ", $fullList).") = {value} OR CONCAT(".implode(", ", $fullListReverse).") = {value})", + ), + 'orderBy' => implode(", ", array_map(function ($item) {return $item . ' {direction}';}, $fieldList)), + ), + ), + ), + ); + } - protected function getSelect(array $fullList) - { - foreach ($fullList as &$item) { + protected function getSelect(array $fullList) + { + foreach ($fullList as &$item) { - $rowItem = trim($item, " '"); + $rowItem = trim($item, " '"); - if (!empty($rowItem)) { - $item = "IFNULL(".$item.", '')"; - } - } + if (!empty($rowItem)) { + $item = "IFNULL(".$item.", '')"; + } + } - $select = "TRIM(CONCAT(".implode(", ", $fullList)."))"; + $select = "TRIM(CONCAT(".implode(", ", $fullList)."))"; - return $select; - } + return $select; + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Fields/Phone.php b/application/Espo/Core/Utils/Database/Orm/Fields/Phone.php index fb0a863b26..8e5baa60fa 100644 --- a/application/Espo/Core/Utils/Database/Orm/Fields/Phone.php +++ b/application/Espo/Core/Utils/Database/Orm/Fields/Phone.php @@ -24,74 +24,74 @@ namespace Espo\Core\Utils\Database\Orm\Fields; class Phone extends \Espo\Core\Utils\Database\Orm\Base { - protected function load($fieldName, $entityName) - { - return array( - $entityName => array( - 'fields' => array( - $fieldName => array( - 'select' => 'phone_number.name', - 'where' => - array ( - 'LIKE' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( - SELECT entity_id - FROM entity_phone_number - JOIN phone_number ON phone_number.id = entity_phone_number.phone_number_id - WHERE - entity_phone_number.deleted = 0 AND entity_phone_number.entity_type = '{$entityName}' AND - phone_number.deleted = 0 AND phone_number.name LIKE {value} - )", - '=' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( - SELECT entity_id - FROM entity_phone_number - JOIN phone_number ON phone_number.id = entity_phone_number.phone_number_id - WHERE - entity_phone_number.deleted = 0 AND entity_phone_number.entity_type = '{$entityName}' AND - phone_number.deleted = 0 AND phone_number.name = {value} - )", - '<>' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( - SELECT entity_id - FROM entity_phone_number - JOIN phone_number ON phone_number.id = entity_phone_number.phone_number_id - WHERE - entity_phone_number.deleted = 0 AND entity_phone_number.entity_type = '{$entityName}' AND - phone_number.deleted = 0 AND phone_number.name <> {value} - )" - ), - 'orderBy' => 'phone_number.name {direction}', - ), - $fieldName .'Data' => array( - 'type' => 'text', - 'notStorable' => true - ), - ), - 'relations' => array( - $fieldName.'s' => array( - 'type' => 'manyMany', - 'entity' => 'PhoneNumber', - 'relationName' => 'entityPhoneNumber', - 'midKeys' => array( - 'entity_id', - 'phone_number_id', - ), - 'conditions' => array( - 'entityType' => $entityName, - ), - 'additionalColumns' => array( - 'entityType' => array( - 'type' => 'varchar', - 'len' => 100, - ), - 'primary' => array( - 'type' => 'bool', - 'default' => false, - ), - ), - ), - ), - ), - ); - } + protected function load($fieldName, $entityName) + { + return array( + $entityName => array( + 'fields' => array( + $fieldName => array( + 'select' => 'phone_number.name', + 'where' => + array ( + 'LIKE' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( + SELECT entity_id + FROM entity_phone_number + JOIN phone_number ON phone_number.id = entity_phone_number.phone_number_id + WHERE + entity_phone_number.deleted = 0 AND entity_phone_number.entity_type = '{$entityName}' AND + phone_number.deleted = 0 AND phone_number.name LIKE {value} + )", + '=' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( + SELECT entity_id + FROM entity_phone_number + JOIN phone_number ON phone_number.id = entity_phone_number.phone_number_id + WHERE + entity_phone_number.deleted = 0 AND entity_phone_number.entity_type = '{$entityName}' AND + phone_number.deleted = 0 AND phone_number.name = {value} + )", + '<>' => \Espo\Core\Utils\Util::toUnderScore($entityName) . ".id IN ( + SELECT entity_id + FROM entity_phone_number + JOIN phone_number ON phone_number.id = entity_phone_number.phone_number_id + WHERE + entity_phone_number.deleted = 0 AND entity_phone_number.entity_type = '{$entityName}' AND + phone_number.deleted = 0 AND phone_number.name <> {value} + )" + ), + 'orderBy' => 'phone_number.name {direction}', + ), + $fieldName .'Data' => array( + 'type' => 'text', + 'notStorable' => true + ), + ), + 'relations' => array( + $fieldName.'s' => array( + 'type' => 'manyMany', + 'entity' => 'PhoneNumber', + 'relationName' => 'entityPhoneNumber', + 'midKeys' => array( + 'entity_id', + 'phone_number_id', + ), + 'conditions' => array( + 'entityType' => $entityName, + ), + 'additionalColumns' => array( + 'entityType' => array( + 'type' => 'varchar', + 'len' => 100, + ), + 'primary' => array( + 'type' => 'bool', + 'default' => false, + ), + ), + ), + ), + ), + ); + } } diff --git a/application/Espo/Core/Utils/Database/Orm/RelationManager.php b/application/Espo/Core/Utils/Database/Orm/RelationManager.php index 14b0cc15f5..4d9903bcb0 100644 --- a/application/Espo/Core/Utils/Database/Orm/RelationManager.php +++ b/application/Espo/Core/Utils/Database/Orm/RelationManager.php @@ -26,118 +26,118 @@ use Espo\Core\Utils\Util; class RelationManager { - private $metadata; + private $metadata; - private $entityDefs; + private $entityDefs; - public function __construct(\Espo\Core\Utils\Metadata $metadata) - { - $this->metadata = $metadata; + public function __construct(\Espo\Core\Utils\Metadata $metadata) + { + $this->metadata = $metadata; - $this->entityDefs = $this->getMetadata()->get('entityDefs'); - } + $this->entityDefs = $this->getMetadata()->get('entityDefs'); + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - protected function getEntityDefs() - { - return $this->entityDefs; - } + protected function getEntityDefs() + { + return $this->entityDefs; + } - public function getLinkEntityName($entityName, $linkParams) - { - return isset($linkParams['entity']) ? $linkParams['entity'] : $entityName; - } + public function getLinkEntityName($entityName, $linkParams) + { + return isset($linkParams['entity']) ? $linkParams['entity'] : $entityName; + } - public function isRelationExists($relationName) - { - if ($this->getRelationClass($relationName) !== false) { - return true; - } + public function isRelationExists($relationName) + { + if ($this->getRelationClass($relationName) !== false) { + return true; + } - return false; - } + return false; + } - protected function getRelationClass($relationName) - { - $relationName = ucfirst($relationName); + protected function getRelationClass($relationName) + { + $relationName = ucfirst($relationName); - $className = '\Espo\Custom\Core\Utils\Database\Orm\Relations\\'.$relationName; - if (!class_exists($className)) { - $className = '\Espo\Core\Utils\Database\Orm\Relations\\'.$relationName; - } + $className = '\Espo\Custom\Core\Utils\Database\Orm\Relations\\'.$relationName; + if (!class_exists($className)) { + $className = '\Espo\Core\Utils\Database\Orm\Relations\\'.$relationName; + } - if (class_exists($className)) { - return $className; - } + if (class_exists($className)) { + return $className; + } - return false; - } + return false; + } - protected function isMethodExists($relationName) - { - $className = $this->getRelationClass($relationName); + protected function isMethodExists($relationName) + { + $className = $this->getRelationClass($relationName); - return method_exists($className, 'load'); - } + return method_exists($className, 'load'); + } - /** - * Get foreign Link - * - * @param string $parentLinkName - * @param array $parentLinkParams - * @param array $currentEntityDefs - * - * @return array - in format array('name', 'params') - */ - private function getForeignLink($parentLinkName, $parentLinkParams, $currentEntityDefs) - { - if (isset($parentLinkParams['foreign']) && isset($currentEntityDefs['links'][$parentLinkParams['foreign']])) { - return array( - 'name' => $parentLinkParams['foreign'], - 'params' => $currentEntityDefs['links'][$parentLinkParams['foreign']], - ); - } + /** + * Get foreign Link + * + * @param string $parentLinkName + * @param array $parentLinkParams + * @param array $currentEntityDefs + * + * @return array - in format array('name', 'params') + */ + private function getForeignLink($parentLinkName, $parentLinkParams, $currentEntityDefs) + { + if (isset($parentLinkParams['foreign']) && isset($currentEntityDefs['links'][$parentLinkParams['foreign']])) { + return array( + 'name' => $parentLinkParams['foreign'], + 'params' => $currentEntityDefs['links'][$parentLinkParams['foreign']], + ); + } - return false; - } + return false; + } - public function convert($linkName, $linkParams, $entityName, $ormMeta) - { - $entityDefs = $this->getEntityDefs(); + public function convert($linkName, $linkParams, $entityName, $ormMeta) + { + $entityDefs = $this->getEntityDefs(); - $foreignEntityName = $this->getLinkEntityName($entityName, $linkParams); - $foreignLink = $this->getForeignLink($linkName, $linkParams, $entityDefs[$foreignEntityName]); + $foreignEntityName = $this->getLinkEntityName($entityName, $linkParams); + $foreignLink = $this->getForeignLink($linkName, $linkParams, $entityDefs[$foreignEntityName]); - $currentType = $linkParams['type']; + $currentType = $linkParams['type']; - $method = $currentType; - if ($foreignLink !== false) { - $method .= '-'.$foreignLink['params']['type']; - } - $method = Util::toCamelCase($method); + $method = $currentType; + if ($foreignLink !== false) { + $method .= '-'.$foreignLink['params']['type']; + } + $method = Util::toCamelCase($method); - $relationName = $this->isRelationExists($method) ? $method /*hasManyHasMany*/ : $currentType /*hasMany*/; + $relationName = $this->isRelationExists($method) ? $method /*hasManyHasMany*/ : $currentType /*hasMany*/; - //relationDefs defined in separate file - if (isset($linkParams['relationName']) && $this->isMethodExists($linkParams['relationName'])) { - $className = $this->getRelationClass($linkParams['relationName']); - } else if ($this->isMethodExists($relationName)) { - $className = $this->getRelationClass($relationName); - } + //relationDefs defined in separate file + if (isset($linkParams['relationName']) && $this->isMethodExists($linkParams['relationName'])) { + $className = $this->getRelationClass($linkParams['relationName']); + } else if ($this->isMethodExists($relationName)) { + $className = $this->getRelationClass($relationName); + } - if (isset($className) && $className !== false) { - $helperClass = new $className($this->metadata, $ormMeta, $entityDefs); - return $helperClass->process($linkName, $entityName, $foreignLink['name'], $foreignEntityName); - } - //END: relationDefs defined in separate file + if (isset($className) && $className !== false) { + $helperClass = new $className($this->metadata, $ormMeta, $entityDefs); + return $helperClass->process($linkName, $entityName, $foreignLink['name'], $foreignEntityName); + } + //END: relationDefs defined in separate file - return null; - } + return null; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/Base.php b/application/Espo/Core/Utils/Database/Orm/Relations/Base.php index 5348e946f3..66c8ee5e9e 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/Base.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/Base.php @@ -24,128 +24,128 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class Base extends \Espo\Core\Utils\Database\Orm\Base { - private $params; + private $params; - private $foreignParams; + private $foreignParams; - protected $foreignLinkName = null; - protected $foreignEntityName = null; + protected $foreignLinkName = null; + protected $foreignEntityName = null; - protected $allowedParams = array( - 'relationName', - 'conditions', - 'additionalColumns', - 'midKeys', - ); + protected $allowedParams = array( + 'relationName', + 'conditions', + 'additionalColumns', + 'midKeys', + ); - protected function getParams() - { - return $this->params; - } + protected function getParams() + { + return $this->params; + } - protected function getForeignParams() - { - return $this->foreignParams; - } + protected function getForeignParams() + { + return $this->foreignParams; + } - protected function setParams(array $params) - { - $this->params = $params; - } + protected function setParams(array $params) + { + $this->params = $params; + } - protected function setForeignParams(array $foreignParams) - { - $this->foreignParams = $foreignParams; - } + protected function setForeignParams(array $foreignParams) + { + $this->foreignParams = $foreignParams; + } - protected function setForeignLinkName($foreignLinkName) - { - $this->foreignLinkName = $foreignLinkName; - } + protected function setForeignLinkName($foreignLinkName) + { + $this->foreignLinkName = $foreignLinkName; + } - protected function getForeignLinkName() - { - return $this->foreignLinkName; - } + protected function getForeignLinkName() + { + return $this->foreignLinkName; + } - protected function setForeignEntityName($foreignEntityName) - { - $this->foreignEntityName = $foreignEntityName; - } + protected function setForeignEntityName($foreignEntityName) + { + $this->foreignEntityName = $foreignEntityName; + } - protected function getForeignEntityName() - { - return $this->foreignEntityName; - } + protected function getForeignEntityName() + { + return $this->foreignEntityName; + } - protected function getForeignLinkParams() - { - $foreignLinkName = $this->getForeignLinkName(); - $foreignEntityName = $this->getForeignEntityName(); - $foreignLinkParams = $this->getLinkParams($foreignLinkName, $foreignEntityName); + protected function getForeignLinkParams() + { + $foreignLinkName = $this->getForeignLinkName(); + $foreignEntityName = $this->getForeignEntityName(); + $foreignLinkParams = $this->getLinkParams($foreignLinkName, $foreignEntityName); - return $foreignLinkParams; - } + return $foreignLinkParams; + } - public function process($linkName, $entityName, $foreignLinkName, $foreignEntityName) - { - $inputs = array( - 'itemName' => $linkName, - 'entityName' => $entityName, - 'foreignLinkName' => $foreignLinkName, - 'foreignEntityName' => $foreignEntityName, - ); - $this->setMethods($inputs); + public function process($linkName, $entityName, $foreignLinkName, $foreignEntityName) + { + $inputs = array( + 'itemName' => $linkName, + 'entityName' => $entityName, + 'foreignLinkName' => $foreignLinkName, + 'foreignEntityName' => $foreignEntityName, + ); + $this->setMethods($inputs); - $convertedDefs = $this->load($linkName, $entityName); - $convertedDefs = $this->mergeAllowedParams($convertedDefs); + $convertedDefs = $this->load($linkName, $entityName); + $convertedDefs = $this->mergeAllowedParams($convertedDefs); - $inputs = $this->setArrayValue(null, $inputs); - $this->setMethods($inputs); + $inputs = $this->setArrayValue(null, $inputs); + $this->setMethods($inputs); - return $convertedDefs; - } + return $convertedDefs; + } - private function mergeAllowedParams($loads) - { - $linkName = $this->getLinkName(); - $entityName = $this->getEntityName(); + private function mergeAllowedParams($loads) + { + $linkName = $this->getLinkName(); + $entityName = $this->getEntityName(); - if (!empty($this->allowedParams)) { - $linkParams = &$loads[$entityName]['relations'][$linkName]; + if (!empty($this->allowedParams)) { + $linkParams = &$loads[$entityName]['relations'][$linkName]; - foreach ($this->allowedParams as $name) { + foreach ($this->allowedParams as $name) { - $additionalParrams = $this->getAllowedAdditionalParams($name); + $additionalParrams = $this->getAllowedAdditionalParams($name); - if (isset($additionalParrams) && !isset($linkParams[$name])) { - $linkParams[$name] = $additionalParrams; - } - } - } + if (isset($additionalParrams) && !isset($linkParams[$name])) { + $linkParams[$name] = $additionalParrams; + } + } + } - return $loads; - } + return $loads; + } - private function getAllowedAdditionalParams($allowedItemName) - { - $linkParams = $this->getLinkParams(); - $foreignLinkParams = $this->getForeignLinkParams(); + private function getAllowedAdditionalParams($allowedItemName) + { + $linkParams = $this->getLinkParams(); + $foreignLinkParams = $this->getForeignLinkParams(); - $itemLinkParams = isset($linkParams[$allowedItemName]) ? $linkParams[$allowedItemName] : null; - $itemForeignLinkParams = isset($foreignLinkParams[$allowedItemName]) ? $foreignLinkParams[$allowedItemName] : null; + $itemLinkParams = isset($linkParams[$allowedItemName]) ? $linkParams[$allowedItemName] : null; + $itemForeignLinkParams = isset($foreignLinkParams[$allowedItemName]) ? $foreignLinkParams[$allowedItemName] : null; - $additionalParrams = null; + $additionalParrams = null; - if (isset($itemLinkParams) && isset($itemForeignLinkParams)) { - $additionalParrams = Util::merge($itemLinkParams, $itemForeignLinkParams); - } else if (isset($itemLinkParams)) { - $additionalParrams = $itemLinkParams; - } else if (isset($itemForeignLinkParams)) { - $additionalParrams = $itemForeignLinkParams; - } + if (isset($itemLinkParams) && isset($itemForeignLinkParams)) { + $additionalParrams = Util::merge($itemLinkParams, $itemForeignLinkParams); + } else if (isset($itemLinkParams)) { + $additionalParrams = $itemLinkParams; + } else if (isset($itemForeignLinkParams)) { + $additionalParrams = $itemForeignLinkParams; + } - return $additionalParrams; - } + return $additionalParrams; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/BelongsTo.php b/application/Espo/Core/Utils/Database/Orm/Relations/BelongsTo.php index 1991ba3b14..6e2dd88dc4 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/BelongsTo.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/BelongsTo.php @@ -24,33 +24,33 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class BelongsTo extends Base { - protected function load($linkName, $entityName) - { - $foreignEntityName = $this->getForeignEntityName(); + protected function load($linkName, $entityName) + { + $foreignEntityName = $this->getForeignEntityName(); - return array ( - $entityName => array ( - 'fields' => array( - $linkName.'Name' => array( - 'type' => 'foreign', - 'relation' => $linkName, - 'foreign' => $this->getForeignField('name', $foreignEntityName), - ), - $linkName.'Id' => array( - 'type' => 'foreignId', - 'index' => true, - ), - ), - 'relations' => array( - $linkName => array( - 'type' => 'belongsTo', - 'entity' => $foreignEntityName, - 'key' => $linkName.'Id', - 'foreignKey' => 'id', //???? - ), - ), - ), - ); - } + return array ( + $entityName => array ( + 'fields' => array( + $linkName.'Name' => array( + 'type' => 'foreign', + 'relation' => $linkName, + 'foreign' => $this->getForeignField('name', $foreignEntityName), + ), + $linkName.'Id' => array( + 'type' => 'foreignId', + 'index' => true, + ), + ), + 'relations' => array( + $linkName => array( + 'type' => 'belongsTo', + 'entity' => $foreignEntityName, + 'key' => $linkName.'Id', + 'foreignKey' => 'id', //???? + ), + ), + ), + ); + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/EmailEmailAddress.php b/application/Espo/Core/Utils/Database/Orm/Relations/EmailEmailAddress.php index 0349fab96b..c5de43f7e8 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/EmailEmailAddress.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/EmailEmailAddress.php @@ -24,28 +24,28 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class EmailEmailAddress extends HasMany { - protected function load($linkName, $entityName) - { - $parentRelation = parent::load($linkName, $entityName); + protected function load($linkName, $entityName) + { + $parentRelation = parent::load($linkName, $entityName); - $foreignEntityName = $this->getForeignEntityName(); + $foreignEntityName = $this->getForeignEntityName(); - $relation = array( - $entityName => array ( - 'relations' => array( - $linkName => array( - 'midKeys' => array( - lcfirst($entityName).'Id', - lcfirst($foreignEntityName).'Id', - ), - ), - ), - ), - ); + $relation = array( + $entityName => array ( + 'relations' => array( + $linkName => array( + 'midKeys' => array( + lcfirst($entityName).'Id', + lcfirst($foreignEntityName).'Id', + ), + ), + ), + ), + ); - $relation = \Espo\Core\Utils\Util::merge($parentRelation, $relation); + $relation = \Espo\Core\Utils\Util::merge($parentRelation, $relation); - return $relation; - } + return $relation; + } } diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/EntityTeam.php b/application/Espo/Core/Utils/Database/Orm/Relations/EntityTeam.php index b387058e47..7f5f689995 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/EntityTeam.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/EntityTeam.php @@ -24,35 +24,35 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class EntityTeam extends Base { - protected function load($linkName, $entityName) - { - $linkParams = $this->getLinkParams(); - $foreignEntityName = $this->getForeignEntityName(); + protected function load($linkName, $entityName) + { + $linkParams = $this->getLinkParams(); + $foreignEntityName = $this->getForeignEntityName(); - return array( - $entityName => array( - 'relations' => array( - $linkName => array( - 'type' => 'manyMany', - 'entity' => $foreignEntityName, - 'relationName' => lcfirst($linkParams['relationName']), - 'midKeys' => array( - 'entity_id', - 'team_id', - ), - 'conditions' => array( - 'entityType' => $entityName, - ), - 'additionalColumns' => array( - 'entityType' => array( - 'type' => 'varchar', - 'len' => 100, - ), - ), - ), - ), - ), - ); - } + return array( + $entityName => array( + 'relations' => array( + $linkName => array( + 'type' => 'manyMany', + 'entity' => $foreignEntityName, + 'relationName' => lcfirst($linkParams['relationName']), + 'midKeys' => array( + 'entity_id', + 'team_id', + ), + 'conditions' => array( + 'entityType' => $entityName, + ), + 'additionalColumns' => array( + 'entityType' => array( + 'type' => 'varchar', + 'len' => 100, + ), + ), + ), + ), + ), + ); + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/HasChildren.php b/application/Espo/Core/Utils/Database/Orm/Relations/HasChildren.php index cdc67ce6ce..486e0f448d 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/HasChildren.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/HasChildren.php @@ -24,34 +24,34 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class HasChildren extends Base { - protected function load($linkName, $entityName) - { - $foreignLinkName = $this->getForeignLinkName(); - $foreignEntityName = $this->getForeignEntityName(); + protected function load($linkName, $entityName) + { + $foreignLinkName = $this->getForeignLinkName(); + $foreignEntityName = $this->getForeignEntityName(); - return array( - $entityName => array ( - 'fields' => array( - $linkName.'Ids' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - $linkName.'Names' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - ), - 'relations' => array( - $linkName => array( - 'type' => 'hasChildren', - 'entity' => $foreignEntityName, - 'foreignKey' => $foreignLinkName.'Id', - 'foreignType' => $foreignLinkName.'Type', - ), - ), - ), - ); - } + return array( + $entityName => array ( + 'fields' => array( + $linkName.'Ids' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + $linkName.'Names' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + ), + 'relations' => array( + $linkName => array( + 'type' => 'hasChildren', + 'entity' => $foreignEntityName, + 'foreignKey' => $foreignLinkName.'Id', + 'foreignType' => $foreignLinkName.'Type', + ), + ), + ), + ); + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/HasMany.php b/application/Espo/Core/Utils/Database/Orm/Relations/HasMany.php index be20d6d0ae..8e5b29e52a 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/HasMany.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/HasMany.php @@ -24,38 +24,38 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class HasMany extends Base { - protected function load($linkName, $entityName) - { - $linkParams = $this->getLinkParams(); - $foreignLinkName = $this->getForeignLinkName(); - $foreignEntityName = $this->getForeignEntityName(); + protected function load($linkName, $entityName) + { + $linkParams = $this->getLinkParams(); + $foreignLinkName = $this->getForeignLinkName(); + $foreignEntityName = $this->getForeignEntityName(); - $relationType = isset($linkParams['relationName']) ? 'manyMany' : 'hasMany'; + $relationType = isset($linkParams['relationName']) ? 'manyMany' : 'hasMany'; - $relation = array( - $entityName => array ( - 'fields' => array( - $linkName.'Ids' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - $linkName.'Names' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - ), - 'relations' => array( - $linkName => array( - 'type' => $relationType, - 'entity' => $foreignEntityName, - 'foreignKey' => lcfirst($foreignLinkName.'Id'), - ), - ), - ), - ); + $relation = array( + $entityName => array ( + 'fields' => array( + $linkName.'Ids' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + $linkName.'Names' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + ), + 'relations' => array( + $linkName => array( + 'type' => $relationType, + 'entity' => $foreignEntityName, + 'foreignKey' => lcfirst($foreignLinkName.'Id'), + ), + ), + ), + ); return $relation; - } + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/ManyMany.php b/application/Espo/Core/Utils/Database/Orm/Relations/ManyMany.php index 0606901ffa..54e4e109a3 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/ManyMany.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/ManyMany.php @@ -26,56 +26,56 @@ use Espo\Core\Utils\Util; class ManyMany extends Base { - protected function load($linkName, $entityName) - { - $foreignEntityName = $this->getForeignEntityName(); + protected function load($linkName, $entityName) + { + $foreignEntityName = $this->getForeignEntityName(); - return array( - $entityName => array( - 'fields' => array( - $linkName.'Ids' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - $linkName.'Names' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - ), - 'relations' => array( - $linkName => array( - 'type' => 'manyMany', - 'entity' => $foreignEntityName, - 'relationName' => $this->getJoinTable($entityName, $foreignEntityName), - 'key' => 'id', //todo specify 'key' - 'foreignKey' => 'id', //todo specify 'foreignKey' - 'midKeys' => array( - lcfirst($entityName).'Id', - lcfirst($foreignEntityName).'Id', - ), - ), - ), - ), - ); - } + return array( + $entityName => array( + 'fields' => array( + $linkName.'Ids' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + $linkName.'Names' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + ), + 'relations' => array( + $linkName => array( + 'type' => 'manyMany', + 'entity' => $foreignEntityName, + 'relationName' => $this->getJoinTable($entityName, $foreignEntityName), + 'key' => 'id', //todo specify 'key' + 'foreignKey' => 'id', //todo specify 'foreignKey' + 'midKeys' => array( + lcfirst($entityName).'Id', + lcfirst($foreignEntityName).'Id', + ), + ), + ), + ), + ); + } - protected function getJoinTable($tableName1, $tableName2) - { - $tables = $this->getSortEntities($tableName1, $tableName2); + protected function getJoinTable($tableName1, $tableName2) + { + $tables = $this->getSortEntities($tableName1, $tableName2); - return Util::toCamelCase( implode('-', $tables) ); - } + return Util::toCamelCase( implode('-', $tables) ); + } protected function getSortEntities($entity1, $entity2) - { - $entities = array( - Util::toCamelCase(lcfirst($entity1)), - Util::toCamelCase(lcfirst($entity2)), - ); + { + $entities = array( + Util::toCamelCase(lcfirst($entity1)), + Util::toCamelCase(lcfirst($entity2)), + ); - sort($entities); + sort($entities); - return $entities; - } + return $entities; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/Database/Orm/Relations/NoteAttachments.php b/application/Espo/Core/Utils/Database/Orm/Relations/NoteAttachments.php index fb937000a5..713a617ae1 100644 --- a/application/Espo/Core/Utils/Database/Orm/Relations/NoteAttachments.php +++ b/application/Espo/Core/Utils/Database/Orm/Relations/NoteAttachments.php @@ -24,24 +24,24 @@ namespace Espo\Core\Utils\Database\Orm\Relations; class NoteAttachments extends HasChildren { - protected function load($linkName, $entityName) - { - $parentRelation = parent::load($linkName, $entityName); + protected function load($linkName, $entityName) + { + $parentRelation = parent::load($linkName, $entityName); - $relation = array( - $entityName => array ( - 'fields' => array( - $linkName.'Types' => array( - 'type' => 'varchar', - 'notStorable' => true, - ), - ), - ), - ); + $relation = array( + $entityName => array ( + 'fields' => array( + $linkName.'Types' => array( + 'type' => 'varchar', + 'notStorable' => true, + ), + ), + ), + ); - $relation = \Espo\Core\Utils\Util::merge($parentRelation, $relation); + $relation = \Espo\Core\Utils\Util::merge($parentRelation, $relation); - return $relation; - } + return $relation; + } } diff --git a/application/Espo/Core/Utils/Database/Schema/BaseRebuildActions.php b/application/Espo/Core/Utils/Database/Schema/BaseRebuildActions.php index 786aabec4e..b7afcf6b45 100644 --- a/application/Espo/Core/Utils/Database/Schema/BaseRebuildActions.php +++ b/application/Espo/Core/Utils/Database/Schema/BaseRebuildActions.php @@ -24,69 +24,69 @@ namespace Espo\Core\Utils\Database\Schema; abstract class BaseRebuildActions { - private $metadata; + private $metadata; - private $config; + private $config; - private $entityManager; - - protected $currentSchema = null; + private $entityManager; + + protected $currentSchema = null; - protected $metadataSchema = null; + protected $metadataSchema = null; - public function __construct(\Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\Config $config, \Espo\Core\ORM\EntityManager $entityManager) - { - $this->metadata = $metadata; - $this->config = $config; - $this->entityManager = $entityManager; - } - - protected function getEntityManager() - { - return $this->entityManager; - } - - protected function getConfig() - { - return $this->config; - } - - protected function getMetadata() - { - return $this->metadata; - } + public function __construct(\Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\Config $config, \Espo\Core\ORM\EntityManager $entityManager) + { + $this->metadata = $metadata; + $this->config = $config; + $this->entityManager = $entityManager; + } + + protected function getEntityManager() + { + return $this->entityManager; + } + + protected function getConfig() + { + return $this->config; + } + + protected function getMetadata() + { + return $this->metadata; + } - public function setCurrentSchema(\Doctrine\DBAL\Schema\Schema $currentSchema) - { - $this->currentSchema = $currentSchema; - } + public function setCurrentSchema(\Doctrine\DBAL\Schema\Schema $currentSchema) + { + $this->currentSchema = $currentSchema; + } - public function setMetadataSchema(\Doctrine\DBAL\Schema\Schema $metadataSchema) - { - $this->metadataSchema = $metadataSchema; - } + public function setMetadataSchema(\Doctrine\DBAL\Schema\Schema $metadataSchema) + { + $this->metadataSchema = $metadataSchema; + } - protected function getCurrentSchema() - { - return $this->currentSchema; - } + protected function getCurrentSchema() + { + return $this->currentSchema; + } - protected function getMetadataSchema() - { - return $this->metadataSchema; - } + protected function getMetadataSchema() + { + return $this->metadataSchema; + } - /* - public function beforeRebuild() - { - } + /* + public function beforeRebuild() + { + } - public function afterRebuild() - { - } - */ - - + public function afterRebuild() + { + } + */ + + } diff --git a/application/Espo/Core/Utils/Database/Schema/Converter.php b/application/Espo/Core/Utils/Database/Schema/Converter.php index b337f50340..aa6c741764 100644 --- a/application/Espo/Core/Utils/Database/Schema/Converter.php +++ b/application/Espo/Core/Utils/Database/Schema/Converter.php @@ -23,343 +23,343 @@ namespace Espo\Core\Utils\Database\Schema; use Espo\Core\Utils\Util, - Espo\ORM\Entity, - Espo\Core\Exceptions\Error; + Espo\ORM\Entity, + Espo\Core\Exceptions\Error; class Converter { - private $dbalSchema; - private $fileManager; + private $dbalSchema; + private $fileManager; - private $ormMeta = null; + private $ormMeta = null; - private $customTablePath = 'application/Espo/Core/Utils/Database/Schema/tables'; + private $customTablePath = 'application/Espo/Core/Utils/Database/Schema/tables'; - protected $typeList; + protected $typeList; - //pair ORM => doctrine - protected $allowedDbFieldParams = array( - 'len' => 'length', - 'default' => 'default', - 'notNull' => 'notnull', - 'autoincrement' => 'autoincrement', - 'unique' => 'unique', - ); + //pair ORM => doctrine + protected $allowedDbFieldParams = array( + 'len' => 'length', + 'default' => 'default', + 'notNull' => 'notnull', + 'autoincrement' => 'autoincrement', + 'unique' => 'unique', + ); - //todo: same array in Converters\Orm - protected $idParams = array( - 'dbType' => 'varchar', - 'len' => '24', - ); + //todo: same array in Converters\Orm + protected $idParams = array( + 'dbType' => 'varchar', + 'len' => '24', + ); - //todo: same array in Converters\Orm - protected $defaultLength = array( - 'varchar' => 255, - 'int' => 11, - ); + //todo: same array in Converters\Orm + protected $defaultLength = array( + 'varchar' => 255, + 'int' => 11, + ); - protected $notStorableTypes = array( - 'foreign' - ); + protected $notStorableTypes = array( + 'foreign' + ); - public function __construct(\Espo\Core\Utils\File\Manager $fileManager) - { - $this->fileManager = $fileManager; - - $this->dbalSchema = new \Espo\Core\Utils\Database\DBAL\Schema\Schema(); - - $this->typeList = array_keys(\Doctrine\DBAL\Types\Type::getTypesMap()); - } - - protected function getFileManager() - { - return $this->fileManager; - } - - protected function getSchema() - { - return $this->dbalSchema; - } + public function __construct(\Espo\Core\Utils\File\Manager $fileManager) + { + $this->fileManager = $fileManager; + + $this->dbalSchema = new \Espo\Core\Utils\Database\DBAL\Schema\Schema(); + + $this->typeList = array_keys(\Doctrine\DBAL\Types\Type::getTypesMap()); + } + + protected function getFileManager() + { + return $this->fileManager; + } + + protected function getSchema() + { + return $this->dbalSchema; + } - public function process(array $ormMeta, $entityDefs, $entityList = null) - { - $GLOBALS['log']->debug('Schema\Converter - Start: building schema'); + public function process(array $ormMeta, $entityDefs, $entityList = null) + { + $GLOBALS['log']->debug('Schema\Converter - Start: building schema'); - //check if exist files in "Tables" directory and merge with ormMetadata - $ormMeta = Util::merge($ormMeta, $this->getCustomTables()); - - //unset some keys in orm - if (isset($ormMeta['unset'])) { - $ormMeta = Util::unsetInArray($ormMeta, $ormMeta['unset']); - unset($ormMeta['unset']); - } //END: unset some keys in orm - - if (isset($entityList)) { - $entityList = is_string($entityList) ? (array) $entityList : $entityList; - - $dependentEntities = $this->getDependentEntities($entityList, $ormMeta); - $GLOBALS['log']->debug('Rebuild Database for entities: ['.implode(', ', $entityList).'] with dependent entities: ['.implode(', ', $dependentEntities).']'); - - $ormMeta = array_intersect_key($ormMeta, array_flip($dependentEntities)); - } - - $schema = $this->getSchema(); - - $tables = array(); - foreach ($ormMeta as $entityName => $entityParams) { - - $tableName = Util::toUnderScore($entityName); - - if ($schema->hasTable($tableName)) { - if (!isset($tables[$entityName])) { - $tables[$entityName] = $schema->getTable($tableName); - } - $GLOBALS['log']->debug('DBAL: Table ['.$tableName.'] exists.'); - continue; - } - - $tables[$entityName] = $schema->createTable($tableName); - - $primaryColumns = array(); - $uniqueColumns = array(); - $indexList = array(); //list of indexes like array( array(comlumn1, column2), array(column3)) - foreach ($entityParams['fields'] as $fieldName => $fieldParams) { - - if ((isset($fieldParams['notStorable']) && $fieldParams['notStorable']) || in_array($fieldParams['type'], $this->notStorableTypes)) { - continue; - } - - switch ($fieldParams['type']) { - case 'id': - $primaryColumns[] = Util::toUnderScore($fieldName); - break; - } - - $fieldType = isset($fieldParams['dbType']) ? $fieldParams['dbType'] : $fieldParams['type']; - $fieldType = strtolower($fieldType); /** doctrine uses strtolower for all field types */ - if (!in_array($fieldType, $this->typeList)) { - $GLOBALS['log']->debug('Converters\Schema::process(): Field type ['.$fieldType.'] does not exist '.$entityName.':'.$fieldName); - continue; - } - - $columnName = Util::toUnderScore($fieldName); - if (!$tables[$entityName]->hasColumn($columnName)) { - $tables[$entityName]->addColumn($columnName, $fieldType, $this->getDbFieldParams($fieldParams)); - } - - //add unique - if ($fieldParams['type']!= 'id' && isset($fieldParams['unique'])) { - $uniqueColumns = $this->getKeyList($columnName, $fieldParams['unique'], $uniqueColumns); - } //END: add unique - - //add index. It can be defined in entityDefs as "index" - if (isset($fieldParams['index'])) { - $indexList = $this->getKeyList($columnName, $fieldParams['index'], $indexList); - } //END: add index - } - - $tables[$entityName]->setPrimaryKey($primaryColumns); - if (!empty($indexList)) { - foreach($indexList as $indexItem) { - $tables[$entityName]->addIndex($indexItem); - } - } - - if (!empty($uniqueColumns)) { - foreach($uniqueColumns as $uniqueItem) { - $tables[$entityName]->addUniqueIndex($uniqueItem); - } - } - } - - //check and create columns/tables for relations - foreach ($ormMeta as $entityName => $entityParams) { - - if (!isset($entityParams['relations'])) { - continue; - } - - foreach ($entityParams['relations'] as $relationName => $relationParams) { - - switch ($relationParams['type']) { - case 'manyMany': - $tableName = $relationParams['relationName']; - - //check for duplication tables - if (!isset($tables[$tableName])) { //no needs to create the table if it already exists - $tables[$tableName] = $this->prepareManyMany($entityName, $relationParams, $tables); - } - break; - - case 'belongsTo': - $columnName = Util::toUnderScore($relationParams['key']); - $tables[$entityName]->addIndex(array($columnName)); - break; - } - } - } - //END: check and create columns/tables for relations - - $GLOBALS['log']->debug('Schema\Converter - End: building schema'); - - return $schema; - } - - /** - * Prepare a relation table for the manyMany relation - * - * @param string $entityName - * @param array $relationParams - * @param array $tables - * - * @return \Doctrine\DBAL\Schema\Table - */ - protected function prepareManyMany($entityName, $relationParams, $tables) - { - $tableName = Util::toUnderScore($relationParams['relationName']); - - if ($this->getSchema()->hasTable($tableName)) { - $GLOBALS['log']->debug('DBAL: Table ['.$tableName.'] exists.'); - return $this->getSchema()->getTable($tableName); - } - - $table = $this->getSchema()->createTable($tableName); - $table->addColumn('id', 'int', array('length'=>$this->defaultLength['int'], 'autoincrement' => true, 'notnull' => true,)); //'unique' => true, - - //add midKeys to a schema - foreach($relationParams['midKeys'] as $index => $midKey) { - - $usMidKey = Util::toUnderScore($midKey); - $table->addColumn($usMidKey, $this->idParams['dbType'], array('length'=>$this->idParams['len'])); - $table->addIndex(array($usMidKey)); - - } //END: add midKeys to a schema - - //add additionalColumns - if (isset($relationParams['additionalColumns'])) { - foreach($relationParams['additionalColumns'] as $fieldName => $fieldParams) { - - if (!isset($fieldParams['type'])) { - $fieldParams = array_merge($fieldParams, array( - 'type' => 'varchar', - 'length' => $this->defaultLength['varchar'], - )); - } - - $table->addColumn(Util::toUnderScore($fieldName), $fieldParams['type'], $this->getDbFieldParams($fieldParams)); - } - } //END: add additionalColumns - - - $table->addColumn('deleted', 'bool', array('default' => 0)); - $table->setPrimaryKey(array("id")); - - return $table; - } - - - protected function getDbFieldParams($fieldParams) - { - $dbFieldParams = array(); - - foreach($this->allowedDbFieldParams as $espoName => $dbalName) { - - if (isset($fieldParams[$espoName])) { - $dbFieldParams[$dbalName] = $fieldParams[$espoName]; - } - } - - switch ($fieldParams['type']) { - case 'array': - case 'jsonArray': - case 'text': - case 'longtext': - unset($dbFieldParams['default']); //for db type TEXT can't be defined a default value - break; - - case 'bool': - $dbFieldParams['default'] = intval($dbFieldParams['default']); - break; - } - - - if ( isset($fieldParams['autoincrement']) && $fieldParams['autoincrement'] ) { - $dbFieldParams['unique'] = true; - $dbFieldParams['notnull'] = true; - } - - return $dbFieldParams; - } - - /** - * Get key list (index, unique). Ex. index => true OR index => 'somename' - * @param string $columnName Column name (underscore field name) - * @param bool | string $keyValue - * @return array - */ - protected function getKeyList($columnName, $keyValue, array $keyList) - { - if ($keyValue === true) { - $keyList[] = array($columnName); - } else if (is_string($keyValue)) { - $keyList[$keyValue][] = $columnName; - } - - return $keyList; - } - - - /* - * @return array - ormMeta - */ - protected function getCustomTables() - { - $customTables = array(); + //check if exist files in "Tables" directory and merge with ormMetadata + $ormMeta = Util::merge($ormMeta, $this->getCustomTables()); + + //unset some keys in orm + if (isset($ormMeta['unset'])) { + $ormMeta = Util::unsetInArray($ormMeta, $ormMeta['unset']); + unset($ormMeta['unset']); + } //END: unset some keys in orm + + if (isset($entityList)) { + $entityList = is_string($entityList) ? (array) $entityList : $entityList; + + $dependentEntities = $this->getDependentEntities($entityList, $ormMeta); + $GLOBALS['log']->debug('Rebuild Database for entities: ['.implode(', ', $entityList).'] with dependent entities: ['.implode(', ', $dependentEntities).']'); + + $ormMeta = array_intersect_key($ormMeta, array_flip($dependentEntities)); + } + + $schema = $this->getSchema(); + + $tables = array(); + foreach ($ormMeta as $entityName => $entityParams) { + + $tableName = Util::toUnderScore($entityName); + + if ($schema->hasTable($tableName)) { + if (!isset($tables[$entityName])) { + $tables[$entityName] = $schema->getTable($tableName); + } + $GLOBALS['log']->debug('DBAL: Table ['.$tableName.'] exists.'); + continue; + } + + $tables[$entityName] = $schema->createTable($tableName); + + $primaryColumns = array(); + $uniqueColumns = array(); + $indexList = array(); //list of indexes like array( array(comlumn1, column2), array(column3)) + foreach ($entityParams['fields'] as $fieldName => $fieldParams) { + + if ((isset($fieldParams['notStorable']) && $fieldParams['notStorable']) || in_array($fieldParams['type'], $this->notStorableTypes)) { + continue; + } + + switch ($fieldParams['type']) { + case 'id': + $primaryColumns[] = Util::toUnderScore($fieldName); + break; + } + + $fieldType = isset($fieldParams['dbType']) ? $fieldParams['dbType'] : $fieldParams['type']; + $fieldType = strtolower($fieldType); /** doctrine uses strtolower for all field types */ + if (!in_array($fieldType, $this->typeList)) { + $GLOBALS['log']->debug('Converters\Schema::process(): Field type ['.$fieldType.'] does not exist '.$entityName.':'.$fieldName); + continue; + } + + $columnName = Util::toUnderScore($fieldName); + if (!$tables[$entityName]->hasColumn($columnName)) { + $tables[$entityName]->addColumn($columnName, $fieldType, $this->getDbFieldParams($fieldParams)); + } + + //add unique + if ($fieldParams['type']!= 'id' && isset($fieldParams['unique'])) { + $uniqueColumns = $this->getKeyList($columnName, $fieldParams['unique'], $uniqueColumns); + } //END: add unique + + //add index. It can be defined in entityDefs as "index" + if (isset($fieldParams['index'])) { + $indexList = $this->getKeyList($columnName, $fieldParams['index'], $indexList); + } //END: add index + } + + $tables[$entityName]->setPrimaryKey($primaryColumns); + if (!empty($indexList)) { + foreach($indexList as $indexItem) { + $tables[$entityName]->addIndex($indexItem); + } + } + + if (!empty($uniqueColumns)) { + foreach($uniqueColumns as $uniqueItem) { + $tables[$entityName]->addUniqueIndex($uniqueItem); + } + } + } + + //check and create columns/tables for relations + foreach ($ormMeta as $entityName => $entityParams) { + + if (!isset($entityParams['relations'])) { + continue; + } + + foreach ($entityParams['relations'] as $relationName => $relationParams) { + + switch ($relationParams['type']) { + case 'manyMany': + $tableName = $relationParams['relationName']; + + //check for duplication tables + if (!isset($tables[$tableName])) { //no needs to create the table if it already exists + $tables[$tableName] = $this->prepareManyMany($entityName, $relationParams, $tables); + } + break; + + case 'belongsTo': + $columnName = Util::toUnderScore($relationParams['key']); + $tables[$entityName]->addIndex(array($columnName)); + break; + } + } + } + //END: check and create columns/tables for relations + + $GLOBALS['log']->debug('Schema\Converter - End: building schema'); + + return $schema; + } + + /** + * Prepare a relation table for the manyMany relation + * + * @param string $entityName + * @param array $relationParams + * @param array $tables + * + * @return \Doctrine\DBAL\Schema\Table + */ + protected function prepareManyMany($entityName, $relationParams, $tables) + { + $tableName = Util::toUnderScore($relationParams['relationName']); + + if ($this->getSchema()->hasTable($tableName)) { + $GLOBALS['log']->debug('DBAL: Table ['.$tableName.'] exists.'); + return $this->getSchema()->getTable($tableName); + } + + $table = $this->getSchema()->createTable($tableName); + $table->addColumn('id', 'int', array('length'=>$this->defaultLength['int'], 'autoincrement' => true, 'notnull' => true,)); //'unique' => true, + + //add midKeys to a schema + foreach($relationParams['midKeys'] as $index => $midKey) { + + $usMidKey = Util::toUnderScore($midKey); + $table->addColumn($usMidKey, $this->idParams['dbType'], array('length'=>$this->idParams['len'])); + $table->addIndex(array($usMidKey)); + + } //END: add midKeys to a schema + + //add additionalColumns + if (isset($relationParams['additionalColumns'])) { + foreach($relationParams['additionalColumns'] as $fieldName => $fieldParams) { + + if (!isset($fieldParams['type'])) { + $fieldParams = array_merge($fieldParams, array( + 'type' => 'varchar', + 'length' => $this->defaultLength['varchar'], + )); + } + + $table->addColumn(Util::toUnderScore($fieldName), $fieldParams['type'], $this->getDbFieldParams($fieldParams)); + } + } //END: add additionalColumns + + + $table->addColumn('deleted', 'bool', array('default' => 0)); + $table->setPrimaryKey(array("id")); + + return $table; + } + + + protected function getDbFieldParams($fieldParams) + { + $dbFieldParams = array(); + + foreach($this->allowedDbFieldParams as $espoName => $dbalName) { + + if (isset($fieldParams[$espoName])) { + $dbFieldParams[$dbalName] = $fieldParams[$espoName]; + } + } + + switch ($fieldParams['type']) { + case 'array': + case 'jsonArray': + case 'text': + case 'longtext': + unset($dbFieldParams['default']); //for db type TEXT can't be defined a default value + break; + + case 'bool': + $dbFieldParams['default'] = intval($dbFieldParams['default']); + break; + } + + + if ( isset($fieldParams['autoincrement']) && $fieldParams['autoincrement'] ) { + $dbFieldParams['unique'] = true; + $dbFieldParams['notnull'] = true; + } + + return $dbFieldParams; + } + + /** + * Get key list (index, unique). Ex. index => true OR index => 'somename' + * @param string $columnName Column name (underscore field name) + * @param bool | string $keyValue + * @return array + */ + protected function getKeyList($columnName, $keyValue, array $keyList) + { + if ($keyValue === true) { + $keyList[] = array($columnName); + } else if (is_string($keyValue)) { + $keyList[$keyValue][] = $columnName; + } + + return $keyList; + } + + + /* + * @return array - ormMeta + */ + protected function getCustomTables() + { + $customTables = array(); - $fileList = $this->getFileManager()->getFileList($this->customTablePath, false, '\.php$', 'file'); + $fileList = $this->getFileManager()->getFileList($this->customTablePath, false, '\.php$', 'file'); - foreach($fileList as $fileName) { - $fileData = $this->getFileManager()->getContents( array($this->customTablePath, $fileName) ); - if (is_array($fileData)) { - $customTables = Util::merge($customTables, $fileData); - } - } + foreach($fileList as $fileName) { + $fileData = $this->getFileManager()->getContents( array($this->customTablePath, $fileName) ); + if (is_array($fileData)) { + $customTables = Util::merge($customTables, $fileData); + } + } - return $customTables; - } + return $customTables; + } - protected function getDependentEntities($entityList, $ormMeta, $dependentEntities = array()) - { - if (is_string($entityList)) { - $entityList = (array) $entityList; - } + protected function getDependentEntities($entityList, $ormMeta, $dependentEntities = array()) + { + if (is_string($entityList)) { + $entityList = (array) $entityList; + } - foreach ($entityList as $entityName) { + foreach ($entityList as $entityName) { - if (in_array($entityName, $dependentEntities)) { - continue; - } + if (in_array($entityName, $dependentEntities)) { + continue; + } - $dependentEntities[] = $entityName; + $dependentEntities[] = $entityName; - foreach ($ormMeta[$entityName]['relations'] as $relationName => $relationParams) { + foreach ($ormMeta[$entityName]['relations'] as $relationName => $relationParams) { - if (isset($relationParams['entity'])) { - $relationEntity = $relationParams['entity']; + if (isset($relationParams['entity'])) { + $relationEntity = $relationParams['entity']; - if (!in_array($relationEntity, $dependentEntities)) { - $dependentEntities = $this->getDependentEntities($relationEntity, $ormMeta, $dependentEntities); - } - } - } + if (!in_array($relationEntity, $dependentEntities)) { + $dependentEntities = $this->getDependentEntities($relationEntity, $ormMeta, $dependentEntities); + } + } + } - } + } - return $dependentEntities; - } + return $dependentEntities; + } } diff --git a/application/Espo/Core/Utils/Database/Schema/Schema.php b/application/Espo/Core/Utils/Database/Schema/Schema.php index e0e51249ec..3a4eddebce 100644 --- a/application/Espo/Core/Utils/Database/Schema/Schema.php +++ b/application/Espo/Core/Utils/Database/Schema/Schema.php @@ -23,282 +23,282 @@ namespace Espo\Core\Utils\Database\Schema; use Doctrine\DBAL\Types\Type, - Espo\Core\Utils\Util; + Espo\Core\Utils\Util; class Schema { - private $config; + private $config; - private $metadata; + private $metadata; - private $fileManager; + private $fileManager; - private $entityManager; + private $entityManager; - private $classParser; + private $classParser; - private $comparator; + private $comparator; - private $converter; + private $converter; - private $connection; + private $connection; - protected $drivers = array( - 'mysqli' => '\Espo\Core\Utils\Database\DBAL\Driver\Mysqli\Driver', - 'pdo_mysql' => '\Espo\Core\Utils\Database\DBAL\Driver\PDOMySql\Driver', - ); + protected $drivers = array( + 'mysqli' => '\Espo\Core\Utils\Database\DBAL\Driver\Mysqli\Driver', + 'pdo_mysql' => '\Espo\Core\Utils\Database\DBAL\Driver\PDOMySql\Driver', + ); - protected $fieldTypePaths = array( - 'application/Espo/Core/Utils/Database/DBAL/FieldTypes', - 'custom/Espo/Custom/Core/Utils/Database/DBAL/FieldTypes', - ); + protected $fieldTypePaths = array( + 'application/Espo/Core/Utils/Database/DBAL/FieldTypes', + 'custom/Espo/Custom/Core/Utils/Database/DBAL/FieldTypes', + ); - /** - * Paths of rebuild action folders - * @var array - */ - protected $rebuildActionsPath = array( - 'corePath' => 'application/Espo/Core/Utils/Database/Schema/rebuildActions', - 'customPath' => 'custom/Espo/Custom/Core/Utils/Database/Schema/rebuildActions', - ); + /** + * Paths of rebuild action folders + * @var array + */ + protected $rebuildActionsPath = array( + 'corePath' => 'application/Espo/Core/Utils/Database/Schema/rebuildActions', + 'customPath' => 'custom/Espo/Custom/Core/Utils/Database/Schema/rebuildActions', + ); - /** - * Array of rebuildActions classes in format: - * array( - * 'beforeRebuild' => array(...), - * 'afterRebuild' => array(...), - * ) - * @var array - */ - protected $rebuildActionClasses = null; + /** + * Array of rebuildActions classes in format: + * array( + * 'beforeRebuild' => array(...), + * 'afterRebuild' => array(...), + * ) + * @var array + */ + protected $rebuildActionClasses = null; - public function __construct(\Espo\Core\Utils\Config $config, \Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\File\Manager $fileManager, \Espo\Core\ORM\EntityManager $entityManager, \Espo\Core\Utils\File\ClassParser $classParser) - { - $this->config = $config; - $this->metadata = $metadata; - $this->fileManager = $fileManager; - $this->entityManager = $entityManager; - $this->classParser = $classParser; + public function __construct(\Espo\Core\Utils\Config $config, \Espo\Core\Utils\Metadata $metadata, \Espo\Core\Utils\File\Manager $fileManager, \Espo\Core\ORM\EntityManager $entityManager, \Espo\Core\Utils\File\ClassParser $classParser) + { + $this->config = $config; + $this->metadata = $metadata; + $this->fileManager = $fileManager; + $this->entityManager = $entityManager; + $this->classParser = $classParser; - $this->comparator = new \Espo\Core\Utils\Database\DBAL\Schema\Comparator(); - $this->initFieldTypes(); + $this->comparator = new \Espo\Core\Utils\Database\DBAL\Schema\Comparator(); + $this->initFieldTypes(); - $this->converter = new \Espo\Core\Utils\Database\Converter($this->metadata, $this->fileManager); - } + $this->converter = new \Espo\Core\Utils\Database\Converter($this->metadata, $this->fileManager); + } - protected function getConfig() - { - return $this->config; - } + protected function getConfig() + { + return $this->config; + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - protected function getFileManager() - { - return $this->fileManager; - } + protected function getFileManager() + { + return $this->fileManager; + } - protected function getEntityManager() - { - return $this->entityManager; - } + protected function getEntityManager() + { + return $this->entityManager; + } - protected function getComparator() - { - return $this->comparator; - } + protected function getComparator() + { + return $this->comparator; + } - protected function getConverter() - { - return $this->converter; - } + protected function getConverter() + { + return $this->converter; + } - protected function getClassParser() - { - return $this->classParser; - } + protected function getClassParser() + { + return $this->classParser; + } - public function getPlatform() - { - return $this->getConnection()->getDatabasePlatform(); - } + public function getPlatform() + { + return $this->getConnection()->getDatabasePlatform(); + } - public function getConnection() - { - if (isset($this->connection)) { - return $this->connection; - } + public function getConnection() + { + if (isset($this->connection)) { + return $this->connection; + } - $dbalConfig = new \Doctrine\DBAL\Configuration(); + $dbalConfig = new \Doctrine\DBAL\Configuration(); - $connectionParams = $this->getConfig()->get('database'); + $connectionParams = $this->getConfig()->get('database'); - $connectionParams['driverClass'] = $this->drivers[ $connectionParams['driver'] ]; - unset($connectionParams['driver']); + $connectionParams['driverClass'] = $this->drivers[ $connectionParams['driver'] ]; + unset($connectionParams['driver']); - $this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $dbalConfig); + $this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $dbalConfig); - return $this->connection; - } + return $this->connection; + } - protected function initFieldTypes() - { - foreach($this->fieldTypePaths as $path) { + protected function initFieldTypes() + { + foreach($this->fieldTypePaths as $path) { - $typeList = $this->getFileManager()->getFileList($path, false, '\.php$'); - if ($typeList !== false) { - foreach($typeList as $name) { - $typeName = preg_replace('/\.php$/i', '', $name); - $dbalTypeName = strtolower($typeName); + $typeList = $this->getFileManager()->getFileList($path, false, '\.php$'); + if ($typeList !== false) { + foreach($typeList as $name) { + $typeName = preg_replace('/\.php$/i', '', $name); + $dbalTypeName = strtolower($typeName); - $filePath = Util::concatPath($path, $typeName); - $class = Util::getClassName($filePath); + $filePath = Util::concatPath($path, $typeName); + $class = Util::getClassName($filePath); - if( ! Type::hasType($dbalTypeName) ) { - Type::addType($dbalTypeName, $class); - } else { - Type::overrideType($dbalTypeName, $class); - } + if( ! Type::hasType($dbalTypeName) ) { + Type::addType($dbalTypeName, $class); + } else { + Type::overrideType($dbalTypeName, $class); + } - $dbTypeName = method_exists($class, 'getDbTypeName') ? $class::getDbTypeName() : $dbalTypeName; + $dbTypeName = method_exists($class, 'getDbTypeName') ? $class::getDbTypeName() : $dbalTypeName; - $this->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping($dbTypeName, $dbalTypeName); - } - } - } - } + $this->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping($dbTypeName, $dbalTypeName); + } + } + } + } - /* - * Rebuild database schema - */ - public function rebuild($entityList = null) - { - if ($this->getConverter()->process() === false) { - return false; - } + /* + * Rebuild database schema + */ + public function rebuild($entityList = null) + { + if ($this->getConverter()->process() === false) { + return false; + } - $currentSchema = $this->getCurrentSchema(); - $metadataSchema = $this->getConverter()->getSchemaFromMetadata($entityList); + $currentSchema = $this->getCurrentSchema(); + $metadataSchema = $this->getConverter()->getSchemaFromMetadata($entityList); - $this->initRebuildActions($currentSchema, $metadataSchema); - $this->executeRebuildActions('beforeRebuild'); + $this->initRebuildActions($currentSchema, $metadataSchema); + $this->executeRebuildActions('beforeRebuild'); - $queries = $this->getDiffSql($currentSchema, $metadataSchema); + $queries = $this->getDiffSql($currentSchema, $metadataSchema); - $result = true; - $connection = $this->getConnection(); - foreach ($queries as $sql) { - $GLOBALS['log']->debug('SCHEMA, Execute Query: '.$sql); - try { - $result &= (bool) $connection->executeQuery($sql); - } catch (\Exception $e) { - $GLOBALS['log']->alert('Rebuild database fault: '.$e); - $result = false; - } - } + $result = true; + $connection = $this->getConnection(); + foreach ($queries as $sql) { + $GLOBALS['log']->debug('SCHEMA, Execute Query: '.$sql); + try { + $result &= (bool) $connection->executeQuery($sql); + } catch (\Exception $e) { + $GLOBALS['log']->alert('Rebuild database fault: '.$e); + $result = false; + } + } - $this->executeRebuildActions('afterRebuild'); + $this->executeRebuildActions('afterRebuild'); - return (bool) $result; - } + return (bool) $result; + } - /* - * Get current database schema - * - * @return \Doctrine\DBAL\Schema\Schema - */ - protected function getCurrentSchema() - { - return $this->getConnection()->getSchemaManager()->createSchema(); - } + /* + * Get current database schema + * + * @return \Doctrine\DBAL\Schema\Schema + */ + protected function getCurrentSchema() + { + return $this->getConnection()->getSchemaManager()->createSchema(); + } - /* - * Get SQL queries of database schema - * - * @params \Doctrine\DBAL\Schema\Schema $schema - * - * @return array - array of SQL queries - */ - public function toSql(\Doctrine\DBAL\Schema\SchemaDiff $schema) //Doctrine\DBAL\Schema\SchemaDiff | \Doctrine\DBAL\Schema\Schema - { - return $schema->toSaveSql($this->getPlatform()); - //return $schema->toSql($this->getPlatform()); //it can return with DROP TABLE - } + /* + * Get SQL queries of database schema + * + * @params \Doctrine\DBAL\Schema\Schema $schema + * + * @return array - array of SQL queries + */ + public function toSql(\Doctrine\DBAL\Schema\SchemaDiff $schema) //Doctrine\DBAL\Schema\SchemaDiff | \Doctrine\DBAL\Schema\Schema + { + return $schema->toSaveSql($this->getPlatform()); + //return $schema->toSql($this->getPlatform()); //it can return with DROP TABLE + } - /* - * Get SQL queries to get from one to another schema - * - * @return array - array of SQL queries - */ - public function getDiffSql(\Doctrine\DBAL\Schema\Schema $fromSchema, \Doctrine\DBAL\Schema\Schema $toSchema) - { - $schemaDiff = $this->getComparator()->compare($fromSchema, $toSchema); + /* + * Get SQL queries to get from one to another schema + * + * @return array - array of SQL queries + */ + public function getDiffSql(\Doctrine\DBAL\Schema\Schema $fromSchema, \Doctrine\DBAL\Schema\Schema $toSchema) + { + $schemaDiff = $this->getComparator()->compare($fromSchema, $toSchema); - return $this->toSql($schemaDiff); //$schemaDiff->toSql($this->getPlatform()); - } + return $this->toSql($schemaDiff); //$schemaDiff->toSql($this->getPlatform()); + } - /** - * Init Rebuild Actions, get all classes and create them - * @return void - */ - protected function initRebuildActions($currentSchema = null, $metadataSchema = null) - { - $methods = array('beforeRebuild', 'afterRebuild'); + /** + * Init Rebuild Actions, get all classes and create them + * @return void + */ + protected function initRebuildActions($currentSchema = null, $metadataSchema = null) + { + $methods = array('beforeRebuild', 'afterRebuild'); - $this->getClassParser()->setAllowedMethods($methods); - $rebuildActions = $this->getClassParser()->getData($this->rebuildActionsPath); + $this->getClassParser()->setAllowedMethods($methods); + $rebuildActions = $this->getClassParser()->getData($this->rebuildActionsPath); - $classes = array(); - foreach ($rebuildActions as $actionName => $actionClass) { - $rebuildActionClass = new $actionClass($this->metadata, $this->config, $this->entityManager); - if (isset($currentSchema)) { - $rebuildActionClass->setCurrentSchema($currentSchema); - } - if (isset($metadataSchema)) { - $rebuildActionClass->setMetadataSchema($metadataSchema); - } + $classes = array(); + foreach ($rebuildActions as $actionName => $actionClass) { + $rebuildActionClass = new $actionClass($this->metadata, $this->config, $this->entityManager); + if (isset($currentSchema)) { + $rebuildActionClass->setCurrentSchema($currentSchema); + } + if (isset($metadataSchema)) { + $rebuildActionClass->setMetadataSchema($metadataSchema); + } - foreach ($methods as $methodName) { - if (method_exists($rebuildActionClass, $methodName)) { - $classes[$methodName][] = $rebuildActionClass; - } - } - } + foreach ($methods as $methodName) { + if (method_exists($rebuildActionClass, $methodName)) { + $classes[$methodName][] = $rebuildActionClass; + } + } + } - $this->rebuildActionClasses = $classes; - } + $this->rebuildActionClasses = $classes; + } - /** - * Execute actions for RebuildAction classes - * @param string $action action name, possible values 'beforeRebuild' | 'afterRebuild' - * @return void - */ - protected function executeRebuildActions($action = 'beforeRebuild') - { - if (!isset($this->rebuildActionClasses)) { - $this->initRebuildActions(); - } + /** + * Execute actions for RebuildAction classes + * @param string $action action name, possible values 'beforeRebuild' | 'afterRebuild' + * @return void + */ + protected function executeRebuildActions($action = 'beforeRebuild') + { + if (!isset($this->rebuildActionClasses)) { + $this->initRebuildActions(); + } - if (isset($this->rebuildActionClasses[$action])) { - foreach ($this->rebuildActionClasses[$action] as $rebuildActionClass) { - $rebuildActionClass->$action(); - } - } - } + if (isset($this->rebuildActionClasses[$action])) { + foreach ($this->rebuildActionClasses[$action] as $rebuildActionClass) { + $rebuildActionClass->$action(); + } + } + } } diff --git a/application/Espo/Core/Utils/Database/Schema/rebuildActions/AddSystemUser.php b/application/Espo/Core/Utils/Database/Schema/rebuildActions/AddSystemUser.php index 5bfc2cba15..0c618fd520 100644 --- a/application/Espo/Core/Utils/Database/Schema/rebuildActions/AddSystemUser.php +++ b/application/Espo/Core/Utils/Database/Schema/rebuildActions/AddSystemUser.php @@ -24,23 +24,23 @@ namespace Espo\Core\Utils\Database\Schema\rebuildActions; class AddSystemUser extends \Espo\Core\Utils\Database\Schema\BaseRebuildActions { - - public function afterRebuild() - { - $userId = $this->getConfig()->get('systemUser.id'); + + public function afterRebuild() + { + $userId = $this->getConfig()->get('systemUser.id'); - $entity = $this->getEntityManager()->getEntity('User', $userId); + $entity = $this->getEntityManager()->getEntity('User', $userId); - if (!isset($entity)) { + if (!isset($entity)) { - $systemUser = $this->getConfig()->get('systemUser'); + $systemUser = $this->getConfig()->get('systemUser'); - $entity = $this->getEntityManager()->getEntity('User'); - $entity->set($systemUser); + $entity = $this->getEntityManager()->getEntity('User'); + $entity->set($systemUser); - return $this->getEntityManager()->saveEntity($entity); - } - } - + return $this->getEntityManager()->saveEntity($entity); + } + } + } diff --git a/application/Espo/Core/Utils/Database/Schema/rebuildActions/Currency.php b/application/Espo/Core/Utils/Database/Schema/rebuildActions/Currency.php index d6aed5179d..b5e030d360 100644 --- a/application/Espo/Core/Utils/Database/Schema/rebuildActions/Currency.php +++ b/application/Espo/Core/Utils/Database/Schema/rebuildActions/Currency.php @@ -25,60 +25,60 @@ namespace Espo\Core\Utils\Database\Schema\rebuildActions; class Currency extends \Espo\Core\Utils\Database\Schema\BaseRebuildActions { - public function afterRebuild() - { - $defaultCurrency = $this->getConfig()->get('defaultCurrency'); + public function afterRebuild() + { + $defaultCurrency = $this->getConfig()->get('defaultCurrency'); - $baseCurrency = $this->getConfig()->get('baseCurrency'); - $currencyRates = $this->getConfig()->get('currencyRates'); + $baseCurrency = $this->getConfig()->get('baseCurrency'); + $currencyRates = $this->getConfig()->get('currencyRates'); - if ($defaultCurrency != $baseCurrency) { - $currencyRates = $this->exchangeRates($baseCurrency, $defaultCurrency, $currencyRates); - } + if ($defaultCurrency != $baseCurrency) { + $currencyRates = $this->exchangeRates($baseCurrency, $defaultCurrency, $currencyRates); + } - $currencyRates[$defaultCurrency] = '1.00'; + $currencyRates[$defaultCurrency] = '1.00'; - $pdo = $this->getEntityManager()->getPDO(); + $pdo = $this->getEntityManager()->getPDO(); - $sql = "TRUNCATE `currency`"; - $pdo->prepare($sql)->execute(); + $sql = "TRUNCATE `currency`"; + $pdo->prepare($sql)->execute(); - foreach ($currencyRates as $currencyName => $rate) { + foreach ($currencyRates as $currencyName => $rate) { - $sql = " - INSERT INTO `currency` - (id, rate) - VALUES - (".$pdo->quote($currencyName) . ", " . $pdo->quote($rate) . ") - "; - $pdo->prepare($sql)->execute(); - } - } + $sql = " + INSERT INTO `currency` + (id, rate) + VALUES + (".$pdo->quote($currencyName) . ", " . $pdo->quote($rate) . ") + "; + $pdo->prepare($sql)->execute(); + } + } - /** - * Calculate exchange rates if defaultCurrency doesn't equals baseCurrency - * - * @param string $baseCurrency - * @param string $defaultCurrency - * @param array $currencyRates [description] - * @return array - List of new currency rates - */ - protected function exchangeRates($baseCurrency, $defaultCurrency, array $currencyRates) - { - $precision = 5; - $defaultCurrencyRate = round(1 / $currencyRates[$defaultCurrency], $precision); + /** + * Calculate exchange rates if defaultCurrency doesn't equals baseCurrency + * + * @param string $baseCurrency + * @param string $defaultCurrency + * @param array $currencyRates [description] + * @return array - List of new currency rates + */ + protected function exchangeRates($baseCurrency, $defaultCurrency, array $currencyRates) + { + $precision = 5; + $defaultCurrencyRate = round(1 / $currencyRates[$defaultCurrency], $precision); - $exchangedRates = array(); - $exchangedRates[$baseCurrency] = $defaultCurrencyRate; + $exchangedRates = array(); + $exchangedRates[$baseCurrency] = $defaultCurrencyRate; - unset($currencyRates[$baseCurrency], $currencyRates[$defaultCurrency]); + unset($currencyRates[$baseCurrency], $currencyRates[$defaultCurrency]); - foreach ($currencyRates as $currencyName => $rate) { - $exchangedRates[$currencyName] = round($rate * $defaultCurrencyRate, $precision); - } + foreach ($currencyRates as $currencyName => $rate) { + $exchangedRates[$currencyName] = round($rate * $defaultCurrencyRate, $precision); + } - return $exchangedRates; - } + return $exchangedRates; + } } diff --git a/application/Espo/Core/Utils/Database/Schema/tables/preferences.php b/application/Espo/Core/Utils/Database/Schema/tables/preferences.php index 50e4c0560d..ef661452e3 100644 --- a/application/Espo/Core/Utils/Database/Schema/tables/preferences.php +++ b/application/Espo/Core/Utils/Database/Schema/tables/preferences.php @@ -20,11 +20,11 @@ * along with EspoCRM. If not, see http://www.gnu.org/licenses/. ************************************************************************/ -return array( +return array( - 'unset' => array( - 'Preferences', - ), + 'unset' => array( + 'Preferences', + ), ); diff --git a/application/Espo/Core/Utils/Database/Schema/tables/settings.php b/application/Espo/Core/Utils/Database/Schema/tables/settings.php index d5a0c366fd..be2b892cb9 100644 --- a/application/Espo/Core/Utils/Database/Schema/tables/settings.php +++ b/application/Espo/Core/Utils/Database/Schema/tables/settings.php @@ -20,11 +20,11 @@ * along with EspoCRM. If not, see http://www.gnu.org/licenses/. ************************************************************************/ -return array( +return array( - 'unset' => array( - 'Settings', - ), + 'unset' => array( + 'Settings', + ), ); diff --git a/application/Espo/Core/Utils/Database/Schema/tables/subscription.php b/application/Espo/Core/Utils/Database/Schema/tables/subscription.php index 43cef1ae42..157530d161 100644 --- a/application/Espo/Core/Utils/Database/Schema/tables/subscription.php +++ b/application/Espo/Core/Utils/Database/Schema/tables/subscription.php @@ -22,32 +22,32 @@ return array( - 'Subscription' => array( - 'fields' => array( - 'id' => array( - 'type' => 'id', - 'dbType' => 'int', - 'len' => '11', - 'autoincrement' => true, - 'unique' => true, - ), - 'entityId' => array( - 'type' => 'varchar', - 'len' => '24', - 'index' => 'entity', - ), - 'entityType' => array( - 'type' => 'varchar', - 'len' => '100', - 'index' => 'entity', - ), - 'userId' => array( - 'type' => 'varchar', - 'len' => '24', - 'index' => true, - ), - ), - ), + 'Subscription' => array( + 'fields' => array( + 'id' => array( + 'type' => 'id', + 'dbType' => 'int', + 'len' => '11', + 'autoincrement' => true, + 'unique' => true, + ), + 'entityId' => array( + 'type' => 'varchar', + 'len' => '24', + 'index' => 'entity', + ), + 'entityType' => array( + 'type' => 'varchar', + 'len' => '100', + 'index' => 'entity', + ), + 'userId' => array( + 'type' => 'varchar', + 'len' => '24', + 'index' => true, + ), + ), + ), ); diff --git a/application/Espo/Core/Utils/DateTime.php b/application/Espo/Core/Utils/DateTime.php index b406c678e6..ee15ef8f99 100644 --- a/application/Espo/Core/Utils/DateTime.php +++ b/application/Espo/Core/Utils/DateTime.php @@ -24,60 +24,60 @@ namespace Espo\Core\Utils; class DateTime { - protected $dataFormat; - - protected $timeFormat; - - protected $timezone; - - protected $dateFormats = array( - 'MM/DD/YYYY' => 'm/d/Y', - 'YYYY-MM-DD' => 'Y-m-d', - 'DD.MM.YYYY' => 'd.m.Y', - ); - - protected $timeFormats = array( - 'HH:mm' => 'H:i', - 'hh:mm A' => 'h:i A', - 'hh:mm a' => 'h:ia', - 'hh:mmA' => 'h:iA', - ); - - public function __construct($dateFormat = 'YYYY-MM-DD', $timeFormat = 'HH:mm', $timeZone = 'UTC') - { - $this->dateFormat = $dateFormat; - $this->timeFormat = $timeFormat; - - $this->timezone = new \DateTimeZone($timeZone); - } - - protected function getPhpDateFormat() - { - return $this->dateFormats[$this->dateFormat]; - } - - protected function getPhpDateTimeFormat() - { - return $this->dateFormats[$this->dateFormat] . ' ' . $this->timeFormats[$this->timeFormat]; - } - - public function convertSystemDateToGlobal($string) - { - $dateTime = \DateTime::createFromFormat('Y-m-d', $string); - if ($dateTime) { - return $dateTime->format($this->getPhpDateFormat()); - } - return null; - } - - public function convertSystemDateTimeToGlobal($string) - { - $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', $string); - if ($dateTime) { - return $dateTime->setTimezone($this->timezone)->format($this->getPhpDateTimeFormat()); - } - return null; - } + protected $dataFormat; + + protected $timeFormat; + + protected $timezone; + + protected $dateFormats = array( + 'MM/DD/YYYY' => 'm/d/Y', + 'YYYY-MM-DD' => 'Y-m-d', + 'DD.MM.YYYY' => 'd.m.Y', + ); + + protected $timeFormats = array( + 'HH:mm' => 'H:i', + 'hh:mm A' => 'h:i A', + 'hh:mm a' => 'h:ia', + 'hh:mmA' => 'h:iA', + ); + + public function __construct($dateFormat = 'YYYY-MM-DD', $timeFormat = 'HH:mm', $timeZone = 'UTC') + { + $this->dateFormat = $dateFormat; + $this->timeFormat = $timeFormat; + + $this->timezone = new \DateTimeZone($timeZone); + } + + protected function getPhpDateFormat() + { + return $this->dateFormats[$this->dateFormat]; + } + + protected function getPhpDateTimeFormat() + { + return $this->dateFormats[$this->dateFormat] . ' ' . $this->timeFormats[$this->timeFormat]; + } + + public function convertSystemDateToGlobal($string) + { + $dateTime = \DateTime::createFromFormat('Y-m-d', $string); + if ($dateTime) { + return $dateTime->format($this->getPhpDateFormat()); + } + return null; + } + + public function convertSystemDateTimeToGlobal($string) + { + $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', $string); + if ($dateTime) { + return $dateTime->setTimezone($this->timezone)->format($this->getPhpDateTimeFormat()); + } + return null; + } } diff --git a/application/Espo/Core/Utils/FieldManager.php b/application/Espo/Core/Utils/FieldManager.php index 8ccae1fcdb..27cc6e1730 100644 --- a/application/Espo/Core/Utils/FieldManager.php +++ b/application/Espo/Core/Utils/FieldManager.php @@ -23,243 +23,243 @@ namespace Espo\Core\Utils; use \Espo\Core\Exceptions\Error, - \Espo\Core\Exceptions\Conflict; + \Espo\Core\Exceptions\Conflict; class FieldManager { - private $metadata; + private $metadata; - private $language; + private $language; - private $metadataUtils; + private $metadataUtils; - protected $isChanged = null; + protected $isChanged = null; - protected $metadataType = 'entityDefs'; + protected $metadataType = 'entityDefs'; - protected $customOptionName = 'isCustom'; + protected $customOptionName = 'isCustom'; - public function __construct(Metadata $metadata, Language $language) - { - $this->metadata = $metadata; - $this->language = $language; + public function __construct(Metadata $metadata, Language $language) + { + $this->metadata = $metadata; + $this->language = $language; - $this->metadataUtils = new \Espo\Core\Utils\Metadata\Utils($this->metadata); - } + $this->metadataUtils = new \Espo\Core\Utils\Metadata\Utils($this->metadata); + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - protected function getLanguage() - { - return $this->language; - } + protected function getLanguage() + { + return $this->language; + } - protected function getMetadataUtils() - { - return $this->metadataUtils; - } + protected function getMetadataUtils() + { + return $this->metadataUtils; + } - public function read($name, $scope) - { - $fieldDef = $this->getFieldDef($name, $scope); + public function read($name, $scope) + { + $fieldDef = $this->getFieldDef($name, $scope); - $fieldDef['label'] = $this->getLanguage()->translate($name, 'fields', $scope); + $fieldDef['label'] = $this->getLanguage()->translate($name, 'fields', $scope); - return $fieldDef; - } + return $fieldDef; + } - public function create($name, $fieldDef, $scope) - { - $existingField = $this->getFieldDef($name, $scope); - if (isset($existingField)) { - throw new Conflict('Field ['.$name.'] exists in '.$scope); - } + public function create($name, $fieldDef, $scope) + { + $existingField = $this->getFieldDef($name, $scope); + if (isset($existingField)) { + throw new Conflict('Field ['.$name.'] exists in '.$scope); + } - return $this->update($name, $fieldDef, $scope); - } + return $this->update($name, $fieldDef, $scope); + } - public function update($name, $fieldDef, $scope) - { - /*Add option to metadata to identify the custom field*/ - if (!$this->isCore($name, $scope)) { - $fieldDef[$this->customOptionName] = true; - } + public function update($name, $fieldDef, $scope) + { + /*Add option to metadata to identify the custom field*/ + if (!$this->isCore($name, $scope)) { + $fieldDef[$this->customOptionName] = true; + } - $res = true; - if (isset($fieldDef['label'])) { - $res &= $this->setLabel($name, $fieldDef['label'], $scope); - } + $res = true; + if (isset($fieldDef['label'])) { + $res &= $this->setLabel($name, $fieldDef['label'], $scope); + } - if ($this->isDefsChanged($name, $fieldDef, $scope)) { - $res &= $this->setEntityDefs($name, $fieldDef, $scope); - } + if ($this->isDefsChanged($name, $fieldDef, $scope)) { + $res &= $this->setEntityDefs($name, $fieldDef, $scope); + } - return (bool) $res; - } + return (bool) $res; + } - public function delete($name, $scope) - { - if ($this->isCore($name, $scope)) { - throw new Error('Cannot delete core field ['.$name.'] in '.$scope); - } + public function delete($name, $scope) + { + if ($this->isCore($name, $scope)) { + throw new Error('Cannot delete core field ['.$name.'] in '.$scope); + } - $unsets = array( - 'fields.'.$name, - 'links.'.$name, - ); + $unsets = array( + 'fields.'.$name, + 'links.'.$name, + ); - $res = $this->getMetadata()->delete($unsets, $this->metadataType, $scope); + $res = $this->getMetadata()->delete($unsets, $this->metadataType, $scope); - $this->deleteLabel($name, $scope); + $this->deleteLabel($name, $scope); - return $res; - } + return $res; + } - protected function setEntityDefs($name, $fieldDef, $scope) - { - $fieldDef = $this->normalizeDefs($name, $fieldDef, $scope); + protected function setEntityDefs($name, $fieldDef, $scope) + { + $fieldDef = $this->normalizeDefs($name, $fieldDef, $scope); - $data = Json::encode($fieldDef); - $res = $this->getMetadata()->set($data, $this->metadataType, $scope); + $data = Json::encode($fieldDef); + $res = $this->getMetadata()->set($data, $this->metadataType, $scope); - return $res; - } + return $res; + } - protected function setLabel($name, $value, $scope) - { - return $this->getLanguage()->set($name, $value, 'fields', $scope); - } + protected function setLabel($name, $value, $scope) + { + return $this->getLanguage()->set($name, $value, 'fields', $scope); + } - protected function deleteLabel($name, $scope) - { - return $this->getLanguage()->delete($name, 'fields', $scope); - } + protected function deleteLabel($name, $scope) + { + return $this->getLanguage()->delete($name, 'fields', $scope); + } - protected function getFieldDef($name, $scope) - { - return $this->getMetadata()->get($this->metadataType.'.'.$scope.'.fields.'.$name); - } + protected function getFieldDef($name, $scope) + { + return $this->getMetadata()->get($this->metadataType.'.'.$scope.'.fields.'.$name); + } - protected function getLinkDef($name, $scope) - { - return $this->getMetadata()->get($this->metadataType.'.'.$scope.'.links.'.$name); - } + protected function getLinkDef($name, $scope) + { + return $this->getMetadata()->get($this->metadataType.'.'.$scope.'.links.'.$name); + } - /** - * Prepare input fieldDefs, remove unnecessary fields - * - * @param string $fieldName - * @param array $fieldDef - * @param string $scope - * @return array - */ - protected function prepareFieldDef($name, $fieldDef, $scope) - { - $unnecessaryFields = array( - 'name', - 'label', - ); + /** + * Prepare input fieldDefs, remove unnecessary fields + * + * @param string $fieldName + * @param array $fieldDef + * @param string $scope + * @return array + */ + protected function prepareFieldDef($name, $fieldDef, $scope) + { + $unnecessaryFields = array( + 'name', + 'label', + ); - foreach ($unnecessaryFields as $fieldName) { - if (isset($fieldDef[$fieldName])) { - unset($fieldDef[$fieldName]); - } - } + foreach ($unnecessaryFields as $fieldName) { + if (isset($fieldDef[$fieldName])) { + unset($fieldDef[$fieldName]); + } + } - if (isset($fieldDef['linkDefs'])) { - $linkDefs = $fieldDef['linkDefs']; - unset($fieldDef['linkDefs']); - } + if (isset($fieldDef['linkDefs'])) { + $linkDefs = $fieldDef['linkDefs']; + unset($fieldDef['linkDefs']); + } - $currentOptionList = array_keys((array) $this->getFieldDef($name, $scope)); - foreach ($fieldDef as $defName => $defValue) { - if ( (!isset($defValue) || $defValue === '') && !in_array($defName, $currentOptionList) ) { - unset($fieldDef[$defName]); - } - } + $currentOptionList = array_keys((array) $this->getFieldDef($name, $scope)); + foreach ($fieldDef as $defName => $defValue) { + if ( (!isset($defValue) || $defValue === '') && !in_array($defName, $currentOptionList) ) { + unset($fieldDef[$defName]); + } + } - return $fieldDef; - } + return $fieldDef; + } - /** - * Add all needed block for a field defenition - * - * @param string $fieldName - * @param array $fieldDef - * @param string $scope - * @return array - */ - protected function normalizeDefs($fieldName, array $fieldDef, $scope) - { - $fieldDef = $this->prepareFieldDef($fieldName, $fieldDef, $scope); + /** + * Add all needed block for a field defenition + * + * @param string $fieldName + * @param array $fieldDef + * @param string $scope + * @return array + */ + protected function normalizeDefs($fieldName, array $fieldDef, $scope) + { + $fieldDef = $this->prepareFieldDef($fieldName, $fieldDef, $scope); - $metaFieldDef = $this->getMetadataUtils()->getFieldDefsInFieldMeta($fieldDef); - if (isset($metaFieldDef)) { - $fieldDef = Util::merge($metaFieldDef, $fieldDef); - } + $metaFieldDef = $this->getMetadataUtils()->getFieldDefsInFieldMeta($fieldDef); + if (isset($metaFieldDef)) { + $fieldDef = Util::merge($metaFieldDef, $fieldDef); + } - $defs = array( - 'fields' => array( - $fieldName => $fieldDef, - ), - ); + $defs = array( + 'fields' => array( + $fieldName => $fieldDef, + ), + ); - /** Save links for a field. */ - $metaLinkDef = $this->getMetadataUtils()->getLinkDefsInFieldMeta($scope, $fieldDef); - if (isset($linkDefs) || isset($metaLinkDef)) { - $linkDefs = Util::merge((array) $metaLinkDef, (array) $linkDefs); - $defs['links'] = array( - $fieldName => $linkDefs, - ); - } + /** Save links for a field. */ + $metaLinkDef = $this->getMetadataUtils()->getLinkDefsInFieldMeta($scope, $fieldDef); + if (isset($linkDefs) || isset($metaLinkDef)) { + $linkDefs = Util::merge((array) $metaLinkDef, (array) $linkDefs); + $defs['links'] = array( + $fieldName => $linkDefs, + ); + } - return $defs; - } + return $defs; + } - /** - * Check if changed metadata defenition for a field except 'label' - * - * @return boolean - */ - protected function isDefsChanged($name, $fieldDef, $scope) - { - $fieldDef = $this->prepareFieldDef($name, $fieldDef, $scope); - $currentFieldDef = $this->getFieldDef($name, $scope); + /** + * Check if changed metadata defenition for a field except 'label' + * + * @return boolean + */ + protected function isDefsChanged($name, $fieldDef, $scope) + { + $fieldDef = $this->prepareFieldDef($name, $fieldDef, $scope); + $currentFieldDef = $this->getFieldDef($name, $scope); - $this->isChanged = Util::isEquals($fieldDef, $currentFieldDef) ? false : true; + $this->isChanged = Util::isEquals($fieldDef, $currentFieldDef) ? false : true; - return $this->isChanged; - } + return $this->isChanged; + } - /** - * Only for update method - * - * @return boolean - */ - public function isChanged() - { - return $this->isChanged; - } + /** + * Only for update method + * + * @return boolean + */ + public function isChanged() + { + return $this->isChanged; + } - /** - * Check if a field is core field - * - * @param string $name - * @param string $scope - * @return boolean - */ - protected function isCore($name, $scope) - { - $existingField = $this->getFieldDef($name, $scope); - if (isset($existingField) && (!isset($existingField[$this->customOptionName]) || !$existingField[$this->customOptionName])) { - return true; - } + /** + * Check if a field is core field + * + * @param string $name + * @param string $scope + * @return boolean + */ + protected function isCore($name, $scope) + { + $existingField = $this->getFieldDef($name, $scope); + if (isset($existingField) && (!isset($existingField[$this->customOptionName]) || !$existingField[$this->customOptionName])) { + return true; + } - return false; - } + return false; + } } \ No newline at end of file diff --git a/application/Espo/Core/Utils/File/ClassParser.php b/application/Espo/Core/Utils/File/ClassParser.php index a404c54736..81fa76b8d6 100644 --- a/application/Espo/Core/Utils/File/ClassParser.php +++ b/application/Espo/Core/Utils/File/ClassParser.php @@ -26,124 +26,124 @@ use \Espo\Core\Utils\Util; class ClassParser { - private $fileManager; + private $fileManager; - private $config; + private $config; - private $metadata; + private $metadata; - protected $cacheFile = null; + protected $cacheFile = null; - protected $allowedMethods = array( - 'run', - ); + protected $allowedMethods = array( + 'run', + ); - public function __construct(\Espo\Core\Utils\File\Manager $fileManager, \Espo\Core\Utils\Config $config, \Espo\Core\Utils\Metadata $metadata) - { - $this->fileManager = $fileManager; - $this->config = $config; - $this->metadata = $metadata; - } + public function __construct(\Espo\Core\Utils\File\Manager $fileManager, \Espo\Core\Utils\Config $config, \Espo\Core\Utils\Metadata $metadata) + { + $this->fileManager = $fileManager; + $this->config = $config; + $this->metadata = $metadata; + } - protected function getFileManager() - { - return $this->fileManager; - } + protected function getFileManager() + { + return $this->fileManager; + } - protected function getConfig() - { - return $this->config; - } + protected function getConfig() + { + return $this->config; + } - protected function getMetadata() - { - return $this->metadata; - } + protected function getMetadata() + { + return $this->metadata; + } - public function setAllowedMethods(array $methods) - { - $this->allowedMethods = $methods; - } + public function setAllowedMethods(array $methods) + { + $this->allowedMethods = $methods; + } - /** - * Return path data of classes - * @param string $cacheFile full path for a cache file, ex. data/cache/application/entryPoints.php - * @param string | array $paths in format array( - * 'corePath' => '', - * 'modulePath' => '', - * 'customPath' => '', - * ); - * @return array - */ - public function getData($paths, $cacheFile = false) - { - $data = null; + /** + * Return path data of classes + * @param string $cacheFile full path for a cache file, ex. data/cache/application/entryPoints.php + * @param string | array $paths in format array( + * 'corePath' => '', + * 'modulePath' => '', + * 'customPath' => '', + * ); + * @return array + */ + public function getData($paths, $cacheFile = false) + { + $data = null; - if (is_string($paths)) { - $paths = array( - 'corePath' => $paths, - ); - } + if (is_string($paths)) { + $paths = array( + 'corePath' => $paths, + ); + } - if ($cacheFile && file_exists($cacheFile) && $this->getConfig()->get('useCache')) { - $data = $this->getFileManager()->getContents($cacheFile); - } else { - $data = $this->getClassNameHash($paths['corePath']); + if ($cacheFile && file_exists($cacheFile) && $this->getConfig()->get('useCache')) { + $data = $this->getFileManager()->getContents($cacheFile); + } else { + $data = $this->getClassNameHash($paths['corePath']); - if (isset($paths['modulePath'])) { - foreach ($this->getMetadata()->getModuleList() as $moduleName) { - $path = str_replace('{*}', $moduleName, $paths['modulePath']); + if (isset($paths['modulePath'])) { + foreach ($this->getMetadata()->getModuleList() as $moduleName) { + $path = str_replace('{*}', $moduleName, $paths['modulePath']); - $data = array_merge($data, $this->getClassNameHash($path)); - } - } + $data = array_merge($data, $this->getClassNameHash($path)); + } + } - if (isset($paths['customPath'])) { - $data = array_merge($data, $this->getClassNameHash($paths['customPath'])); - } - - if ($cacheFile && $this->getConfig()->get('useCache')) { - $result = $this->getFileManager()->putContentsPHP($cacheFile, $data); - if ($result == false) { - throw new \Espo\Core\Exceptions\Error(); - } - } - } + if (isset($paths['customPath'])) { + $data = array_merge($data, $this->getClassNameHash($paths['customPath'])); + } + + if ($cacheFile && $this->getConfig()->get('useCache')) { + $result = $this->getFileManager()->putContentsPHP($cacheFile, $data); + if ($result == false) { + throw new \Espo\Core\Exceptions\Error(); + } + } + } - return $data; - } - + return $data; + } + - protected function getClassNameHash($dirs) - { - if (is_string($dirs)) { - $dirs = (array) $dirs; - } + protected function getClassNameHash($dirs) + { + if (is_string($dirs)) { + $dirs = (array) $dirs; + } - $data = array(); - foreach ($dirs as $dir) { - if (file_exists($dir)) { - $fileList = $this->getFileManager()->getFileList($dir, false, '\.php$', 'file'); + $data = array(); + foreach ($dirs as $dir) { + if (file_exists($dir)) { + $fileList = $this->getFileManager()->getFileList($dir, false, '\.php$', 'file'); - foreach ($fileList as $file) { - $filePath = Util::concatPath($dir, $file); - $className = Util::getClassName($filePath); - $fileName = $this->getFileManager()->getFileName($filePath); - $fileName = ucfirst($fileName); + foreach ($fileList as $file) { + $filePath = Util::concatPath($dir, $file); + $className = Util::getClassName($filePath); + $fileName = $this->getFileManager()->getFileName($filePath); + $fileName = ucfirst($fileName); - foreach ($this->allowedMethods as $methodName) { - if (method_exists($className, $methodName)) { - $data[$fileName] = $className; - } - } - - } - } - } + foreach ($this->allowedMethods as $methodName) { + if (method_exists($className, $methodName)) { + $data[$fileName] = $className; + } + } + + } + } + } - return $data; - } - + return $data; + } + } \ No newline at end of file diff --git a/application/Espo/Core/Utils/File/Manager.php b/application/Espo/Core/Utils/File/Manager.php index 7865cc2f22..5197a5ee28 100644 --- a/application/Espo/Core/Utils/File/Manager.php +++ b/application/Espo/Core/Utils/File/Manager.php @@ -23,613 +23,613 @@ namespace Espo\Core\Utils\File; use Espo\Core\Utils, - Espo\Core\Exceptions\Error; + Espo\Core\Exceptions\Error; class Manager { - private $permission; - - public function __construct(\Espo\Core\Utils\Config $config = null) - { - $params = null; - if (isset($config)) { - $params = array( - 'defaultPermissions' => $config->get('defaultPermissions'), - 'permissionMap' => $config->get('permissionMap'), - ); - } - - $this->permission = new Permission($this, $params); - } - - public function getPermissionUtils() - { - return $this->permission; - } - - /** - * Get a list of files in specified directory - * - * @param string $path string - Folder path, Ex. myfolder - * @param bool | int $recursively - Find files in subfolders - * @param string $filter - Filter for files. Use regular expression, Ex. \.json$ - * @param string $fileType [all, file, dir] - Filter for type of files/directories. - * @param bool $isReturnSingleArray - if need to return a single array of file list - * - * @return array - */ - public function getFileList($path, $recursively=false, $filter='', $fileType='all', $isReturnSingleArray = false) - { - if (!file_exists($path)) { - return false; - } - - $result = array(); - - $cdir = scandir($path); - foreach ($cdir as $key => $value) - { - if (!in_array($value,array(".",".."))) - { - $add= false; - if (is_dir($path . Utils\Util::getSeparator() . $value)) { - if ($recursively || (is_int($recursively) && $recursively!=0) ) { - $nextRecursively = is_int($recursively) ? ($recursively-1) : $recursively; - $result[$value] = $this->getFileList($path.Utils\Util::getSeparator().$value, $nextRecursively, $filter, $fileType); - } - else if (in_array($fileType, array('all', 'dir'))){ - $add= true; - } - } - else if (in_array($fileType, array('all', 'file'))) { - $add= true; - } - - if ($add) { - if (!empty($filter)) { - if (preg_match('/'.$filter.'/i', $value)) { - $result[] = $value; - } - } - else { - $result[] = $value; - } - } - - } - } - - if ($isReturnSingleArray) { - return $this->getSingeFileList($result); - } - - return $result; - } - - /** - * Convert file list to a single array - * - * @param aray $fileList - * @param string $parentDirName - * - * @return aray - */ - protected function getSingeFileList(array $fileList, $parentDirName = '') - { - $singleFileList = array(); - foreach($fileList as $dirName => $fileName) { - - if (is_array($fileName)) { - $currentDir = Utils\Util::concatPath($parentDirName, $dirName); - $singleFileList = array_merge($singleFileList, $this->getSingeFileList($fileName, $currentDir)); - } else { - $singleFileList[] = Utils\Util::concatPath($parentDirName, $fileName); - } - } - - return $singleFileList; - } - - /** - * Reads entire file into a string - * - * @param string | array $path Ex. 'path.php' OR array('dir', 'path.php') - * @param boolean $useIncludePath - * @param resource $context - * @param integer $offset - * @param integer $maxlen - * @return mixed - */ - public function getContents($path, $useIncludePath = false, $context = null, $offset = -1, $maxlen = null) - { - $fullPath = $this->concatPaths($path); - - if (file_exists($fullPath)) { - - if (strtolower(substr($fullPath, -4))=='.php') { - return include($fullPath); - } else { - if (isset($maxlen)) { - return file_get_contents($fullPath, $useIncludePath, $context, $offset, $maxlen); - } else { - return file_get_contents($fullPath, $useIncludePath, $context, $offset); - } - } - - } - - return false; - } - - /** - * Write data to a file - * - * @param string | array $path - * @param mixed $data - * @param integer $flags - * @param resource $context - * - * @return bool - */ - public function putContents($path, $data, $flags = 0, $context = null) - { - $fullPath = $this->concatPaths($path); //todo remove after changing the params - - if ($this->checkCreateFile($fullPath) === false) { - throw new Error('Permission denied in '. $fullPath); - } - - $res = (file_put_contents($fullPath, $data, $flags, $context) !== FALSE); - if ($res && function_exists('opcache_invalidate')) { - opcache_invalidate($fullPath); - } - - return $res; - } - - /** - * Save PHP content to file - * - * @param string | array $path - * @param string $data - * - * @return bool - */ - public function putContentsPHP($path, $data) - { - return $this->putContents($path, $this->getPHPFormat($data)); - } - - /** - * Save JSON content to file - * - * @param string | array $path - * @param string $data - * @param integer $flags - * @param resource $context - * - * @return bool - */ - public function putContentsJson($path, $data) - { - if (!Utils\Json::isJSON($data)) { - $data = Utils\Json::encode($data, JSON_PRETTY_PRINT); - } - - return $this->putContents($path, $data); - } - - /** - * Merge file content and save it to a file - * - * @param string | array $path - * @param string $content JSON string - * @param bool $isJSON - * @param string | array $removeOptions - List of unset keys from content - * @param bool $isReturn - Is result to be returned or stored - * - * @return bool | array - */ - public function mergeContents($path, $content, $isJSON = false, $removeOptions = null, $isReturn = false) - { - $fileContent = $this->getContents($path); - - $savedDataArray = Utils\Json::getArrayData($fileContent); - $newDataArray = Utils\Json::getArrayData($content); - - if (isset($removeOptions)) { - $savedDataArray = Utils\Util::unsetInArray($savedDataArray, $removeOptions); - $newDataArray = Utils\Util::unsetInArray($newDataArray, $removeOptions); - } - - $data = Utils\Util::merge($savedDataArray, $newDataArray); - if ($isJSON) { - $data = Utils\Json::encode($data, JSON_PRETTY_PRINT); - } - - if ($isReturn) { - return $data; - } - - return $this->putContents($path, $data); - } - - /** - * Merge PHP content and save it to a file - * - * @param string | array $path - * @param string $content JSON string - * @param string | array $removeOptions - List of unset keys from content - * @return bool - */ - public function mergeContentsPHP($path, $content, $removeOptions = null) - { - $data = $this->mergeContents($path, $content, false, $removeOptions, true); - - return $this->putContentsPHP($path, $data); - } - - /** - * Append the content to the end of the file - * - * @param string | array $path - * @param mixed $data - * - * @return bool - */ - public function appendContents($path, $data) - { - return $this->putContents($path, $data, FILE_APPEND | LOCK_EX); - } - - /** - * Unset some element of content data - * - * @param string | array $path - * @param array | string $unsets [description] - * @return bool - */ - public function unsetContents($path, $unsets, $isJSON = true) - { - $currentData = $this->getContents($path); - if ($currentData == false) { - $GLOBALS['log']->notice('FileManager::unsetContents: File ['.$this->concatPaths($path).'] does not exist.'); - return false; - } - - $currentDataArray = Utils\Json::getArrayData($currentData); - - $unsettedData = Utils\Util::unsetInArray($currentDataArray, $unsets); - - if ($isJSON) { - return $this->putContentsJson($path, $unsettedData); - } - - return $this->putContents($path, $unsettedData); - } - - - /** - * Concat paths - * @param string | array $paths Ex. array('pathPart1', 'pathPart2', 'pathPart3') - * @return string - */ - protected function concatPaths($paths) - { - if (is_string($paths)) { - return $paths; - } - - $fullPath = ''; - foreach ($paths as $path) { - $fullPath = Utils\Util::concatPath($fullPath, $path); - } - - return $fullPath; - } - - /** - * Create a new dir - * - * @param string | array $path - * @param int $permission - ex. 0755 - * @return bool - */ - public function mkdir($path, $permission = null) - { - $fullPath = $this->concatPaths($path); - - if (file_exists($fullPath) && is_dir($path)) { - return true; - } - - if (!isset($permission)) { - $defaultPermissions = $this->getPermissionUtils()->getDefaultPermissions(); - $permission = (string) $defaultPermissions['dir']; - $permission = base_convert($permission, 8, 10); - } - - try { - $result = mkdir($fullPath, $permission, true); - } catch (\Exception $e) { - $GLOBALS['log']->critical('Permission denied: unable to create the folder on the server - '.$fullPath); - } - - return isset($result) ? $result : false; - } - - /** - * Copy files from one direcoty to another - * Ex. $sourcePath = 'data/uploads/extensions/file.json', $destPath = 'data/uploads/backup', result will be data/uploads/backup/data/uploads/backup/file.json. - * - * @param string $sourcePath - * @param string $destPath - * @param boolean $recursively - * @param array $fileList - list of files that should be copied - * @param boolean $copyOnlyFiles - copy only files, instead of full path with directories, Ex. $sourcePath = 'data/uploads/extensions/file.json', $destPath = 'data/uploads/backup', result will be 'data/uploads/backup/file.json' - * @return boolen - */ - public function copy($sourcePath, $destPath, $recursively = false, array $fileList = null, $copyOnlyFiles = false) - { - $sourcePath = $this->concatPaths($sourcePath); - $destPath = $this->concatPaths($destPath); - - if (isset($fileList)) { - if (!empty($sourcePath)) { - foreach ($fileList as &$fileName) { - $fileName = $this->concatPaths(array($sourcePath, $fileName)); - } - } - } else { - $fileList = is_file($sourcePath) ? (array) $sourcePath : $this->getFileList($sourcePath, $recursively, '', 'file', true); - } - - /** Check permission before copying */ - $permissionDeniedList = array(); - foreach ($fileList as $file) { - - if ($copyOnlyFiles) { - $file = pathinfo($file, PATHINFO_BASENAME); - } - - $destFile = $this->concatPaths(array($destPath, $file)); - - $isFileExists = file_exists($destFile); - - if ($this->checkCreateFile($destFile) === false) { - $permissionDeniedList[] = $destFile; - } else if (!$isFileExists) { - $this->removeFile($destFile); - } - } - /** END */ - - if (!empty($permissionDeniedList)) { - $betterPermissionList = $this->getPermissionUtils()->arrangePermissionList($permissionDeniedList); - throw new Error("Permission denied in