diff --git a/.gitignore b/.gitignore index 9316009db..a39a2abc1 100755 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,4 @@ workflow/public_html/build-log.html temp.txt update.sh workflow/public_html/translations/ +build-prod.zip diff --git a/Rakefile b/Rakefile index d90e3fdf6..075899ae0 100644 --- a/Rakefile +++ b/Rakefile @@ -36,7 +36,6 @@ task :build => [:required] do puts "Seems it is not a ProcessMaker installation" exit(1) end - if mode == "production" targetDir = publicDir + "/lib" pmUIFontsDir = targetDir + "/fonts" @@ -55,9 +54,10 @@ task :build => [:required] do pmdynaformDir = targetDir + "/pmdynaform" prepareDirs([targetDir, pmUIDir, mafeDir, pmdynaformDir, jsTargetDir, cssTargetDir, cssImagesTargetDir, imgTargetDir, pmUIFontsDir]) - + buildPmUi(Dir.pwd + "/vendor/colosa/pmUI", targetDir, mode) buildPmdynaform(Dir.pwd + "/vendor/colosa/pmDynaform", targetDir, mode) + buildPmdynaformZip(Dir.pwd + "/vendor/colosa/pmDynaform", publicDir) buildMafe(Dir.pwd + "/vendor/colosa/MichelangeloFE", targetDir, mode) @@ -67,7 +67,7 @@ task :build => [:required] do pmdynaformHash = getHash(Dir.pwd + "/vendor/colosa/pmDynaform") hashVendors = pmuiHash+"-"+mafeHash - ## Building minified JS Files + ## Building minified JS Files puts "Building file: " + "/js/mafe-#{hashVendors}.js".cyan mafeCompresedFile = targetDir + "/js/mafe-#{hashVendors}.js" mafeCompresedContent = "" @@ -168,18 +168,18 @@ end def buildPmdynaform(homeDir, targetDir, mode) puts "\nBuilding PmDynaform library".green.bold - + # Defining target directories pmdynaformDir = targetDir + "/pmdynaform" - + executeInto(homeDir, [ "default"]) - + require 'fileutils' Dir.mkdir("#{pmdynaformDir}/build") FileUtils.cp_r(Dir["#{homeDir}/build/*"],"#{pmdynaformDir}/build") Dir.mkdir("#{pmdynaformDir}/libs") FileUtils.cp_r(Dir["#{homeDir}/libs/*"],"#{pmdynaformDir}/libs") - + template = "" config = File.read "#{homeDir}/config/templates.json" json = JSON.parse config @@ -191,14 +191,14 @@ def buildPmdynaform(homeDir, targetDir, mode) end template += s end - + htmlTemplates=["pmdynaform.html"] htmlTemplates.each do |htmlTemplate| - + FileUtils.cp("#{Dir.pwd}/workflow/engine/templates/cases/#{htmlTemplate}", "#{pmdynaformDir}/build/#{htmlTemplate}") - + target = "#{pmdynaformDir}/build/#{htmlTemplate}" - html = File.read target + html = File.read target while html['###TEMPLATES##'] do html['###TEMPLATES###'] = template end @@ -206,10 +206,17 @@ def buildPmdynaform(homeDir, targetDir, mode) file.write html end end - + puts "\nPmDynaform Build Finished!".magenta end +def buildPmdynaformZip(homeDir, targetDir) + puts "\nBuilding Compress Zip library".green.bold + executeInto(homeDir, [ "mobile"]) + copyFiles({homeDir + "/build-prod-zip/build-prod.zip" => targetDir + "/build-prod.zip"}) + puts "\nPmDynaform Zip Build Finished!".magenta +end + def buildMafe(homeDir, targetDir, mode) puts "\nBuilding PM Michelangelo FE".green.bold diff --git a/composer.json b/composer.json index 25c917942..5bde68138 100644 --- a/composer.json +++ b/composer.json @@ -29,10 +29,11 @@ "require": { "luracast/restler": "3.0.0-RC4", "bshaffer/oauth2-server-php": "v1.0", - "colosa/pmUI": "3.0.1.7-dev", - "colosa/MichelangeloFE": "3.0.1.7-dev", - "colosa/pmdynaform": "3.0.1.7-dev", - "google/apiclient": "1.1.*" + "colosa/pmUI": "3.0.1.8-dev", + "colosa/MichelangeloFE": "3.0.1.8-dev", + "colosa/pmdynaform": "3.0.1.8-dev", + "google/apiclient": "1.1.6", + "dapphp/securimage": "^3.6" }, "require-dev": { "guzzle/guzzle": "~3.1.1", diff --git a/composer.lock b/composer.lock index ef1071ec8..f551bbfc2 100644 --- a/composer.lock +++ b/composer.lock @@ -1,11 +1,10 @@ { "_readme": [ "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "825573bc1314750cc28719fdefa10188", - "content-hash": "5676f6b643350586ab660d49aa2020be", + "hash": "9c7ee173ce908a40f4ed9aecaa30b068", "packages": [ { "name": "bshaffer/oauth2-server-php", @@ -30,7 +29,7 @@ "OAuth2": "src/" } }, - "notification-url": "http://packagist.org/downloads/", + "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], @@ -38,7 +37,7 @@ { "name": "Brent Shaffer", "email": "bshafs@gmail.com", - "homepage": "http://github.com/bshaffer" + "homepage": "http://brentertainment.com" } ], "description": "OAuth2 Server for PHP", @@ -52,14 +51,14 @@ }, { "name": "colosa/MichelangeloFE", - "version": "3.0.1.7-dev", + "version": "3.0.1.8-dev", "source": { "type": "git", "url": "git@bitbucket.org:colosa/michelangelofe.git", - "reference": "4e32cb2a2dce6e0dbe697634f9b1abaa4c1dae62" + "reference": "8878311a3f6c08cad2a0ee2cff9f6ecb7aa097a7" }, "require": { - "colosa/pmui": "3.0.1.7-dev" + "colosa/pmui": "3.0.1.8-dev" }, "type": "library", "description": "ProcessMaker Michelangelo Front End", @@ -67,15 +66,15 @@ "keywords": [ "js app ProcessMaker" ], - "time": "2015-11-30 23:51:44" + "time": "2016-02-29 19:49:15" }, { "name": "colosa/pmDynaform", - "version": "3.0.1.7-dev", + "version": "3.0.1.8-dev", "source": { "type": "git", "url": "git@bitbucket.org:colosa/pmdynaform.git", - "reference": "a785a3322788a09c403e9d21cb1629e34582da23" + "reference": "320128bf394f851209d9216123a45afd269bcf4c" }, "type": "library", "description": "JS Library to render ProcessMaker Dynaforms", @@ -83,15 +82,15 @@ "keywords": [ "js lib ProcessMaker Dynaforms" ], - "time": "2015-11-30 22:02:05" + "time": "2016-02-26 21:40:47" }, { "name": "colosa/pmUI", - "version": "3.0.1.7-dev", + "version": "3.0.1.8-dev", "source": { "type": "git", "url": "git@bitbucket.org:colosa/pmui.git", - "reference": "4b43a3747d8e70788c1163b166d08e5ae81f968d" + "reference": "851ee86a1006df111ee8b281bf2b033cdbcc6f0b" }, "type": "library", "description": "JS UI Library", @@ -99,7 +98,7 @@ "keywords": [ "js lib ProcessMaker UI" ], - "time": "2015-11-25 14:03:05" + "time": "2016-02-26 21:41:50" }, { "name": "google/apiclient", @@ -222,723 +221,25 @@ "packages-dev": [ { "name": "behat/behat", - "version": "v2.4.6", - "source": { - "type": "git", - "url": "https://github.com/Behat/Behat.git", - "reference": "f1d2964667cf4b21bb6c2c1564f26829a6954155" - }, + "version": "2.4.6", "dist": { "type": "zip", "url": "https://api.github.com/repos/Behat/Behat/zipball/f1d2964667cf4b21bb6c2c1564f26829a6954155", - "reference": "f1d2964667cf4b21bb6c2c1564f26829a6954155", - "shasum": "" + "reference": null, + "shasum": "d8aada3ba96925c26f242a602f4692709810a39b" }, - "require": { - "behat/gherkin": "~2.2.9", - "php": ">=5.3.1", - "symfony/config": "~2.0", - "symfony/console": "~2.0", - "symfony/dependency-injection": "~2.0", - "symfony/event-dispatcher": "~2.0", - "symfony/finder": "~2.0", - "symfony/translation": "~2.0", - "symfony/yaml": "~2.0" - }, - "require-dev": { - "phpunit/phpunit": "~3.7.19" - }, - "suggest": { - "behat/mink-extension": "for integration with Mink testing framework", - "behat/symfony2-extension": "for integration with Symfony2 web framework", - "behat/yii-extension": "for integration with Yii web framework" - }, - "bin": [ - "bin/behat" - ], - "type": "library", - "extra": { - "branch-alias": { - "dev-develop": "2.4-dev" - } - }, - "autoload": { - "psr-0": { - "Behat\\Behat": "src/" - } - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Konstantin Kudryashov", - "email": "ever.zet@gmail.com", - "homepage": "http://everzet.com" - } - ], - "description": "Scenario-oriented BDD framework for PHP 5.3", - "homepage": "http://behat.org/", - "keywords": [ - "BDD", - "Behat", - "Symfony2" - ], - "time": "2013-06-06 10:46:48" - }, - { - "name": "behat/gherkin", - "version": "v2.2.9", - "source": { - "type": "git", - "url": "https://github.com/Behat/Gherkin.git", - "reference": "cca2c477921ca38578d6e9759ea5e450f29c2d8f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Behat/Gherkin/zipball/cca2c477921ca38578d6e9759ea5e450f29c2d8f", - "reference": "cca2c477921ca38578d6e9759ea5e450f29c2d8f", - "shasum": "" - }, - "require": { - "php": ">=5.3.1", - "symfony/finder": ">=2.0,<2.4-dev" - }, - "require-dev": { - "symfony/config": ">=2.0,<2.4-dev", - "symfony/translation": ">=2.0,<2.4-dev", - "symfony/yaml": ">=2.0,<2.4-dev" - }, - "suggest": { - "symfony/config": "If you want to use Config component to manage resources", - "symfony/translation": "If you want to use Symfony2 translations adapter", - "symfony/yaml": "If you want to parse features, represented in YAML files" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-develop": "2.2-dev" - } - }, - "autoload": { - "psr-0": { - "Behat\\Gherkin": "src/" - } - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Konstantin Kudryashov", - "email": "ever.zet@gmail.com", - "homepage": "http://everzet.com" - } - ], - "description": "Gherkin DSL parser for PHP 5.3", - "homepage": "http://behat.org/", - "keywords": [ - "BDD", - "Behat", - "DSL", - "Symfony2", - "parser" - ], - "time": "2013-03-02 10:38:40" + "type": "library" }, { "name": "guzzle/guzzle", - "version": "v3.1.2", - "source": { - "type": "git", - "url": "https://github.com/guzzle/guzzle.git", - "reference": "7901ea7d27373d0cc85eac6f6694e4c2ced90a26" - }, + "version": "3.1.2", "dist": { "type": "zip", "url": "https://api.github.com/repos/guzzle/guzzle/zipball/7901ea7d27373d0cc85eac6f6694e4c2ced90a26", - "reference": "7901ea7d27373d0cc85eac6f6694e4c2ced90a26", - "shasum": "" + "reference": null, + "shasum": "25bc38119541c151c455c3140b4dc388d7ec4187" }, - "require": { - "ext-curl": "*", - "php": ">=5.3.2", - "symfony/event-dispatcher": ">=2.1" - }, - "replace": { - "guzzle/batch": "self.version", - "guzzle/cache": "self.version", - "guzzle/common": "self.version", - "guzzle/http": "self.version", - "guzzle/inflection": "self.version", - "guzzle/iterator": "self.version", - "guzzle/log": "self.version", - "guzzle/parser": "self.version", - "guzzle/plugin": "self.version", - "guzzle/plugin-async": "self.version", - "guzzle/plugin-backoff": "self.version", - "guzzle/plugin-cache": "self.version", - "guzzle/plugin-cookie": "self.version", - "guzzle/plugin-curlauth": "self.version", - "guzzle/plugin-history": "self.version", - "guzzle/plugin-log": "self.version", - "guzzle/plugin-md5": "self.version", - "guzzle/plugin-mock": "self.version", - "guzzle/plugin-oauth": "self.version", - "guzzle/service": "self.version", - "guzzle/stream": "self.version" - }, - "require-dev": { - "doctrine/common": "*", - "monolog/monolog": "1.*", - "phpunit/phpunit": "3.7.*", - "symfony/class-loader": "*", - "zend/zend-cache1": "1.12", - "zend/zend-log1": "1.12", - "zendframework/zend-cache": "2.0.*", - "zendframework/zend-log": "2.0.*" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "3.1-dev" - } - }, - "autoload": { - "psr-0": { - "Guzzle\\Tests": "tests/", - "Guzzle": "src/" - } - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Michael Dowling", - "email": "mtdowling@gmail.com", - "homepage": "https://github.com/mtdowling" - }, - { - "name": "Guzzle Community", - "homepage": "https://github.com/guzzle/guzzle/contributors" - } - ], - "description": "Guzzle is a PHP HTTP client library and framework for building RESTful web service clients", - "homepage": "http://guzzlephp.org/", - "keywords": [ - "client", - "curl", - "framework", - "http", - "http client", - "rest", - "web service" - ], - "time": "2013-01-28 00:07:40" - }, - { - "name": "symfony/config", - "version": "v2.8.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/config.git", - "reference": "f21c97aec1b5302d2dc0d17047ea8f4e4ff93aae" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/f21c97aec1b5302d2dc0d17047ea8f4e4ff93aae", - "reference": "f21c97aec1b5302d2dc0d17047ea8f4e4ff93aae", - "shasum": "" - }, - "require": { - "php": ">=5.3.9", - "symfony/filesystem": "~2.3|~3.0.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.8-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\Config\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Config Component", - "homepage": "https://symfony.com", - "time": "2015-11-23 20:38:01" - }, - { - "name": "symfony/console", - "version": "v2.8.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/console.git", - "reference": "d232bfc100dfd32b18ccbcab4bcc8f28697b7e41" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/d232bfc100dfd32b18ccbcab4bcc8f28697b7e41", - "reference": "d232bfc100dfd32b18ccbcab4bcc8f28697b7e41", - "shasum": "" - }, - "require": { - "php": ">=5.3.9", - "symfony/polyfill-mbstring": "~1.0" - }, - "require-dev": { - "psr/log": "~1.0", - "symfony/event-dispatcher": "~2.1|~3.0.0", - "symfony/process": "~2.1|~3.0.0" - }, - "suggest": { - "psr/log": "For using the console logger", - "symfony/event-dispatcher": "", - "symfony/process": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.8-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\Console\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Console Component", - "homepage": "https://symfony.com", - "time": "2015-11-30 12:35:10" - }, - { - "name": "symfony/dependency-injection", - "version": "v2.8.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/dependency-injection.git", - "reference": "1ac8ce1a1cff7ff9467d44bc71b0f71dfa751ba4" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/1ac8ce1a1cff7ff9467d44bc71b0f71dfa751ba4", - "reference": "1ac8ce1a1cff7ff9467d44bc71b0f71dfa751ba4", - "shasum": "" - }, - "require": { - "php": ">=5.3.9" - }, - "conflict": { - "symfony/expression-language": "<2.6" - }, - "require-dev": { - "symfony/config": "~2.2|~3.0.0", - "symfony/expression-language": "~2.6|~3.0.0", - "symfony/yaml": "~2.1|~3.0.0" - }, - "suggest": { - "symfony/config": "", - "symfony/proxy-manager-bridge": "Generate service proxies to lazy load them", - "symfony/yaml": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.8-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\DependencyInjection\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony DependencyInjection Component", - "homepage": "https://symfony.com", - "time": "2015-11-30 06:56:28" - }, - { - "name": "symfony/event-dispatcher", - "version": "v2.8.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "a5eb815363c0388e83247e7e9853e5dbc14999cc" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/a5eb815363c0388e83247e7e9853e5dbc14999cc", - "reference": "a5eb815363c0388e83247e7e9853e5dbc14999cc", - "shasum": "" - }, - "require": { - "php": ">=5.3.9" - }, - "require-dev": { - "psr/log": "~1.0", - "symfony/config": "~2.0,>=2.0.5|~3.0.0", - "symfony/dependency-injection": "~2.6|~3.0.0", - "symfony/expression-language": "~2.6|~3.0.0", - "symfony/stopwatch": "~2.3|~3.0.0" - }, - "suggest": { - "symfony/dependency-injection": "", - "symfony/http-kernel": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.8-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\EventDispatcher\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony EventDispatcher Component", - "homepage": "https://symfony.com", - "time": "2015-10-30 20:15:42" - }, - { - "name": "symfony/filesystem", - "version": "v3.0.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/filesystem.git", - "reference": "692d98d813e4ef314b9c22775c86ddbeb0f44884" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/692d98d813e4ef314b9c22775c86ddbeb0f44884", - "reference": "692d98d813e4ef314b9c22775c86ddbeb0f44884", - "shasum": "" - }, - "require": { - "php": ">=5.5.9" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "3.0-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\Filesystem\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Filesystem Component", - "homepage": "https://symfony.com", - "time": "2015-11-23 10:41:47" - }, - { - "name": "symfony/finder", - "version": "v2.3.35", - "target-dir": "Symfony/Component/Finder", - "source": { - "type": "git", - "url": "https://github.com/symfony/finder.git", - "reference": "5baf7b74657db10c4ad8ca0934be74151268b741" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/5baf7b74657db10c4ad8ca0934be74151268b741", - "reference": "5baf7b74657db10c4ad8ca0934be74151268b741", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.3-dev" - } - }, - "autoload": { - "psr-0": { - "Symfony\\Component\\Finder\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Finder Component", - "homepage": "https://symfony.com", - "time": "2015-11-18 08:19:46" - }, - { - "name": "symfony/polyfill-mbstring", - "version": "v1.0.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "0b6a8940385311a24e060ec1fe35680e17c74497" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/0b6a8940385311a24e060ec1fe35680e17c74497", - "reference": "0b6a8940385311a24e060ec1fe35680e17c74497", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Polyfill\\Mbstring\\": "" - }, - "files": [ - "bootstrap.php" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for the Mbstring extension", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "mbstring", - "polyfill", - "portable", - "shim" - ], - "time": "2015-11-04 20:28:58" - }, - { - "name": "symfony/translation", - "version": "v2.8.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/translation.git", - "reference": "6772657767649fc3b31df12705194fb4af11ef98" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/6772657767649fc3b31df12705194fb4af11ef98", - "reference": "6772657767649fc3b31df12705194fb4af11ef98", - "shasum": "" - }, - "require": { - "php": ">=5.3.9", - "symfony/polyfill-mbstring": "~1.0" - }, - "conflict": { - "symfony/config": "<2.7" - }, - "require-dev": { - "psr/log": "~1.0", - "symfony/config": "~2.8", - "symfony/intl": "~2.4|~3.0.0", - "symfony/yaml": "~2.2|~3.0.0" - }, - "suggest": { - "psr/log": "To use logging capability in translator", - "symfony/config": "", - "symfony/yaml": "" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.8-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\Translation\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Translation Component", - "homepage": "https://symfony.com", - "time": "2015-11-18 13:45:00" - }, - { - "name": "symfony/yaml", - "version": "v2.8.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/yaml.git", - "reference": "f79824187de95064a2f5038904c4d7f0227fedb5" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/f79824187de95064a2f5038904c4d7f0227fedb5", - "reference": "f79824187de95064a2f5038904c4d7f0227fedb5", - "shasum": "" - }, - "require": { - "php": ">=5.3.9" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.8-dev" - } - }, - "autoload": { - "psr-4": { - "Symfony\\Component\\Yaml\\": "" - }, - "exclude-from-classmap": [ - "/Tests/" - ] - }, - "notification-url": "http://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony Yaml Component", - "homepage": "https://symfony.com", - "time": "2015-11-30 12:35:10" + "type": "library" } ], "aliases": [], diff --git a/framework/src/templates/Exception.phtml b/framework/src/templates/Exception.phtml index 0d821fb2f..af2526926 100644 --- a/framework/src/templates/Exception.phtml +++ b/framework/src/templates/Exception.phtml @@ -70,7 +70,7 @@

RuntimeException: -
+

@@ -88,4 +88,4 @@
- \ No newline at end of file + diff --git a/gulliver/js/ext/min/ext-all.js b/gulliver/js/ext/min/ext-all.js index 25af08e02..dc465ea52 100644 --- a/gulliver/js/ext/min/ext-all.js +++ b/gulliver/js/ext/min/ext-all.js @@ -69,6 +69,10 @@ function stringReplace(strSearch,strReplace,str) {var expression=eval("/"+strSearch+"/g");return str.replace(expression,strReplace);} function getBrowserTimeZoneOffset() {return-1*((new Date()).getTimezoneOffset()*60);} +function setExtStateManagerSetProvider(cache,additionalPrefix){var workspace='ws-undefined';var pathname=location.pathname.split('/');var cookieProvider=new Ext.state.CookieProvider();var i;if(additionalPrefix===undefined){additionalPrefix='';} +if(pathname.length>1){workspace=pathname[1].replace('sys','');} +workspace=workspace+additionalPrefix;cookieProvider.on('statechange',function(provider,key,value){if(value!==null&&JSON.stringify(Ext.state.Manager.get(workspace+cache))!==JSON.stringify(value)){Ext.state.Manager.set(workspace+cache,value);}});Ext.state.Manager.setProvider(cookieProvider);Ext.state.Manager.clear(cache);try{if(window.extJsViewState!==undefined){for(i in extJsViewState){Ext.state.Manager.clear(i);} +Ext.state.Manager.set(cache,Ext.state.Manager.getProvider().decodeValue(extJsViewState[workspace+cache]));}}catch(e){}} Ext.namespace("Ext.ux.plugin");Ext.onReady(function(){var a=Ext.util.CSS;if(a){a.getRule(".x-hide-nosize")||a.createStyleSheet(".x-hide-nosize{height:0px!important;width:0px!important;border:none!important;zoom:1;}.x-hide-nosize * {height:0px!important;width:0px!important;border:none!important;zoom:1;}");a.refreshCache()}});(function(){var g=Ext.Element,b=Ext.lib.Anim,a=g.prototype;var f="visibility",d="display",c="hidden",i="none";var e={};e.El={setDisplayed:function(k){var j=this;j.visibilityCls?(j[k!==false?"removeClass":"addClass"](j.visibilityCls)):a.setDisplayed.call(j,k);return j},isDisplayed:function(){return!(this.hasClass(this.visibilityCls)||this.isStyle(d,i))},fixDisplay:function(){var j=this;a.fixDisplay.call(j);j.visibilityCls&&j.removeClass(j.visibilityCls)},isVisible:function(k){var l=this.visible||(!this.isStyle(f,c)&&(this.visibilityCls?!this.hasClass(this.visibilityCls):!this.isStyle(d,i)));if(k!==true||!l){return l}var m=this.dom.parentNode,j=/^body/i;while(m&&!j.test(m.tagName)){if(!Ext.fly(m,"_isVisible").isVisible()){return false}m=m.parentNode}return true},isStyle:a.isStyle||function(j,k){return this.getStyle(j)==k}};Ext.override(g.Flyweight,e.El);Ext.ux.plugin.VisibilityMode=function(k){Ext.apply(this,k||{});var j=Ext.util.CSS;if(j&&!Ext.isIE&&this.fixMaximizedWindow!==false&&!Ext.ux.plugin.VisibilityMode.MaxWinFixed){j.updateRule(".x-window-maximized-ct","overflow","");Ext.ux.plugin.VisibilityMode.MaxWinFixed=true}};Ext.extend(Ext.ux.plugin.VisibilityMode,Object,{bubble:true,fixMaximizedWindow:true,elements:null,visibilityCls:"x-hide-nosize",hideMode:"nosize",ptype:"uxvismode",init:function(n){var k=this.hideMode||n.hideMode,m=this,j=Ext.Container.prototype.bubble,l=function(){var q=[this.collapseEl,this.actionMode].concat(m.elements||[]);Ext.each(q,function(r){m.extend(this[r]||r)},this);var p={visFixed:true,animCollapse:false,animFloat:false,hideMode:k,defaults:this.defaults||{}};p.defaults.hideMode=k;Ext.apply(this,p);Ext.apply(this.initialConfig||{},p)};n.on("render",function(){if(m.bubble!==false&&this.ownerCt){j.call(this.ownerCt,function(){this.visFixed||this.on("afterlayout",l,this,{single:true})})}l.call(this)},n,{single:true})},extend:function(j,k){j&&Ext.each([].concat(j),function(l){if(l&&l.dom){if("visibilityCls"in l){return}Ext.apply(l,e.El);l.visibilityCls=k||this.visibilityCls}},this);return this}});Ext.preg&&Ext.preg("uxvismode",Ext.ux.plugin.VisibilityMode);Ext.provide&&Ext.provide("uxvismode")})();(function(){var J=Ext.Element,n,u=Ext.lib.Dom,al=Ext.lib.Anim,m=Ext.EventManager,aj=Ext.lib.Event,an=document,t=function(){},ap=Object.prototype,aA=ap.toString,B=/^body/i,q="[object HTMLDocument]";if(!Ext.elCache||parseInt(Ext.version.replace(/\./g,""),10)<311){alert("Ext Release "+Ext.version+" is not supported")}Ext._documents={};Ext._documents[Ext.id(document,"_doc")]=Ext.elCache;var T=u.resolveDocumentCache=function(E,aF){Ext._documents[Ext.id(document,"_doc")]=Ext.elCache;var aE=e(E),aG=Ext.isDocument(aE)?Ext.id(aE):aF,A=Ext._documents[aG]||null;return A||(aG?Ext._documents[aG]={}:null)},aD=u.clearDocumentCache=function(A){delete Ext._documents[A]};J.addMethods||(J.addMethods=function(A){Ext.apply(J.prototype,A||{})});Ext.removeNode=function(aH){var aG=aH?aH.dom||aH:null,aE,aF,A=T(aG),E;if(aG&&(aF=A[aG.id])&&(aE=aF.el)){if(aE.dom){Ext.enableNestedListenerRemoval?m.purgeElement(aE.dom,true):m.removeAll(aE.dom)}delete A[aG.id];delete aE.dom;delete aE._context;aE=null}if(aG&&!aG.navigator&&!Ext.isDocument(aG)&&!B.test(aG.tagName)){(E=aG.parentElement||aG.parentNode)&&E.removeChild(aG)}aG=E=null};var f=function(aI,aG){var aH=typeof aI==="function"?aI:function aF(){};var aE=aH._ovl;if(!aE){aE={base:aH};aE[aH.length||0]=aH;aH=function aF(){var aL=arguments.callee._ovl;var aK=aL[arguments.length]||aL.base;return aK&&aK!=arguments.callee?aK.apply(this,arguments):undefined}}var aJ=[].concat(aG);for(var E=0,A=aJ.length;EA||aQaI){aN.scrollTop=aO-A}}aN.scrollTop=aN.scrollTop;if(aH!==false){if(aG.offsetWidth>aN.clientWidth||aJaL){aN.scrollLeft=E-aN.clientWidth}}aN.scrollLeft=aN.scrollLeft}return this},contains:function(A){try{return!A?false:u.isAncestor(this.dom,A.dom?A.dom:A)}catch(E){return false}},getScroll:function(){var aI=this.dom,aH=this.getDocument(),A=aH.body,aE=aH.documentElement,E,aG,aF;if(Ext.isDocument(aI)||aI==A){if(Ext.isIE&&u.docIsStrict(aH)){E=aE.scrollLeft;aG=aE.scrollTop}else{E=window.pageXOffset;aG=window.pageYOffset}aF={left:E||(A?A.scrollLeft:0),top:aG||(A?A.scrollTop:0)}}else{aF={left:aI.scrollLeft,top:aI.scrollTop}}return aF},getStyle:function(){var A=at&&at.getComputedStyle?function E(aL){var aI=!this._isDoc?this.dom:null,aE,aH,aF,aJ,aK=Ext.isWebKit,aJ,aG;if(!aI||!aI.style){return null}aG=aI.style;aL=aq(aL);aH=at.getComputedStyle(aI,null);aF=(aH)?aH[aL]:null;if(aK){if(aF&&ay.test(aL)&&aG.position!="absolute"&&aF!="0px"){aJ=aG.display;aG.display="inline-block";aF=at.getComputedStyle(aI,null)[aL];aG.display=aJ}else{if(aF=="rgba(0, 0, 0, 0)"){aF="transparent"}}}return aF||aG[aL]}:function E(aJ){var aH=!this._isDoc?this.dom:null,aE,aG,aF;if(!aH||!aH.style){return null}aF=aH.style;if(aJ==Y){if(aF.filter.match){if(aE=aF.filter.match(i)){var aI=parseFloat(aE[1]);if(!isNaN(aI)){return aI?aI/100:0}}}return 1}aJ=aq(aJ);return((aG=aH.currentStyle)?aG[aJ]:null)||aH.style[aJ]};var E=null;return A}(),setStyle:function(aF,aE){if(this._isDoc||Ext.isDocument(this.dom)){return this}var A,E;if(typeof aF!="object"){A={};A[aF]=aE;aF=A}for(E in aF){if(aF.hasOwnProperty(E)){aE=aF[E];E==Y?this.setOpacity(aE):this.dom.style[aq(E)]=aE}}return this},center:function(A){return this.alignTo(A||this.getDocument(),"c-c")},mask:function(E,aH){var aJ=this,aF=aJ.dom,aI=Ext.DomHelper,aG="ext-el-mask-msg",A,aK;if(aJ.getStyle("position")=="static"){aJ.addClass(F)}if((A=I(aF,"maskMsg"))){A.remove()}if((A=I(aF,"mask"))){A.remove()}aK=aI.append(aF,{cls:"ext-el-mask"},true);I(aF,"mask",aK);aJ.addClass(O);aK.setDisplayed(true);if(typeof E=="string"){var aE=aI.append(aF,{cls:aG,cn:{tag:"div"}},true);I(aF,"maskMsg",aE);aE.dom.className=aH?aG+" "+aH:aG;aE.dom.firstChild.innerHTML=E;aE.setDisplayed(true);aE.center(aJ)}if(Ext.isIE&&!(Ext.isIE7&&Ext.isStrict)&&aJ.getStyle("height")=="auto"){aK.setSize(undefined,aJ.getHeight())}return aK},unmask:function(){var aE=this,aF=aE.dom,A=I(aF,"mask"),E=I(aF,"maskMsg");if(A){if(E){E.remove();I(aF,"maskMsg",undefined)}A.remove();I(aF,"mask",undefined)}aE.removeClass([O,F])},isMasked:function(){var A=I(this.dom,"mask");return A&&A.isVisible()},getCenterXY:function(){return this.getAlignToXY(this.getDocument(),"c-c")},getAnchorXY:function(aG,aL,aQ){aG=(aG||"tl").toLowerCase();aQ=aQ||{};var aK=this,aN=this.getDocument(),E=aK.dom==aN.body||aK.dom==aN,aO=aQ.width||E?u.getViewWidth(false,aN):aK.getWidth(),aI=aQ.height||E?u.getViewHeight(false,aN):aK.getHeight(),aP,A=Math.round,aE=aK.getXY(),aM=aK.getScroll(),aJ=E?aM.left:!aL?aE[0]:0,aH=E?aM.top:!aL?aE[1]:0,aF={c:[A(aO*0.5),A(aI*0.5)],t:[A(aO*0.5),0],l:[0,A(aI*0.5)],r:[aO,A(aI*0.5)],b:[A(aO*0.5),aI],tl:[0,0],bl:[0,aI],br:[aO,aI],tr:[aO,0]};aP=aF[aG];return[aP[0]+aJ,aP[1]+aH]},anchorTo:function(E,aH,aE,A,aJ,aK){var aI=this,aG=aI.dom;function aF(){ai(aG).alignTo(E,aH,aE,A);Ext.callback(aK,ai(aG))}Ext.EventManager.onWindowResize(aF,aI);if(!Ext.isEmpty(aJ)){Ext.EventManager.on(window,"scroll",aF,aI,{buffer:!isNaN(aJ)?aJ:50})}aF.call(aI);return aI},getScroll:function(){var aI=this.dom,aH=this.getDocument(),A=aH.body,aE=aH.documentElement,E,aG,aF;if(aI==aH||aI==A){if(Ext.isIE&&u.docIsStrict(aH)){E=aE.scrollLeft;aG=aE.scrollTop}else{E=window.pageXOffset;aG=window.pageYOffset}aF={left:E||(A?A.scrollLeft:0),top:aG||(A?A.scrollTop:0)}}else{aF={left:aI.scrollLeft,top:aI.scrollTop}}return aF},getAlignToXY:function(aF,aR,aS){var a6;aF=Ext.get(aF,a6=this.getDocument());if(!aF||!aF.dom){throw"Element.getAlignToXY with an element that doesn't exist"}aS=aS||[0,0];aR=(aR=="?"?"tl-bl?":(!/-/.test(aR)&&aR!=""?"tl-"+aR:aR||"tl-bl")).toLowerCase();var a3=this,aY=a3.dom,a5,a4,aK,aJ,aM,aW,aP,aN=u.getViewWidth(false,a6)-10,aX=u.getViewHeight(false,a6)-10,E,aG,aH,aI,aO,aQ,a0=a6.documentElement,aL=a6.body,aV=(a0.scrollLeft||aL.scrollLeft||0)+5,aU=(a0.scrollTop||aL.scrollTop||0)+5,aZ=false,aE="",A="",aT=aR.match(/^([a-z]+)-([a-z]+)(\?)?$/);if(!aT){throw"Element.getAlignToXY with an invalid alignment "+aR}aE=aT[1];A=aT[2];aZ=!!aT[3];a5=a3.getAnchorXY(aE,true);a4=aF.getAnchorXY(A,false);aK=a4[0]-a5[0]+aS[0];aJ=a4[1]-a5[1]+aS[1];if(aZ){aM=a3.getWidth();aW=a3.getHeight();aP=aF.getRegion();E=aE.charAt(0);aG=aE.charAt(aE.length-1);aH=A.charAt(0);aI=A.charAt(A.length-1);aO=((E=="t"&&aH=="b")||(E=="b"&&aH=="t"));aQ=((aG=="r"&&aI=="l")||(aG=="l"&&aI=="r"));if(aK+aM>aN+aV){aK=aQ?aP.left-aM:aN+aV-aM}if(aKaX+aU){aJ=aO?aP.top-aW:aX+aU-aW}if(aJaU){x=aU-w;aO=true}if((y+h)>aM){y=aM-h;aO=true}if(x)((\n|\r|.)*?)(?:<\/script>)/gi,update:function(content,loadScripts,callback,scope){loadScripts=loadScripts||this.getUpdater().loadScripts||false;content=Ext.DomHelper.markup(content||"");content=loadScripts===true?content:content.replace(this.scriptRE,"");var doc;if((doc=this.getFrameDocument())&&!!content.length){this._unHook();this.src=null;this.showMask();Ext.isFunction(callback)&&this._observable.addListener("_docload",callback,scope||this,{single:true});this._targetURI=location.href;doc.open();this._frameAction=true;doc.write(content);doc.close();this.checkDOM()}else{this.hideMask(true);Ext.isFunction(callback)&&callback.call(scope,this)}return this},execCommand:function(command,userInterface,value,validate){var doc,assert;if((doc=this.getFrameDocument())&&!!command){try{Ext.isIE&&this.getWindow().focus();assert=validate&&Ext.isFunction(doc.queryCommandEnabled)?doc.queryCommandEnabled(command):true;return assert&&doc.execCommand(command,!!userInterface,value)}catch(eex){return false}}return false},setDesignMode:function(active){var doc;(doc=this.getFrameDocument())&&(doc.designMode=(/on|true/i).test(String(active))?"on":"off")},getUpdater:function(){return this.updateManager||(this.updateManager=new MIF.Updater(this))},getHistory:function(){var h=null;try{h=this.getWindow().history}catch(eh){}return h},get:function(el){var doc=this.getFrameDocument();return doc?Ext.get(el,doc):doc=null},fly:function(el,named){var doc=this.getFrameDocument();return doc?Ext.fly(el,named,doc):null},getDom:function(el){var d;if(!el||!(d=this.getFrameDocument())){return(d=null)}return Ext.getDom(el,d)},select:function(selector,unique){var d;return(d=this.getFrameDocument())?Ext.Element.select(selector,unique,d):d=null},query:function(selector){var d;return(d=this.getFrameDocument())?Ext.DomQuery.select(selector,d):null},removeNode:Ext.removeNode,_renderHook:function(){this._windowContext=null;this.CSS=this.CSS?this.CSS.destroy():null;this._hooked=false;try{if(this.writeScript('(function(){(window.hostMIF = parent.document.getElementById("'+this.id+'").ownerCt)._windowContext='+(Ext.isIE?"window":'{eval:function(s){return new Function("return ("+s+")")();}}')+";})()")){var w,p=this._frameProxy,D=this.getFrameDocument();if(w=this.getWindow()){p||(p=this._frameProxy=this._eventProxy.createDelegate(this));addListener(w,"focus",p);addListener(w,"blur",p);addListener(w,"resize",p);addListener(w,"unload",p);D&&addListener(Ext.isIE?w:D,"scroll",p)}D&&(this.CSS=new Ext.ux.ManagedIFrame.CSS(D))}}catch(ex){}return this.domWritable()},_unHook:function(){if(this._hooked){this._windowContext&&(this._windowContext.hostMIF=null);this._windowContext=null;var w,p=this._frameProxy;if(p&&this.domWritable()&&(w=this.getWindow())){removeListener(w,"focus",p);removeListener(w,"blur",p);removeListener(w,"resize",p);removeListener(w,"unload",p);removeListener(Ext.isIE?w:this.getFrameDocument(),"scroll",p)}}ELD.clearDocumentCache&&ELD.clearDocumentCache(this.id);this.CSS=this.CSS?this.CSS.destroy():null;this.domFired=this._frameAction=this.domReady=this._hooked=false},_windowContext:null,getFrameDocument:function(){var win=this.getWindow(),doc=null;try{doc=(Ext.isIE&&win?win.document:null)||this.dom.contentDocument||window.frames[this.dom.name].document||null}catch(gdEx){ELD.clearDocumentCache&&ELD.clearDocumentCache(this.id);return false}doc=(doc&&Ext.isFunction(ELD.getDocument))?ELD.getDocument(doc,true):doc;return doc},getDoc:function(){var D=this.getFrameDocument();return Ext.get(D,D)},getBody:function(){var d;return(d=this.getFrameDocument())?this.get(d.body||d.documentElement):null},getDocumentURI:function(){var URI,d;try{URI=this.src&&(d=this.getFrameDocument())?d.location.href:null}catch(ex){}return URI||(Ext.isFunction(this.src)?this.src():this.src)},getWindowURI:function(){var URI,w;try{URI=(w=this.getWindow())?w.location.href:null}catch(ex){}return URI||(Ext.isFunction(this.src)?this.src():this.src)},getWindow:function(){var dom=this.dom,win=null;try{win=dom.contentWindow||window.frames[dom.name]||null}catch(gwEx){}return win},scrollChildIntoView:function(child,container,hscroll){this.fly(child,"_scrollChildIntoView").scrollIntoView(this.getDom(container)||this.getBody().dom,hscroll);return this},print:function(){try{var win;if(win=this.getWindow()){Ext.isIE&&win.focus();win.print()}}catch(ex){throw new MIF.Error("printexception",ex.description||ex.message||ex)}return this},domWritable:function(){return!!Ext.isDocument(this.getFrameDocument(),true)&&!!this._windowContext},execScript:function(block,useDOM){try{if(this.domWritable()){if(useDOM){this.writeScript(block)}else{return this._windowContext.eval(block)}}else{throw new MIF.Error("execscript-secure-context")}}catch(ex){this._observable.fireEvent.call(this._observable,"exception",this,ex);return false}return true},writeScript:function(block,attributes){attributes=Ext.apply({},attributes||{},{type:"text/javascript",text:block});try{var head,script,doc=this.getFrameDocument();if(doc&&typeof doc.getElementsByTagName!="undefined"){if(!(head=doc.getElementsByTagName("head")[0])){head=doc.createElement("head");doc.getElementsByTagName("html")[0].appendChild(head)}if(head&&(script=doc.createElement("script"))){for(var attrib in attributes){if(attributes.hasOwnProperty(attrib)&&attrib in script){script[attrib]=attributes[attrib]}}return!!head.appendChild(script)}}}catch(ex){this._observable.fireEvent.call(this._observable,"exception",this,ex)}finally{script=head=null}return false},loadFunction:function(fn,useDOM,invokeIt){var name=fn.name||fn;var fnSrc=fn.fn||window[fn];name&&fnSrc&&this.execScript(name+"="+fnSrc,useDOM);invokeIt&&this.execScript(name+"()")},loadHandler:function(e,target){var rstatus=(this.dom||{}).readyState||(e||{}).type;if(this.eventsFollowFrameLinks||this._frameAction||this.isReset){switch(rstatus){case"domready":case"DOMFrameContentLoaded":case"domfail":this._onDocReady(rstatus);break;case"load":case"complete":var frame=this;frame._onDocLoaded(rstatus);this._frameAction=false;break;case"error":this._observable.fireEvent.apply(this._observable,["exception",this].concat(arguments));break;default:}this.frameState=rstatus}},_onDocReady:function(eventName){var w,obv=this._observable,D;try{if(!this.isReset&&this.focusOnLoad&&(w=this.getWindow())){w.focus()}(D=this.getDoc())&&(D.isReady=true)}catch(ex){}obv.fireEvent("_docready",this);if(!this.domFired&&(this._hooked=this._renderHook())){this.domFired=true;this.isReset||obv.fireEvent.call(obv,"domready",this)}this.domReady=true;this.hideMask()},_onDocLoaded:function(eventName){var obv=this._observable,w;this.domReady||this._onDocReady("domready");obv.fireEvent("_docload",this);this.isReset||obv.fireEvent("documentloaded",this);this.hideMask(true);this._frameAction=this.isReset=false},checkDOM:function(win){if(Ext.isGecko){return}var n=0,frame=this,domReady=false,b,l,d,max=this.domReadyRetries||2500,polling=false,startLocation=(this.getFrameDocument()||{location:{}}).location.href;(function(){d=frame.getFrameDocument()||{location:{}};polling=(d.location.href!==startLocation||d.location.href===frame._targetURI);if(frame.domReady){return}domReady=polling&&((b=frame.getBody())&&!!(b.dom.innerHTML||"").length)||false;if(d.location.href&&!domReady&&(++n'},onRender:function(ct,position){Ext.ux.LocationBar.superclass.onRender.call(this,ct,position);this.repaint();},onClick:function(node){if(this.selectHandler){this.selectHandler(node);}else{if(node.parentNode){node.parentNode.expand(false,true);node.ensureVisible();} diff --git a/gulliver/js/ext/pmos-common.js b/gulliver/js/ext/pmos-common.js index 45679ca82..4df92a014 100755 --- a/gulliver/js/ext/pmos-common.js +++ b/gulliver/js/ext/pmos-common.js @@ -557,3 +557,42 @@ function getBrowserTimeZoneOffset() return -1 * ((new Date()).getTimezoneOffset() * 60); } +/** + * This is the global state manager. By default all components that are + * "state aware" check this class for state information if you don't pass them a + * custom state provider. In order for this class to be useful, it must be + * initialized with a provider when your application initializes. + * + * @param {string} cache + * @param {string} additionalPrefix + * @returns {undefined} + */ +function setExtStateManagerSetProvider(cache, additionalPrefix) { + var workspace = 'ws-undefined'; + var pathname = location.pathname.split('/'); + var cookieProvider = new Ext.state.CookieProvider(); + var i; + if (additionalPrefix === undefined) { + additionalPrefix = ''; + } + if (pathname.length > 1) { + workspace = pathname[1].replace('sys', ''); + } + workspace = workspace + additionalPrefix; + cookieProvider.on('statechange', function (provider, key, value) { + if (value !== null && JSON.stringify(Ext.state.Manager.get(workspace + cache)) !== JSON.stringify(value)) { + Ext.state.Manager.set(workspace + cache, value); + } + }); + Ext.state.Manager.setProvider(cookieProvider); + Ext.state.Manager.clear(cache); + try { + if (window.extJsViewState !== undefined) { + for (i in extJsViewState) { + Ext.state.Manager.clear(i); + } + Ext.state.Manager.set(cache, Ext.state.Manager.getProvider().decodeValue(extJsViewState[workspace + cache])); + } + } catch (e) { + } +} diff --git a/gulliver/system/class.bootstrap.php b/gulliver/system/class.bootstrap.php index 58066d358..c7ebf4897 100644 --- a/gulliver/system/class.bootstrap.php +++ b/gulliver/system/class.bootstrap.php @@ -199,7 +199,6 @@ class Bootstrap //self::registerClass("GroupUser", PATH_CLASSES . "class.groupUser.php"); -> this have conflicts with model/GroupUser.php self::registerClass("Groups", PATH_CLASSES . "class.groups.php"); self::registerClass("JavaBridgePM", PATH_CLASSES . "class.javaBridgePM.php"); - self::registerClass("Jrml", PATH_CLASSES . "class.jrml.php"); self::registerClass("PMmemcached", PATH_CLASSES . "class.memcached.php"); self::registerClass("multipleFilesBackup", PATH_CLASSES . "class.multipleFilesBackup.php"); self::registerClass("NET", PATH_CLASSES . "class.net.php"); @@ -464,12 +463,12 @@ class Bootstrap $file = $filter->xssFilterHard($file); $downloadFileName = $filter->xssFilterHard($downloadFileName); - $fileNameIni = $file; - $browserCacheFilesUid = G::browserCacheFilesGetUid(); if ($browserCacheFilesUid != null) { - $file = str_replace(".$browserCacheFilesUid", null, $file); + $fileNameIni = $file = str_replace(".$browserCacheFilesUid", null, $file); + } else { + $fileNameIni = $file; } $folderarray = explode('/', $file); diff --git a/gulliver/system/class.g.php b/gulliver/system/class.g.php index 98548910c..23269b8a4 100644 --- a/gulliver/system/class.g.php +++ b/gulliver/system/class.g.php @@ -229,7 +229,7 @@ class G * @param string $key * @return string */ - public function encrypt ($string, $key) + public static function encrypt ($string, $key) { //print $string; // if ( defined ( 'ENABLE_ENCRYPT' ) && ENABLE_ENCRYPT == 'yes' ) { @@ -3368,7 +3368,7 @@ class G * * @author Erik A.O. */ - public function json_decode($Json, $assoc = false) + public static function json_decode($Json, $assoc = false) { if (function_exists('json_decode')) { return json_decode($Json, $assoc); @@ -5034,7 +5034,7 @@ class G $rest->handle(); } - public function reservedWordsSql () + public static function reservedWordsSql () { //Reserved words SQL $reservedWordsSql = array ("ACCESSIBLE","ACTION","ADD","ALL","ALTER","ANALYZE","AND","ANY","AS","ASC","ASENSITIVE","AUTHORIZATION","BACKUP","BEFORE","BEGIN","BETWEEN","BIGINT","BINARY","BIT","BLOB","BOTH","BREAK","BROWSE","BULK","BY","CALL","CASCADE","CASE","CHANGE","CHAR","CHARACTER","CHECK","CHECKPOINT","CLOSE","CLUSTERED","COALESCE","COLLATE","COLUMN","COMMIT","COMPUTE","CONDITION","CONSTRAINT","CONTAINS","CONTAINSTABLE","CONTINUE","CONVERT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DATE","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DBCC","DEALLOCATE","DEC","DECIMAL","DECLARE","DEFAULT","DELAYED","DELETE","DENY","DESC","DESCRIBE","DETERMINISTIC","DISK","DISTINCT","DISTINCTROW", diff --git a/gulliver/system/class.headPublisher.php b/gulliver/system/class.headPublisher.php index 0c07341c8..156fa6aab 100644 --- a/gulliver/system/class.headPublisher.php +++ b/gulliver/system/class.headPublisher.php @@ -737,5 +737,41 @@ class headPublisher { $this->disableHeaderScripts = true; } + + /** + * Gets an array that contains the status of the view. + * + * @return array $views + */ + public function getExtJsViewState() + { + $views = array(); + $keyState = "extJsViewState"; + $prefixExtJs = "ys-"; + $oServerConf = &serverConf::getSingleton(); + $deleteCache = true; + + $sjson = $oServerConf->getProperty($keyState); + if ($sjson !== "") { + $json = G::json_decode($sjson); + if ((is_array($json) || is_object($json)) && sizeof($json)){ + foreach ($json as $key => $value) { + $views[$key] = $value; + } + } + } + $httpCookies = explode("; ", $_SERVER['HTTP_COOKIE']); + foreach ($httpCookies as $cookie) { + $value = explode("=", $cookie); + if (count($value) > 1 && substr($value[0], 0, 3) === $prefixExtJs) { + $deleteCache = false; + $key = substr($value[0], 3); + $views[$key] = $value[1]; + } + } + $oServerConf->setProperty($keyState, G::json_encode($views)); + return $views; + } + } diff --git a/gulliver/system/class.rbac.php b/gulliver/system/class.rbac.php index 6d71e3256..531e20279 100755 --- a/gulliver/system/class.rbac.php +++ b/gulliver/system/class.rbac.php @@ -46,6 +46,7 @@ class RBAC { + const SETUPERMISSIONUID= '00000000000000000000000000000002'; /** * * @access private @@ -159,27 +160,75 @@ class RBAC * @access public * @return $this->permissionsAdmin[ $permissionsAdmin ] */ - public function loadPermissionAdmin () + public function loadPermissionAdmin() { - $permissionsAdmin = array (array ("PER_UID" => "00000000000000000000000000000001","PER_CODE" => "PM_LOGIN" - ),array ("PER_UID" => "00000000000000000000000000000002","PER_CODE" => "PM_SETUP" - ),array ("PER_UID" => "00000000000000000000000000000003","PER_CODE" => "PM_USERS" - ),array ("PER_UID" => "00000000000000000000000000000004","PER_CODE" => "PM_FACTORY" - ),array ("PER_UID" => "00000000000000000000000000000005","PER_CODE" => "PM_CASES" - ),array ("PER_UID" => "00000000000000000000000000000006","PER_CODE" => "PM_ALLCASES" - ),array ("PER_UID" => "00000000000000000000000000000007","PER_CODE" => "PM_REASSIGNCASE" - ),array ("PER_UID" => "00000000000000000000000000000008","PER_CODE" => "PM_REPORTS" - ),array ("PER_UID" => "00000000000000000000000000000009","PER_CODE" => "PM_SUPERVISOR" - ),array ("PER_UID" => "00000000000000000000000000000010","PER_CODE" => "PM_SETUP_ADVANCE" - ),array ("PER_UID" => "00000000000000000000000000000011","PER_CODE" => "PM_DASHBOARD" - ),array ("PER_UID" => "00000000000000000000000000000012","PER_CODE" => "PM_WEBDAV" - ),array ("PER_UID" => "00000000000000000000000000000013","PER_CODE" => "PM_DELETECASE" - ),array ("PER_UID" => "00000000000000000000000000000014","PER_CODE" => "PM_EDITPERSONALINFO" - ),array ("PER_UID" => "00000000000000000000000000000015","PER_CODE" => "PM_FOLDERS_VIEW" - ),array ("PER_UID" => "00000000000000000000000000000016","PER_CODE" => "PM_FOLDERS_ADD_FOLDER" - ),array ("PER_UID" => "00000000000000000000000000000017","PER_CODE" => "PM_FOLDERS_ADD_FILE" - ),array ("PER_UID" => "00000000000000000000000000000018","PER_CODE" => "PM_CANCELCASE" - ),array ("PER_UID" => "00000000000000000000000000000019","PER_CODE" => "PM_FOLDER_DELETE" + $permissionsAdmin = array(array("PER_UID" => "00000000000000000000000000000001", "PER_CODE" => "PM_LOGIN", + "PER_NAME" => "Login" + ), array("PER_UID" => "00000000000000000000000000000002", "PER_CODE" => "PM_SETUP", "PER_NAME" => "Setup" + ), array("PER_UID" => "00000000000000000000000000000003", "PER_CODE" => "PM_USERS", "PER_NAME" => "Users" + ), array("PER_UID" => "00000000000000000000000000000004", "PER_CODE" => "PM_FACTORY", "PER_NAME" => "Design + Process" + ), array("PER_UID" => "00000000000000000000000000000005", "PER_CODE" => "PM_CASES", "PER_NAME" => "Create Users" + ), array("PER_UID" => "00000000000000000000000000000006", "PER_CODE" => "PM_ALLCASES", "PER_NAME" => "All Cases" + ), array("PER_UID" => "00000000000000000000000000000007", "PER_CODE" => "PM_REASSIGNCASE", "PER_NAME" => + "Reassign case" + ), array("PER_UID" => "00000000000000000000000000000008", "PER_CODE" => "PM_REPORTS", "PER_NAME" => "PM reports" + ), array("PER_UID" => "00000000000000000000000000000009", "PER_CODE" => "PM_SUPERVISOR", "PER_NAME" => + "Supervisor" + ), array("PER_UID" => "00000000000000000000000000000010", "PER_CODE" => "PM_SETUP_ADVANCE", "PER_NAME" => + "Setup Advanced" + ), array("PER_UID" => "00000000000000000000000000000011", "PER_CODE" => "PM_DASHBOARD", "PER_NAME" => "Dashboard" + ), array("PER_UID" => "00000000000000000000000000000012", "PER_CODE" => "PM_WEBDAV", "PER_NAME" => "WebDav" + ), array("PER_UID" => "00000000000000000000000000000013", "PER_CODE" => "PM_DELETECASE", "PER_NAME" => "Cancel + cases" + ), array("PER_UID" => "00000000000000000000000000000014", "PER_CODE" => "PM_EDITPERSONALINFO", "PER_NAME" => + "Edit Personal Info" + ), array("PER_UID" => "00000000000000000000000000000015", "PER_CODE" => "PM_FOLDERS_VIEW", "PER_NAME" => "View + Folders" + ), array("PER_UID" => "00000000000000000000000000000016", "PER_CODE" => "PM_FOLDERS_ADD_FOLDER", "PER_NAME" => + "Delete folders" + ), array("PER_UID" => "00000000000000000000000000000017", "PER_CODE" => "PM_FOLDERS_ADD_FILE", "PER_NAME" => + "Delete folders" + ), array("PER_UID" => "00000000000000000000000000000018", "PER_CODE" => "PM_CANCELCASE", "PER_NAME" => "Cancel + cases" + ), array("PER_UID" => "00000000000000000000000000000019", "PER_CODE" => "PM_FOLDER_DELETE", "PER_NAME" => + "Cancel cases" + ), array("PER_UID" => "00000000000000000000000000000020", "PER_CODE" => "PM_SETUP_LOGO", "PER_NAME" => "Setup + Logo" + ), array("PER_UID" => "00000000000000000000000000000021", "PER_CODE" => "PM_SETUP_EMAIL", "PER_NAME" => "Setup + Email" + ), array("PER_UID" => "00000000000000000000000000000022", "PER_CODE" => "PM_SETUP_CALENDAR", "PER_NAME" => + "Setup Calendar" + ), array("PER_UID" => "00000000000000000000000000000023", "PER_CODE" => "PM_SETUP_PROCESS_CATEGORIES", + "PER_NAME" => "Setup Process Categories" + ), array("PER_UID" => "00000000000000000000000000000024", "PER_CODE" => "PM_SETUP_CLEAR_CACHE", "PER_NAME" => + "Setup Clear Cache" + ), array("PER_UID" => "00000000000000000000000000000025", "PER_CODE" => "PM_SETUP_HEART_BEAT", "PER_NAME" => + "Setup Heart Beat" + ), array("PER_UID" => "00000000000000000000000000000026", "PER_CODE" => "PM_SETUP_ENVIRONMENT", "PER_NAME" => + "Setup Environment" + ), array("PER_UID" => "00000000000000000000000000000027", "PER_CODE" => "PM_SETUP_PM_TABLES", "PER_NAME" => + "Setup PM Tables" + ), array("PER_UID" => "00000000000000000000000000000028", "PER_CODE" => "PM_SETUP_LOGIN", "PER_NAME" => "Setup + Login" + ), array("PER_UID" => "00000000000000000000000000000029", "PER_CODE" => "PM_SETUP_DASHBOARDS", "PER_NAME" => + "Setup Dashboards" + ), array("PER_UID" => "00000000000000000000000000000030", "PER_CODE" => "PM_SETUP_LANGUAGE", "PER_NAME" => + "Setup Language" + ), array("PER_UID" => "00000000000000000000000000000031", "PER_CODE" => "PM_SETUP_SKIN", "PER_NAME" => "Setup + Skin" + ), array("PER_UID" => "00000000000000000000000000000032", "PER_CODE" => "PM_SETUP_CASES_LIST_CACHE_BUILDER", + "PER_NAME" => "Setup Case List Cache Builder" + ), array("PER_UID" => "00000000000000000000000000000033", "PER_CODE" => "PM_SETUP_PLUGINS", "PER_NAME" => + "Setup Plugins" + ), array("PER_UID" => "00000000000000000000000000000034", "PER_CODE" => + "PM_SETUP_USERS_AUTHENTICATION_SOURCES", "PER_NAME" => "Setup User Authentication Sources" + ), array("PER_UID" => "00000000000000000000000000000035", "PER_CODE" => "PM_SETUP_LOGS", "PER_NAME" => "Setup + Logs" + ), array("PER_UID" => "00000000000000000000000000000036", "PER_CODE" => "DELETE_PROCESS_CASES", "PER_NAME" => + "Delete process cases" + ), array("PER_UID" => "00000000000000000000000000000037", "PER_CODE" => "PM_EDITPERSONALINFO_CALENDAR", + "PER_NAME" => "Edit personal info Calendar" ) ); return $permissionsAdmin; @@ -400,7 +449,7 @@ class RBAC * @param string $uid id of user * @param string $system Code of System * @param string $perm id of Permissions - * @return 1: If it is ok + * @return int 1: If it is ok * -1: System doesn't exists * -2: The User has not a Role * -3: The User has not this Permission. @@ -827,6 +876,20 @@ class RBAC return $this->rolesObj->assignUserToRole( $aData ); } + /** + * this function gets role permission + * + * + * @access public + * + * @param string $ROL_UID + * @return $this->rolesObj->getRolePermissionsByPerUid + */ + public function getRolePermissionsByPerUid ($ROL_UID) + { + return $this->rolesObj->getRolePermissionsByPerUid( $ROL_UID ); + } + /** * this function gets role permission * @@ -1134,6 +1197,9 @@ class RBAC return true; } else { switch ($access) { + case - 3: + G::pr(G::LoadTranslation("ID_GRID_PAGE_NO_PERMISSIONS_MESSAGE")); + break; case - 2: G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels' ); G::header( 'location: ../login/login' ); @@ -1224,6 +1290,8 @@ class RBAC $aRow = $dataset->getRow(); } foreach($listPermissions as $key => $item) { + //Adding new permissions + $data = array(); $data['PER_UID'] = $item['PER_UID']; $data['PER_CODE'] = $item['PER_CODE']; $data['PER_CREATE_DATE'] = date('Y-m-d H:i:s'); @@ -1233,6 +1301,33 @@ class RBAC $permission->fromArray($data, BasePeer::TYPE_FIELDNAME); $permission->save(); $message[] = 'Add permission missing ' . $item['PER_CODE']; + + //Adding new labels for new permissions + $o = new RolesPermissions(); + $o->setPerUid($item['PER_UID']); + $o->setPermissionName($item['PER_NAME']); + + //Assigning new permissions + $rolesWithPermissionSetup = $this->getRolePermissionsByPerUid(self::SETUPERMISSIONUID); + $rolesWithPermissionSetup->next(); + while ($aRow = $rolesWithPermissionSetup->getRow()) { + $userRolePermission = $this->getRolePermissions($aRow['ROL_UID']); + $userRolePermission->next(); + $valueNewPermissions = false; + while ($aRowPermission = $userRolePermission->getRow()) { + if ($item['PER_CODE'] === $aRowPermission['PER_CODE']) { + $valueNewPermissions = true; + } + $userRolePermission->next(); + } + $dataPermissions = array(); + if (!$valueNewPermissions) { + $dataPermissions['ROL_UID'] = $aRow['ROL_UID']; + $dataPermissions['PER_UID'] = $item['PER_UID']; + $this->assignPermissionRole($dataPermissions); + } + $rolesWithPermissionSetup->next(); + } } return $message; } diff --git a/gulliver/system/class.restClient.php b/gulliver/system/class.restClient.php index 83442f496..5cc5d29cd 100755 --- a/gulliver/system/class.restClient.php +++ b/gulliver/system/class.restClient.php @@ -33,7 +33,7 @@ class RestClient * * @return RestClient */ - public function execute () + public function execute ($getResponseIfDelete = false) { if ($this->method === "POST") { curl_setopt( $this->curl, CURLOPT_POST, true ); @@ -59,7 +59,7 @@ class RestClient } curl_setopt( $this->curl, CURLOPT_URL, $this->url ); $r = curl_exec( $this->curl ); - if ($this->method !== "DELETE") { + if ($this->method !== "DELETE" || $getResponseIfDelete) { $this->treatResponse( $r ); // Extract the headers and response return $this; } else { @@ -325,9 +325,9 @@ class RestClient * @param string $password=null [optional] * @return RestClient */ - public static function delete ($url, $user = null, $pwd = null, $contentType = null) + public static function delete ($url, $user = null, $pwd = null, $contentType = null, $getResponse = false) { - return self::call( "DELETE", $url, null, $user, $pwd, $contentType ); + return self::call( "DELETE", $url, null, $user, $pwd, $contentType, $getResponse ); } /** @@ -341,9 +341,9 @@ class RestClient * @param string $contentType=null [optional] * @return RestClient */ - public static function call ($method, $url, $body, $user = null, $pwd = null, $contentType = null) + public static function call ($method, $url, $body, $user = null, $pwd = null, $contentType = null, $getResponseIfDelete) { - return self::createClient( $url )->setParameters( $body )->setMethod( $method )->setCredentials( $user, $pwd )->setContentType( $contentType )->execute()->close(); + return self::createClient( $url )->setParameters( $body )->setMethod( $method )->setCredentials( $user, $pwd )->setContentType( $contentType )->execute($getResponseIfDelete)->close(); } } diff --git a/gulliver/system/class.xmlDocument.php b/gulliver/system/class.xmlDocument.php index 8b75d6137..6c8ac1704 100755 --- a/gulliver/system/class.xmlDocument.php +++ b/gulliver/system/class.xmlDocument.php @@ -284,7 +284,7 @@ class Xml_document extends Xml_Node { //$content is a new variable, if it has any value then use it instead of the file content. if ($content == "") { if (! file_exists( $filename )) { - throw (new Exception( "failed to open Xmlform File : No such file or directory in $filename " )); + throw (new Exception( "failed to open Xmlform File : No such file or directory in ".htmlspecialchars($filename) )); } $data = implode( '', file( $filename ) ); } else { diff --git a/gulliver/system/class.xmlform.php b/gulliver/system/class.xmlform.php index 954d6315d..4d7cc0805 100755 --- a/gulliver/system/class.xmlform.php +++ b/gulliver/system/class.xmlform.php @@ -280,6 +280,9 @@ class XmlForm_Field $rs = $con->executeQuery( $query, ResultSet::FETCHMODE_NUM ); } catch (Exception $e) { //dismiss error because dbarray shouldnt be defined in some contexts. + $workspace = defined("SYS_SYS")? SYS_SYS : "Wokspace Undefined"; + G::log($workspace . " | ip: | " . G::getIpAddress() . " | type error: | " . $e->getMessage() . " | query: " . $query, PATH_DATA, "queriesWithErrors.log"); + return $result; } } else { @@ -289,6 +292,9 @@ class XmlForm_Field $rs = $stmt->executeQuery( $query, ResultSet::FETCHMODE_NUM ); } catch (Exception $e) { //dismiss error because dbarray shouldnt be defined in some contexts. + $workspace = defined("SYS_SYS")? SYS_SYS : "Wokspace Undefined"; + G::log($workspace . " | ip: | " . G::getIpAddress() . " | type error: | " . $e->getMessage() . " | query: " . $query, PATH_DATA, "queriesWithErrors.log"); + return $result; } } @@ -1583,8 +1589,8 @@ class XmlForm_Field_Suggest extends XmlForm_Field_SimpleText //by neyek if (strlen( trim( $formVariableValue ) ) > 0) { $value = $formVariableValue; } - $name = "'" . $this->name . "'"; - $str = 'NSDependentFields( true ) . ' '; $str .= $this->NSRequiredValue() . ' '; $str .= $this->NSGridLabel() . ' '; @@ -1709,9 +1715,16 @@ class XmlForm_Field_Suggest extends XmlForm_Field_SimpleText //by neyek return $str; } } else { - $str = 'NSGridType() . ' >'; - $str .= $this->htmlentities( $formVariableValue, ENT_COMPAT, 'utf-8' ); - $str .= ''; + $str = $this->htmlentities($formVariableValue, ENT_COMPAT, 'utf-8'); + $str .= 'NSDependentFields(true) . ' '; + $str .= $this->NSRequiredValue() . ' '; + $str .= $this->NSGridLabel() . ' '; + $str .= '/>'; + $str .= 'NSGridType() . ' '; + $str .= '/>'; + return $str; } } diff --git a/gulliver/thirdparty/creole/drivers/oracle/OCI8Connection.php b/gulliver/thirdparty/creole/drivers/oracle/OCI8Connection.php index f728e74f6..5a6a34ef9 100755 --- a/gulliver/thirdparty/creole/drivers/oracle/OCI8Connection.php +++ b/gulliver/thirdparty/creole/drivers/oracle/OCI8Connection.php @@ -153,7 +153,7 @@ class OCI8Connection extends ConnectionCommon implements Connection ); } - $success = oci_execute( $result, $this->execMode ); + $success = @oci_execute($result, $this->execMode); if ( ! $success ) { diff --git a/rbac/engine/classes/model/Roles.php b/rbac/engine/classes/model/Roles.php index 2561aeff2..d789b82cd 100755 --- a/rbac/engine/classes/model/Roles.php +++ b/rbac/engine/classes/model/Roles.php @@ -545,6 +545,22 @@ class Roles extends BaseRoles { G::auditLog("DeleteUserToRole", "Delete user ".$user['USR_USERNAME']." (".$USR_UID.") to Role ".$rol['ROL_NAME']." (".$ROL_UID.") "); } + function getRolePermissionsByPerUid($roleUid){ + try { + $criteria = new Criteria(); + $criteria->addSelectColumn(RolesPermissionsPeer::ROL_UID); + $criteria->addSelectColumn(RolesPermissionsPeer::PER_UID); + $criteria->add(RolesPermissionsPeer::PER_UID, $roleUid); + + $oDataset = RolesPeer::doSelectRS($criteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + return $oDataset; + + } catch( exception $e ) { + throw $e; + } + } function getRolePermissions($ROL_UID, $filter='', $status=null) { try { $criteria = new Criteria(); diff --git a/rbac/engine/config/schema.xml b/rbac/engine/config/schema.xml index 2b82770e3..74a992a53 100755 --- a/rbac/engine/config/schema.xml +++ b/rbac/engine/config/schema.xml @@ -23,7 +23,7 @@ - + diff --git a/rbac/engine/data/mssql/schema.sql b/rbac/engine/data/mssql/schema.sql index e004b83f4..918be57b2 100755 --- a/rbac/engine/data/mssql/schema.sql +++ b/rbac/engine/data/mssql/schema.sql @@ -33,7 +33,7 @@ END CREATE TABLE [RBAC_PERMISSIONS] ( [PER_UID] VARCHAR(32) default '' NOT NULL, - [PER_CODE] VARCHAR(32) default '' NOT NULL, + [PER_CODE] VARCHAR(64) default '' NOT NULL, [PER_CREATE_DATE] CHAR(19) default '0000-00-00 00:00:00' NOT NULL, [PER_UPDATE_DATE] CHAR(19) default '0000-00-00 00:00:00' NOT NULL, [PER_STATUS] INT default 1 NOT NULL, diff --git a/rbac/engine/data/mysql/insert.sql b/rbac/engine/data/mysql/insert.sql index 02318ce50..a74b10359 100755 --- a/rbac/engine/data/mysql/insert.sql +++ b/rbac/engine/data/mysql/insert.sql @@ -17,7 +17,23 @@ INSERT INTO `RBAC_PERMISSIONS` VALUES ('00000000000000000000000000000016','PM_FOLDERS_ADD_FOLDER','2009-10-12 00:00:00',NULL,1,'00000000000000000000000000000002'), ('00000000000000000000000000000017','PM_FOLDERS_ADD_FILE','2009-10-12 00:00:00',NULL,1,'00000000000000000000000000000002'), ('00000000000000000000000000000018','PM_CANCELCASE','2011-12-11 00:00:00','2011-12-11 00:00:00',1,'00000000000000000000000000000002'), -('00000000000000000000000000000019','PM_FOLDER_DELETE','2011-12-11 00:00:00','2011-12-11 00:00:00',1,'00000000000000000000000000000002'); +('00000000000000000000000000000019','PM_FOLDER_DELETE','2011-12-11 00:00:00','2011-12-11 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000020','PM_SETUP_LOGO','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000021','PM_SETUP_EMAIL','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'000000000000000000000000000000022'), +('00000000000000000000000000000022','PM_SETUP_CALENDAR','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000023','PM_SETUP_PROCESS_CATEGORIES','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000024','PM_SETUP_CLEAR_CACHE','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000025','PM_SETUP_HEART_BEAT','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000026','PM_SETUP_ENVIRONMENT','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000027','PM_SETUP_PM_TABLES','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000028','PM_SETUP_LOGIN','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000029','PM_SETUP_DASHBOARDS','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000030','PM_SETUP_LANGUAGE','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000031','PM_SETUP_SKIN','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000032','PM_SETUP_CASES_LIST_CACHE_BUILDER','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000033','PM_SETUP_PLUGINS','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000034','PM_SETUP_USERS_AUTHENTICATION_SOURCES','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'), +('00000000000000000000000000000035','PM_SETUP_LOGS','2016-03-01 00:00:00','0000-00-00 00:00:00',1,'00000000000000000000000000000002'); INSERT INTO `RBAC_ROLES` VALUES ('00000000000000000000000000000001','','00000000000000000000000000000001','RBAC_ADMIN','2007-07-31 19:10:22','2007-08-03 12:24:36',1), @@ -46,23 +62,59 @@ INSERT INTO `RBAC_ROLES_PERMISSIONS` VALUES ('00000000000000000000000000000002','00000000000000000000000000000017'), ('00000000000000000000000000000002','00000000000000000000000000000018'), ('00000000000000000000000000000002','00000000000000000000000000000019'), +('00000000000000000000000000000002','00000000000000000000000000000020'), +('00000000000000000000000000000002','00000000000000000000000000000021'), +('00000000000000000000000000000002','00000000000000000000000000000022'), +('00000000000000000000000000000002','00000000000000000000000000000023'), +('00000000000000000000000000000002','00000000000000000000000000000024'), +('00000000000000000000000000000002','00000000000000000000000000000025'), +('00000000000000000000000000000002','00000000000000000000000000000026'), +('00000000000000000000000000000002','00000000000000000000000000000027'), +('00000000000000000000000000000002','00000000000000000000000000000028'), +('00000000000000000000000000000002','00000000000000000000000000000029'), +('00000000000000000000000000000002','00000000000000000000000000000030'), +('00000000000000000000000000000002','00000000000000000000000000000031'), +('00000000000000000000000000000002','00000000000000000000000000000032'), +('00000000000000000000000000000002','00000000000000000000000000000033'), +('00000000000000000000000000000002','00000000000000000000000000000034'), +('00000000000000000000000000000002','00000000000000000000000000000035'), +('00000000000000000000000000000002','00000000000000000000000000000036'), +('00000000000000000000000000000002','00000000000000000000000000000037'), ('00000000000000000000000000000003','00000000000000000000000000000001'), ('00000000000000000000000000000003','00000000000000000000000000000005'), -('00000000000000000000000000000004', '00000000000000000000000000000001'), -('00000000000000000000000000000004', '00000000000000000000000000000003'), -('00000000000000000000000000000004', '00000000000000000000000000000005'), -('00000000000000000000000000000004', '00000000000000000000000000000006'), -('00000000000000000000000000000004', '00000000000000000000000000000007'), -('00000000000000000000000000000004', '00000000000000000000000000000008'), -('00000000000000000000000000000004', '00000000000000000000000000000009'), -('00000000000000000000000000000004', '00000000000000000000000000000011'), -('00000000000000000000000000000004', '00000000000000000000000000000013'), -('00000000000000000000000000000004', '00000000000000000000000000000014'), -('00000000000000000000000000000004', '00000000000000000000000000000015'), -('00000000000000000000000000000004', '00000000000000000000000000000016'), -('00000000000000000000000000000004', '00000000000000000000000000000017'), -('00000000000000000000000000000004', '00000000000000000000000000000018'), -('00000000000000000000000000000004', '00000000000000000000000000000019'); +('00000000000000000000000000000004','00000000000000000000000000000001'), +('00000000000000000000000000000004','00000000000000000000000000000003'), +('00000000000000000000000000000004','00000000000000000000000000000005'), +('00000000000000000000000000000004','00000000000000000000000000000006'), +('00000000000000000000000000000004','00000000000000000000000000000007'), +('00000000000000000000000000000004','00000000000000000000000000000008'), +('00000000000000000000000000000004','00000000000000000000000000000009'), +('00000000000000000000000000000004','00000000000000000000000000000011'), +('00000000000000000000000000000004','00000000000000000000000000000013'), +('00000000000000000000000000000004','00000000000000000000000000000014'), +('00000000000000000000000000000004','00000000000000000000000000000015'), +('00000000000000000000000000000004','00000000000000000000000000000016'), +('00000000000000000000000000000004','00000000000000000000000000000017'), +('00000000000000000000000000000004','00000000000000000000000000000018'), +('00000000000000000000000000000004','00000000000000000000000000000019'), +('00000000000000000000000000000004','00000000000000000000000000000020'), +('00000000000000000000000000000004','00000000000000000000000000000021'), +('00000000000000000000000000000004','00000000000000000000000000000022'), +('00000000000000000000000000000004','00000000000000000000000000000023'), +('00000000000000000000000000000004','00000000000000000000000000000024'), +('00000000000000000000000000000004','00000000000000000000000000000025'), +('00000000000000000000000000000004','00000000000000000000000000000026'), +('00000000000000000000000000000004','00000000000000000000000000000027'), +('00000000000000000000000000000004','00000000000000000000000000000028'), +('00000000000000000000000000000004','00000000000000000000000000000029'), +('00000000000000000000000000000004','00000000000000000000000000000030'), +('00000000000000000000000000000004','00000000000000000000000000000031'), +('00000000000000000000000000000004','00000000000000000000000000000032'), +('00000000000000000000000000000004','00000000000000000000000000000033'), +('00000000000000000000000000000004','00000000000000000000000000000034'), +('00000000000000000000000000000004','00000000000000000000000000000035'), +('00000000000000000000000000000004','00000000000000000000000000000036'), +('00000000000000000000000000000004','00000000000000000000000000000037'); INSERT INTO `RBAC_SYSTEMS` VALUES ('00000000000000000000000000000001','RBAC','2007-07-31 19:10:22','2007-08-03 12:24:36',1),('00000000000000000000000000000002','PROCESSMAKER','2007-07-31 19:10:22','2007-08-03 12:24:36',1); INSERT INTO `RBAC_USERS` VALUES ('00000000000000000000000000000001','admin','21232f297a57a5a743894a0e4a801fc3','Administrator','','admin@processmaker.com','2020-01-01','2007-08-03 12:24:36','2008-02-13 07:24:07',1,'MYSQL','00000000000000000000000000000000','',''); diff --git a/rbac/engine/data/mysql/schema.sql b/rbac/engine/data/mysql/schema.sql index 40de34f8c..a4078ddac 100755 --- a/rbac/engine/data/mysql/schema.sql +++ b/rbac/engine/data/mysql/schema.sql @@ -13,7 +13,7 @@ DROP TABLE IF EXISTS `RBAC_PERMISSIONS`; CREATE TABLE `RBAC_PERMISSIONS` ( `PER_UID` VARCHAR(32) default '' NOT NULL, - `PER_CODE` VARCHAR(32) default '' NOT NULL, + `PER_CODE` VARCHAR(64) default '' NOT NULL, `PER_CREATE_DATE` DATETIME, `PER_UPDATE_DATE` DATETIME, `PER_STATUS` INTEGER default 1 NOT NULL, diff --git a/rbac/engine/data/oracle/schema.sql b/rbac/engine/data/oracle/schema.sql index dc61283d7..913713729 100755 --- a/rbac/engine/data/oracle/schema.sql +++ b/rbac/engine/data/oracle/schema.sql @@ -10,7 +10,7 @@ DROP TABLE "RBAC_PERMISSIONS" CASCADE CONSTRAINTS; CREATE TABLE "RBAC_PERMISSIONS" ( "PER_UID" VARCHAR2(32) default '' NOT NULL, - "PER_CODE" VARCHAR2(32) default '' NOT NULL, + "PER_CODE" VARCHAR2(64) default '' NOT NULL, "PER_CREATE_DATE" DATE default '0000-00-00 00:00:00' NOT NULL, "PER_UPDATE_DATE" DATE default '0000-00-00 00:00:00' NOT NULL, "PER_STATUS" NUMBER default 1 NOT NULL diff --git a/tests/automated/workflow/engine/classes/classJrmlTest.php b/tests/automated/workflow/engine/classes/classJrmlTest.php deleted file mode 100644 index 8eaae8da7..000000000 --- a/tests/automated/workflow/engine/classes/classJrmlTest.php +++ /dev/null @@ -1,139 +0,0 @@ -'', 'type'=> array()); - $this->object = new Jrml($array); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * This is the default method to test, if the class still having - * the same number of methods. - */ - public function testNumberOfMethodsInThisClass() - { - $methods = get_class_methods('Jrml'); - $this->assertTrue( count($methods) == 7); - } - - /** - * @covers Jrml::__construct - * @todo Implement test__construct(). - */ - public function test__construct() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('__construct', $methods ), 'exists method __construct' ); - $r = new ReflectionMethod('Jrml', '__construct'); - $params = $r->getParameters(); - $this->assertTrue( $params[0]->getName() == 'data'); - $this->assertTrue( $params[0]->isArray() == false); - $this->assertTrue( $params[0]->isOptional () == true); - $this->assertTrue( $params[0]->getDefaultValue() == array()); - } - - /** - * @covers Jrml::get_md - * @todo Implement testget_md(). - */ - public function testget_md() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('get_md', $methods ), 'exists method get_md' ); - $r = new ReflectionMethod('Jrml', 'get_md'); - $params = $r->getParameters(); - } - - /** - * @covers Jrml::get_header - * @todo Implement testget_header(). - */ - public function testget_header() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('get_header', $methods ), 'exists method get_header' ); - $r = new ReflectionMethod('Jrml', 'get_header'); - $params = $r->getParameters(); - } - - /** - * @covers Jrml::get_column_header - * @todo Implement testget_column_header(). - */ - public function testget_column_header() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('get_column_header', $methods ), 'exists method get_column_header' ); - $r = new ReflectionMethod('Jrml', 'get_column_header'); - $params = $r->getParameters(); - } - - /** - * @covers Jrml::get_detail - * @todo Implement testget_detail(). - */ - public function testget_detail() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('get_detail', $methods ), 'exists method get_detail' ); - $r = new ReflectionMethod('Jrml', 'get_detail'); - $params = $r->getParameters(); - } - - /** - * @covers Jrml::get_footer - * @todo Implement testget_footer(). - */ - public function testget_footer() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('get_footer', $methods ), 'exists method get_footer' ); - $r = new ReflectionMethod('Jrml', 'get_footer'); - $params = $r->getParameters(); - } - - /** - * @covers Jrml::export - * @todo Implement testexport(). - */ - public function testexport() - { - $methods = get_class_methods($this->object); - $this->assertTrue( in_array('export', $methods ), 'exists method export' ); - $r = new ReflectionMethod('Jrml', 'export'); - $params = $r->getParameters(); - } -} - diff --git a/workflow/engine/bin/cron_single.php b/workflow/engine/bin/cron_single.php index 39ccef9ba..d261d6b4e 100755 --- a/workflow/engine/bin/cron_single.php +++ b/workflow/engine/bin/cron_single.php @@ -339,6 +339,8 @@ function processWorkspace() /*----------------------------------********---------------------------------*/ fillReportByUser(); fillReportByProcess(); + synchronizeDrive(); + synchronizeGmailLabels(); /*----------------------------------********---------------------------------*/ } catch (Exception $oError) { saveLog("main", "error", "Error processing workspace : " . $oError->getMessage() . "\n"); @@ -957,5 +959,66 @@ function fillReportByProcess () saveLog("fillReportByProcess", "error", "Error in fill report by process: " . $e->getMessage()); } } -/*----------------------------------********---------------------------------*/ +function synchronizeDrive () +{ + try { + global $argvx; + + if (strpos($argvx, "synchronize-documents-drive") === false) { + return false; + } + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if ($licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M=')) { + G::LoadClass('AppDocumentDrive'); + $drive = new AppDocumentDrive(); + if ($drive->getStatusDrive()) { + setExecutionMessage("Synchronize documents to Drive"); + $drive->synchronizeDrive(true); + } else { + setExecutionMessage("It has not enabled Feature Drive"); + } + } else { + setExecutionMessage("The Drive license is not enabled"); + } + setExecutionResultMessage("DONE"); + + } catch (Exception $e) { + setExecutionResultMessage("WITH ERRORS", "error"); + eprintln(" '-" . $e->getMessage(), "red"); + saveLog("synchronizeDocumentsDrive", "error", "Error in synchronize documents to drive: " . $e->getMessage()); + } +} + +function synchronizeGmailLabels() +{ + try { + global $argvx; + + if (strpos($argvx, "synchronize-gmail-labels") === false) { + return false; + } + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + G::LoadClass("pmGoogleApi"); + $pmGoogle = new PMGoogleApi(); + if ($pmGoogle->getServiceGmailStatus()) { + setExecutionMessage("Synchronize labels in Gmail"); + G::LoadClass('labelsGmail'); + $labGmail = new labelsGmail(); + $labGmail->processPendingRelabelingInQueue(); + } else { + setExecutionMessage("It has not enabled Feature Gmail"); + } + } else { + setExecutionMessage("The Gmail license is not enabled"); + } + setExecutionResultMessage("DONE"); + + } catch (Exception $e) { + setExecutionResultMessage("WITH ERRORS", "error"); + eprintln(" '-" . $e->getMessage(), "red"); + saveLog("synchronizeGmailLabels", "error", "Error when synchronizing Gmail labels: " . $e->getMessage()); + } +} +/*----------------------------------********---------------------------------*/ diff --git a/workflow/engine/classes/class.AppDocumentDrive.php b/workflow/engine/classes/class.AppDocumentDrive.php new file mode 100644 index 000000000..91f7f8429 --- /dev/null +++ b/workflow/engine/classes/class.AppDocumentDrive.php @@ -0,0 +1,441 @@ +drive = new PMDrive(); + $status = $this->drive->getServiceDriveStatus(); + $status = !empty($status) ? ($status == 1 ? true : false): false; + $this->usersEmail = ''; + $this->setStatusDrive($status); + } + + /** + * @return boolean + */ + public function getStatusDrive() + { + return $this->statusDrive; + } + + /** + * @param boolen $statusDrive + */ + public function setStatusDrive($statusDrive) + { + $this->statusDrive = $statusDrive; + } + + public function loadUser ($usrUid) + { + $this->user = new Users(); + $this->user->load($usrUid); + $this->drive->setDriveUser($this->user->getUsrEmail()); + } + + public function loadApplication ($appUid) + { + $this->app = new Application(); + $this->app->Load($appUid); + } + + public function existAppFolderDrive () + { + try { + if ($this->app->getAppDriveFolderUid() == null) { + $process = new Process(); + $process->setProUid($this->app->getProUid()); + + $result = $this->drive->createFolder( + $process->getProTitle() . ' - ' . G::LoadTranslation("ID_CASE") . ' #' . $this->app->getAppNumber(), + $this->drive->getFolderIdPMDrive($this->user->getUsrUid()) + ); + $this->app->setAppDriveFolderUid($result->id); + $this->app->update($this->app->toArray(BasePeer::TYPE_FIELDNAME)); + } + } catch (Exception $e) { + error_log('Error create folder Drive: ' . $e->getMessage()); + } + } + + public function permission ($appUid, $folderUid, $fileIdDrive) + { + $criteria = new Criteria('workflow'); + $criteria->addSelectColumn(ApplicationPeer::PRO_UID); + $criteria->addSelectColumn(TaskUserPeer::TAS_UID); + $criteria->addSelectColumn(TaskUserPeer::USR_UID); + $criteria->addSelectColumn(TaskUserPeer::TU_RELATION); + + $criteria->add(ApplicationPeer::APP_UID, $appUid); + $criteria->addJoin(ApplicationPeer::PRO_UID, TaskPeer::PRO_UID, Criteria::LEFT_JOIN); + $criteria->addJoin(TaskPeer::TAS_UID, TaskUserPeer::TAS_UID, Criteria::LEFT_JOIN); + + $rs = ApplicationPeer::doSelectRS($criteria); + $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $userPermission = array(); + $user = new Users(); + + while ($rs->next()) { + $row = $rs->getRow(); + if ($row['TU_RELATION'] == 1) { + //users + $dataUser = $user->load($row['USR_UID']); + if (array_search($dataUser['USR_EMAIL'], $userPermission) === false) { + $objectPermissions = $this->getAllObjects($row['PRO_UID'], $appUid, $row['TAS_UID'], + $row['USR_UID']); + $userPermission[] = $dataUser['USR_EMAIL']; + } + } else { + //Groups + $criteria = new Criteria('workflow'); + $criteria->addSelectColumn(UsersPeer::USR_EMAIL); + $criteria->addSelectColumn(UsersPeer::USR_UID); + $criteria->add(GroupUserPeer::GRP_UID, $row['USR_UID']); + $criteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); + + $rsGroup = AppDelegationPeer::doSelectRS($criteria); + $rsGroup->setFetchmode(ResultSet::FETCHMODE_ASSOC); + while ($rsGroup->next()) { + $aRow = $rsGroup->getRow(); + if (array_search($aRow['USR_EMAIL'], $userPermission) === false) { + $objectPermissions = $this->getAllObjects($row['PRO_UID'], $appUid, + $row['TAS_UID'], $aRow['USR_UID']); + $userPermission[] = $aRow['USR_EMAIL']; + } + } + } + } + $userPermission = array_unique($userPermission); + + foreach ($userPermission as $key => $val) { + $this->drive->setPermission($folderUid, $val, 'user', 'writer'); + $this->drive->setPermission($fileIdDrive, $val); + } + } + + public function addUserEmail ($email) + { + if (empty($email)) { + return; + } + if ($this->usersEmail == '') { + $this->usersEmail = $email; + } else { + $emails = explode('|', $this->usersEmail); + if (array_search($email, $emails) === false) { + $this->usersEmail .= '|' . $email; + } + } + } + /** + * Get email of task users to app_uid + * @param $appUid id application + * + * @throws \Exception + */ + public function getEmailUsersTask($appUid) + { + try { + $criteria = new Criteria('workflow'); + $criteria->add(AppDelegationPeer::APP_UID, $appUid); + $criteria->add(AppDelegationPeer::DEL_THREAD_STATUS, 'OPEN'); + + $rsAppDelegation = AppDelegationPeer::doSelectRS($criteria); + $rsAppDelegation->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $group = new Groups(); + $user = new Users(); + $data = []; + while ($rsAppDelegation->next()) { + $row = $rsAppDelegation->getRow(); + if ($user->userExists($row['USR_UID'])) { + $data = []; + $data[] = $user->load($row['USR_UID']); + } else { + $data = $group->getUsersOfGroup($row['USR_UID']); + } + + foreach ($data as $dataUser) { + $this->addUserEmail($dataUser["USR_EMAIL"]); + } + } + } catch (Exception $exception) { + error_log('Error: ' . $exception); + } + } + + /** + * @param array $appDocument + * @param string $typeDocument type document INPUT, OUTPUT_DOC, OUTPUT_PDF, ATTACHED + * @param string $mime MIME type of the file to insert. + * @param string $src location of the file to insert. + * @param string $name Title of the file to insert, including the extension. + * return string uid + */ + public function upload ($appDocument, $typeDocument, $mime, $src, $name) + { + try + { + $idFileDrive = null; + $this->existAppFolderDrive(); + $appDoc = new AppDocument(); + $result = $this->drive->uploadFile( + $mime, + $src, + $name, + $this->app->getAppDriveFolderUid() + ); + if ($result->id !== null) { + $idFileDrive = $result->id; + $appDoc->setDriveDownload($typeDocument, $result->id); + $appDoc->update($appDocument); + } + return $idFileDrive; + } catch (Exception $e) { + error_log('Error upload file drive: ' . $e->getMessage()); + } + } + + /** + * Download file drive + * @param $uidFileDrive + */ + public function download ($uidFileDrive) + { + try + { + $result = $this->drive->downloadFile($uidFileDrive); + + } catch (Exception $e) { + error_log('Error Download file drive: ' . $e->getMessage()); + } + return $result; + } + + + /** + * @param array $data + * @param string $typeDoc value INPUT, OUTPUT_DOC, OUTPUT_PDF, ATTACHED + * + * @return string url drive + */ + public function changeUrlDrive ($data, $typeDoc) + { + try + { + + $urlDrive = $data['APP_DOC_DRIVE_DOWNLOAD']; + if ($this->getStatusDrive()) { + $driveDownload = @unserialize($data['APP_DOC_DRIVE_DOWNLOAD']); + $urlDrive = $driveDownload !== false + && is_array($driveDownload) + && array_key_exists($typeDoc, $driveDownload) ? + $driveDownload[$typeDoc] : $urlDrive; + } + + } catch (Exception $e) { + error_log('Error change url drive: ' . $e->getMessage()); + } + + return $urlDrive; + } + + /** + * Synchronize documents drive + * + * @param boolean $log enable print cron + */ + public function synchronizeDrive ($log) + { + if (!$this->statusDrive) { + error_log("It has not enabled Feature Gmail"); + return; + } + $criteria = new Criteria( 'workflow' ); + $criteria->addSelectColumn(AppDocumentPeer::APP_DOC_UID); + $criteria->addSelectColumn(AppDocumentPeer::DOC_VERSION); + $criteria->add( + $criteria->getNewCriterion( AppDocumentPeer::SYNC_WITH_DRIVE, 'UNSYNCHRONIZED', Criteria::EQUAL )-> + addOr($criteria->getNewCriterion( AppDocumentPeer::SYNC_PERMISSIONS, null, Criteria::NOT_EQUAL )) + ); + + $criteria->addAscendingOrderByColumn( 'APP_DOC_CREATE_DATE' ); + $criteria->addAscendingOrderByColumn( 'APP_UID' ); + $rs = AppDocumentPeer::doSelectRS( $criteria ); + $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + + while ($rs->next()) { + $row = $rs->getRow(); + $appDoc = new AppDocument(); + $fields = $appDoc->load($row['APP_DOC_UID'], $row['DOC_VERSION']); + + $appDocUid = $appDoc->getAppDocUid(); + $docVersion = $appDoc->getDocVersion(); + $filename = pathinfo( $appDoc->getAppDocFilename() ); + $name = !empty($filename['basename'])? $filename['basename'] : ''; + $ext = !empty($filename['extension'])? $filename['extension'] : ''; + $appUid = G::getPathFromUID($appDoc->getAppUid()); + $file = G::getPathFromFileUID($appDoc->getAppUid(), $appDocUid ); + + + $sw_file_exists_doc = false; + $sw_file_exists_pdf = false; + if ($appDoc->getAppDocType() == 'OUTPUT') { + //$name = substr($name, 1, -1); + $realPathDoc = PATH_DOCUMENT . $appUid . '/outdocs/' . $appDocUid . '_' . $docVersion . '.' . 'doc'; + $realPathDoc1 = PATH_DOCUMENT . $appUid . '/outdocs/' . $name . '_' . $docVersion . '.' . 'doc'; + $realPathDoc2 = PATH_DOCUMENT . $appUid . '/outdocs/' . $name . '.' . 'doc'; + + $sw_file_exists = false; + if (file_exists( $realPathDoc )) { + $sw_file_exists = true; + $sw_file_exists_doc = true; + } elseif (file_exists( $realPathDoc1 )) { + $sw_file_exists = true; + $sw_file_exists_doc = true; + $realPathDoc = $realPathDoc1; + } elseif (file_exists( $realPathDoc2 )) { + $sw_file_exists = true; + $sw_file_exists_doc = true; + $realPathDoc = $realPathDoc2; + } + + $realPathPdf = PATH_DOCUMENT . $appUid . '/outdocs/' . $appDocUid . '_' . $docVersion . '.' . 'pdf'; + $realPathPdf1 = PATH_DOCUMENT . $appUid . '/outdocs/' . $name . '_' .$docVersion . '.' . 'pdf'; + $realPathPdf2 = PATH_DOCUMENT . $appUid . '/outdocs/' . $name . '.' . 'pdf'; + + if (file_exists( $realPathPdf )) { + $sw_file_exists = true; + $sw_file_exists_pdf = true; + } elseif (file_exists( $realPathPdf1 )) { + $sw_file_exists = true; + $sw_file_exists_pdf = true; + $realPathPdf = $realPathPdf1; + } elseif (file_exists( $realPathPdf2 )) { + $sw_file_exists = true; + $sw_file_exists_pdf = true; + $realPathPdf = $realPathPdf2; + } + } else { + $realPath = PATH_DOCUMENT . $appUid . '/' . $file[0] . $file[1] . '_' . $docVersion . '.' . $ext; + $realPath1 = PATH_DOCUMENT . $appUid . '/' . $file[0] . $file[1] . '.' . $ext; + $sw_file_exists = false; + if (file_exists( $realPath )) { + $sw_file_exists = true; + } elseif (file_exists( $realPath1 )) { + $sw_file_exists = true; + $realPath = $realPath1; + } + } + if ($sw_file_exists) { + + $this->loadApplication($appDoc->getAppUid()); + $this->loadUser($fields['USR_UID']); + + $emails = $appDoc->getSyncPermissions(); + $emails = !empty($emails) ? explode('|', $emails) : array(); + $result = null; + foreach ($emails as $index => $email) { + if (!empty($email)) { + + if ($index == 0 && $fields['SYNC_WITH_DRIVE'] == 'UNSYNCHRONIZED') { + if ($log) { + eprintln('upload file:' . $name , 'green'); + } + $this->drive->setDriveUser($email); + $info = finfo_open(FILEINFO_MIME_TYPE); + $mime = finfo_file($info, $realPath); + $type = $appDoc->getAppDocType(); + + if ($appDoc->getAppDocType() == 'OUTPUT') { + + if ($sw_file_exists_doc) { + $realPath = $realPathDoc; + $name = array_pop(explode('/', $realPathDoc)); + $mime = 'application/msword'; + $type = 'OUTPUT_DOC'; + } + if ($sw_file_exists_pdf) { + $realPath = $realPathPdf; + $name = array_pop(explode('/', $realPathPdf)); + $mime = finfo_file($info, $realPathPdf); + $type = 'OUTPUT_PDF'; + } + } + $result = $this->upload($fields, $type, $mime, $realPath, $name); + } else { + $this->drive->setDriveUser($this->user->getUsrEmail()); + } + if ($log) { + eprintln('Set Permission:' . $email , 'green'); + } + $this->drive->setPermission($this->app->getAppDriveFolderUid(), $email, 'user', 'writer'); + + } + } + if ($result != null) { + $fields['SYNC_WITH_DRIVE'] = 'SYNCHRONIZED'; + $fields['SYNC_PERMISSIONS'] = null; + } + } else { + $fields['SYNC_WITH_DRIVE'] = 'NO_EXIST_FILE_PM'; + if ($log) { + eprintln('File no exists:' . $name , 'red'); + } + } + $appDoc->update($fields); + } + } + + public function addUsersDocumentDrive ($appUid) + { + $this->getEmailUsersTask($appUid); + + $criteria = new Criteria( 'workflow' ); + $criteria->add( AppDocumentPeer::APP_UID, $appUid ); + $criteria->addAscendingOrderByColumn( 'DOC_VERSION' ); + $rs = AppDocumentPeer::doSelectRS( $criteria ); + $rs->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + + $appDoc = new AppDocument(); + while ($rs->next()) { + $row = $rs->getRow(); + if (empty($row['SYNC_PERMISSIONS'])) { + $row['SYNC_PERMISSIONS'] = $this->usersEmail; + } else { + $emails = explode('|', $row['SYNC_PERMISSIONS']); + foreach ($emails as $email) { + $this->addUserEmail($email); + } + } + $appDoc->update($row); + } + } +} \ No newline at end of file diff --git a/workflow/engine/classes/class.applications.php b/workflow/engine/classes/class.applications.php index 46f814a31..4653e642c 100755 --- a/workflow/engine/classes/class.applications.php +++ b/workflow/engine/classes/class.applications.php @@ -18,7 +18,9 @@ class Applications $sort = "APP_CACHE_VIEW.APP_NUMBER", $category = null, $configuration = true, - $paged = true + $paged = true, + $newerThan = '', + $oldestThan = '' ) { $callback = isset($callback)? $callback : "stcCallback1001"; $dir = isset($dir)? $dir : "DESC"; @@ -301,7 +303,7 @@ class Applications } $Criteria->add( $Criteria->getNewCriterion( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateFrom, Criteria::GREATER_EQUAL )->addAnd( $Criteria->getNewCriterion( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateTo, Criteria::LESS_EQUAL ) ) ); - $CriteriaCount->add( $CriteriaCount->getNewCriterion( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateFrom, Criteria::GREATER_EQUAL )->addAnd( $Criteria->getNewCriterion( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateTo, Criteria::LESS_EQUAL ) ) ); + $CriteriaCount->add( $CriteriaCount->getNewCriterion( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateFrom, Criteria::GREATER_EQUAL )->addAnd( $CriteriaCount->getNewCriterion( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateTo, Criteria::LESS_EQUAL ) ) ); } else { $dateFrom = $dateFrom . " 00:00:00"; @@ -315,6 +317,27 @@ class Applications $CriteriaCount->add( AppCacheViewPeer::DEL_DELEGATE_DATE, $dateTo, Criteria::LESS_EQUAL ); } + if ($newerThan != '') { + if ($oldestThan != '') { + $Criteria->add( + $Criteria->getNewCriterion(AppCacheViewPeer::DEL_DELEGATE_DATE, $newerThan, Criteria::GREATER_THAN)->addAnd( + $Criteria->getNewCriterion(AppCacheViewPeer::DEL_DELEGATE_DATE, $oldestThan, Criteria::LESS_THAN)) + ); + $CriteriaCount->add( + $CriteriaCount->getNewCriterion(AppCacheViewPeer::DEL_DELEGATE_DATE, $newerThan, Criteria::GREATER_THAN)->addAnd( + $CriteriaCount->getNewCriterion(AppCacheViewPeer::DEL_DELEGATE_DATE, $oldestThan, Criteria::LESS_THAN)) + ); + } else { + $Criteria->add(AppCacheViewPeer::DEL_DELEGATE_DATE, $newerThan, Criteria::GREATER_THAN); + $CriteriaCount->add( AppCacheViewPeer::DEL_DELEGATE_DATE, $newerThan, Criteria::GREATER_THAN); + } + } else { + if ($oldestThan != '') { + $Criteria->add(AppCacheViewPeer::DEL_DELEGATE_DATE, $oldestThan, Criteria::LESS_THAN); + $CriteriaCount->add(AppCacheViewPeer::DEL_DELEGATE_DATE, $oldestThan, Criteria::LESS_THAN); + } + } + //add the filter if ($filter != '') { switch ($filter) { @@ -474,7 +497,7 @@ class Applications $sort = ""; //Current delegation (*) - if (($action == "sent" || $action == "search" || $action == "simple_search" || $action == "to_revise" || $action == "to_reassign") && ($status != "TO_DO")) { + if ($action == 'sent' || $action == 'simple_search' || $action == 'to_reassign') { switch ($sortBk) { case "APP_CACHE_VIEW.APP_CURRENT_USER": $sort = "USRCR_" . $conf->userNameFormatGetFirstFieldByUsersTable(); @@ -578,8 +601,8 @@ class Applications $maxDataset->close(); }*/ - //Current delegation (*) || $action == "search" || $action == "to_revise" - if (($action == "sent" || $action == "simple_search" || $action == "to_reassign") && ($status != "TO_DO")) { + //Current delegation (*) + if ($action == 'sent' || $action == 'simple_search' || $action == 'to_reassign') { //Current task $aRow["APP_TAS_TITLE"] = $aRow["APPDELCR_APP_TAS_TITLE"]; diff --git a/workflow/engine/classes/class.case.php b/workflow/engine/classes/class.case.php index 9d19d4af9..51ea76891 100755 --- a/workflow/engine/classes/class.case.php +++ b/workflow/engine/classes/class.case.php @@ -338,12 +338,8 @@ class Cases $c->addJoinMC($aConditions, Criteria::LEFT_JOIN); $c->add(TaskPeer::TAS_UID, $tasks, Criteria::IN); - if ($typeView == 'category') { - $c->addDescendingOrderByColumn('PRO_CATEGORY'); - } else { - $c->addAscendingOrderByColumn('PRO_TITLE'); - $c->addAscendingOrderByColumn('TAS_TITLE'); - } + $c->addAscendingOrderByColumn('PRO_TITLE'); + $c->addAscendingOrderByColumn('TAS_TITLE'); $rs = TaskPeer::doSelectRS($c); $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); @@ -378,7 +374,13 @@ class Cases $rs->next(); $row = $rs->getRow(); } - return $rows; + + $rowsToReturn = $rows; + if ($typeView === 'category') { + $rowsToReturn = $this->orderStartCasesByCategoryAndName($rows); + } + + return $rowsToReturn; } /* @@ -1126,23 +1128,16 @@ class Cases * @return Fields */ - public function removeCase($sAppUid) + public function removeCase($sAppUid, $deleteDelegation = true) { try { $this->getExecuteTriggerProcess($sAppUid, 'DELETED'); - $oAppDelegation = new AppDelegation(); $oAppDocument = new AppDocument(); - //Delete the delegations of a application - $oCriteria2 = new Criteria('workflow'); - $oCriteria2->add(AppDelegationPeer::APP_UID, $sAppUid); - $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); - $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset2->next(); - while ($aRow2 = $oDataset2->getRow()) { - $oAppDelegation->remove($sAppUid, $aRow2['DEL_INDEX']); - $oDataset2->next(); + if($deleteDelegation) { + //Delete the delegations of a application + $this->deleteDelegation($sAppUid); } //Delete the documents assigned to a application $oCriteria2 = new Criteria('workflow'); @@ -1237,6 +1232,9 @@ class Cases $oCriteria = new Criteria('workflow'); $oCriteria->add(ListParticipatedLastPeer::APP_UID, $sAppUid); ListParticipatedLastPeer::doDelete($oCriteria); + $oCriteria = new Criteria('workflow'); + $oCriteria->add(ListPausedPeer::APP_UID, $sAppUid); + ListPausedPeer::doDelete($oCriteria); /*----------------------------------********---------------------------------*/ return $result; } catch (exception $e) { @@ -1446,7 +1444,12 @@ class Cases //there is an open delegation, so we need to return the delegation row return $delegations['open']; } else { - return array(); //returning empty array + if(count($delegations['paused']) > 0){ + //there is an paused delegation, so we need to return the delegation row + return $delegations['paused']; + }else{ + return array(); //returning empty array + } } } // if not we check previous tasks @@ -1493,13 +1496,12 @@ class Cases * Get reviewed tasks (delegations started) * @param string $taskUid * @param string $sAppUid - * @author erik amaru ortiz * @return array within the open & closed tasks * false -> when has not any delegation started for that task */ public function getReviewedTasks($taskUid, $sAppUid) { - $openTasks = $closedTasks = array(); + $openTasks = $closedTasks = $pausedTasks = array(); // get all delegations fro this task $oCriteria2 = new Criteria('workflow'); @@ -1515,14 +1517,52 @@ class Cases if ($row['DEL_THREAD_STATUS'] == 'OPEN') { $openTasks[] = $row; } else { + //If exist paused cases $closedTasks[] = $row; + $aIndex[] = $row['DEL_INDEX']; + $pausedTasks = $this->getReviewedTasksPaused($sAppUid,$aIndex); } } - if (count($openTasks) == 0 && count($closedTasks) == 0) { + if (count($openTasks) === 0 && count($closedTasks) === 0 && count($pausedTasks) === 0) { return false; // return false because there is not any delegation for this task. } else { - return array('open' => $openTasks, 'closed' => $closedTasks); + return array('open' => $openTasks, 'closed' => $closedTasks, 'paused' => $pausedTasks); + } + } + + /** + * Get reviewed tasks is Paused (delegations started) + * @param string $sAppUid + * @param array $aDelIndex + * @return array within the paused tasks + * false -> when has not any delegation started for that task + */ + public function getReviewedTasksPaused($sAppUid,$aDelIndex) + { + $oCriteria = new Criteria('workflow'); + $oCriteria->add(AppDelayPeer::APP_UID, $sAppUid); + $oCriteria->add(AppDelayPeer::APP_DEL_INDEX, $aDelIndex, Criteria::IN); + $oCriteria->add(AppDelayPeer::APP_TYPE, 'PAUSE'); + $oCriteria->add( + $oCriteria->getNewCriterion(AppDelayPeer::APP_DISABLE_ACTION_USER, 0, Criteria::EQUAL)->addOr( + $oCriteria->getNewCriterion(AppDelayPeer::APP_DISABLE_ACTION_USER, null, Criteria::ISNULL)) + ); + + $oDataset = AppDelayPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $pausedTask = array(); + // loop and separate open & closed delegations in theirs respective arrays + while ($oDataset->next()) { + $row = $oDataset->getRow(); + $pausedTask[] = $row; + } + + if (count($pausedTask) == 0) { + return false; // return false because there is not any delegation for this task. + } else { + return array('pause' => $pausedTask); } } @@ -3640,15 +3680,6 @@ class Cases 'APP_DOC_FILENAME' => 'char', 'APP_DOC_INDEX' => 'integer' ); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ while ($aRow = $oDataset->getRow()) { $aAux = $oAppDocument->load($aRow['APP_DOC_UID'], $aRow['DOC_VERSION']); @@ -3709,15 +3740,6 @@ class Cases } } $aFields['COMMENT'] = $aFields['APP_DOC_COMMENT']; - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('INPUT', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['INPUT']; - } - /*----------------------------------********---------------------------------*/ if (($aRow['DOC_VERSION'] == $lastVersion) || ($sAppDocuUID != "")) { $aInputDocuments[] = $aFields; } @@ -3942,93 +3964,6 @@ class Cases $strPathName = PATH_DOCUMENT . G::getPathFromUID($applicationUid) . PATH_SEP; $strFileName = $appDocUid . "_" . $docVersion . "." . $extension; - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - if ($pmDrive->getStatusService()) { - $app = new Application(); - $user = new Users(); - $dataUser = $user->load($userUid); - $pmDrive->setDriveUser($dataUser['USR_EMAIL']); - - $appData = $app->Load($applicationUid); - if ($appData['APP_DRIVE_FOLDER_UID'] == null) { - $process = new Process(); - $process->setProUid($appData['PRO_UID']); - - $result = $pmDrive->createFolder($process->getProTitle() . ' - ' . G::LoadTranslation("ID_CASE") . ' #' . $appData['APP_NUMBER'], - $pmDrive->getFolderIdPMDrive($userUid)); - $appData['APP_DRIVE_FOLDER_UID'] = $result->id; - $app->update($appData); - } - - $result = $pmDrive->uploadFile('application/' . $extension, $fileTmpName, $file, - $appData['APP_DRIVE_FOLDER_UID']); - $appDocument->setDriveDownload('INPUT', $result->webContentLink); - $fileIdDrive = $result->id; - $arrayField['DOC_VERSION'] = $docVersion; - $arrayField['APP_DOC_UID'] = $appDocUid; - - $appDocument->update($arrayField); - - //add permissions - $criteria = new Criteria('workflow'); - $criteria->addSelectColumn(ApplicationPeer::PRO_UID); - $criteria->addSelectColumn(TaskUserPeer::TAS_UID); - $criteria->addSelectColumn(TaskUserPeer::USR_UID); - $criteria->addSelectColumn(TaskUserPeer::TU_RELATION); - - $criteria->add(ApplicationPeer::APP_UID, $applicationUid); - $criteria->addJoin(ApplicationPeer::PRO_UID, TaskPeer::PRO_UID, Criteria::LEFT_JOIN); - $criteria->addJoin(TaskPeer::TAS_UID, TaskUserPeer::TAS_UID, Criteria::LEFT_JOIN); - - $dataset = ApplicationPeer::doSelectRS($criteria); - $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - - $userPermission = array(); - - while ($dataset->next()) { - $row = $dataset->getRow(); - if ($row['TU_RELATION'] == 1) { - //users - $dataUser = $user->load($row['USR_UID']); - if (array_search($dataUser['USR_EMAIL'], $userPermission) === false) { - $objectPermissions = $this->getAllObjects($row['PRO_UID'], $applicationUid, $row['TAS_UID'], - $row['USR_UID']); - $userPermission[] = $dataUser['USR_EMAIL']; - } - } else { - //Groups - $criteria = new Criteria('workflow'); - $criteria->addSelectColumn(UsersPeer::USR_EMAIL); - $criteria->addSelectColumn(UsersPeer::USR_UID); - $criteria->add(GroupUserPeer::GRP_UID, $row['USR_UID']); - $criteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); - - $oDataset = AppDelegationPeer::doSelectRS($criteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($oDataset->next()) { - $aRow = $oDataset->getRow(); - if (array_search($aRow['USR_EMAIL'], $userPermission) === false) { - $objectPermissions = $this->getAllObjects($row['PRO_UID'], $applicationUid, - $row['TAS_UID'], $aRow['USR_UID']); - $userPermission[] = $aRow['USR_EMAIL']; - } - } - } - } - $userPermission = array_unique($userPermission); - - foreach ($userPermission as $key => $val) { - $pmDrive->setPermission($appData['APP_DRIVE_FOLDER_UID'], $val, 'user', 'writer'); - $pmDrive->setPermission($fileIdDrive, $val); - } - } - } - /*----------------------------------********---------------------------------*/ - switch ($option) { case "xmlform": G::uploadFile($fileTmpName, $strPathName, $strFileName); @@ -4228,19 +4163,6 @@ class Cases $oListPaused = new ListPaused(); $oListPaused->create($data); /*----------------------------------********---------------------------------*/ - - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - if (!empty($enablePMGmail) && $enablePMGmail == 1) { - $pmGmail = new \ProcessMaker\BusinessModel\Pmgmail(); - $pmGmail->modifyMailToPauseCase($aData['APP_UID'], $aData['APP_DEL_INDEX']); - } - } - /*----------------------------------********---------------------------------*/ } /* @@ -4337,19 +4259,6 @@ class Cases $oListPaused = new ListPaused(); $oListPaused->remove($sApplicationUID, $iDelegation, $aData); /*----------------------------------********---------------------------------*/ - - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - if (!empty($enablePMGmail) && $enablePMGmail == 1) { - $pmGmail = new \ProcessMaker\BusinessModel\Pmgmail(); - $pmGmail->modifyMailToUnpauseCase($aData['APP_UID'], $aData['DEL_INDEX']); - } - } - /*----------------------------------********---------------------------------*/ } /* @@ -4729,15 +4638,6 @@ class Cases 'APP_DOC_FILENAME' => 'char', 'APP_DOC_INDEX' => 'integer' ); $oUser = new Users(); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ while ($aRow = $oDataset->getRow()) { $oCriteria2 = new Criteria('workflow'); $oCriteria2->add(AppDelegationPeer::APP_UID, $sApplicationUID); @@ -4798,15 +4698,6 @@ class Cases } } } - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('INPUT', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['INPUT']; - } - /*----------------------------------********---------------------------------*/ if ($lastVersion == $aRow['DOC_VERSION']) { //Show only last version $aInputDocuments[] = $aFields; @@ -4884,15 +4775,6 @@ class Cases $aFields['DOWNLOAD_LABEL'] = G::LoadTranslation('ID_DOWNLOAD'); $aFields['DOWNLOAD_LINK'] = "cases_ShowDocument?a=" . $aRow['APP_DOC_UID']; - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('ATTACHED', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['ATTACHED']; - } - /*----------------------------------********---------------------------------*/ if ($lastVersion == $aRow['DOC_VERSION']) { //Show only last version $aInputDocuments[] = $aFields; @@ -4960,15 +4842,6 @@ class Cases } } } - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('INPUT', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['INPUT']; - } - /*----------------------------------********---------------------------------*/ if ($lastVersion == $aRow['DOC_VERSION']) { //Show only last version $aInputDocuments[] = $aFields; @@ -5076,15 +4949,6 @@ class Cases 'APP_DOC_INDEX' => 'integer' ); $oUser = new Users(); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ while ($aRow = $oDataset->getRow()) { $oCriteria2 = new Criteria('workflow'); $oCriteria2->add(AppDelegationPeer::APP_UID, $sApplicationUID); @@ -5188,21 +5052,6 @@ class Cases $firstDocLabel = $fileDocLabel; } - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aAux['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_DOC', - $driveDownload) && $enablePMGmail - ) { - $fileDoc = $driveDownload['OUTPUT_DOC']; - } - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_PDF', - $driveDownload) && $enablePMGmail - ) { - $filePdf = $driveDownload['OUTPUT_PDF']; - } - /*----------------------------------********---------------------------------*/ - $aFields = array( 'APP_DOC_UID' => $aAux['APP_DOC_UID'], 'DOC_UID' => $aAux['DOC_UID'], @@ -7444,5 +7293,49 @@ class Cases return $processList; } + public function deleteDelegation($sAppUid) + { + $oAppDelegation = new AppDelegation(); + $oCriteria2 = new Criteria('workflow'); + $oCriteria2->add(AppDelegationPeer::APP_UID, $sAppUid); + $oDataset2 = AppDelegationPeer::doSelectRS($oCriteria2); + $oDataset2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $oDataset2->next(); + while ($aRow2 = $oDataset2->getRow()) { + $oAppDelegation->remove($sAppUid, $aRow2['DEL_INDEX']); + $oDataset2->next(); + } + } + + private function orderStartCasesByCategoryAndName ($rows) { + //now we order in category, proces_name order: + $comparatorSequence = array( + function($a, $b) { + $retval = 0; + if(array_key_exists('catname', $a) && array_key_exists('catname', $b)) { + $retval = strcmp($a['catname'], $b['catname']); + } + return $retval; + } + , function($a, $b) { + $retval = 0; + if(array_key_exists('value', $a) && array_key_exists('value', $b)) { + $retval = strcmp($a['value'], $b['value']); + } + return $retval; + } + ); + + usort($rows, function($a, $b) use ($comparatorSequence) { + foreach ($comparatorSequence as $cmpFn) { + $diff = call_user_func($cmpFn, $a, $b); + if ($diff !== 0) { + return $diff; + } + } + return 0; + }); + return $rows; + } } diff --git a/workflow/engine/classes/class.dbConnections.php b/workflow/engine/classes/class.dbConnections.php index 462932612..17641b478 100755 --- a/workflow/engine/classes/class.dbConnections.php +++ b/workflow/engine/classes/class.dbConnections.php @@ -137,7 +137,7 @@ class dbConnections * getConnectionsProUid * * Parameter $only list of items displayed, everything else is ignored. - * + * * @param string $pProUid * @param string $only * @return Array $connections @@ -153,6 +153,8 @@ class dbConnections $c->addSelectColumn( DbSourcePeer::DBS_TYPE ); $c->addSelectColumn( DbSourcePeer::DBS_SERVER ); $c->addSelectColumn( DbSourcePeer::DBS_DATABASE_NAME ); + $c->addSelectColumn( DbSourcePeer::DBS_CONNECTION_TYPE ); + $c->addSelectColumn( DbSourcePeer::DBS_TNS ); $result = DbSourcePeer::doSelectRS( $c ); $result->next(); @@ -161,8 +163,31 @@ class dbConnections $sw = count($only) > 0; while ($row = $result->getRow()) { if ((trim( $pProUid ) == trim( $row[1] )) && ( $sw ? in_array($row[2], $only) : true )) { - $connections[] = Array ('DBS_UID' => $row[0],'DBS_NAME' => '[' . $row[3] . '] ' . $row[2] . ': ' . $row[4] - ); + $dbUid = $row[0]; + + $dbDescription = ''; + + $criteria2 = new Criteria('workflow'); + + $criteria2->addSelectColumn(ContentPeer::CON_VALUE); + $criteria2->add(ContentPeer::CON_ID, $dbUid, Criteria::EQUAL); + + $rsCriteria2 = ContentPeer::doSelectRS($criteria2); + $rsCriteria2->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria2->next()) { + $row2 = $rsCriteria2->getRow(); + + if ($row2['CON_VALUE'] != '') { + $dbDescription = ' - [' . $row2['CON_VALUE'] . ']'; + } + } + + if ($row[5] == 'NORMAL') { + $connections[] = array('DBS_UID' => $row[0], 'DBS_NAME' => '[' . $row[3] . '] ' . $row[2] . ': ' . $row[4] . $dbDescription); + } else { + $connections[] = array('DBS_UID' => $row[0], 'DBS_NAME' => '[' . $row[6] . '] ' . $row[2] . ': ' . $row[6] . $dbDescription); + } } $result->next(); } diff --git a/workflow/engine/classes/class.derivation.php b/workflow/engine/classes/class.derivation.php index 460a12415..2607dea14 100755 --- a/workflow/engine/classes/class.derivation.php +++ b/workflow/engine/classes/class.derivation.php @@ -297,13 +297,11 @@ class Derivation //1. There is no rule if (empty($arrayNextTask)) { - $oProcess = new Process(); - $oProcessFieds = $oProcess->Load( $_SESSION['PROCESS'] ); - if(isset($oProcessFieds['PRO_BPMN']) && $oProcessFieds['PRO_BPMN'] == 1){ - throw new Exception(G::LoadTranslation("ID_NO_DERIVATION_BPMN_RULE")); - }else{ - throw new Exception(G::LoadTranslation("ID_NO_DERIVATION_RULE")); - } + $bpmn = new \ProcessMaker\Project\Bpmn(); + + throw new Exception(G::LoadTranslation( + 'ID_NO_DERIVATION_' . (($bpmn->exists($arrayApplicationData['PRO_UID']))? 'BPMN_RULE' : 'RULE') + )); } //Return @@ -636,15 +634,12 @@ class Derivation */ function getDenpendentUser ($USR_UID) { - //Here the uid to next user - $oC = new Criteria(); - $oC->addSelectColumn( UsersPeer::USR_REPORTS_TO ); - $oC->add( UsersPeer::USR_UID, $USR_UID ); - $oDataset = UsersPeer::doSelectRS( $oC ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - $aRow = $oDataset->getRow(); - return $aRow['USR_REPORTS_TO'] != '' ? $aRow['USR_REPORTS_TO'] : $USR_UID; + $user = new \ProcessMaker\BusinessModel\User(); + + $manager = $user->getUsersManager($USR_UID); + + //Return + return ($manager !== false)? $manager : $USR_UID; } /* setTasLastAssigned diff --git a/workflow/engine/classes/class.groups.php b/workflow/engine/classes/class.groups.php index e0c8241e4..5a13aaf07 100755 --- a/workflow/engine/classes/class.groups.php +++ b/workflow/engine/classes/class.groups.php @@ -43,15 +43,18 @@ class Groups * * @param string $sGroupUID * @return array + * @throws Exception */ - public function getUsersOfGroup($sGroupUID) + public function getUsersOfGroup($sGroupUID, $statusUser = 'ACTIVE') { try { $aUsers = array(); $oCriteria = new Criteria(); $oCriteria->addJoin(UsersPeer::USR_UID, GroupUserPeer::USR_UID, Criteria::LEFT_JOIN); $oCriteria->add(GroupUserPeer::GRP_UID, $sGroupUID); - $oCriteria->add(UsersPeer::USR_STATUS, 'ACTIVE'); + if($statusUser !== 'ALL'){ + $$oCriteria->add(UsersPeer::USR_STATUS, $statusUser); + } $oDataset = UsersPeer::doSelectRS($oCriteria); $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); diff --git a/workflow/engine/classes/class.jrml.php b/workflow/engine/classes/class.jrml.php deleted file mode 100755 index 813ec7e08..000000000 --- a/workflow/engine/classes/class.jrml.php +++ /dev/null @@ -1,228 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - * - */ - -/** - * Jrml - Jrml class - * - * @package workflow.engine.ProcessMaker - * @author Maborak - * @copyright 2008 COLOSA - */ - -class Jrml -{ - public $rows; - public $sql; - private $data; - - /** - * This function is the constructor of the class Jrml - * - * @param array $data - * @return void - */ - function __construct ($data = array()) - { - $this->data = $data; - $this->sql = $data['sql']; - $this->rows = $this->get_rows( $data['type'] ); - $this->md = $this->get_md(); - } - - /** - * This function is for get rows - * - * @param array $a - * @return array - */ - private function get_rows ($a) - { - $b = array (); - foreach ($a as $key => $value) { - $b[] = $key; - } - return $b; - } - - public function get_md () - { - } - - /** - * This function is for get the header - * - * @return string - */ - public function get_header () - { - $xml = "sql}]]>"; - foreach ($this->data['type'] as $key => $value) { - $xml .= ""; - } - $xml .= ""; - $xml .= ' - - <band height="58"> - <line> - <reportElement x="0" y="8" width="555" height="1"/> - </line> - <line> - <reportElement positionType="FixRelativeToBottom" x="0" y="51" width="555" height="1"/> - </line> - <staticText> - <reportElement x="65" y="13" width="424" height="35"/> - <textElement textAlignment="Center"> - <font size="26" isBold="true"/> - </textElement> - <text><![CDATA[' . $this->data['title'] . ']]></text> - </staticText> - </band> - - - - '; - return $xml; - } - - /** - * This function is for get a column of the header - * - * @return string - */ - public function get_column_header () - { - $xml = ""; - $w = (int) ($this->data['columnWidth'] / sizeof( $this->rows )); - $i = 0; - foreach ($this->data['type'] as $key => $value) { - $xml .= " - - - - - "; - $i = $i + $w; - } - $xml .= " "; - return $xml; - } - - /** - * This function is for get the detail - * - * @return string - */ - public function get_detail () - { - $xml = ''; - $w = (int) ($this->data['columnWidth'] / sizeof( $this->rows )); - $i = 0; - foreach ($this->data['type'] as $key => $value) { - $xml .= ""; - $i = $i + $w; - } - $xml .= ''; - return $xml; - } - - /** - * This function is for get the footer - * - * @return string - */ - public function get_footer () - { - $xml = ' - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - '; - return $xml; - } - - /** - * This function is for export - * - * @return string - */ - public function export () - { - $xml = ' - '; - $xml .= $this->get_header(); - $xml .= $this->get_column_header(); - $xml .= $this->get_detail(); - $xml .= $this->get_footer(); - $xml .= ''; - return $xml; - } -} \ No newline at end of file diff --git a/workflow/engine/classes/class.labelsGmail.php b/workflow/engine/classes/class.labelsGmail.php index 6b6680c8d..a0771a6d7 100644 --- a/workflow/engine/classes/class.labelsGmail.php +++ b/workflow/engine/classes/class.labelsGmail.php @@ -1,4 +1,6 @@ getMessage(); + throw ($e); } return $labels; } @@ -19,14 +22,15 @@ class labelsGmail /** * Modify the Labels a Message is associated with. * - * @param Google_Service_Gmail $service Authorized Gmail API instance. - * @param string $userId User's email address. The special value 'me' - * can be used to indicate the authenticated user. - * @param string $messageId ID of Message to modify. - * @param array $labelsToAdd Array of Labels to add. - * @param array $labelsToRemove Array of Labels to remove. + * @param Google_Service_Gmail $service Authorized Gmail API instance. + * @param string $userId User's email address. The special value 'me' + * can be used to indicate the authenticated user. + * @param string $messageId ID of Message to modify. + * @param array $labelsToAdd Array of Labels to add. + * @param array $labelsToRemove Array of Labels to remove. */ - function modifyMessage($service, $userId, $messageId, $labelsToAdd, $labelsToRemove) { + function modifyMessage($service, $userId, $messageId, $labelsToAdd, $labelsToRemove) + { $mods = new Google_Service_Gmail_ModifyMessageRequest(); $mods->setAddLabelIds($labelsToAdd); $mods->setRemoveLabelIds($labelsToRemove); @@ -34,6 +38,7 @@ class labelsGmail $message = $service->users_messages->modify($userId, $messageId, $mods); } catch (Exception $e) { print G::LoadTranslation("ID_PMGMAIL_GENERAL_ERROR") . $e->getMessage(); + throw ($e); } } @@ -41,12 +46,14 @@ class labelsGmail * Get list of Messages in user's mailbox. * * @param Google_Service_Gmail $service Authorized Gmail API instance. - * @param string $userId User's email address. The special value 'me' - * can be used to indicate the authenticated user. + * @param string $userId User's email address. The special value 'me' + * can be used to indicate the authenticated user. + * * @return array Array of Messages. */ - function listMessages($service, $userId, $query, $labels) { - $pageToken = NULL; + function listMessages($service, $userId, $query, $labels) + { + $pageToken = null; $messages = array(); $opt_param = array(); do { @@ -63,71 +70,19 @@ class labelsGmail } } catch (Exception $e) { print G::LoadTranslation("ID_PMGMAIL_GENERAL_ERROR") . $e->getMessage(); + throw ($e); } } while ($pageToken); return $messages; } - public function setLabelsToPauseCase ($caseId, $index) { - require_once PATH_TRUNK . 'vendor' . PATH_SEP . 'google' . PATH_SEP . 'apiclient' . PATH_SEP . 'src' . PATH_SEP . 'Google' . PATH_SEP . 'autoload.php'; - require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.pmGoogleApi.php"); - - $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); - $appData = $Pmgmail->getDraftApp($caseId, $index); - - foreach ($appData as $application){ - $appNumber = $application['APP_NUMBER']; - $index = $application['DEL_INDEX']; - $threadUsr = $application['USR_UID']; - $proName = $application['APP_PRO_TITLE']; - $threadStatus = $application['DEL_THREAD_STATUS']; - $appStatus = $application['APP_STATUS']; - } - - //Getting the privious User email - $oUsers = new \Users(); - $usrData = $oUsers->loadDetails($threadUsr); - $mail = $usrData['USR_EMAIL']; - - //The Subject to search the email - $subject = "[PM] " .$proName. " Case: ". $appNumber; - - $pmGoogle = new PMGoogleApi(); - $pmGoogle->setUser($mail); - $pmGoogle->setScope('https://www.googleapis.com/auth/gmail.modify'); - $client = $pmGoogle->serviceClient(); - $service = new Google_Service_Gmail($client); - $labelsIds = $this->getLabelsIds($service); - - if($appStatus == 'DRAFT'){ - $labelsToRemove = $labelsIds['Draft']; - $labelsToSearch = "*-draft"; - $labelsToAdd = $labelsIds['Paused']; - } - - if($appStatus == 'TO_DO'){ - $labelsToRemove = $labelsIds['Inbox']; - $labelsToSearch = "*-inbox"; - $labelsToAdd = $labelsIds['Paused']; - } - - $q = "subject:('".preg_quote($subject, '-')."') label:('".$labelsToSearch."')"; - $messageList = $this->listMessages($service, $mail, $q, $labelsToRemove); - foreach ($messageList as $message) { - $messageId = $message->getId(); - $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), array($labelsToRemove)); - } - } - - function setLabelsTounpauseCase ($caseId, $index) { - require_once PATH_TRUNK . 'vendor' . PATH_SEP . 'google' . PATH_SEP . 'apiclient' . PATH_SEP . 'src' . PATH_SEP . 'Google' . PATH_SEP . 'autoload.php'; - require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.pmGoogleApi.php"); - + public function setLabelsToPauseCase($caseId, $index) + { $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); $appData = $Pmgmail->getDraftApp($caseId, $index); - foreach ($appData as $application){ + foreach ($appData as $application) { $appNumber = $application['APP_NUMBER']; $index = $application['DEL_INDEX']; $threadUsr = $application['USR_UID']; @@ -142,41 +97,42 @@ class labelsGmail $mail = $usrData['USR_EMAIL']; //The Subject to search the email - $subject = "[PM] " .$proName. " Case: ". $appNumber; + $subject = "[PM] " . $proName . " Case: " . $appNumber; $pmGoogle = new PMGoogleApi(); $pmGoogle->setUser($mail); - $pmGoogle->setScope('https://www.googleapis.com/auth/gmail.modify'); + $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); $labelsIds = $this->getLabelsIds($service); - if($appStatus == 'DRAFT'){ - $labelsToRemove = $labelsIds['Paused']; - $labelsToSearch = "*-paused"; - $labelsToAdd = $labelsIds['Draft']; + if ($appStatus == 'DRAFT') { + $labelsToRemove = $labelsIds['Draft']; + $labelsToSearch = "*-draft"; + $labelsToAdd = $labelsIds['Paused']; } - if($appStatus == 'TO_DO'){ - $labelsToRemove = $labelsIds['Paused']; - $labelsToSearch = "*-paused"; - $labelsToAdd = $labelsIds['Inbox']; + if ($appStatus == 'TO_DO') { + $labelsToRemove = $labelsIds['Inbox']; + $labelsToSearch = "*-inbox"; + $labelsToAdd = $labelsIds['Paused']; } - $q = "subject:('".preg_quote($subject, '-')."') label:('".$labelsToSearch."')"; + $q = "subject:('" . preg_quote($subject, '-') . "') label:('" . $labelsToSearch . "')"; $messageList = $this->listMessages($service, $mail, $q, $labelsToRemove); foreach ($messageList as $message) { $messageId = $message->getId(); - $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), array($labelsToRemove)); + $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), + array($labelsToRemove)); } } - public function setLabels($caseId, $index, $actualLastIndex, $unassigned=false){ - //First getting the actual thread data + function setLabelsTounpauseCase($caseId, $index) + { $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); $appData = $Pmgmail->getDraftApp($caseId, $index); - foreach ($appData as $application){ + foreach ($appData as $application) { $appNumber = $application['APP_NUMBER']; $index = $application['DEL_INDEX']; $threadUsr = $application['USR_UID']; @@ -185,7 +141,59 @@ class labelsGmail $appStatus = $application['APP_STATUS']; } - if($threadStatus == 'CLOSED' || $unassigned == true) { + //Getting the privious User email + $oUsers = new \Users(); + $usrData = $oUsers->loadDetails($threadUsr); + $mail = $usrData['USR_EMAIL']; + + //The Subject to search the email + $subject = "[PM] " . $proName . " Case: " . $appNumber; + + $pmGoogle = new PMGoogleApi(); + $pmGoogle->setUser($mail); + $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $client = $pmGoogle->serviceClient(); + $service = new Google_Service_Gmail($client); + $labelsIds = $this->getLabelsIds($service); + + if ($appStatus == 'DRAFT') { + $labelsToRemove = $labelsIds['Paused']; + $labelsToSearch = "*-paused"; + $labelsToAdd = $labelsIds['Draft']; + } + + if ($appStatus == 'TO_DO') { + $labelsToRemove = $labelsIds['Paused']; + $labelsToSearch = "*-paused"; + $labelsToAdd = $labelsIds['Inbox']; + } + + $q = "subject:('" . preg_quote($subject, '-') . "') label:('" . $labelsToSearch . "')"; + $messageList = $this->listMessages($service, $mail, $q, $labelsToRemove); + foreach ($messageList as $message) { + $messageId = $message->getId(); + $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), + array($labelsToRemove)); + } + } + + public function setLabels($caseId, $index, $actualLastIndex, $unassigned = false) + { + //First getting the actual thread data + $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); + $appData = $Pmgmail->getDraftApp($caseId, $index); + + foreach ($appData as $application) { + $appNumber = $application['APP_NUMBER']; + $index = $application['DEL_INDEX']; + $threadUsr = $application['USR_UID']; + $proName = $application['APP_PRO_TITLE']; + $threadStatus = $application['DEL_THREAD_STATUS']; + $appStatus = $application['APP_STATUS']; + $tasUid = $application['TAS_UID']; + } + + if ($threadStatus == 'CLOSED' || $unassigned == true) { //Getting the privious User email $oUsers = new \Users(); @@ -193,125 +201,215 @@ class labelsGmail $mail = $usrData['USR_EMAIL']; //The Subject to search the email - $subject = "[PM] " .$proName. " Case: ". $appNumber; + $subject = "[PM] " . $proName . " Case: " . $appNumber; - require_once PATH_TRUNK . 'vendor' . PATH_SEP . 'google' . PATH_SEP . 'apiclient' . PATH_SEP . 'src' . PATH_SEP . 'Google' . PATH_SEP . 'autoload.php'; - require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.pmGoogleApi.php"); $pmGoogle = new PMGoogleApi(); $pmGoogle->setUser($mail); - $pmGoogle->setScope('https://www.googleapis.com/auth/gmail.modify'); + $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); $client = $pmGoogle->serviceClient(); $service = new Google_Service_Gmail($client); $labelsIds = $this->getLabelsIds($service); - if($actualLastIndex == 0){ + if ($actualLastIndex == 0) { $labelsToRemove = $labelsIds['Draft']; $labelsToSearch = "*-draft"; $labelsToAdd = $labelsIds['Participated']; - } else if ( ($actualLastIndex == -1) && ($unassigned == true) ){ //Unassigned - $labelsToRemove = $labelsIds['Unassigned']; - $labelsToSearch = "*-unassigned"; - $labelsToAdd = $labelsIds['Inbox']; - } else if($actualLastIndex >= 1) { - $labelsToRemove = $labelsIds['Inbox']; - $labelsToSearch = "*-inbox"; - $labelsToAdd = $labelsIds['Participated']; + } else { + if (($actualLastIndex == -1) && ($unassigned == true)) { //Unassigned + $labelsToRemove = $labelsIds['Unassigned']; + $labelsToSearch = "*-unassigned"; + $labelsToAdd = $labelsIds['Inbox']; + } else { + if ($actualLastIndex >= 1) { + $labelsToRemove = $labelsIds['Inbox']; + $labelsToSearch = "*-inbox"; + $labelsToAdd = $labelsIds['Participated']; + } + } } //Searching the email in the user's mail - $q = "subject:('".preg_quote($subject, '-')."') label:('".$labelsToSearch."')"; - + $q = "subject:('" . preg_quote($subject, '-') . "') label:('" . $labelsToSearch . "')"; $messageList = $this->listMessages($service, $mail, $q, $labelsToRemove); foreach ($messageList as $message) { $messageId = $message->getId(); - $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), array($labelsToRemove)); + $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), + array($labelsToRemove)); } + + //in is unassigned we must remove the label to the orher users + if ($labelsToRemove === $labelsIds['Unassigned']) { + require_once(PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "TaskUser.php"); + $oTaskUsers = new \TaskUser(); + $taskUsers = $oTaskUsers->getAllUsersTask($tasUid); + foreach ($taskUsers as $user) { + $usrData = $oUsers->loadDetails($user['USR_UID']); + $nextMail = $usrData['USR_EMAIL']; + //this operation is just for the users that didn't make the case claim + if ($nextMail !== $mail) { + $this->changeLabelsOfUnassigned($appData[0], $nextMail); + } + } + } } } - + + function changeLabelsOfUnassigned($application, $mail) + { + $appNumber = $application['APP_NUMBER']; + $index = $application['DEL_INDEX']; + $threadUsr = $application['USR_UID']; + $proName = $application['APP_PRO_TITLE']; + $threadStatus = $application['DEL_THREAD_STATUS']; + $appStatus = $application['APP_STATUS']; + $tasUid = $application['TAS_UID']; + + //The Subject to search the email + $subject = "[PM] " . $proName . " Case: " . $appNumber; + $pmGoogle = new PMGoogleApi(); + $pmGoogle->setUser($mail); + $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $client = $pmGoogle->serviceClient(); + $service = new Google_Service_Gmail($client); + $labelsIds = $this->getLabelsIds($service); + $labelsToRemove = $labelsIds['Unassigned']; + $labelsToSearch = "*-unassigned"; + $labelsToAdd = $labelsIds['Participated']; + + //Searching the email in the user's mail + $q = "subject:('" . preg_quote($subject, '-') . "') label:('" . $labelsToSearch . "')"; + $messageList = $this->listMessages($service, $mail, $q, $labelsToRemove); + + foreach ($messageList as $message) { + $messageId = $message->getId(); + $modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), + array($labelsToRemove)); + + } + } + + /** * Delete Label with given ID. * * @param Google_Service_Gmail $service Authorized Gmail API instance. - * @param string $userId User's email address. The special value 'me' - * can be used to indicate the authenticated user. - * @param string $labelId Id of Label to be updated. + * @param string $userId User's email address. The special value 'me' + * can be used to indicate the authenticated user. + * @param string $labelId Id of Label to be updated. */ public function deleteLabel($service, $user, $labelId) { - try { - $service->users_labels->delete($user, $labelId); - } catch (Exception $e) { - error_log(G::LoadTranslation("ID_PMGMAIL_GENERAL_ERROR") . $e->getMessage()); - } + try { + $service->users_labels->delete($user, $labelId); + } catch (Exception $e) { + error_log(G::LoadTranslation("ID_PMGMAIL_GENERAL_ERROR") . $e->getMessage()); + } } - + /** * Delete PMGmail integration labels getting the list of labels in an email account. + * * @param string $mail User mail adress. * */ public function deletePMGmailLabels($mail) { - require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.pmGoogleApi.php"); - $pmGoogle = new PMGoogleApi(); - - $pmGoogle->setUser($mail); - - $pmGoogle->setScope('https://www.googleapis.com/auth/gmail.modify'); - $client = $pmGoogle->serviceClient(); - - $service = new Google_Service_Gmail($client); - $count = 0; - $listlabels = $this->listLabels($service); - foreach ($listlabels as $label) { - if ($label->getName() == '* Inbox' || - $label->getName() == '* Participated' || - $label->getName() == '* Unassigned' || - $label->getName() == '* Draft' || - $label->getName() == '* Inbox' || - $label->getName() == '*-- ProcessMaker --*' || - $label->getName() == '* Paused' - ) { - $oresp = $this->deleteLabel($service, 'me', $label->getId()); - $count++; - } - } - return $count . ' labels successfully deleted.'; - } + $pmGoogle = new PMGoogleApi(); + $pmGoogle->setUser($mail); - private function getLabelsIds($service) { - $result = array(); + $pmGoogle->setScope(PMGoogleApi::GMAIL_MODIFY); + $client = $pmGoogle->serviceClient(); + + $service = new Google_Service_Gmail($client); + $count = 0; $listlabels = $this->listLabels($service); foreach ($listlabels as $label) { - $labId = $label->getId(); - $labName = $label->getName(); - switch($labName){ - case "* Inbox": - $result['Inbox'] = $labId; - break; - case "* Participated": - $result['Participated'] = $labId; - break; - case "* Unassigned": - $result['Unassigned'] = $labId; - break; - case "* Draft": - $result['Draft'] = $labId; - break; - case "* Paused": - $result['Paused'] = $labId; - break; + if ($label->getName() == '* Inbox' || + $label->getName() == '* Participated' || + $label->getName() == '* Unassigned' || + $label->getName() == '* Draft' || + $label->getName() == '* Inbox' || + $label->getName() == '* --- ProcessMaker ---' || + $label->getName() == '* Paused' + ) { + $oresp = $this->deleteLabel($service, 'me', $label->getId()); + $count++; } } + return $count . ' labels successfully deleted.'; + } + + public function addRelabelingToQueue($caseId, $index, $actualLastIndex, $unassigned = false) + { + $labelingQueue = new GmailRelabeling(); + $labelingQueue->setCreateDate(date('Y-m-d H:i:s')); + $labelingQueue->setLabelingUid(G::generateUniqueID()); + $labelingQueue->setAppUid($caseId); + $labelingQueue->setDelIndex($index); + $labelingQueue->setCurrentLastIndex($actualLastIndex); + $labelingQueue->setUnassigned(($unassigned === true) ? 1 : 0); + $labelingQueue->setStatus('pending'); + $labelingQueue->save(); + } + + public function processPendingRelabelingInQueue() + { + $c = new \Criteria('workflow'); + $c->add(\GmailRelabelingPeer::STATUS, 'pending'); + $c->addAscendingOrderByColumn('CREATE_DATE'); + $list = \GmailRelabelingPeer::doSelect($c); + foreach ($list as $task) { + try { + $oResponse = $this->setLabels($task->getAppUid(), + $task->getDelIndex(), + $task->getCurrentLastIndex(), + ($task->getUnassigned() === 1) ? true : false + ); + $task->setStatus('completed'); + } catch (exception $e) { + $task->setMsgError($e->getMessage()); + $task->setStatus('pending'); + } + $task->save(); + } + } + + private function getLabelsIds($service) + { + $result = array(); + try { + $listlabels = $this->listLabels($service); + foreach ($listlabels as $label) { + $labId = $label->getId(); + $labName = $label->getName(); + switch ($labName) { + case "* Inbox": + $result['Inbox'] = $labId; + break; + case "* Participated": + $result['Participated'] = $labId; + break; + case "* Unassigned": + $result['Unassigned'] = $labId; + break; + case "* Draft": + $result['Draft'] = $labId; + break; + case "* Paused": + $result['Paused'] = $labId; + break; + } + } + } catch (Exception $e) { + throw $e; + } return $result; } } - diff --git a/workflow/engine/classes/class.pluginRegistry.php b/workflow/engine/classes/class.pluginRegistry.php index efb6baba8..fcb4aafd5 100755 --- a/workflow/engine/classes/class.pluginRegistry.php +++ b/workflow/engine/classes/class.pluginRegistry.php @@ -1010,6 +1010,7 @@ class PMPluginRegistry */ public function executeTriggers ($triggerId, $oData) { + G::LoadThirdParty( "pear", "PEAR" ); foreach ($this->_aTriggers as $row => $detail) { if ($triggerId == $detail->sTriggerId) { //review all folders registered for this namespace @@ -1116,8 +1117,9 @@ class PMPluginRegistry */ public function &getPlugin ($sNamespace) { + $oPlugin = null; if (array_key_exists( $sNamespace, $this->_aPlugins )) { - return $this->_aPlugins[$sNamespace]; + $oPlugin = $this->_aPlugins[$sNamespace]; } /* $aDetails = KTUtil::arrayGet($this->_aPluginDetails, $sNamespace); @@ -1133,6 +1135,7 @@ class PMPluginRegistry $this->_aPlugins[$sNamespace] =& $oPlugin; return $oPlugin; */ + return $oPlugin; } /** diff --git a/workflow/engine/classes/class.pmDrive.php b/workflow/engine/classes/class.pmDrive.php index 398764aaa..16915a642 100755 --- a/workflow/engine/classes/class.pmDrive.php +++ b/workflow/engine/classes/class.pmDrive.php @@ -94,12 +94,13 @@ class PMDrive extends PMGoogleApi */ public function listFolder($fileId) { - $this->setScope('https://www.googleapis.com/auth/drive'); - $this->setScope('https://www.googleapis.com/auth/drive.file'); - $this->setScope('https://www.googleapis.com/auth/drive.readonly'); - $this->setScope('https://www.googleapis.com/auth/drive.metadata.readonly'); - $this->setScope('https://www.googleapis.com/auth/drive.appdata'); - $this->setScope('https://www.googleapis.com/auth/drive.metadata'); + $this->setScope(static::DRIVE); + $this->setScope(static::DRIVE_FILE); + $this->setScope(static::DRIVE_READONLY); + $this->setScope(static::DRIVE_METADATA); + $this->setScope(static::DRIVE_METADATA_READONLY); + $this->setScope(static::DRIVE_APPDATA); + $service = $this->serviceDrive(); try { @@ -126,7 +127,7 @@ class PMDrive extends PMGoogleApi */ public function createFolder($name, $parentId = null) { - $this->setScope('https://www.googleapis.com/auth/drive.file'); + $this->setScope(static::DRIVE_FILE); $service = $this->serviceDrive(); @@ -159,12 +160,12 @@ class PMDrive extends PMGoogleApi */ public function uploadFile($mime, $src, $name, $parentId = null) { - $this->setScope('https://www.googleapis.com/auth/drive.file'); + $this->setScope(static::DRIVE_FILE); $service = $this->serviceDrive(); $file = new Google_Service_Drive_DriveFile(); - $file->setMimeType("*/*"); + $file->setMimeType($mime); $file->setTitle($name); // Set the parent folder. @@ -200,25 +201,24 @@ class PMDrive extends PMGoogleApi */ public function downloadFile($fileId) { - $this->setScope('https://www.googleapis.com/auth/drive'); - $this->setScope('https://www.googleapis.com/auth/drive.appdata'); - $this->setScope('https://www.googleapis.com/auth/drive.apps.readonly'); - $this->setScope('https://www.googleapis.com/auth/drive.file'); - $this->setScope('https://www.googleapis.com/auth/drive.metadata'); - $this->setScope('https://www.googleapis.com/auth/drive.metadata.readonly'); - $this->setScope('https://www.googleapis.com/auth/drive.readonly'); + $this->setScope(static::DRIVE); + $this->setScope(static::DRIVE_APPDATA); + $this->setScope(static::DRIVE_APPS_READONLY); + $this->setScope(static::DRIVE_FILE); + $this->setScope(static::DRIVE_METADATA); + $this->setScope(static::DRIVE_METADATA_READONLY); + $this->setScope(static::DRIVE_READONLY); $service = $this->serviceDrive(); + $response = null; try { $file = $service->files->get($fileId); - $response = null; - $downloadUrl = $file->getDownloadUrl(); if ($downloadUrl) { $request = new Google_Http_Request($downloadUrl, 'GET', null, null); $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request); if ($httpRequest->getResponseHttpCode() == 200) { - $response = $httpRequest->getResponseBody(); + $response = $httpRequest->getResponseBody(); } else { error_log(G::LoadTranslation("ID_MSG_AJAX_FAILURE")); } @@ -242,10 +242,11 @@ class PMDrive extends PMGoogleApi */ public function setPermission($fileId, $value, $type = 'user', $role = 'reader', $sendNotification = false) { - $this->setScope('https://www.googleapis.com/auth/drive'); - $this->setScope('https://www.googleapis.com/auth/drive.file'); + $this->setScope(static::DRIVE); + $this->setScope(static::DRIVE_FILE); $service = $this->serviceDrive(); + $permission = null; $newPermission = new Google_Service_Drive_Permission(); $newPermission->setValue($value); diff --git a/workflow/engine/classes/class.pmDynaform.php b/workflow/engine/classes/class.pmDynaform.php index bba15e712..d7ace3297 100644 --- a/workflow/engine/classes/class.pmDynaform.php +++ b/workflow/engine/classes/class.pmDynaform.php @@ -17,6 +17,7 @@ class pmDynaform public $credentials = null; public $lang = SYS_LANG; public $langs = null; + public $displayMode = null; public $onPropertyRead = "onPropertyReadFormInstance"; public function __construct($fields = array()) @@ -35,6 +36,17 @@ class pmDynaform $this->record["DYN_CONTENT"] = $decode; } } + + //todo: compatibility checkbox + $json = G::json_decode($this->record["DYN_CONTENT"]); + $fields = $this->jsonsf2($json, "checkbox", "type"); + foreach ($fields as $field) { + if (isset($field->dataType) && $field->dataType === "string") { + $field->type = "checkgroup"; + } + $this->jsonReplace($json, $field->id, "id", $field); + } + $this->record["DYN_CONTENT"] = G::json_encode($json); } public function getDynaformTitle($idDynaform) @@ -139,7 +151,7 @@ class pmDynaform if (!$sw1 && !$sw2) { //read event $fn = $this->onPropertyRead; - if (function_exists($fn)) { + if (is_callable($fn) || function_exists($fn)) { $fn($json, $key, $value); } //set properties from trigger @@ -175,22 +187,43 @@ class pmDynaform if (!isset($json->sql)) $json->sql = ""; $json->optionsSql = array(); - if ($json->dbConnection !== "" && $json->dbConnection !== "none" && $json->sql !== "") { - $cnn = Propel::getConnection($json->dbConnection); - $stmt = $cnn->createStatement(); - try { - $sql = G::replaceDataField($json->sql, $this->getValuesDependentFields($json)); - $rs = $stmt->executeQuery($sql, \ResultSet::FETCHMODE_NUM); - while ($rs->next()) { - $row = $rs->getRow(); - $option = new stdClass(); - $option->value = $row[0]; - $option->label = isset($row[1]) ? $row[1] : $row[0]; - array_push($json->optionsSql, $option); + + switch ((isset($json->datasource)) ? $json->datasource : 'database') { + case 'dataVariable': + $dataVariable = (preg_match('/^\s*@.(.+)\s*$/', $json->dataVariable, $arrayMatch)) ? + $arrayMatch[1] : $json->dataVariable; + if (isset($this->fields['APP_DATA'][$dataVariable]) && + is_array($this->fields['APP_DATA'][$dataVariable]) && + !empty($this->fields['APP_DATA'][$dataVariable]) + ) { + foreach ($this->fields['APP_DATA'][$dataVariable] as $row) { + $option = new stdClass(); + $option->value = $row[0]; + $option->label = isset($row[1]) ? $row[1] : ""; + $json->optionsSql[] = $option; + } } - } catch (Exception $e) { - - } + break; + default: + //database + if ($json->dbConnection !== '' && $json->dbConnection !== 'none' && $json->sql !== '') { + try { + $cnn = Propel::getConnection($json->dbConnection); + $stmt = $cnn->createStatement(); + $sql = G::replaceDataField($json->sql, $this->getValuesDependentFields($json)); + $rs = $stmt->executeQuery($sql, \ResultSet::FETCHMODE_NUM); + while ($rs->next()) { + $row = $rs->getRow(); + $option = new stdClass(); + $option->value = $row[0]; + $option->label = isset($row[1]) ? $row[1] : ""; + $json->optionsSql[] = $option; + } + } catch (Exception $e) { + + } + } + break; } } //data @@ -210,7 +243,6 @@ class pmDynaform $json->data->value = $this->fields["APP_DATA"][$json->name]; $json->data->label = $this->fields["APP_DATA"][$json->name]; } - $json->optionsSql = array(); } if ($key === "type" && ($value === "dropdown")) { $json->data = new stdClass(); @@ -263,7 +295,6 @@ class pmDynaform if (isset($this->fields["APP_DATA"][$json->name . "_label"])) { $json->data->label = $this->fields["APP_DATA"][$json->name . "_label"]; } - $json->optionsSql = array(); } if ($key === "type" && ($value === "radio")) { $json->data = new stdClass(); @@ -373,24 +404,10 @@ class pmDynaform } } if ($key === "type" && ($value === "file") && isset($this->fields["APP_DATA"]["APPLICATION"])) { - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass("pmDrive"); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ $oCriteria = new Criteria("workflow"); $oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_UID); $oCriteria->addSelectColumn(AppDocumentPeer::DOC_VERSION); $oCriteria->addSelectColumn(ContentPeer::CON_VALUE); - /*----------------------------------********---------------------------------*/ - if ($enablePMGmail) { - $oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD); - } - /*----------------------------------********---------------------------------*/ $oCriteria->addJoin(AppDocumentPeer::APP_DOC_UID, ContentPeer::CON_ID, Criteria::LEFT_JOIN); $oCriteria->add(AppDocumentPeer::APP_UID, $this->fields["APP_DATA"]["APPLICATION"]); $oCriteria->add(AppDocumentPeer::APP_DOC_FIELDNAME, $json->name); @@ -402,14 +419,6 @@ class pmDynaform while ($rs->next()) { $row = $rs->getRow(); $linkDownload = "../cases/cases_ShowDocument?a=" . $row["APP_DOC_UID"] . "&v=" . $row["DOC_VERSION"]; - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($row['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('ATTACHED', $driveDownload) && $enablePMGmail - ) { - $linkDownload = $driveDownload['ATTACHED']; - } - /*----------------------------------********---------------------------------*/ array_push($links, $linkDownload); array_push($labelsFromDb, $row["CON_VALUE"]); } @@ -436,15 +445,15 @@ class pmDynaform } } //synchronize var_label - if ($key === "type" && ($value === "dropdown" || $value === "suggest")) { + if ($key === "type" && ($value === "dropdown" || $value === "suggest" || $value === "radio")) { if (isset($this->fields["APP_DATA"]["__VAR_CHANGED__"]) && in_array($json->name, explode(",", $this->fields["APP_DATA"]["__VAR_CHANGED__"]))) { foreach ($json->optionsSql as $io) { - if ($json->data->value === $io->value) { + if ($this->toStringNotNullValues($json->data->value) === $io->value) { $json->data->label = $io->label; } } foreach ($json->options as $io) { - if ($json->data->value === $io->value) { + if ($this->toStringNotNullValues($json->data->value) === $io->value) { $json->data->label = $io->label; } } @@ -458,17 +467,20 @@ class pmDynaform $dv = array(); if (isset($this->fields["APP_DATA"][$json->name])) $dv = $this->fields["APP_DATA"][$json->name]; + if (!is_array($dv)) { + $dv = explode(",", $dv); + } foreach ($dv as $idv) { foreach ($json->optionsSql as $os) { if ($os->value === $idv) { - array_push($dataValue, $os->value); - array_push($dataLabel, $os->label); + $dataValue[] = $os->value; + $dataLabel[] = $os->label; } } foreach ($json->options as $os) { if ($os->value === $idv) { - array_push($dataValue, $os->value); - array_push($dataLabel, $os->label); + $dataValue[] = $os->value; + $dataLabel[] = $os->label; } } } @@ -483,6 +495,10 @@ class pmDynaform $_SESSION["TRIGGER_DEBUG"]["DATA"][] = Array("key" => $json->name . "_label", "value" => $json->data->label); } } + //clear optionsSql + if ($key === "type" && ($value === "text" || $value === "textarea" || $value === "hidden" || $value === "suggest")) { + $json->optionsSql = array(); + } //grid if ($key === "type" && ($value === "grid")) { if (isset($this->fields["APP_DATA"][$json->name])) { @@ -534,12 +550,16 @@ class pmDynaform if (isset($this->fields["STEP_MODE"]) && $this->fields["STEP_MODE"] === "VIEW" && isset($json->mode)) { $json->mode = "view"; } + if ($this->displayMode !== null && isset($json->mode)) { + $json->mode = $this->displayMode; + } if ($key === "type" && ($value === "form") && $this->records != null) { foreach ($this->records as $ri) { if ($json->id === $ri["DYN_UID"] && !isset($json->jsonUpdate)) { $jsonUpdate = G::json_decode($ri["DYN_CONTENT"]); $jsonUpdate = $jsonUpdate->items[0]; $jsonUpdate->colSpan = $json->colSpan; + $jsonUpdate->mode = $json->mode; $jsonUpdate->jsonUpdate = true; $json = $jsonUpdate; $this->jsonr($json); @@ -672,6 +692,7 @@ class pmDynaform public function printView() { ob_clean(); + $this->displayMode = "disabled"; $json = G::json_decode($this->record["DYN_CONTENT"]); $this->jsonr($json); $javascrip = "" . @@ -691,7 +712,6 @@ class pmDynaform "var sysLang = '" . SYS_LANG . "';\n" . "$(window).load(function () {\n" . " var data = jsondata;\n" . - " data.items[0].mode = 'disabled';\n" . " window.project = new PMDynaform.core.Project({\n" . " data: data,\n" . " keys: {\n" . @@ -702,6 +722,10 @@ class pmDynaform " token: credentials,\n" . " submitRest: false\n" . " });\n" . + " $(document).find('form').find('button').on('click', function (e) {\n" . + " e.preventDefault();\n" . + " return false;\n" . + " });\n" . " $(document).find('form').submit(function (e) {\n" . " e.preventDefault();\n" . " return false;\n" . @@ -963,6 +987,7 @@ class pmDynaform $jsonUpdate = G::json_decode($ri["DYN_CONTENT"]); $jsonUpdate = $jsonUpdate->items[0]; $jsonUpdate->colSpan = $jsonSearch->colSpan; + $jsonUpdate->mode = $jsonSearch->mode; $this->jsonReplace($json, $ri["DYN_UID"], "id", $jsonUpdate); } $this->record["DYN_CONTENT"] = G::json_encode($json); @@ -1184,6 +1209,35 @@ class pmDynaform return null; } + /** + * You obtain an array of elements according to search criteria. + * + * @param object $json + * @param string $id + * @param string $for + * @return array + */ + private function jsonsf2(&$json, $id, $for = "id") + { + $result = array(); + foreach ($json as $key => $value) { + $sw1 = is_array($value); + $sw2 = is_object($value); + if ($sw1 || $sw2) { + $fields = $this->jsonsf2($value, $id, $for); + foreach ($fields as $field) { + $result[] = $field; + } + } + if (!$sw1 && !$sw2) { + if ($key === $for && $id === $value) { + $result[] = $json; + } + } + } + return $result; + } + public function downloadLanguage($dyn_uid, $lang) { if ($lang === "en") { @@ -1373,6 +1427,80 @@ class pmDynaform $con->commit(); } + /** + * Remove the posted values that are not in the definition of Dynaform. + * @param array $post + * @return array + */ + public function validatePost($post = array()) + { + $aux = $post; + $json = G::json_decode($this->record["DYN_CONTENT"]); + $modeForm = $json->items[0]->mode; + foreach ($aux as $key => $value) { + if (substr($key, -6, 6) === "_label") { + continue; + } + $modeField = null; + $protectedValue = null; + $field = $this->jsonsf($json, $key, "variable"); + if ($field !== null) { + if (isset($field->mode)) { + $modeField = $field->mode; + } + if ($modeField === "parent") { + $modeField = $modeForm; + } + if (isset($field->protectedValue)) { + $protectedValue = $field->protectedValue; + } + } + //insert for strict validation: || $modeField === "view" || $this->fields["STEP_MODE"] === "VIEW" + if ($field === null || $protectedValue === true) { + if (isset($post[$key])) { + unset($post[$key]); + } + if (isset($post[$key . "_label"])) { + unset($post[$key . "_label"]); + } + } + //columns + if (is_array($value)) { + foreach ($value as $keyRow => $valueRow) { + foreach ($valueRow as $keyCell => $valueCell) { + if (substr($keyCell, -6, 6) === "_label") { + continue; + } + $modeField = null; + $protectedValue = null; + $field = $this->jsonsf($json, $keyCell, "id"); + if ($field !== null) { + if (isset($field->mode)) { + $modeField = $field->mode; + } + if ($modeField === "parent") { + $modeField = $modeForm; + } + if (isset($field->protectedValue)) { + $protectedValue = $field->protectedValue; + } + } + //insert for strict validation: || $modeField === "view" || $this->fields["STEP_MODE"] === "VIEW" + if ($field === null || $protectedValue === true) { + if (isset($post[$key][$keyRow][$keyCell])) { + unset($post[$key][$keyRow][$keyCell]); + } + if (isset($post[$key][$keyRow][$keyCell . "_label"])) { + unset($post[$key][$keyRow][$keyCell . "_label"]); + } + } + } + } + } + } + return $post; + } + private function clientToken() { $client = $this->getClientCredentials(); @@ -1440,4 +1568,18 @@ class pmDynaform return array('dsn' => $dsn, 'username' => DB_USER, 'password' => DB_PASS); } + /** + * Returns the value converted to string if it is not null. + * + * @param string $string + * @return string + */ + private function toStringNotNullValues($value) + { + if (is_null($value)) { + return ""; + } + return (string) $value; + } + } diff --git a/workflow/engine/classes/class.pmFunctions.php b/workflow/engine/classes/class.pmFunctions.php index d7cd2d5a2..2811f826b 100755 --- a/workflow/engine/classes/class.pmFunctions.php +++ b/workflow/engine/classes/class.pmFunctions.php @@ -28,7 +28,7 @@ // // License: LGPL, see LICENSE //////////////////////////////////////////////////// - +use ProcessMaker\Util\ElementTranslation; if (! class_exists( 'PMScript' )) { G::LoadClass( 'pmScript' ); @@ -242,8 +242,51 @@ function executeQuery ($SqlStatement, $DBConnectionUID = 'workflow', $aParameter { $con = Propel::getConnection( $DBConnectionUID ); $con->begin(); - + G::loadClass('system'); + $blackList = System::getQueryBlackList(); + $aListQueries = explode('|', $blackList['queries']); + $aListAllTables = explode('|', $blackList['tables'].$blackList['pmtables']); + $parseSqlStm = new PHPSQLParser($SqlStatement); try { + //Parsing queries and check the blacklist + foreach ($parseSqlStm as $key => $value) { + if($key === 'parsed'){ + $aParseSqlStm = $value; + continue; + } + } + $nameOfTable = ''; + $arrayOfTables = array(); + foreach ($aParseSqlStm as $key => $value) { + if(in_array($key, $aListQueries)){ + if(isset($value['table'])){ + $nameOfTable = $value['table']; + } else { + foreach ($value as $valueTab) { + if(is_array($valueTab)){ + $arrayOfTables = $valueTab; + } else { + $nameOfTable = $valueTab; + } + } + } + if(isset($nameOfTable)){ + if(in_array($nameOfTable,$aListAllTables)){ + G::SendTemporalMessage( 'ID_NOT_EXECUTE_QUERY', 'error', 'labels' ); + throw new SQLException(G::loadTranslation('ID_NOT_EXECUTE_QUERY')); + } + } + if (!empty($arrayOfTables)) { + foreach ($arrayOfTables as $row) { + if(in_array($row, $aListAllTables)){ + G::SendTemporalMessage( 'ID_NOT_EXECUTE_QUERY', 'error', 'labels' ); + throw new SQLException(G::loadTranslation('ID_NOT_EXECUTE_QUERY')); + } + } + } + } + } + $statement = trim( $SqlStatement ); $statement = str_replace( '(', '', $statement ); @@ -264,8 +307,11 @@ function executeQuery ($SqlStatement, $DBConnectionUID = 'workflow', $aParameter $rs = $con->executeUpdate( $SqlStatement ); $result = $con->getUpdateCount(); $con->commit(); - //$result = $lastId->getId(); - // $result = 1; + break; + case preg_match( "/^REPLACE\s/i", $statement ): + $rs = $con->executeUpdate( $SqlStatement ); + $result = $con->getUpdateCount(); + $con->commit(); break; case preg_match( "/^UPDATE\s/i", $statement ): $rs = $con->executeUpdate( $SqlStatement ); @@ -2907,61 +2953,368 @@ function PMFSaveCurrentData () return $result; } +/** + * @method + * Return an array of associative arrays which contain the unique task ID and title. + * @name PMFTasksListByProcessId + * @label PMF Tasks List By Process Id + * @param string | $processId | ID Process | To get the current process id, use the system variable @@PROCESS + * @param string | $lang | Language | Is the language of the text, that must be the same to the column: "CON_LANG" of the CONTENT table + * @return array | $result | Array result | Array of associative arrays which contain the unique task ID and title + */ +function PMFTasksListByProcessId($processId, $lang = 'en') +{ + $result = array(); + $criteria = new Criteria("workflow"); + $criteria->addSelectColumn(TaskPeer::TAS_UID); + $criteria->addSelectColumn(ContentPeer::CON_VALUE); + $criteria->addSelectColumn(ContentPeer::CON_LANG); + $criteria->addJoin(TaskPeer::TAS_UID, ContentPeer::CON_ID, Criteria::INNER_JOIN); + $criteria->add(ContentPeer::CON_CATEGORY, 'TAS_TITLE', Criteria::EQUAL); + $criteria->add(ContentPeer::CON_LANG, $lang, Criteria::EQUAL); + $criteria->add(TaskPeer::PRO_UID, $processId, Criteria::EQUAL); + $ds = TaskPeer::doSelectRS($criteria); + $ds->setFetchmode(ResultSet::FETCHMODE_ASSOC); + while ($ds->next()) { + $result[] = $ds->getRow(); + } + return $result; +} + +/** + * + * @method + * + * Get the Unique id of Process by name + * + * @name PMFGetProcessUidByName + * @label PMF Get the Unique id of Process by name + * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFGetProcessUidByName.28.29 + * + * @param string | $processName = '' | Name of Process | Name of Process + * @return string(32) | $processUid | Unique id of Process | Returns the Unique id of Process, FALSE otherwise + * + */ +function PMFGetProcessUidByName($processName = '') +{ + try { + $processUid = ''; + + if ($processName == '') { + //Return + return (isset($_SESSION['PROCESS']))? $_SESSION['PROCESS'] : false; + } + + $criteria = new Criteria('workflow'); + + $criteria->addSelectColumn(ProcessPeer::PRO_UID); + + $criteria->addJoin(ContentPeer::CON_ID, ProcessPeer::PRO_UID, Criteria::LEFT_JOIN); + $criteria->add(ContentPeer::CON_VALUE, $processName, Criteria::EQUAL); + $criteria->add(ContentPeer::CON_CATEGORY, 'PRO_TITLE', Criteria::EQUAL); + + $rsCriteria = ContentPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + $processUid = $row['PRO_UID']; + } else { + //Return + return false; + } + + //Return + return $processUid; + } catch (Exception $e) { + throw $e; + } +} /** * @method - * This function determines if the domain of the passed email addres is hosted in - * a gmail server. - * This function test just the domain, so there isn't any validation related to the - * email address existence or validity. - * @param string | $email | emailAddress that will be examined to determine if it is hosted in Gmail - * @return boolean | $result | true if the emailAddress domain is hosted in gmail, false otherwise - * */ -function isEmailAddressHostedInGmail($email) { - $g = new G(); - if ($g->emailAddress($email) === false) { - throw new Exception ('the passed email address is not valid.'); - } - - $result = FALSE; - //the accepted domains for a gemail server are: - $gmailDomainsRegExp = "/gmail\.com|googlemail\.com/"; - - if (preg_match($gmailDomainsRegExp, $email) == 1) { - $result = TRUE; - } else { - $domainName = preg_split('/@/', $email)[1]; - - foreach(getNamedServerMXRecord($domainName) as $emailServer) { - if (preg_match($gmailDomainsRegExp, $emailServer) == 1) { - $result = TRUE; - } - } - } - return $result; + * The requested text in the specified language | If not found returns false + * @name PMFGeti18nText + * @label PMF Get i18n Text + * @param string | $id | ID Text | Is the identifier of text, that must be the same to the column: "CON_ID" of the CONTENT table + * @param string | $category | Category | Is the category of the text, that must be the same to the column: "CON_CATEGORY" of the CONTENT table + * @param string | $lang | Language | Is the language of the text, that must be the same to the column: "CON_LANG" of the CONTENT table + * @return string | $text | Translated text | the translated text of a string in Content + */ +function PMFGeti18nText($id, $category, $lang = "en") +{ + $text = false; + $criteria = new Criteria("workflow"); + $criteria->addSelectColumn(ContentPeer::CON_VALUE); + $criteria->add(ContentPeer::CON_ID, $id, Criteria::EQUAL); + $criteria->add(ContentPeer::CON_CATEGORY, $category, Criteria::EQUAL); + $criteria->add(ContentPeer::CON_LANG, $lang, Criteria::EQUAL); + $ds = ContentPeer::doSelectRS($criteria); + $ds->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $ds->next(); + $row = $ds->getRow(); + if (isset($row["CON_VALUE"])) { + $text = $row["CON_VALUE"]; + } + return $text; } - /** * @method - * Returns an array with the Mail Exchanger info of a Named Domain - * a gmail server. - * This function test just the domain, so there isn't any validation related to the - * email address existence or validity. - * @param string | $domainName | Domain Name e.g. processmaker.com - * @return array | $result | array - * */ -function getNamedServerMXRecord($domainName) { + * Function to return an array of objects containing the properties of the fields + * in a specified DynaForm. + * It also inserts the "value" and "value_label" as properties in the fields' objects, + * if the case is specified. + * @name PMFDynaFormFields + * @label PMF DynaForm Fields + * @param string | $dynUid | Dynaform ID | Id of the dynaform + * @param string | $appUid | Case ID | Id of the case + * @param int | $delIndex | Delegation index | Delegation index for case + * @return array | $fields | List of fields | Return a list of fields + */ +function PMFDynaFormFields($dynUid, $appUid = false, $delIndex = 0) +{ + G::LoadClass("pmDynaform"); + $fields = array(); + $data = array(); - //in some windows distributions getmxxr does not exist, so if this happens, a wrapper function - //is created. - if (!function_exists('getmxrr')) { - function getmxrr($hostname, &$mxhosts, &$mxweight=false) { - return win_getmxrr($hostname, $mxhosts, $mxweight); - } - } + if ($appUid !== false) { + if ($delIndex < 0) { + throw new Exception(G::LoadTranslation('ID_INVALID_DELEGATION_INDEX_FOR_CASE') . "'" . $appUid . "'."); + } + $cases = new Cases(); + $data = $cases->loadCase($appUid, $delIndex); + } else { + global $oPMScript; + if (isset($oPMScript->aFields) && is_array($oPMScript->aFields)) { + $data['APP_DATA'] = $oPMScript->aFields; + } + } + $data["CURRENT_DYNAFORM"] = $dynUid; - $mailExchangerHosts = array(); - getmxrr($domainName, $mailExchangerHosts); - return $mailExchangerHosts; + $dynaform = new pmDynaform($data); + $dynaform->onPropertyRead = function(&$json, $key, $value) { + if (isset($json->data) && !isset($json->value)) { + $json->value = $json->data->value; + $json->value_label = $json->data->label; + } + }; + + if ($dynaform->isResponsive()) { + $json = G::json_decode($dynaform->record["DYN_CONTENT"]); + $dynaform->jsonr($json); + + $rows = $json->items[0]->items; + foreach ($rows as $items) { + foreach ($items as $item) { + $fields[] = $item; + } + } + } else { + $oldDynaform = new Dynaform(); + $aFields = $oldDynaform->getDynaformFields($dynUid); + foreach ($aFields as $value) { + if (isset($data["APP_DATA"]) && isset($data["APP_DATA"][$value->name])) { + $value->value = $data["APP_DATA"][$value->name]; + } + $fields[] = $value; + } + } + return $fields; } + +/** + * @method + * Return the task title of the specified task uid | If not found returns false + * @name PMFGetTaskName + * @label PMF Get Task Title Text + * @param string | $taskUid | ID Task | Is the identifier of task, that must be the same to the column: "TAS_UID" of the TASK table + * @param string | $lang | Language | Is the language of the text, that must be the same to the column: "CON_LANG" of the CONTENT table + * @return string | $text | Translated text | the translated text of a string in Content + */ +function PMFGetTaskName($taskUid, $lang = SYS_LANG) { + if (empty($taskUid)) { + return false; + } + return PMFGeti18nText($taskUid, 'TAS_TITLE', $lang); +} + +/** + * @method + * Return the group title of the specified group uid | If not found returns false + * @name PMFGetGroupName + * @label PMF Get Group Title Text + * @param string | $grpUid | ID Group | Is the identifier of group, that must be the same to the column: "GPR_UID" of the GROUPWF table + * @param string | $lang | Language | Is the language of the text, that must be the same to the column: "CON_LANG" of the CONTENT table + * @return string | $text | Translated text | the translated text of a string in Content + */ +function PMFGetGroupName($grpUid, $lang = SYS_LANG) { + if (empty($grpUid)) { + return false; + } + return PMFGeti18nText($grpUid, 'GRP_TITLE', $lang); +} + +/** + * @method + * The identifier of the element found using the text. + * @name PMFGetUidFromText + * @label PMF Get Uid From Text + * @param string | $text | Text + * @param string | $category | Category + * @param string | $proUid | ProcessUid + * @param string | $lang | Languaje + * @return array + */ +function PMFGetUidFromText($text, $category, $proUid = null, $lang = SYS_LANG) +{ + $obj = new ElementTranslation(); + $uids = $obj->getUidFromTextI18n($text, $category, $proUid, $lang); + return $uids; +} + +/** + * @method + * Get UID of a Dynaform + * @name PMFGetDynaformUID + * @label PMF Get Dynafrom UID + * @param string | $dynaformName | Name Dynaform | Is the name of a Dynaform + * @param string | $proUid = null | Process ID | The process identifier to search the dynaform name. If not specified the current process is used. + * @return array | $result | array + */ +function PMFGetDynaformUID($dynaformName, $proUid = null) +{ + return PMFGetUidFromText($dynaformName, 'DYN_TITLE', $proUid); +} + +/** + * @method + * Get UID of a Group + * @name PMFGetGroupUID + * @label PMF Get Group UID + * @param string | $groupName | Name Group | Is the name of a Group + * @return array | $result | array + */ +function PMFGetGroupUID($groupName) +{ + return PMFGetUidFromText($groupName, 'GRP_TITLE'); +} + +/** + * @method + * Get UID of a Task + * @name PMFGetTaskUID + * @label PMF Get Task UID + * @param string | $taskName | Name Task | Is the name of a Task + * @param string | $proUid = null| Process ID | The process identifier to search the dynaform name. If not specified the current process is used. + * @return array | $result | array + */ +function PMFGetTaskUID($taskName, $proUid = null) +{ + return PMFGetUidFromText($taskName, 'TAS_TITLE', $proUid); +} + +/** + * @method + * Get Group Users + * @name PMFGetGroupUsers + * @label PMF Group Users + * @param string | $GroupUID | Is UID of Group + * @return array | $result | array + */ +function PMFGetGroupUsers($GroupUID) +{ + G::LoadClass('groups'); + $groups = new Groups(); + $usersGroup = $groups->getUsersOfGroup($GroupUID, 'ALL'); + return $usersGroup; + +} + +/** + * @method + * + * Get next derivation info + * + * @name PMFGetNextDerivationInfo + * @label PMF Get next derivation info + * @link http://wiki.processmaker.com/index.php/ProcessMaker_Functions#PMFGetNextDerivationInfo.28.29 + * + * @param string(32) | $caseUid | ID of the case | The unique ID of the case + * @param int | $delIndex | Delegation index of the case | The delegation index of the current task in the case + * + * @return array | $arrayNextDerivationInfo | Next derivation info | Returns the next derivation info, FALSE otherwise + */ +function PMFGetNextDerivationInfo($caseUid, $delIndex) +{ + try { + $arrayNextDerivationInfo = []; + + //Verify data and Set variables + $case = new \ProcessMaker\BusinessModel\Cases(); + + $arrayAppDelegationData = $case->getAppDelegationRecordByPk( + $caseUid, + $delIndex, + ['$applicationUid' => '$caseUid', '$delIndex' => '$delIndex'], + false + ); + + if ($arrayAppDelegationData === false) { + return false; + } + + //Set variables + $processUid = $arrayAppDelegationData['PRO_UID']; + $userUid = $arrayAppDelegationData['USR_UID']; + + //Get next derivation + $derivation = new Derivation(); + + $arrayData = $derivation->prepareInformation([ + 'APP_UID' => $caseUid, + 'DEL_INDEX' => $delIndex, + 'USER_UID' => $userUid //User logged + ]); + + $task = new \ProcessMaker\BusinessModel\Task(); + + foreach ($arrayData as $value) { + $arrayInfo = $value; + + $nextTaskUid = $arrayInfo['NEXT_TASK']['TAS_UID']; + + $arrayUserUid = []; + $arrayGroupUid = []; + + if ($nextTaskUid != '-1') { + $arrayResult = $task->getTaskAssignees($processUid, $nextTaskUid, 'ASSIGNEE', 1); + + foreach ($arrayResult['data'] as $value2) { + $arrayAssigneeData = $value2; + + switch ($arrayAssigneeData['aas_type']) { + case 'user': + $arrayUserUid[] = $arrayAssigneeData['aas_uid']; + break; + case 'group': + $arrayGroupUid[] = $arrayAssigneeData['aas_uid']; + break; + } + } + } + + $arrayNextDerivationInfo[] = [ + 'taskUid' => $nextTaskUid, + 'users' => $arrayUserUid, + 'groups' => $arrayGroupUid, + ]; + } + + //Return + return $arrayNextDerivationInfo; + } catch (Exception $e) { + throw $e; + } +} + diff --git a/workflow/engine/classes/class.pmGoogleApi.php b/workflow/engine/classes/class.pmGoogleApi.php index 89426007a..85f778008 100755 --- a/workflow/engine/classes/class.pmGoogleApi.php +++ b/workflow/engine/classes/class.pmGoogleApi.php @@ -9,20 +9,28 @@ require_once PATH_TRUNK . 'vendor' . PATH_SEP . 'google' . PATH_SEP . 'apiclient class PMGoogleApi { + const DRIVE = 'https://www.googleapis.com/auth/drive'; + const DRIVE_FILE = 'https://www.googleapis.com/auth/drive.file'; + const DRIVE_APPS_READONLY = 'https://www.googleapis.com/auth/drive.apps.readonly'; + const DRIVE_READONLY = 'https://www.googleapis.com/auth/drive.readonly'; + const DRIVE_METADATA = 'https://www.googleapis.com/auth/drive.metadata'; + const DRIVE_METADATA_READONLY = 'https://www.googleapis.com/auth/drive.metadata.readonly'; + const DRIVE_APPDATA = 'https://www.googleapis.com/auth/drive.appdata'; + const DRIVE_PHOTOS_READONLY = 'https://www.googleapis.com/auth/drive.photos.readonly'; + const GMAIL_MODIFY = 'https://www.googleapis.com/auth/gmail.modify'; + private $scope = array(); private $serviceAccountEmail; - private $serviceAccountP12; - private $statusService; - private $domain; + private $serviceAccountCertificate; private $user; - - private $typeAuthentication; - private $accountJson; + private $serviceGmailStatus = false; + private $serviceDriveStatus = false; + private $configuration; public function __construct() { $licensedFeatures = &PMLicensedFeatures::getSingleton(); - if (!$licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + if (!($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09') || $licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M='))) { G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); G::header('location: ../login/login'); die; @@ -50,35 +58,21 @@ class PMGoogleApi return $this->user; } - public function setStatusService($status) - { - $conf = $this->getConfigGmail(); - - $conf->aConfig['statusService'] = $status; - $conf->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); - - $this->statusService = $status; - } - - public function getStatusService() - { - return $this->statusService; - } - public function getConfigGmail() { - $conf = new Configurations(); - $conf->loadConfig($gmail, 'GOOGLE_API_SETTINGS', ''); - return $conf; + $this->configuration = new Configurations(); + $this->configuration->loadConfig($gmail, 'GOOGLE_API_SETTINGS', ''); + } + + public function setConfigGmail ($id, $value) + { + $this->configuration->aConfig[$id] = $value; + $this->configuration->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); } public function setServiceAccountEmail($serviceAccountEmail) { - $conf = $this->getConfigGmail(); - - $conf->aConfig['serviceAccountEmail'] = $serviceAccountEmail; - $conf->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); - + $this->setConfigGmail('serviceAccountEmail', $serviceAccountEmail); $this->serviceAccountEmail = $serviceAccountEmail; } @@ -87,64 +81,45 @@ class PMGoogleApi return $this->serviceAccountEmail; } - public function setServiceAccountP12($serviceAccountP12) + public function setServiceAccountCertificate ($serviceAccountCertificate) { - $conf = $this->getConfigGmail(); - - $conf->aConfig['serviceAccountP12'] = $serviceAccountP12; - $conf->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); - - $this->serviceAccountP12 = $serviceAccountP12; + $this->setConfigGmail('serviceAccountCertificate', $serviceAccountCertificate); + $this->serviceAccountCertificate = $serviceAccountCertificate; } - public function getServiceAccountP12() + public function getServiceAccountCertificate() { - return $this->serviceAccountP12; + return $this->serviceAccountCertificate; } - public function setDomain($domain) + public function setServiceGmailStatus($status) { - $conf = $this->getConfigGmail(); - - $conf->aConfig['domain'] = $domain; - $conf->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); - - $this->domain = $domain; + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if (!$licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + $status = false; + } + $this->setConfigGmail('serviceGmailStatus', $status); + $this->serviceGmailStatus = $status; } - public function getDomain() + public function getServiceGmailStatus() { - return $this->domain; + return $this->serviceGmailStatus; } - public function setTypeAuthentication($type) + public function setServiceDriveStatus($status) { - $conf = $this->getConfigGmail(); - - $conf->aConfig['typeAuthentication'] = $type; - $conf->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); - - $this->typeAuthentication = $type; + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if (!$licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M=')) { + $status = false; + } + $this->setConfigGmail('serviceDriveStatus', $status); + $this->serviceDriveStatus = $status; } - public function getTypeAuthentication() + public function getServiceDriveStatus() { - return $this->typeAuthentication; - } - - public function setAccountJson($accountJson) - { - $conf = $this->getConfigGmail(); - - $conf->aConfig['accountJson'] = $accountJson; - $conf->saveConfig('GOOGLE_API_SETTINGS', '', '', ''); - - $this->accountJson = $accountJson; - } - - public function getAccountJson() - { - return $this->accountJson; + return $this->serviceDriveStatus; } /** @@ -153,23 +128,19 @@ class PMGoogleApi */ public function loadSettings() { - $conf = $this->getConfigGmail(); + $this->getConfigGmail(); - $typeAuthentication = empty($conf->aConfig['typeAuthentication']) ? '' : $conf->aConfig['typeAuthentication']; - $accountJson = empty($conf->aConfig['accountJson']) ? '' : $conf->aConfig['accountJson']; - - $serviceAccountP12 = empty($conf->aConfig['serviceAccountP12']) ? '' : $conf->aConfig['serviceAccountP12']; - $serviceAccountEmail = empty($conf->aConfig['serviceAccountEmail']) ? '' : $conf->aConfig['serviceAccountEmail']; - $statusService = empty($conf->aConfig['statusService']) ? '' : $conf->aConfig['statusService']; + $serviceAccountCertificate = empty($this->configuration->aConfig['serviceAccountCertificate']) ? '' : $this->configuration->aConfig['serviceAccountCertificate']; + $serviceAccountEmail = empty($this->configuration->aConfig['serviceAccountEmail']) ? '' : $this->configuration->aConfig['serviceAccountEmail']; + $serviceGmailStatus = empty($this->configuration->aConfig['serviceGmailStatus']) ? false : $this->configuration->aConfig['serviceGmailStatus']; + $serviceDriveStatus = empty($this->configuration->aConfig['serviceDriveStatus']) ? false : $this->configuration->aConfig['serviceDriveStatus']; $this->scope = array(); - $this->setTypeAuthentication($typeAuthentication); - $this->setAccountJson($accountJson); - - $this->setServiceAccountEmail($serviceAccountEmail); - $this->setServiceAccountP12($serviceAccountP12); - $this->setStatusService($statusService); + $this->serviceAccountEmail = $serviceAccountEmail; + $this->serviceAccountCertificate = $serviceAccountCertificate; + $this->serviceGmailStatus = $serviceGmailStatus; + $this->serviceDriveStatus = $serviceDriveStatus; } /** @@ -180,127 +151,65 @@ class PMGoogleApi public function serviceClient() { $client = null; - if ($this->typeAuthentication == 'webApplication') { - if (file_exists(PATH_DATA_SITE . $this->accountJson)) { - $credential = file_get_contents(PATH_DATA_SITE . $this->accountJson); - } else { - throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_JSON_ERROR')); - } - - - $client = new Google_Client(); - $client->setAuthConfig($credential); - $client->addScope($this->scope); - - if (!empty($_SESSION['google_token'])) { - $client->setAccessToken($_SESSION['google_token']); - if ($client->isAccessTokenExpired()) { - $client->getRefreshToken(); - unset($_SESSION['google_token']); - $_SESSION['google_token'] = $client->getAccessToken(); - } - } else if (!empty($_SESSION['CODE_GMAIL'])) { - $token = $client->authenticate($_SESSION['CODE_GMAIL']); - $_SESSION['google_token'] = $client->getAccessToken(); - } else { - $authUrl = $client->createAuthUrl(); - echo ''; - die; - } - } else if ($this->typeAuthentication == 'serviceAccount') { - - if (file_exists(PATH_DATA_SITE . $this->serviceAccountP12)) { - $key = file_get_contents(PATH_DATA_SITE . $this->serviceAccountP12); - } else { - throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_P12_ERROR')); - } - - $assertionCredentials = new Google_Auth_AssertionCredentials( - $this->serviceAccountEmail, - $this->scope, - $key - ); - $assertionCredentials->sub = $this->user; - - $client = new Google_Client(); - $client->setApplicationName("PMDrive"); - $client->setAssertionCredentials($assertionCredentials); + if (file_exists(PATH_DATA_SITE . $this->serviceAccountCertificate)) { + $key = file_get_contents(PATH_DATA_SITE . $this->serviceAccountCertificate); } else { - throw new Exception(G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR')); + throw new Exception(G::LoadTranslation('ID_GOOGLE_CERTIFICATE_ERROR')); } + $data = json_decode($key); + $assertionCredentials = new Google_Auth_AssertionCredentials( + $this->serviceAccountEmail, + $this->scope, + $data->private_key + ); + + $assertionCredentials->sub = $this->user; + + $client = new Google_Client(); + $client->setApplicationName("PMDrive"); + $client->setAssertionCredentials($assertionCredentials); + + return $client; } /** * New service client - Authentication google Api * - * @return Google_Service_Client $service API service instance. + * @param $credentials + * @throws \Exception + * @return \StdClass response. */ public function testService($credentials) { $scope = array( - 'https://www.googleapis.com/auth/drive', - 'https://www.googleapis.com/auth/drive.file', - 'https://www.googleapis.com/auth/drive.readonly', - 'https://www.googleapis.com/auth/drive.metadata.readonly', - 'https://www.googleapis.com/auth/drive.appdata', - 'https://www.googleapis.com/auth/drive.metadata', - 'https://www.googleapis.com/auth/drive.photos.readonly' + static::DRIVE, + static::DRIVE_FILE, + static::DRIVE_READONLY, + static::DRIVE_METADATA, + static::DRIVE_METADATA_READONLY, + static::DRIVE_APPDATA, + static::DRIVE_PHOTOS_READONLY ); - if ($credentials->typeAuth == 'webApplication') { - - if (file_exists($credentials->pathFileJson)) { - $credential = file_get_contents($credentials->pathFileJson); - } else { - throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_JSON_ERROR')); - } - - $client = new Google_Client(); - $client->setAuthConfig($credential); - $client->addScope($scope); - - if (!empty($_SESSION['google_token'])) { - $client->setAccessToken($_SESSION['google_token']); - if ($client->isAccessTokenExpired()) { - unset($_SESSION['google_token']); - } - } else if (!empty($_SESSION['CODE_GMAIL'])) { - $token = $client->authenticate($_SESSION['CODE_GMAIL']); - $_SESSION['google_token'] = $client->getAccessToken(); - } else { - $authUrl = $client->createAuthUrl(); - echo ''; - die; - } + if (file_exists($credentials->pathServiceAccountCertificate)) { + $key = file_get_contents($credentials->pathServiceAccountCertificate); } else { - - if (file_exists($credentials->pathServiceAccountP12)) { - $key = file_get_contents($credentials->pathServiceAccountP12); - } else { - throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_P12_ERROR')); - } - $assertionCredentials = new Google_Auth_AssertionCredentials( - $credentials->emailServiceAccount, - $scope, - $key - ); - $assertionCredentials->sub = $this->user; - - $client = new Google_Client(); - $client->setApplicationName("PMDrive"); - $client->setAssertionCredentials($assertionCredentials); + throw new Exception(G::LoadTranslation('ID_GOOGLE_CERTIFICATE_ERROR')); } + $data = json_decode($key); + $assertionCredentials = new Google_Auth_AssertionCredentials( + $credentials->emailServiceAccount, + $scope, + $data->private_key + ); + $assertionCredentials->sub = $this->user; - + $client = new Google_Client(); + $client->setApplicationName("PMDrive"); + $client->setAssertionCredentials($assertionCredentials); $service = new Google_Service_Drive($client); diff --git a/workflow/engine/classes/class.pmScript.php b/workflow/engine/classes/class.pmScript.php index 153f38021..a98368792 100644 --- a/workflow/engine/classes/class.pmScript.php +++ b/workflow/engine/classes/class.pmScript.php @@ -521,7 +521,7 @@ class PMScript $searchTypes = array ('checkgroup','dropdown','suggest'); $processVariables = $pmTablesProxy->getDynaformVariables($_SESSION['PROCESS'],$searchTypes,false); $variables = $this->affected_fields; - $variables = array_unique($variables); + $variables = (is_array($variables))? array_unique($variables) : $variables; $newFields = array(); $arrayValues = array(); $arrayLabels = array(); diff --git a/workflow/engine/classes/class.system.php b/workflow/engine/classes/class.system.php index e422dda8d..b9f866dd2 100755 --- a/workflow/engine/classes/class.system.php +++ b/workflow/engine/classes/class.system.php @@ -1163,6 +1163,29 @@ class System return $config; } + /* + * Get information about the queries permitted and tables we can modified + * @access public + * @param string $globalIniFile + * @return array of execute query Black list + */ + public static function getQueryBlackList($globalIniFile = ''){ + $config = array(); + if (empty($globalIniFile)) { + $blackListIniFile = PATH_CONFIG . 'execute-query-blacklist.ini'; + $sysTablesIniFile = PATH_CONFIG . 'system-tables.ini'; + } + // read the global execute-query-blacklist.ini configuration file + if(file_exists($blackListIniFile)){ + $config = @parse_ini_file($blackListIniFile); + } + if(file_exists($sysTablesIniFile)){ + $systemTables = @parse_ini_file($sysTablesIniFile); + $config['tables'] = $systemTables['tables']; + } + return $config; + } + public function updateIndexFile ($conf) { if (! file_exists( PATH_HTML . 'index.html' )) { diff --git a/workflow/engine/classes/class.triggerLibrary.php b/workflow/engine/classes/class.triggerLibrary.php index 91173e38f..ded37960c 100755 --- a/workflow/engine/classes/class.triggerLibrary.php +++ b/workflow/engine/classes/class.triggerLibrary.php @@ -35,6 +35,7 @@ class triggerLibrary //$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $Fields['APP_TITLE'], $sUsrUid); $oPluginRegistry = &PMPluginRegistry::getSingleton(); $aAvailablePmFunctions = $oPluginRegistry->getPmFunctions(); + $oPluginRegistry->setupPlugins(); //Get and setup enabled plugins foreach ($aAvailablePmFunctions as $key => $class) { $filePlugin = PATH_PLUGINS . $class . PATH_SEP . 'classes' . PATH_SEP . 'class.pmFunctions.php'; diff --git a/workflow/engine/classes/class.wsBase.php b/workflow/engine/classes/class.wsBase.php index 835e4c42c..35bd2cd2c 100755 --- a/workflow/engine/classes/class.wsBase.php +++ b/workflow/engine/classes/class.wsBase.php @@ -1017,14 +1017,17 @@ class wsBase ); $oSpool->create( $messageArray ); - $oSpool->sendMail(); + if ($gmail != 1){ + $oSpool->sendMail(); - if ($oSpool->status == 'sent') { - $result = new wsResponse( 0, G::loadTranslation( 'ID_MESSAGE_SENT' ) . ": " . $sTo ); + if ($oSpool->status == 'sent') { + $result = new wsResponse( 0, G::loadTranslation( 'ID_MESSAGE_SENT' ) . ": " . $sTo ); + } else { + $result = new wsResponse( 29, $oSpool->status . ' ' . $oSpool->error . print_r( $aSetup, 1 ) ); + } } else { - $result = new wsResponse( 29, $oSpool->status . ' ' . $oSpool->error . print_r( $aSetup, 1 ) ); + $result = ""; } - return $result; } catch (Exception $e) { return new wsResponse( 100, $e->getMessage() ); @@ -2664,9 +2667,10 @@ class wsBase $oCriteria = new Criteria( 'workflow' ); $oCriteria->addSelectColumn( AppDelayPeer::APP_UID ); $oCriteria->addSelectColumn( AppDelayPeer::APP_DEL_INDEX ); + $oCriteria->addSelectColumn( AppDelayPeer::APP_TYPE ); $oCriteria->addSelectColumn( AppDelayPeer::APP_DISABLE_ACTION_USER ); $oCriteria->addSelectColumn( AppDelayPeer::APP_DISABLE_ACTION_DATE ); - $oCriteria->add( AppDelayPeer::APP_TYPE, '' ); + $oCriteria->add( AppDelayPeer::APP_UID, $caseId ); $oCriteria->add( $oCriteria->getNewCriterion( AppDelayPeer::APP_TYPE, 'PAUSE' )->addOr( $oCriteria->getNewCriterion( AppDelayPeer::APP_TYPE, 'CANCEL' ) ) ); $oCriteria->addAscendingOrderByColumn( AppDelayPeer::APP_ENABLE_ACTION_DATE ); $oDataset = AppDelayPeer::doSelectRS( $oCriteria ); @@ -2675,7 +2679,7 @@ class wsBase $aRow = $oDataset->getRow(); if (is_array( $aRow )) { - if ($aRow['APP_DISABLE_ACTION_USER'] != 0 && $aRow['APP_DISABLE_ACTION_DATE'] != '') { + if ($aRow['APP_DISABLE_ACTION_USER'] == 0 || is_null($aRow['APP_DISABLE_ACTION_DATE'])) { $result = new wsResponse( 19, G::loadTranslation( 'ID_CASE_IN_STATUS' ) . " " . $aRow['APP_TYPE'] ); $g->sessionVarRestore(); diff --git a/workflow/engine/classes/class.wsTools.php b/workflow/engine/classes/class.wsTools.php index f2e46aded..c714d880e 100755 --- a/workflow/engine/classes/class.wsTools.php +++ b/workflow/engine/classes/class.wsTools.php @@ -185,13 +185,13 @@ class workspaceTools $key = isset($matches['key']) ? $matches['key'] : $matches[2]; $value = isset($matches['value']) ? $matches['value'] : $matches[3]; - if($this->onedb){ - $dbInfo = $this->getDBInfo(); + if ($this->onedb) { + $dbInfo = $this->getDBInfo(); $dbPrefix = array('DB_NAME' => 'wf_', 'DB_USER' => 'wf_', 'DB_RBAC_NAME' => 'wf_', 'DB_RBAC_USER' => 'wf_', 'DB_REPORT_NAME' => 'wf_', 'DB_REPORT_USER' => 'wf_'); - if (array_search($key, array('DB_PASS', 'DB_RBAC_PASS', 'DB_REPORT_PASS'))) { - $value = $dbInfo['DB_PASS']; - } - } else{ + if (array_search($key, array('DB_PASS', 'DB_RBAC_PASS', 'DB_REPORT_PASS'))) { + $value = $dbInfo['DB_PASS']; + } + } else { $dbPrefix = array('DB_NAME' => 'wf_', 'DB_USER' => 'wf_', 'DB_RBAC_NAME' => 'rb_', 'DB_RBAC_USER' => 'rb_', 'DB_REPORT_NAME' => 'rp_', 'DB_REPORT_USER' => 'rp_'); } @@ -203,16 +203,16 @@ class workspaceTools /* Change the database name to the new workspace, following the standard * of prefix (either wf_, rp_, rb_) and the workspace name. */ - if($this->unify){ - $nameDb = explode("_", $value); - if(!isset($nameDb[1])){ - $dbName = $value; - } else { - $dbName = $dbPrefix[$key] . $nameDb[1]; - } - }else { - $dbName = $dbPrefix[$key] . $this->name; - } + if ($this->unify) { + $nameDb = explode("_", $value); + if (!isset($nameDb[1])) { + $dbName = $value; + } else { + $dbName = $dbPrefix[$key] . $nameDb[1]; + } + } else { + $dbName = $dbPrefix[$key] . $this->name; + } } else { $dbName = $value; } @@ -301,10 +301,10 @@ class workspaceTools $rpDetails = $this->getDBCredentials("rp"); $config = array('datasources' => array('workflow' => array('connection' => $wfDetails["dsn"], 'adapter' => $wfDetails["adapter"] - ), 'rbac' => array('connection' => $rbDetails["dsn"], 'adapter' => $rbDetails["adapter"] - ), 'rp' => array('connection' => $rpDetails["dsn"], 'adapter' => $rpDetails["adapter"] - ) - ) + ), 'rbac' => array('connection' => $rbDetails["dsn"], 'adapter' => $rbDetails["adapter"] + ), 'rp' => array('connection' => $rpDetails["dsn"], 'adapter' => $rpDetails["adapter"] + ) + ) ); if ($root) { @@ -327,8 +327,8 @@ class workspaceTools $this->initPropel = true; - require_once ("propel/Propel.php"); - require_once ("creole/Creole.php"); + require_once("propel/Propel.php"); + require_once("creole/Creole.php"); Propel::initConfiguration($config); } @@ -397,10 +397,10 @@ class workspaceTools } G::LoadSystem('database_' . strtolower($this->dbAdapter)); - if ($rbac == true){ + if ($rbac == true) { $this->db = new database($this->dbAdapter, $this->dbRbacHost, $this->dbRbacUser, $this->dbRbacPass, $this->dbRbacName); } else { - $this->db = new database($this->dbAdapter, $this->dbHost, $this->dbUser, $this->dbPass, $this->dbName); + $this->db = new database($this->dbAdapter, $this->dbHost, $this->dbUser, $this->dbPass, $this->dbName); } if (!$this->db->isConnected()) { $this->db->logQuery('No available connection to database!'); @@ -437,7 +437,7 @@ class workspaceTools */ public function getSchema($rbac = false) { - $oDataBase = $this->getDatabase($rbac); + $oDataBase = $this->getDatabase($rbac); $aOldSchema = array(); @@ -491,8 +491,8 @@ class workspaceTools /** * Upgrade triggers of tables (Database) * - * @param bool $flagRecreate Recreate - * @param string $language Language + * @param bool $flagRecreate Recreate + * @param string $language Language * * return void */ @@ -557,19 +557,7 @@ class workspaceTools //Update APP_DELEGATION.DEL_LAST_INDEX data $res = $appCache->updateAppDelegationDelLastIndex($lang, $flagRecreate); - CLI::logging("-> Verifying roles permissions in RBAC \n"); - //Update table RBAC permissions - Bootstrap::LoadSystem( 'rbac' ); - $RBAC = & RBAC::getSingleton(); - $RBAC->initRBAC(); - $result = $RBAC->verifyPermissions(); - if (count($result) > 1) { - foreach ($result as $item) { - CLI::logging(" $item... \n"); - } - } else { - CLI::logging(" All roles permissions already updated \n"); - } + CLI::logging("-> Creating triggers\n"); @@ -595,25 +583,25 @@ class workspaceTools //close connection if (substr(PHP_OS, 0, 3) != 'WIN') { - $connection = Propel::getConnection( 'workflow' ); + $connection = Propel::getConnection('workflow'); $sql_sleep = "SELECT * FROM information_schema.processlist WHERE command = 'Sleep' and user = SUBSTRING_INDEX(USER(),'@',1) and db = DATABASE() ORDER BY id;"; $stmt_sleep = $connection->createStatement(); - $rs_sleep = $stmt_sleep->executeQuery( $sql_sleep, ResultSet::FETCHMODE_ASSOC ); + $rs_sleep = $stmt_sleep->executeQuery($sql_sleep, ResultSet::FETCHMODE_ASSOC); while ($rs_sleep->next()) { $row_sleep = $rs_sleep->getRow(); - $oStatement_sleep = $connection->prepareStatement( "kill ". $row_sleep['ID'] ); + $oStatement_sleep = $connection->prepareStatement("kill " . $row_sleep['ID']); $oStatement_sleep->executeQuery(); } $sql_query = "SELECT * FROM information_schema.processlist WHERE user = SUBSTRING_INDEX(USER(),'@',1) and db = DATABASE() and time > 0 ORDER BY id;"; $stmt_query = $connection->createStatement(); - $rs_query = $stmt_query->executeQuery( $sql_query, ResultSet::FETCHMODE_ASSOC ); + $rs_query = $stmt_query->executeQuery($sql_query, ResultSet::FETCHMODE_ASSOC); while ($rs_query->next()) { $row_query = $rs_query->getRow(); - $oStatement_query = $connection->prepareStatement( "kill ". $row_query['ID'] ); + $oStatement_query = $connection->prepareStatement("kill " . $row_query['ID']); $oStatement_query->executeQuery(); } } @@ -623,9 +611,9 @@ class workspaceTools * fix the 32K issue, by migrating /files directory structure to an uid tree structure based. * @param $workspace got the site(s) the manager wants to upgrade */ - public function upgradeCasesDirectoryStructure ($workspace) + public function upgradeCasesDirectoryStructure($workspace) { - define('PATH_DOCUMENT', PATH_DATA . 'sites/' . $workspace . '/' . 'files/'); + define('PATH_DOCUMENT', PATH_DATA . 'sites/' . $workspace . '/' . 'files/'); $doclevel = explode('/', PATH_DOCUMENT); $length = sizeof(PATH_DOCUMENT); $filesDir = $doclevel[$length - 1]; @@ -640,7 +628,7 @@ class workspaceTools $directory = glob(PATH_DOCUMENT . "*", GLOB_ONLYDIR); $dirslength = sizeof($directory); - if (! @chdir(PATH_DOCUMENT)) { + if (!@chdir(PATH_DOCUMENT)) { CLI::logging(CLI::error("Cannot use Document directory. The upgrade must be done as root.\n")); return; } @@ -704,13 +692,13 @@ class workspaceTools G::LoadClass("configuration"); $conf = new Configurations(); if (!$conf->exists("ENVIRONMENT_SETTINGS")) { - $conf->aConfig = array ("format" => '@userName (@firstName @lastName)', - "dateFormat" => 'd/m/Y', - "startCaseHideProcessInf" => false, - "casesListDateFormat" => 'Y-m-d H:i:s', - "casesListRowNumber" => 25, - "casesListRefreshTime" => 120 ); - $conf->saveConfig( 'ENVIRONMENT_SETTINGS', '' ); + $conf->aConfig = array("format" => '@userName (@firstName @lastName)', + "dateFormat" => 'd/m/Y', + "startCaseHideProcessInf" => false, + "casesListDateFormat" => 'Y-m-d H:i:s', + "casesListRowNumber" => 25, + "casesListRefreshTime" => 120); + $conf->saveConfig('ENVIRONMENT_SETTINGS', ''); } $conf->setDirectoryStructureVer(2); CLI::logging(CLI::info("Version Directory Structure is 2 now.\n")); @@ -736,17 +724,19 @@ class workspaceTools * @param bool $checkOnly only check if the upgrade is needed if true * @return array bool upgradeSchema for more information */ - public function upgradeDatabase ($onedb = false, $checkOnly = false) + public function upgradeDatabase($onedb = false, $checkOnly = false) { G::LoadClass("patch"); - $this->initPropel( true ); + $this->initPropel(true); p11835::$dbAdapter = $this->dbAdapter; p11835::isApplicable(); $systemSchema = System::getSystemSchema($this->dbAdapter); $systemSchemaRbac = System::getSystemSchemaRbac($this->dbAdapter);// get the Rbac Schema - $this->upgradeSchema( $systemSchema ); - $this->upgradeSchema( $systemSchemaRbac, false, true, $onedb ); // perform Upgrade to Rbac + $this->registerSystemTables(array_merge($systemSchema,$systemSchemaRbac)); + $this->upgradeSchema($systemSchema); + $this->upgradeSchema($systemSchemaRbac, false, true, $onedb); // perform Upgrade to Rbac $this->upgradeData(); + $this->checkRbacPermissions();//check or add new permissions //There records in table "EMAIL_SERVER" $criteria = new Criteria("workflow"); @@ -1301,7 +1291,7 @@ class workspaceTools //check function shell_exec $disabled_functions = ini_get('disable_functions'); $flag = false; - if ($disabled_functions!='') { + if ($disabled_functions != '') { $arr = explode(',', $disabled_functions); sort($arr); if (in_array("shell_exec", $arr)) { @@ -1311,39 +1301,39 @@ class workspaceTools // Check if mysql exist on server $flagFunction = null; - if ( !$flag ) { + if (!$flag) { $flagFunction = shell_exec('mysql --version'); } - $arrayRegExpEngineSearch = array("/\)\s*TYPE\s*=\s*(InnoDB)/i", "/\)\s*TYPE\s*=\s*(MyISAM)/i"); + $arrayRegExpEngineSearch = array("/\)\s*TYPE\s*=\s*(InnoDB)/i", "/\)\s*TYPE\s*=\s*(MyISAM)/i"); $arrayRegExpEngineReplace = array(") ENGINE=\\1 DEFAULT CHARSET=utf8", ") ENGINE=\\1"); - if ( !$flag && !is_null($flagFunction) ) { + if (!$flag && !is_null($flagFunction)) { //Replace TYPE by ENGINE $script = preg_replace($arrayRegExpEngineSearch, $arrayRegExpEngineReplace, file_get_contents($filename)); - file_put_contents($filename,$script); + file_put_contents($filename, $script); - $aHost = explode(':',$parameters['dbHost']); + $aHost = explode(':', $parameters['dbHost']); $dbHost = $aHost[0]; - if(isset($aHost[1])){ + if (isset($aHost[1])) { $dbPort = $aHost[1]; $command = 'mysql' - . ' --host=' . $dbHost - . ' --port=' . $dbPort - . ' --user=' . $parameters['dbUser'] - . ' --password=' . str_replace('"', '\"', str_replace("'", "\'", quotemeta($parameters['dbPass'])))//no change! supports the type passwords: .\+*?[^]($)'"\"' - . ' --database=' . mysql_real_escape_string($database) - . ' --default_character_set utf8' - . ' --execute="SOURCE '.$filename.'"'; - }else{ + . ' --host=' . $dbHost + . ' --port=' . $dbPort + . ' --user=' . $parameters['dbUser'] + . ' --password=' . str_replace('"', '\"', str_replace("'", "\'", quotemeta($parameters['dbPass'])))//no change! supports the type passwords: .\+*?[^]($)'"\"' + . ' --database=' . mysql_real_escape_string($database) + . ' --default_character_set utf8' + . ' --execute="SOURCE ' . $filename . '"'; + } else { $command = 'mysql' - . ' --host=' . $dbHost - . ' --user=' . $parameters['dbUser'] - . ' --password=' . str_replace('"', '\"', str_replace("'", "\'", quotemeta($parameters['dbPass'])))//no change! supports the type passwords: .\+*?[^]($)'"\"' - . ' --database=' . mysql_real_escape_string($database) - . ' --default_character_set utf8' - . ' --execute="SOURCE '.$filename.'"'; + . ' --host=' . $dbHost + . ' --user=' . $parameters['dbUser'] + . ' --password=' . str_replace('"', '\"', str_replace("'", "\'", quotemeta($parameters['dbPass'])))//no change! supports the type passwords: .\+*?[^]($)'"\"' + . ' --database=' . mysql_real_escape_string($database) + . ' --default_character_set utf8' + . ' --execute="SOURCE ' . $filename . '"'; } shell_exec($command); } else { @@ -1430,7 +1420,7 @@ class workspaceTools $metafiles = array(); foreach ($backup->listContent() as $backupFile) { $filename = $backupFile["filename"]; - if (strpos($filename, "/") === false && substr_compare($filename, ".meta", - 5, 5, true) === 0) { + if (strpos($filename, "/") === false && substr_compare($filename, ".meta", -5, 5, true) === 0) { if (!$backup->extractList(array($filename), $tempDirectory)) { throw new Exception("Could not extract backup"); } @@ -1444,7 +1434,7 @@ class workspaceTools $data = file_get_contents($metafile); $workspaceData = G::json_decode($data); CLI::logging("\n"); - workspaceTools::printInfo((array) $workspaceData); + workspaceTools::printInfo((array)$workspaceData); } G::rm_dir($tempDirectory); @@ -1457,7 +1447,7 @@ class workspaceTools $chmod = @chmod($filename, $perms); if ($chgrp === false || $chmod === false || $chown === false) { - if (strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN') { + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { exec("icacls \"" . $filename . "\" /grant Administrador:(D,WDAC) /T", $res); } else { CLI::logging(CLI::error("Failed to set permissions for $filename") . "\n"); @@ -1523,7 +1513,7 @@ class workspaceTools } $version = System::getVersion(); - $pmVersion = (preg_match("/^([\d\.]+).*$/", $version, $arrayMatch))? $arrayMatch[1] : ""; //Otherwise: Branch master + $pmVersion = (preg_match("/^([\d\.]+).*$/", $version, $arrayMatch)) ? $arrayMatch[1] : ""; //Otherwise: Branch master CLI::logging(CLI::warning(" Warning: A workspace from a newer version of ProcessMaker can NOT be restored in an older version of @@ -1603,10 +1593,10 @@ class workspaceTools CLI::logging(CLI::error("Could not get the shared folder permissions, not changing workspace permissions") . "\n"); } list ($dbHost, $dbUser, $dbPass) = @explode(SYSTEM_HASH, G::decrypt(HASH_INSTALLATION, SYSTEM_HASH)); - if($port != ''){ - $dbHost = $dbHost.$port; //127.0.0.1:3306 + if ($port != '') { + $dbHost = $dbHost . $port; //127.0.0.1:3306 } - $aParameters = array('dbHost'=>$dbHost,'dbUser'=>$dbUser,'dbPass'=>$dbPass); + $aParameters = array('dbHost' => $dbHost, 'dbUser' => $dbUser, 'dbPass' => $dbPass); //Restore if (!defined("SYS_SYS")) { @@ -1617,7 +1607,7 @@ class workspaceTools define("PATH_DATA_SITE", PATH_DATA . "sites" . PATH_SEP . SYS_SYS . PATH_SEP); } - $pmVersionWorkspaceToRestore = (preg_match("/^([\d\.]+).*$/", $metadata->PM_VERSION, $arrayMatch))? $arrayMatch[1] : ""; + $pmVersionWorkspaceToRestore = (preg_match("/^([\d\.]+).*$/", $metadata->PM_VERSION, $arrayMatch)) ? $arrayMatch[1] : ""; CLI::logging("> Connecting to system database in '$dbHost'\n"); $link = mysql_connect($dbHost, $dbUser, $dbPass); @@ -1637,13 +1627,13 @@ class workspaceTools $dbName = $newDBNames[$db->name]; if (mysql_select_db($dbName, $link)) { - if(!$overwrite) { + if (!$overwrite) { throw new Exception("Destination Database already exist (use -o to overwrite)"); } } CLI::logging("+> Restoring database {$db->name} to $dbName\n"); - $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql",$aParameters); + $workspace->executeSQLScript($dbName, "$tempDirectory/{$db->name}.sql", $aParameters); $workspace->createDBUser($dbName, $db->pass, "localhost", $dbName); $workspace->createDBUser($dbName, $db->pass, "%", $dbName); } @@ -1715,9 +1705,9 @@ class workspaceTools $arrayPathInfo = pathinfo($file); - $f = ($arrayPathInfo["dirname"] == ".")? $dirHotfix . PATH_SEP . $file : $file; + $f = ($arrayPathInfo["dirname"] == ".") ? $dirHotfix . PATH_SEP . $file : $file; - $swv = 1; + $swv = 1; $msgv = ""; if (!file_exists($dirHotfix)) { @@ -1725,13 +1715,13 @@ class workspaceTools } if (!file_exists($f)) { - $swv = 0; - $msgv = $msgv . (($msgv != "")? "\n": null) . "- The file \"$f\" does not exist"; + $swv = 0; + $msgv = $msgv . (($msgv != "") ? "\n" : null) . "- The file \"$f\" does not exist"; } if ($arrayPathInfo["extension"] != "tar") { - $swv = 0; - $msgv = $msgv . (($msgv != "")? "\n": null) . "- The file extension \"$file\" is not \"tar\""; + $swv = 0; + $msgv = $msgv . (($msgv != "") ? "\n" : null) . "- The file extension \"$file\" is not \"tar\""; } if ($swv == 1) { @@ -1995,7 +1985,7 @@ class workspaceTools } $appCache = new AppCacheView(); - $users = new Users(); + $users = new Users(); $case = new Cases(); //Select data CANCELLED @@ -2047,18 +2037,18 @@ class workspaceTools if($row["DEL_THREAD_STATUS"] == 'OPEN'){ //Update information about the previous_user $row["DEL_PREVIOUS_USR_UID"] = $row["PREVIOUS_USR_UID"]; - $criteriaUser->add( UsersPeer::USR_UID, $row["PREVIOUS_USR_UID"] ); + $criteriaUser->add(UsersPeer::USR_UID, $row["PREVIOUS_USR_UID"]); $datasetU = UsersPeer::doSelectRS($criteriaUser); $datasetU->setFetchmode(ResultSet::FETCHMODE_ASSOC); $datasetU->next(); $arrayUsers = $datasetU->getRow(); $row["DEL_PREVIOUS_USR_USERNAME"] = $arrayUsers["USR_USERNAME"]; - $row["DEL_PREVIOUS_USR_FIRSTNAME"]= $arrayUsers["USR_FIRSTNAME"]; + $row["DEL_PREVIOUS_USR_FIRSTNAME"] = $arrayUsers["USR_FIRSTNAME"]; $row["DEL_PREVIOUS_USR_LASTNAME"] = $arrayUsers["USR_LASTNAME"]; //Update the due date - $row["DEL_DUE_DATE"] = $row["DEL_TASK_DUE_DATE"]; + $row["DEL_DUE_DATE"] = $row["DEL_TASK_DUE_DATE"]; $listInbox = new ListInbox(); - $listInbox->remove($row["APP_UID"],$row["DEL_INDEX"]); + $listInbox->remove($row["APP_UID"], $row["DEL_INDEX"]); $listInbox->setDeleted(false); $listInbox->create($row, $isSelfService); } else { @@ -2279,4 +2269,42 @@ class workspaceTools throw $e; } } + + /** + * Register system tables in a file + * + * return void + */ + public static function registerSystemTables($aSquema){ + //Register all tables + $sListTables = ''; + foreach ($aSquema as $key => $value) { + $sListTables .= $key .'|'; + } + + $sysTablesIniFile= PATH_CONFIG . 'system-tables.ini'; + $contents = file_put_contents( $sysTablesIniFile, sprintf( "%s '%s'\n", "tables = ", $sListTables ) ); + if ($contents === null) { + throw (new Exception( G::LoadTranslation('ID_FILE_NOT_WRITEABLE', SYS_LANG, array($sysTablesIniFile) ) )); + } + } + + /** + *return void + */ + public function checkRbacPermissions(){ + CLI::logging("-> Verifying roles permissions in RBAC \n"); + //Update table RBAC permissions + Bootstrap::LoadSystem('rbac'); + $RBAC = &RBAC::getSingleton(); + $RBAC->initRBAC(); + $result = $RBAC->verifyPermissions(); + if (count($result) > 1) { + foreach ($result as $item) { + CLI::logging(" $item... \n"); + } + } else { + CLI::logging(" All roles permissions already updated \n"); + } + } } diff --git a/workflow/engine/classes/model/AdditionalTables.php b/workflow/engine/classes/model/AdditionalTables.php index ccc949199..dc66876aa 100755 --- a/workflow/engine/classes/model/AdditionalTables.php +++ b/workflow/engine/classes/model/AdditionalTables.php @@ -311,7 +311,7 @@ class AdditionalTables extends BaseAdditionalTables $pmTable->remove(); } - public function getPHPName($sName) + public static function getPHPName($sName) { $sName = trim($sName); $aAux = explode('_', $sName); diff --git a/workflow/engine/classes/model/AddonsManager.php b/workflow/engine/classes/model/AddonsManager.php index f9fddeb6a..e55114bf5 100644 --- a/workflow/engine/classes/model/AddonsManager.php +++ b/workflow/engine/classes/model/AddonsManager.php @@ -143,6 +143,7 @@ class AddonsManager extends BaseAddonsManager //$oPluginRegistry->enablePlugin($oDetails->sNamespace); //require_once (PATH_PLUGINS . $this->getAddonName() . ".php"); //ok $oPluginRegistry->enablePlugin($this->getAddonName()); + $oPluginRegistry->setupPlugins(); //get and setup enabled plugins } else { //$oDetails = $oPluginRegistry->getPluginDetails($this->getAddonName()); //$oPluginRegistry->disablePlugin($oDetails->sNamespace); @@ -455,4 +456,3 @@ class AddonsManager extends BaseAddonsManager return true; } } - diff --git a/workflow/engine/classes/model/AppDocument.php b/workflow/engine/classes/model/AppDocument.php index 6e055f881..1fc120fe7 100755 --- a/workflow/engine/classes/model/AppDocument.php +++ b/workflow/engine/classes/model/AppDocument.php @@ -66,6 +66,8 @@ class AppDocument extends BaseAppDocument /*----------------------------------********---------------------------------*/ protected $driveDownload = array(); + protected $syncWithDrive = ''; + protected $syncPermissions = ''; /*----------------------------------********---------------------------------*/ /* @@ -220,6 +222,7 @@ class AppDocument extends BaseAppDocument /*----------------------------------********---------------------------------*/ $aData['APP_DOC_DRIVE_DOWNLOAD'] = serialize($this->driveDownload); + //$aData['SYNC_PERMISSIONS'] = $this->syncPermissions; /*----------------------------------********---------------------------------*/ $oAppDocument->fromArray( $aData, BasePeer::TYPE_FIELDNAME ); $oAppDocument->setDocVersion( $docVersion ); @@ -267,6 +270,7 @@ class AppDocument extends BaseAppDocument $oConnection = Propel::getConnection( AppDocumentPeer::DATABASE_NAME ); try { $oAppDocument = AppDocumentPeer::retrieveByPK( $aData['APP_DOC_UID'], $aData['DOC_VERSION'] ); + if (! is_null( $oAppDocument )) { /*----------------------------------********---------------------------------*/ $driveDownload = @unserialize($oAppDocument->getAppDocDriveDownload()); @@ -275,6 +279,10 @@ class AppDocument extends BaseAppDocument } else { $aData['APP_DOC_DRIVE_DOWNLOAD'] = serialize($this->driveDownload); } + //$aData['SYNC_PERMISSIONS'] = $this->syncPermissions; + //$aData['SYNC_WITH_DRIVE'] = $this->syncWithDrive; + //$oAppDocument->setSyncWithDrive($aData['SYNC_WITH_DRIVE']); + //$oAppDocument->sync_with_drive = $aData['SYNC_WITH_DRIVE']; /*----------------------------------********---------------------------------*/ $oAppDocument->fromArray( $aData, BasePeer::TYPE_FIELDNAME ); if ($oAppDocument->validate()) { @@ -508,6 +516,29 @@ class AppDocument extends BaseAppDocument } return $url; } + /*public function setSyncWithDrive ($key) + { + $data = array('SYNCHRONIZED', 'UNSYNCHRONIZED', 'NO_EXIST_FILE_PM'); + if (array_search($key, $data) === false) { + $key = 'UNSYNCHRONIZED'; + } + $this->syncWithDrive = $key; + }*/ + + /*public function getSyncWithDrive () + { + return $this->syncWithDrive; + }*/ + + /*public function setSyncPermissions ($email) + { + $this->syncPermissions = empty($this->syncPermissions) ? $email : ','.$email; + } + + public function getSyncPermissions () + { + return !empty($this->syncPermissions) ? explode(',', $this->syncPermissions) : ''; + }*/ /*----------------------------------********---------------------------------*/ diff --git a/workflow/engine/classes/model/AppFolder.php b/workflow/engine/classes/model/AppFolder.php index 5bf78d81a..c26c31d91 100755 --- a/workflow/engine/classes/model/AppFolder.php +++ b/workflow/engine/classes/model/AppFolder.php @@ -293,16 +293,6 @@ class AppFolder extends BaseAppFolder //require_once ("classes/model/OutputDocument.php"); //require_once ("classes/model/Users.php"); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ - G::LoadClass( 'case' ); $oCase = new Cases(); G::LoadClass( 'process' ); @@ -328,11 +318,7 @@ class AppFolder extends BaseAppFolder $oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_STATUS); $oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_STATUS_DATE); $oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_FIELDNAME); - /*----------------------------------********---------------------------------*/ - if ($enablePMGmail) { - $oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD); - } - /*----------------------------------********---------------------------------*/ + $oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD); if ((is_array( $docIdFilter )) && (count( $docIdFilter ) > 0)) { //Search by App Doc UID no matter what Folder it is @@ -433,39 +419,6 @@ class AppFolder extends BaseAppFolder //$filesResult [] = $completeInfo; if ($completeInfo['APP_DOC_STATUS'] != "DELETED") { - /*----------------------------------********---------------------------------*/ - if ($enablePMGmail) { - $driveDownload = @unserialize($completeInfo['APP_DOC_DRIVE_DOWNLOAD']); - switch ($completeInfo['APP_DOC_TYPE']) { - case 'INPUT': - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('INPUT', - $driveDownload) - ) { - $completeInfo['DOWNLOAD_LINK'] = $driveDownload['INPUT']; - } - break; - case 'ATTACHED': - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('ATTACHED', - $driveDownload) - ) { - $completeInfo['DOWNLOAD_LINK'] = $driveDownload['ATTACHED']; - } - break; - case 'OUTPUT': - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_DOC', - $driveDownload) - ) { - $completeInfo['DOWNLOAD_LINK1'] = $driveDownload['OUTPUT_DOC']; - } - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_PDF', - $driveDownload) - ) { - $completeInfo['DOWNLOAD_LINK'] = $driveDownload['OUTPUT_PDF']; - } - break; - } - } - /*----------------------------------********---------------------------------*/ if (in_array($row["APP_DOC_UID"], $completeInfo["INPUT_DOCUMENTS"]) || in_array($row["APP_DOC_UID"], $completeInfo["OUTPUT_DOCUMENTS"]) || in_array($completeInfo["USR_UID"], array($_SESSION["USER_LOGGED"], "-1")) || $user == "") { if (count( $docIdFilter ) > 0) { if (in_array( $row['APP_DOC_UID'], $docIdFilter )) { diff --git a/workflow/engine/classes/model/Application.php b/workflow/engine/classes/model/Application.php index c7b754156..f6d63aab7 100755 --- a/workflow/engine/classes/model/Application.php +++ b/workflow/engine/classes/model/Application.php @@ -60,7 +60,7 @@ class Application extends BaseApplication if (!$oApplication->exists($this->getAppUid())) { return false; } - + if ($this->getAppUid() == '') { throw (new Exception( "Error in getAppTitle, the APP_UID can't be blank")); } @@ -373,7 +373,6 @@ class Application extends BaseApplication $this->setAppUpdateDate('now'); $pin = G::generateCode(4, 'ALPHANUMERIC'); - $this->setAppData(serialize(array('PIN' => $pin))); $this->setAppPin(G::encryptOld($pin)); $c = new Criteria(); @@ -385,6 +384,8 @@ class Application extends BaseApplication $maxNumber = $oSequences->getSequeceNumber("APP_NUMBER"); $this->setAppNumber($maxNumber); + $this->setAppData(serialize(['APP_NUMBER' => $maxNumber, 'PIN' => $pin])); + $oSequences->changeSequence('APP_NUMBER', $maxNumber); $oSequences->unlockSequenceTable(); @@ -591,7 +592,7 @@ class Application extends BaseApplication } $calendar = new calendar(); - + $c = new Criteria( 'workflow' ); $c->clearSelectColumns(); $c->addSelectColumn( ApplicationPeer::APP_UID ); @@ -616,7 +617,7 @@ class Application extends BaseApplication $rs->next(); $row = $rs->getRow(); $i = 0; - + $now = strtotime( 'now' ); while (is_array( $row )) { $appNumber = $row['APP_NUMBER']; @@ -634,7 +635,7 @@ class Application extends BaseApplication //get the object, $oApp = ApplicationPeer::retrieveByPk( $row['APP_UID'] ); - + //getting the calendar $calendar->getCalendar(null, $proUid); $calData = $calendar->getCalendarData(); @@ -648,8 +649,8 @@ class Application extends BaseApplication if($appFinishDate == null){//When the process didnt finish yet. //Duration $appDuration = $calendar->dashCalculateDurationWithCalendar($appInitDate, date("Y-m-d H:i:s"), $calData ); - - + + $appDuration = $appDuration / (24 * 60 * 60); //Saving the proDuration in days. The calculateDurationWithCalendar func returns segs. $oApp->setAppDuration( $appDuration ); @@ -662,7 +663,7 @@ class Application extends BaseApplication $appDuration = $calendar->dashCalculateDurationWithCalendar($appInitDate, $appFinishDate, $calData ); $appDuration = $appDuration / (24 * 60 * 60); //Saving the proDuration in days. The calculateDurationWithCalendar func returns mins. $oApp->setAppDuration( $appDuration ); - + //Delay Duration $delayDuration = $calendar->dashCalculateDurationWithCalendar( $proDueDate, $appFinishDate, $calData ); $delayDuration = $delayDuration / (24 * 60 * 60); //Days @@ -674,7 +675,7 @@ class Application extends BaseApplication $rs->next(); $row = $rs->getRow(); } - + if ($cron == 1) { $arrayCron = unserialize( trim( @file_get_contents( PATH_DATA . "cron" ) ) ); $arrayCron["processcTimeStart"] = time(); @@ -683,7 +684,7 @@ class Application extends BaseApplication } catch (Exception $oError) { error_log( $oError->getMessage() ); } - } + } /*----------------------------------********---------------------------------*/ } diff --git a/workflow/engine/classes/model/Department.php b/workflow/engine/classes/model/Department.php index f0bea9d9c..38127f0c3 100755 --- a/workflow/engine/classes/model/Department.php +++ b/workflow/engine/classes/model/Department.php @@ -114,7 +114,7 @@ class Department extends BaseDepartment $res = $this->save(); $con->commit(); - + G::auditLog("Create".$msgLog, $msgLog." Name: ". $aData['DEP_TITLE']); return $this->getDepUid(); @@ -332,7 +332,7 @@ class Department extends BaseDepartment } public function updateDepartmentManager ($depId) - { + { $managerId = ''; $depParent = ''; $oDept = DepartmentPeer::retrieveByPk( $depId ); @@ -347,10 +347,6 @@ class Department extends BaseDepartment $selectCriteria = new Criteria( 'workflow' ); $selectCriteria->add( UsersPeer::DEP_UID, $depId ); $selectCriteria->add( UsersPeer::USR_UID, $managerId, Criteria::NOT_EQUAL ); - - if(empty($depParent)) { - $depParent = $depId; - } // Create a Criteria object includes the value you want to set $updateCriteria = new Criteria( 'workflow' ); @@ -370,7 +366,7 @@ class Department extends BaseDepartment } $oUser->save(); } - + if ($managerId) { $user = $oUser->loadDetailed ($managerId); if (is_object( $oDept ) && get_class( $oDept ) == 'Department') { @@ -393,41 +389,6 @@ class Department extends BaseDepartment } $oDataset->next(); } - - $this->updateUserReportsTo($depId); - } - - public function updateUserReportsTo($depId) - { - $departments = $this->getChildDepartments($depId); - $departments = explode("_",$departments); - $departments = array_filter(array_unique($departments)); - foreach($departments as $depUid) { - $mgrParentId = $this->getDepartmentParentManager($depUid); - $conn = Propel::getConnection( UsersPeer::DATABASE_NAME ); - $selectCriteria = new Criteria( 'workflow' ); - $selectCriteria->add( UsersPeer::DEP_UID, $depUid ); - $updateCriteria = new Criteria( 'workflow' ); - $updateCriteria->add( UsersPeer::USR_REPORTS_TO, $mgrParentId ); - BasePeer::doUpdate( $selectCriteria, $updateCriteria, $conn ); - } - } - - public function getChildDepartments($depId) - { - $depIds = ""; - $depIds .= $depId."_"; - $childrenCriteria = new Criteria( 'workflow' ); - $childrenCriteria->add( DepartmentPeer::DEP_PARENT, $depId ); - $oDataset = DepartmentPeer::doSelectRS( $childrenCriteria ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); - $oDataset->next(); - while ($aRow = $oDataset->getRow()) { - $depId = $aRow['DEP_UID']; - $depIds .= $this->getChildDepartments($depId); - $oDataset->next(); - } - return $depIds; } //add an user to a department and sync all about manager info @@ -623,7 +584,7 @@ class Department extends BaseDepartment $oUser->setDepUid( '' ); $oUser->setUsrReportsTo( '' ); $oUser->save(); - + G::auditLog("RemoveUsersFromDepartament", "Remove user ".$user['USR_USERNAME']."( ".$UsrUid.") from departament ".$dptoTitle['DEPO_TITLE']." (".$DepUid.") "); } } catch (exception $oError) { @@ -738,19 +699,5 @@ class Department extends BaseDepartment } return $departments; } - - public function getDepartmentParentManager($depId) - { - $managerUid = ""; - $depInfo = $this->Load($depId); - if(empty($depInfo['DEP_MANAGER'])) { - if(!empty($depInfo['DEP_PARENT'])) { - $managerUid = $this->getDepartmentParentManager($depInfo['DEP_PARENT']); - } - } else { - $managerUid = $depInfo['DEP_MANAGER']; - } - return $managerUid; - } } diff --git a/workflow/engine/classes/model/GmailRelabeling.php b/workflow/engine/classes/model/GmailRelabeling.php new file mode 100644 index 000000000..29102525c --- /dev/null +++ b/workflow/engine/classes/model/GmailRelabeling.php @@ -0,0 +1,19 @@ +addSelectColumn(ListInboxPeer::DEL_INIT_DATE); $criteria->addSelectColumn(ListInboxPeer::DEL_DUE_DATE); $criteria->addSelectColumn(ListInboxPeer::DEL_PRIORITY); + $criteria->addSelectColumn(UsersPeer::USR_UID); + $criteria->addSelectColumn(UsersPeer::USR_FIRSTNAME); + $criteria->addSelectColumn(UsersPeer::USR_LASTNAME); + $criteria->addSelectColumn(UsersPeer::USR_USERNAME); + $criteria->addJoin( ListInboxPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN ); $criteria->add( ListInboxPeer::USR_UID, $usr_uid, Criteria::EQUAL ); self::loadFilters($criteria, $filters); diff --git a/workflow/engine/classes/model/ListParticipatedLast.php b/workflow/engine/classes/model/ListParticipatedLast.php index 9197aeb3b..47bb2a3c3 100644 --- a/workflow/engine/classes/model/ListParticipatedLast.php +++ b/workflow/engine/classes/model/ListParticipatedLast.php @@ -49,6 +49,7 @@ class ListParticipatedLast extends BaseListParticipatedLast $data['DEL_CURRENT_USR_USERNAME'] = $aRow['USR_USERNAME']; $data['DEL_CURRENT_USR_FIRSTNAME'] = $aRow['USR_FIRSTNAME']; $data['DEL_CURRENT_USR_LASTNAME'] = $aRow['USR_LASTNAME']; + $data['DEL_CURRENT_TAS_TITLE'] = $data['APP_TAS_TITLE']; $users = new Users(); $users->refreshTotal($data['USR_UID'], 'add', 'participated'); @@ -147,6 +148,11 @@ class ListParticipatedLast extends BaseListParticipatedLast $criteriaSet->add(ListParticipatedLastPeer::DEL_CURRENT_USR_USERNAME, $aRow['USR_USERNAME']); $criteriaSet->add(ListParticipatedLastPeer::DEL_CURRENT_USR_FIRSTNAME, $aRow['USR_FIRSTNAME']); $criteriaSet->add(ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME, $aRow['USR_LASTNAME']); + + if (isset($data['APP_TAS_TITLE'])) { + $criteriaSet->add(ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE, $data['APP_TAS_TITLE']); + } + BasePeer::doUpdate($criteriaWhere, $criteriaSet, Propel::getConnection("workflow")); } @@ -308,6 +314,7 @@ class ListParticipatedLast extends BaseListParticipatedLast $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_CURRENT_USR_USERNAME); $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_CURRENT_USR_FIRSTNAME); $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME); + $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE); $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_DELEGATE_DATE); $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_INIT_DATE); $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_DUE_DATE); diff --git a/workflow/engine/classes/model/Process.php b/workflow/engine/classes/model/Process.php index fa953c44d..bacade3b1 100755 --- a/workflow/engine/classes/model/Process.php +++ b/workflow/engine/classes/model/Process.php @@ -340,6 +340,8 @@ class Process extends BaseProcess public function getAll () { + $bpmn = new \ProcessMaker\Project\Bpmn(); + $oCriteria = new Criteria( 'workflow' ); $oCriteria->addSelectColumn( ProcessPeer::PRO_UID ); @@ -359,7 +361,9 @@ class Process extends BaseProcess $processes = Array (); $uids = array (); while ($oDataset->next()) { - $processes[] = $oDataset->getRow(); + $row = $oDataset->getRow(); + $row['PRO_PROCESS_TYPE'] = ($bpmn->exists($row['PRO_UID']))? 'BPMN' : 'CLASSIC'; + $processes[] = $row; $uids[] = $processes[sizeof( $processes ) - 1]['PRO_UID']; } //process details will have the info about the processes @@ -1048,5 +1052,70 @@ class Process extends BaseProcess } return $aProc; } + + public function deleteProcessCases($proUid) + { + try { + /*get cases by process uid*/ + $oCase = new Cases(); + $oCriteria = new Criteria( 'workflow' ); + $oCriteria->addSelectColumn( ApplicationPeer::APP_UID); + $oCriteria->add( ApplicationPeer::PRO_UID, $proUid ); + $oDataset = ApplicationPeer::doSelectRS( $oCriteria, Propel::getDbConnection('workflow_ro') ); + $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + while ($oDataset->next()) { + $row = $oDataset->getRow(); + $oCase->removeCase($row['APP_UID'], false); + } + } catch(Exception $e) { + throw ($e); + } + } + + public function refreshUserAllCountersByProcessesGroupUid($proUidArray) + { + $aTypes = array( + 'to_do', + 'draft', + 'cancelled', + 'sent', + 'paused', + 'completed', + 'selfservice' + ); + $usersArray = array(); + $users = new Users(); + $oCase = new Cases(); + $oCriteria = new Criteria(); + $oCriteria->addSelectColumn( AppDelegationPeer::APP_UID ); + $oCriteria->addSelectColumn( AppDelegationPeer::USR_UID ); + $oCriteria->setDistinct(); + $oCriteria->add( AppDelegationPeer::PRO_UID, $proUidArray, Criteria::IN ); + $oRuleSet = AppDelegationPeer::doSelectRS( $oCriteria ); + $oRuleSet->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + while($oRuleSet->next()) { + $row = $oRuleSet->getRow(); + if(isset($row['USR_UID'])) { + $usersArray[$row['USR_UID']] = $row['USR_UID']; + } + $oCase->deleteDelegation($row['APP_UID']); + } + + foreach($usersArray as $value) { + $oAppCache = new AppCacheView(); + $aCount = $oAppCache->getAllCounters( $aTypes, $value ); + $newData = array( + 'USR_UID' => $value, + 'USR_TOTAL_INBOX' => $aCount['to_do'], + 'USR_TOTAL_DRAFT' => $aCount['draft'], + 'USR_TOTAL_CANCELLED' => $aCount['cancelled'], + 'USR_TOTAL_PARTICIPATED' => $aCount['sent'], + 'USR_TOTAL_PAUSED' => $aCount['paused'], + 'USR_TOTAL_COMPLETED' => $aCount['completed'], + 'USR_TOTAL_UNASSIGNED' => $aCount['selfservice'] + ); + $users->update($newData); + } + } } diff --git a/workflow/engine/classes/model/map/AppDocumentMapBuilder.php b/workflow/engine/classes/model/map/AppDocumentMapBuilder.php index 91955cded..47df4b868 100755 --- a/workflow/engine/classes/model/map/AppDocumentMapBuilder.php +++ b/workflow/engine/classes/model/map/AppDocumentMapBuilder.php @@ -97,6 +97,10 @@ class AppDocumentMapBuilder $tMap->addColumn('APP_DOC_DRIVE_DOWNLOAD', 'AppDocDriveDownload', 'string', CreoleTypes::LONGVARCHAR, false, null); + $tMap->addColumn('SYNC_WITH_DRIVE', 'SyncWithDrive', 'string', CreoleTypes::VARCHAR, true, 32); + + $tMap->addColumn('SYNC_PERMISSIONS', 'SyncPermissions', 'string', CreoleTypes::LONGVARCHAR, false, null); + $tMap->addValidator('APP_DOC_UID', 'maxLength', 'propel.validator.MaxLengthValidator', '32', 'Application Document UID can be no larger than 32 in size'); $tMap->addValidator('APP_DOC_UID', 'required', 'propel.validator.RequiredValidator', '', 'Application Document UID is required.'); @@ -127,6 +131,10 @@ class AppDocumentMapBuilder $tMap->addValidator('APP_DOC_STATUS', 'required', 'propel.validator.RequiredValidator', '', 'Application Document Status is required.'); + $tMap->addValidator('SYNC_WITH_DRIVE', 'validValues', 'propel.validator.ValidValuesValidator', 'SYNCHRONIZED|UNSYNCHRONIZED|NO_EXIST_FILE_PM', 'Please select a valid type.'); + + $tMap->addValidator('SYNC_WITH_DRIVE', 'required', 'propel.validator.RequiredValidator', '', 'Type is required.'); + } // doBuild() } // AppDocumentMapBuilder diff --git a/workflow/engine/classes/model/map/GmailRelabelingMapBuilder.php b/workflow/engine/classes/model/map/GmailRelabelingMapBuilder.php new file mode 100644 index 000000000..02a53d1bb --- /dev/null +++ b/workflow/engine/classes/model/map/GmailRelabelingMapBuilder.php @@ -0,0 +1,86 @@ +dbMap !== null); + } + + /** + * Gets the databasemap this map builder built. + * + * @return the databasemap + */ + public function getDatabaseMap() + { + return $this->dbMap; + } + + /** + * The doBuild() method builds the DatabaseMap + * + * @return void + * @throws PropelException + */ + public function doBuild() + { + $this->dbMap = Propel::getDatabaseMap('workflow'); + + $tMap = $this->dbMap->addTable('GMAIL_RELABELING'); + $tMap->setPhpName('GmailRelabeling'); + + $tMap->setUseIdGenerator(false); + + $tMap->addPrimaryKey('LABELING_UID', 'LabelingUid', 'string', CreoleTypes::VARCHAR, true, 32); + + $tMap->addColumn('CREATE_DATE', 'CreateDate', 'int', CreoleTypes::TIMESTAMP, true, null); + + $tMap->addColumn('APP_UID', 'AppUid', 'string', CreoleTypes::VARCHAR, true, 32); + + $tMap->addColumn('DEL_INDEX', 'DelIndex', 'int', CreoleTypes::INTEGER, true, null); + + $tMap->addColumn('CURRENT_LAST_INDEX', 'CurrentLastIndex', 'int', CreoleTypes::INTEGER, true, null); + + $tMap->addColumn('UNASSIGNED', 'Unassigned', 'int', CreoleTypes::INTEGER, true, null); + + $tMap->addColumn('STATUS', 'Status', 'string', CreoleTypes::VARCHAR, true, 32); + + $tMap->addColumn('MSG_ERROR', 'MsgError', 'string', CreoleTypes::LONGVARCHAR, false, null); + + } // doBuild() + +} // GmailRelabelingMapBuilder diff --git a/workflow/engine/classes/model/map/ListParticipatedLastMapBuilder.php b/workflow/engine/classes/model/map/ListParticipatedLastMapBuilder.php index 62e4c7701..a502485a0 100644 --- a/workflow/engine/classes/model/map/ListParticipatedLastMapBuilder.php +++ b/workflow/engine/classes/model/map/ListParticipatedLastMapBuilder.php @@ -99,6 +99,8 @@ class ListParticipatedLastMapBuilder $tMap->addColumn('DEL_CURRENT_USR_LASTNAME', 'DelCurrentUsrLastname', 'string', CreoleTypes::VARCHAR, false, 50); + $tMap->addColumn('DEL_CURRENT_TAS_TITLE', 'DelCurrentTasTitle', 'string', CreoleTypes::VARCHAR, true, 255); + $tMap->addColumn('DEL_DELEGATE_DATE', 'DelDelegateDate', 'int', CreoleTypes::TIMESTAMP, true, null); $tMap->addColumn('DEL_INIT_DATE', 'DelInitDate', 'int', CreoleTypes::TIMESTAMP, false, null); diff --git a/workflow/engine/classes/model/om/BaseAppDocument.php b/workflow/engine/classes/model/om/BaseAppDocument.php index 8fff73e3a..d6b9eb56e 100755 --- a/workflow/engine/classes/model/om/BaseAppDocument.php +++ b/workflow/engine/classes/model/om/BaseAppDocument.php @@ -123,6 +123,18 @@ abstract class BaseAppDocument extends BaseObject implements Persistent */ protected $app_doc_drive_download; + /** + * The value for the sync_with_drive field. + * @var string + */ + protected $sync_with_drive = 'UNSYNCHRONIZED'; + + /** + * The value for the sync_permissions field. + * @var string + */ + protected $sync_permissions; + /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. @@ -355,6 +367,28 @@ abstract class BaseAppDocument extends BaseObject implements Persistent return $this->app_doc_drive_download; } + /** + * Get the [sync_with_drive] column value. + * + * @return string + */ + public function getSyncWithDrive() + { + + return $this->sync_with_drive; + } + + /** + * Get the [sync_permissions] column value. + * + * @return string + */ + public function getSyncPermissions() + { + + return $this->sync_permissions; + } + /** * Set the value of [app_doc_uid] column. * @@ -721,6 +755,50 @@ abstract class BaseAppDocument extends BaseObject implements Persistent } // setAppDocDriveDownload() + /** + * Set the value of [sync_with_drive] column. + * + * @param string $v new value + * @return void + */ + public function setSyncWithDrive($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->sync_with_drive !== $v || $v === 'UNSYNCHRONIZED') { + $this->sync_with_drive = $v; + $this->modifiedColumns[] = AppDocumentPeer::SYNC_WITH_DRIVE; + } + + } // setSyncWithDrive() + + /** + * Set the value of [sync_permissions] column. + * + * @param string $v new value + * @return void + */ + public function setSyncPermissions($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->sync_permissions !== $v) { + $this->sync_permissions = $v; + $this->modifiedColumns[] = AppDocumentPeer::SYNC_PERMISSIONS; + } + + } // setSyncPermissions() + /** * Hydrates (populates) the object variables with values from the database resultset. * @@ -770,12 +848,16 @@ abstract class BaseAppDocument extends BaseObject implements Persistent $this->app_doc_drive_download = $rs->getString($startcol + 15); + $this->sync_with_drive = $rs->getString($startcol + 16); + + $this->sync_permissions = $rs->getString($startcol + 17); + $this->resetModified(); $this->setNew(false); // FIXME - using NUM_COLUMNS may be clearer. - return $startcol + 16; // 16 = AppDocumentPeer::NUM_COLUMNS - AppDocumentPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 18; // 18 = AppDocumentPeer::NUM_COLUMNS - AppDocumentPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating AppDocument object", $e); @@ -1027,6 +1109,12 @@ abstract class BaseAppDocument extends BaseObject implements Persistent case 15: return $this->getAppDocDriveDownload(); break; + case 16: + return $this->getSyncWithDrive(); + break; + case 17: + return $this->getSyncPermissions(); + break; default: return null; break; @@ -1063,6 +1151,8 @@ abstract class BaseAppDocument extends BaseObject implements Persistent $keys[13] => $this->getAppDocStatusDate(), $keys[14] => $this->getAppDocFieldname(), $keys[15] => $this->getAppDocDriveDownload(), + $keys[16] => $this->getSyncWithDrive(), + $keys[17] => $this->getSyncPermissions(), ); return $result; } @@ -1142,6 +1232,12 @@ abstract class BaseAppDocument extends BaseObject implements Persistent case 15: $this->setAppDocDriveDownload($value); break; + case 16: + $this->setSyncWithDrive($value); + break; + case 17: + $this->setSyncPermissions($value); + break; } // switch() } @@ -1229,6 +1325,14 @@ abstract class BaseAppDocument extends BaseObject implements Persistent $this->setAppDocDriveDownload($arr[$keys[15]]); } + if (array_key_exists($keys[16], $arr)) { + $this->setSyncWithDrive($arr[$keys[16]]); + } + + if (array_key_exists($keys[17], $arr)) { + $this->setSyncPermissions($arr[$keys[17]]); + } + } /** @@ -1304,6 +1408,14 @@ abstract class BaseAppDocument extends BaseObject implements Persistent $criteria->add(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD, $this->app_doc_drive_download); } + if ($this->isColumnModified(AppDocumentPeer::SYNC_WITH_DRIVE)) { + $criteria->add(AppDocumentPeer::SYNC_WITH_DRIVE, $this->sync_with_drive); + } + + if ($this->isColumnModified(AppDocumentPeer::SYNC_PERMISSIONS)) { + $criteria->add(AppDocumentPeer::SYNC_PERMISSIONS, $this->sync_permissions); + } + return $criteria; } @@ -1398,6 +1510,10 @@ abstract class BaseAppDocument extends BaseObject implements Persistent $copyObj->setAppDocDriveDownload($this->app_doc_drive_download); + $copyObj->setSyncWithDrive($this->sync_with_drive); + + $copyObj->setSyncPermissions($this->sync_permissions); + $copyObj->setNew(true); diff --git a/workflow/engine/classes/model/om/BaseAppDocumentPeer.php b/workflow/engine/classes/model/om/BaseAppDocumentPeer.php index f9373766f..988637f48 100755 --- a/workflow/engine/classes/model/om/BaseAppDocumentPeer.php +++ b/workflow/engine/classes/model/om/BaseAppDocumentPeer.php @@ -25,7 +25,7 @@ abstract class BaseAppDocumentPeer const CLASS_DEFAULT = 'classes.model.AppDocument'; /** The total number of columns. */ - const NUM_COLUMNS = 16; + const NUM_COLUMNS = 18; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -79,6 +79,12 @@ abstract class BaseAppDocumentPeer /** the column name for the APP_DOC_DRIVE_DOWNLOAD field */ const APP_DOC_DRIVE_DOWNLOAD = 'APP_DOCUMENT.APP_DOC_DRIVE_DOWNLOAD'; + /** the column name for the SYNC_WITH_DRIVE field */ + const SYNC_WITH_DRIVE = 'APP_DOCUMENT.SYNC_WITH_DRIVE'; + + /** the column name for the SYNC_PERMISSIONS field */ + const SYNC_PERMISSIONS = 'APP_DOCUMENT.SYNC_PERMISSIONS'; + /** The PHP to DB Name Mapping */ private static $phpNameMap = null; @@ -90,10 +96,10 @@ abstract class BaseAppDocumentPeer * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('AppDocUid', 'DocVersion', 'AppUid', 'DelIndex', 'DocUid', 'UsrUid', 'AppDocType', 'AppDocCreateDate', 'AppDocIndex', 'FolderUid', 'AppDocPlugin', 'AppDocTags', 'AppDocStatus', 'AppDocStatusDate', 'AppDocFieldname', 'AppDocDriveDownload', ), - BasePeer::TYPE_COLNAME => array (AppDocumentPeer::APP_DOC_UID, AppDocumentPeer::DOC_VERSION, AppDocumentPeer::APP_UID, AppDocumentPeer::DEL_INDEX, AppDocumentPeer::DOC_UID, AppDocumentPeer::USR_UID, AppDocumentPeer::APP_DOC_TYPE, AppDocumentPeer::APP_DOC_CREATE_DATE, AppDocumentPeer::APP_DOC_INDEX, AppDocumentPeer::FOLDER_UID, AppDocumentPeer::APP_DOC_PLUGIN, AppDocumentPeer::APP_DOC_TAGS, AppDocumentPeer::APP_DOC_STATUS, AppDocumentPeer::APP_DOC_STATUS_DATE, AppDocumentPeer::APP_DOC_FIELDNAME, AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD, ), - BasePeer::TYPE_FIELDNAME => array ('APP_DOC_UID', 'DOC_VERSION', 'APP_UID', 'DEL_INDEX', 'DOC_UID', 'USR_UID', 'APP_DOC_TYPE', 'APP_DOC_CREATE_DATE', 'APP_DOC_INDEX', 'FOLDER_UID', 'APP_DOC_PLUGIN', 'APP_DOC_TAGS', 'APP_DOC_STATUS', 'APP_DOC_STATUS_DATE', 'APP_DOC_FIELDNAME', 'APP_DOC_DRIVE_DOWNLOAD', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) + BasePeer::TYPE_PHPNAME => array ('AppDocUid', 'DocVersion', 'AppUid', 'DelIndex', 'DocUid', 'UsrUid', 'AppDocType', 'AppDocCreateDate', 'AppDocIndex', 'FolderUid', 'AppDocPlugin', 'AppDocTags', 'AppDocStatus', 'AppDocStatusDate', 'AppDocFieldname', 'AppDocDriveDownload', 'SyncWithDrive', 'SyncPermissions', ), + BasePeer::TYPE_COLNAME => array (AppDocumentPeer::APP_DOC_UID, AppDocumentPeer::DOC_VERSION, AppDocumentPeer::APP_UID, AppDocumentPeer::DEL_INDEX, AppDocumentPeer::DOC_UID, AppDocumentPeer::USR_UID, AppDocumentPeer::APP_DOC_TYPE, AppDocumentPeer::APP_DOC_CREATE_DATE, AppDocumentPeer::APP_DOC_INDEX, AppDocumentPeer::FOLDER_UID, AppDocumentPeer::APP_DOC_PLUGIN, AppDocumentPeer::APP_DOC_TAGS, AppDocumentPeer::APP_DOC_STATUS, AppDocumentPeer::APP_DOC_STATUS_DATE, AppDocumentPeer::APP_DOC_FIELDNAME, AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD, AppDocumentPeer::SYNC_WITH_DRIVE, AppDocumentPeer::SYNC_PERMISSIONS, ), + BasePeer::TYPE_FIELDNAME => array ('APP_DOC_UID', 'DOC_VERSION', 'APP_UID', 'DEL_INDEX', 'DOC_UID', 'USR_UID', 'APP_DOC_TYPE', 'APP_DOC_CREATE_DATE', 'APP_DOC_INDEX', 'FOLDER_UID', 'APP_DOC_PLUGIN', 'APP_DOC_TAGS', 'APP_DOC_STATUS', 'APP_DOC_STATUS_DATE', 'APP_DOC_FIELDNAME', 'APP_DOC_DRIVE_DOWNLOAD', 'SYNC_WITH_DRIVE', 'SYNC_PERMISSIONS', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ) ); /** @@ -103,10 +109,10 @@ abstract class BaseAppDocumentPeer * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('AppDocUid' => 0, 'DocVersion' => 1, 'AppUid' => 2, 'DelIndex' => 3, 'DocUid' => 4, 'UsrUid' => 5, 'AppDocType' => 6, 'AppDocCreateDate' => 7, 'AppDocIndex' => 8, 'FolderUid' => 9, 'AppDocPlugin' => 10, 'AppDocTags' => 11, 'AppDocStatus' => 12, 'AppDocStatusDate' => 13, 'AppDocFieldname' => 14, 'AppDocDriveDownload' => 15, ), - BasePeer::TYPE_COLNAME => array (AppDocumentPeer::APP_DOC_UID => 0, AppDocumentPeer::DOC_VERSION => 1, AppDocumentPeer::APP_UID => 2, AppDocumentPeer::DEL_INDEX => 3, AppDocumentPeer::DOC_UID => 4, AppDocumentPeer::USR_UID => 5, AppDocumentPeer::APP_DOC_TYPE => 6, AppDocumentPeer::APP_DOC_CREATE_DATE => 7, AppDocumentPeer::APP_DOC_INDEX => 8, AppDocumentPeer::FOLDER_UID => 9, AppDocumentPeer::APP_DOC_PLUGIN => 10, AppDocumentPeer::APP_DOC_TAGS => 11, AppDocumentPeer::APP_DOC_STATUS => 12, AppDocumentPeer::APP_DOC_STATUS_DATE => 13, AppDocumentPeer::APP_DOC_FIELDNAME => 14, AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD => 15, ), - BasePeer::TYPE_FIELDNAME => array ('APP_DOC_UID' => 0, 'DOC_VERSION' => 1, 'APP_UID' => 2, 'DEL_INDEX' => 3, 'DOC_UID' => 4, 'USR_UID' => 5, 'APP_DOC_TYPE' => 6, 'APP_DOC_CREATE_DATE' => 7, 'APP_DOC_INDEX' => 8, 'FOLDER_UID' => 9, 'APP_DOC_PLUGIN' => 10, 'APP_DOC_TAGS' => 11, 'APP_DOC_STATUS' => 12, 'APP_DOC_STATUS_DATE' => 13, 'APP_DOC_FIELDNAME' => 14, 'APP_DOC_DRIVE_DOWNLOAD' => 15, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) + BasePeer::TYPE_PHPNAME => array ('AppDocUid' => 0, 'DocVersion' => 1, 'AppUid' => 2, 'DelIndex' => 3, 'DocUid' => 4, 'UsrUid' => 5, 'AppDocType' => 6, 'AppDocCreateDate' => 7, 'AppDocIndex' => 8, 'FolderUid' => 9, 'AppDocPlugin' => 10, 'AppDocTags' => 11, 'AppDocStatus' => 12, 'AppDocStatusDate' => 13, 'AppDocFieldname' => 14, 'AppDocDriveDownload' => 15, 'SyncWithDrive' => 16, 'SyncPermissions' => 17, ), + BasePeer::TYPE_COLNAME => array (AppDocumentPeer::APP_DOC_UID => 0, AppDocumentPeer::DOC_VERSION => 1, AppDocumentPeer::APP_UID => 2, AppDocumentPeer::DEL_INDEX => 3, AppDocumentPeer::DOC_UID => 4, AppDocumentPeer::USR_UID => 5, AppDocumentPeer::APP_DOC_TYPE => 6, AppDocumentPeer::APP_DOC_CREATE_DATE => 7, AppDocumentPeer::APP_DOC_INDEX => 8, AppDocumentPeer::FOLDER_UID => 9, AppDocumentPeer::APP_DOC_PLUGIN => 10, AppDocumentPeer::APP_DOC_TAGS => 11, AppDocumentPeer::APP_DOC_STATUS => 12, AppDocumentPeer::APP_DOC_STATUS_DATE => 13, AppDocumentPeer::APP_DOC_FIELDNAME => 14, AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD => 15, AppDocumentPeer::SYNC_WITH_DRIVE => 16, AppDocumentPeer::SYNC_PERMISSIONS => 17, ), + BasePeer::TYPE_FIELDNAME => array ('APP_DOC_UID' => 0, 'DOC_VERSION' => 1, 'APP_UID' => 2, 'DEL_INDEX' => 3, 'DOC_UID' => 4, 'USR_UID' => 5, 'APP_DOC_TYPE' => 6, 'APP_DOC_CREATE_DATE' => 7, 'APP_DOC_INDEX' => 8, 'FOLDER_UID' => 9, 'APP_DOC_PLUGIN' => 10, 'APP_DOC_TAGS' => 11, 'APP_DOC_STATUS' => 12, 'APP_DOC_STATUS_DATE' => 13, 'APP_DOC_FIELDNAME' => 14, 'APP_DOC_DRIVE_DOWNLOAD' => 15, 'SYNC_WITH_DRIVE' => 16, 'SYNC_PERMISSIONS' => 17, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ) ); /** @@ -239,6 +245,10 @@ abstract class BaseAppDocumentPeer $criteria->addSelectColumn(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD); + $criteria->addSelectColumn(AppDocumentPeer::SYNC_WITH_DRIVE); + + $criteria->addSelectColumn(AppDocumentPeer::SYNC_PERMISSIONS); + } const COUNT = 'COUNT(APP_DOCUMENT.APP_DOC_UID)'; @@ -611,6 +621,9 @@ abstract class BaseAppDocumentPeer if ($obj->isNew() || $obj->isColumnModified(AppDocumentPeer::APP_DOC_STATUS)) $columns[AppDocumentPeer::APP_DOC_STATUS] = $obj->getAppDocStatus(); + if ($obj->isNew() || $obj->isColumnModified(AppDocumentPeer::SYNC_WITH_DRIVE)) + $columns[AppDocumentPeer::SYNC_WITH_DRIVE] = $obj->getSyncWithDrive(); + } return BasePeer::doValidate(AppDocumentPeer::DATABASE_NAME, AppDocumentPeer::TABLE_NAME, $columns); diff --git a/workflow/engine/classes/model/om/BaseGmailRelabeling.php b/workflow/engine/classes/model/om/BaseGmailRelabeling.php new file mode 100644 index 000000000..9a5bd34e2 --- /dev/null +++ b/workflow/engine/classes/model/om/BaseGmailRelabeling.php @@ -0,0 +1,944 @@ +labeling_uid; + } + + /** + * Get the [optionally formatted] [create_date] column value. + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the integer unix timestamp will be returned. + * @return mixed Formatted date/time value as string or integer unix timestamp (if format is NULL). + * @throws PropelException - if unable to convert the date/time to timestamp. + */ + public function getCreateDate($format = 'Y-m-d H:i:s') + { + + if ($this->create_date === null || $this->create_date === '') { + return null; + } elseif (!is_int($this->create_date)) { + // a non-timestamp value was set externally, so we convert it + $ts = strtotime($this->create_date); + if ($ts === -1 || $ts === false) { + throw new PropelException("Unable to parse value of [create_date] as date/time value: " . + var_export($this->create_date, true)); + } + } else { + $ts = $this->create_date; + } + if ($format === null) { + return $ts; + } elseif (strpos($format, '%') !== false) { + return strftime($format, $ts); + } else { + return date($format, $ts); + } + } + + /** + * Get the [app_uid] column value. + * + * @return string + */ + public function getAppUid() + { + + return $this->app_uid; + } + + /** + * Get the [del_index] column value. + * + * @return int + */ + public function getDelIndex() + { + + return $this->del_index; + } + + /** + * Get the [current_last_index] column value. + * + * @return int + */ + public function getCurrentLastIndex() + { + + return $this->current_last_index; + } + + /** + * Get the [unassigned] column value. + * + * @return int + */ + public function getUnassigned() + { + + return $this->unassigned; + } + + /** + * Get the [status] column value. + * + * @return string + */ + public function getStatus() + { + + return $this->status; + } + + /** + * Get the [msg_error] column value. + * + * @return string + */ + public function getMsgError() + { + + return $this->msg_error; + } + + /** + * Set the value of [labeling_uid] column. + * + * @param string $v new value + * @return void + */ + public function setLabelingUid($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->labeling_uid !== $v) { + $this->labeling_uid = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::LABELING_UID; + } + + } // setLabelingUid() + + /** + * Set the value of [create_date] column. + * + * @param int $v new value + * @return void + */ + public function setCreateDate($v) + { + + if ($v !== null && !is_int($v)) { + $ts = strtotime($v); + //Date/time accepts null values + if ($v == '') { + $ts = null; + } + if ($ts === -1 || $ts === false) { + throw new PropelException("Unable to parse date/time value for [create_date] from input: " . + var_export($v, true)); + } + } else { + $ts = $v; + } + if ($this->create_date !== $ts) { + $this->create_date = $ts; + $this->modifiedColumns[] = GmailRelabelingPeer::CREATE_DATE; + } + + } // setCreateDate() + + /** + * Set the value of [app_uid] column. + * + * @param string $v new value + * @return void + */ + public function setAppUid($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->app_uid !== $v || $v === '') { + $this->app_uid = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::APP_UID; + } + + } // setAppUid() + + /** + * Set the value of [del_index] column. + * + * @param int $v new value + * @return void + */ + public function setDelIndex($v) + { + + // Since the native PHP type for this column is integer, + // we will cast the input value to an int (if it is not). + if ($v !== null && !is_int($v) && is_numeric($v)) { + $v = (int) $v; + } + + if ($this->del_index !== $v || $v === 0) { + $this->del_index = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::DEL_INDEX; + } + + } // setDelIndex() + + /** + * Set the value of [current_last_index] column. + * + * @param int $v new value + * @return void + */ + public function setCurrentLastIndex($v) + { + + // Since the native PHP type for this column is integer, + // we will cast the input value to an int (if it is not). + if ($v !== null && !is_int($v) && is_numeric($v)) { + $v = (int) $v; + } + + if ($this->current_last_index !== $v || $v === 0) { + $this->current_last_index = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::CURRENT_LAST_INDEX; + } + + } // setCurrentLastIndex() + + /** + * Set the value of [unassigned] column. + * + * @param int $v new value + * @return void + */ + public function setUnassigned($v) + { + + // Since the native PHP type for this column is integer, + // we will cast the input value to an int (if it is not). + if ($v !== null && !is_int($v) && is_numeric($v)) { + $v = (int) $v; + } + + if ($this->unassigned !== $v || $v === 0) { + $this->unassigned = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::UNASSIGNED; + } + + } // setUnassigned() + + /** + * Set the value of [status] column. + * + * @param string $v new value + * @return void + */ + public function setStatus($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->status !== $v || $v === 'pending') { + $this->status = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::STATUS; + } + + } // setStatus() + + /** + * Set the value of [msg_error] column. + * + * @param string $v new value + * @return void + */ + public function setMsgError($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->msg_error !== $v) { + $this->msg_error = $v; + $this->modifiedColumns[] = GmailRelabelingPeer::MSG_ERROR; + } + + } // setMsgError() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (1-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos. + * @param int $startcol 1-based offset column which indicates which restultset column to start with. + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate(ResultSet $rs, $startcol = 1) + { + try { + + $this->labeling_uid = $rs->getString($startcol + 0); + + $this->create_date = $rs->getTimestamp($startcol + 1, null); + + $this->app_uid = $rs->getString($startcol + 2); + + $this->del_index = $rs->getInt($startcol + 3); + + $this->current_last_index = $rs->getInt($startcol + 4); + + $this->unassigned = $rs->getInt($startcol + 5); + + $this->status = $rs->getString($startcol + 6); + + $this->msg_error = $rs->getString($startcol + 7); + + $this->resetModified(); + + $this->setNew(false); + + // FIXME - using NUM_COLUMNS may be clearer. + return $startcol + 8; // 8 = GmailRelabelingPeer::NUM_COLUMNS - GmailRelabelingPeer::NUM_LAZY_LOAD_COLUMNS). + + } catch (Exception $e) { + throw new PropelException("Error populating GmailRelabeling object", $e); + } + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param Connection $con + * @return void + * @throws PropelException + * @see BaseObject::setDeleted() + * @see BaseObject::isDeleted() + */ + public function delete($con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(GmailRelabelingPeer::DATABASE_NAME); + } + + try { + $con->begin(); + GmailRelabelingPeer::doDelete($this, $con); + $this->setDeleted(true); + $con->commit(); + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Stores the object in the database. If the object is new, + * it inserts it; otherwise an update is performed. This method + * wraps the doSave() worker method in a transaction. + * + * @param Connection $con + * @return int The number of rows affected by this insert/update + * @throws PropelException + * @see doSave() + */ + public function save($con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getConnection(GmailRelabelingPeer::DATABASE_NAME); + } + + try { + $con->begin(); + $affectedRows = $this->doSave($con); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Stores the object in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param Connection $con + * @return int The number of rows affected by this insert/update and any referring + * @throws PropelException + * @see save() + */ + protected function doSave($con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + + // If this object has been modified, then save it to the database. + if ($this->isModified()) { + if ($this->isNew()) { + $pk = GmailRelabelingPeer::doInsert($this, $con); + $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which + // should always be true here (even though technically + // BasePeer::doInsert() can insert multiple rows). + + $this->setNew(false); + } else { + $affectedRows += GmailRelabelingPeer::doUpdate($this, $con); + } + $this->resetModified(); // [HL] After being saved an object is no longer 'modified' + } + + $this->alreadyInSave = false; + } + return $affectedRows; + } // doSave() + + /** + * Array of ValidationFailed objects. + * @var array ValidationFailed[] + */ + protected $validationFailures = array(); + + /** + * Gets any ValidationFailed objects that resulted from last call to validate(). + * + * + * @return array ValidationFailed[] + * @see validate() + */ + public function getValidationFailures() + { + return $this->validationFailures; + } + + /** + * Validates the objects modified field values and all objects related to this table. + * + * If $columns is either a column name or an array of column names + * only those columns are validated. + * + * @param mixed $columns Column name or an array of column names. + * @return boolean Whether all columns pass validation. + * @see doValidate() + * @see getValidationFailures() + */ + public function validate($columns = null) + { + $res = $this->doValidate($columns); + if ($res === true) { + $this->validationFailures = array(); + return true; + } else { + $this->validationFailures = $res; + return false; + } + } + + /** + * This function performs the validation work for complex object models. + * + * In addition to checking the current object, all related objects will + * also be validated. If all pass then true is returned; otherwise + * an aggreagated array of ValidationFailed objects will be returned. + * + * @param array $columns Array of column names to validate. + * @return mixed true if all validations pass; + array of ValidationFailed objects otherwise. + */ + protected function doValidate($columns = null) + { + if (!$this->alreadyInValidation) { + $this->alreadyInValidation = true; + $retval = null; + + $failureMap = array(); + + + if (($retval = GmailRelabelingPeer::doValidate($this, $columns)) !== true) { + $failureMap = array_merge($failureMap, $retval); + } + + + + $this->alreadyInValidation = false; + } + + return (!empty($failureMap) ? $failureMap : true); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return mixed Value of field. + */ + public function getByName($name, $type = BasePeer::TYPE_PHPNAME) + { + $pos = GmailRelabelingPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->getByPosition($pos); + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch($pos) { + case 0: + return $this->getLabelingUid(); + break; + case 1: + return $this->getCreateDate(); + break; + case 2: + return $this->getAppUid(); + break; + case 3: + return $this->getDelIndex(); + break; + case 4: + return $this->getCurrentLastIndex(); + break; + case 5: + return $this->getUnassigned(); + break; + case 6: + return $this->getStatus(); + break; + case 7: + return $this->getMsgError(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType One of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = BasePeer::TYPE_PHPNAME) + { + $keys = GmailRelabelingPeer::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getLabelingUid(), + $keys[1] => $this->getCreateDate(), + $keys[2] => $this->getAppUid(), + $keys[3] => $this->getDelIndex(), + $keys[4] => $this->getCurrentLastIndex(), + $keys[5] => $this->getUnassigned(), + $keys[6] => $this->getStatus(), + $keys[7] => $this->getMsgError(), + ); + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name peer name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return void + */ + public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) + { + $pos = GmailRelabelingPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch($pos) { + case 0: + $this->setLabelingUid($value); + break; + case 1: + $this->setCreateDate($value); + break; + case 2: + $this->setAppUid($value); + break; + case 3: + $this->setDelIndex($value); + break; + case 4: + $this->setCurrentLastIndex($value); + break; + case 5: + $this->setUnassigned($value); + break; + case 6: + $this->setStatus($value); + break; + case 7: + $this->setMsgError($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, + * TYPE_NUM. The default key type is the column's phpname (e.g. 'authorId') + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) + { + $keys = GmailRelabelingPeer::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) { + $this->setLabelingUid($arr[$keys[0]]); + } + + if (array_key_exists($keys[1], $arr)) { + $this->setCreateDate($arr[$keys[1]]); + } + + if (array_key_exists($keys[2], $arr)) { + $this->setAppUid($arr[$keys[2]]); + } + + if (array_key_exists($keys[3], $arr)) { + $this->setDelIndex($arr[$keys[3]]); + } + + if (array_key_exists($keys[4], $arr)) { + $this->setCurrentLastIndex($arr[$keys[4]]); + } + + if (array_key_exists($keys[5], $arr)) { + $this->setUnassigned($arr[$keys[5]]); + } + + if (array_key_exists($keys[6], $arr)) { + $this->setStatus($arr[$keys[6]]); + } + + if (array_key_exists($keys[7], $arr)) { + $this->setMsgError($arr[$keys[7]]); + } + + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(GmailRelabelingPeer::DATABASE_NAME); + + if ($this->isColumnModified(GmailRelabelingPeer::LABELING_UID)) { + $criteria->add(GmailRelabelingPeer::LABELING_UID, $this->labeling_uid); + } + + if ($this->isColumnModified(GmailRelabelingPeer::CREATE_DATE)) { + $criteria->add(GmailRelabelingPeer::CREATE_DATE, $this->create_date); + } + + if ($this->isColumnModified(GmailRelabelingPeer::APP_UID)) { + $criteria->add(GmailRelabelingPeer::APP_UID, $this->app_uid); + } + + if ($this->isColumnModified(GmailRelabelingPeer::DEL_INDEX)) { + $criteria->add(GmailRelabelingPeer::DEL_INDEX, $this->del_index); + } + + if ($this->isColumnModified(GmailRelabelingPeer::CURRENT_LAST_INDEX)) { + $criteria->add(GmailRelabelingPeer::CURRENT_LAST_INDEX, $this->current_last_index); + } + + if ($this->isColumnModified(GmailRelabelingPeer::UNASSIGNED)) { + $criteria->add(GmailRelabelingPeer::UNASSIGNED, $this->unassigned); + } + + if ($this->isColumnModified(GmailRelabelingPeer::STATUS)) { + $criteria->add(GmailRelabelingPeer::STATUS, $this->status); + } + + if ($this->isColumnModified(GmailRelabelingPeer::MSG_ERROR)) { + $criteria->add(GmailRelabelingPeer::MSG_ERROR, $this->msg_error); + } + + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(GmailRelabelingPeer::DATABASE_NAME); + + $criteria->add(GmailRelabelingPeer::LABELING_UID, $this->labeling_uid); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return string + */ + public function getPrimaryKey() + { + return $this->getLabelingUid(); + } + + /** + * Generic method to set the primary key (labeling_uid column). + * + * @param string $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setLabelingUid($key); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of GmailRelabeling (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false) + { + + $copyObj->setCreateDate($this->create_date); + + $copyObj->setAppUid($this->app_uid); + + $copyObj->setDelIndex($this->del_index); + + $copyObj->setCurrentLastIndex($this->current_last_index); + + $copyObj->setUnassigned($this->unassigned); + + $copyObj->setStatus($this->status); + + $copyObj->setMsgError($this->msg_error); + + + $copyObj->setNew(true); + + $copyObj->setLabelingUid(NULL); // this is a pkey column, so set to default value + + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return GmailRelabeling Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + return $copyObj; + } + + /** + * Returns a peer instance associated with this om. + * + * Since Peer classes are not to have any instance attributes, this method returns the + * same instance for all member of this class. The method could therefore + * be static, but this would prevent one from overriding the behavior. + * + * @return GmailRelabelingPeer + */ + public function getPeer() + { + if (self::$peer === null) { + self::$peer = new GmailRelabelingPeer(); + } + return self::$peer; + } +} + diff --git a/workflow/engine/classes/model/om/BaseGmailRelabelingPeer.php b/workflow/engine/classes/model/om/BaseGmailRelabelingPeer.php new file mode 100644 index 000000000..ee23b25a1 --- /dev/null +++ b/workflow/engine/classes/model/om/BaseGmailRelabelingPeer.php @@ -0,0 +1,602 @@ + array ('LabelingUid', 'CreateDate', 'AppUid', 'DelIndex', 'CurrentLastIndex', 'Unassigned', 'Status', 'MsgError', ), + BasePeer::TYPE_COLNAME => array (GmailRelabelingPeer::LABELING_UID, GmailRelabelingPeer::CREATE_DATE, GmailRelabelingPeer::APP_UID, GmailRelabelingPeer::DEL_INDEX, GmailRelabelingPeer::CURRENT_LAST_INDEX, GmailRelabelingPeer::UNASSIGNED, GmailRelabelingPeer::STATUS, GmailRelabelingPeer::MSG_ERROR, ), + BasePeer::TYPE_FIELDNAME => array ('LABELING_UID', 'CREATE_DATE', 'APP_UID', 'DEL_INDEX', 'CURRENT_LAST_INDEX', 'UNASSIGNED', 'STATUS', 'MSG_ERROR', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 + */ + private static $fieldKeys = array ( + BasePeer::TYPE_PHPNAME => array ('LabelingUid' => 0, 'CreateDate' => 1, 'AppUid' => 2, 'DelIndex' => 3, 'CurrentLastIndex' => 4, 'Unassigned' => 5, 'Status' => 6, 'MsgError' => 7, ), + BasePeer::TYPE_COLNAME => array (GmailRelabelingPeer::LABELING_UID => 0, GmailRelabelingPeer::CREATE_DATE => 1, GmailRelabelingPeer::APP_UID => 2, GmailRelabelingPeer::DEL_INDEX => 3, GmailRelabelingPeer::CURRENT_LAST_INDEX => 4, GmailRelabelingPeer::UNASSIGNED => 5, GmailRelabelingPeer::STATUS => 6, GmailRelabelingPeer::MSG_ERROR => 7, ), + BasePeer::TYPE_FIELDNAME => array ('LABELING_UID' => 0, 'CREATE_DATE' => 1, 'APP_UID' => 2, 'DEL_INDEX' => 3, 'CURRENT_LAST_INDEX' => 4, 'UNASSIGNED' => 5, 'STATUS' => 6, 'MSG_ERROR' => 7, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, ) + ); + + /** + * @return MapBuilder the map builder for this peer + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getMapBuilder() + { + include_once 'classes/model/map/GmailRelabelingMapBuilder.php'; + return BasePeer::getMapBuilder('classes.model.map.GmailRelabelingMapBuilder'); + } + /** + * Gets a map (hash) of PHP names to DB column names. + * + * @return array The PHP to DB name map for this peer + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @deprecated Use the getFieldNames() and translateFieldName() methods instead of this. + */ + public static function getPhpNameMap() + { + if (self::$phpNameMap === null) { + $map = GmailRelabelingPeer::getTableMap(); + $columns = $map->getColumns(); + $nameMap = array(); + foreach ($columns as $column) { + $nameMap[$column->getPhpName()] = $column->getColumnName(); + } + self::$phpNameMap = $nameMap; + } + return self::$phpNameMap; + } + /** + * Translates a fieldname to another type + * + * @param string $name field name + * @param string $fromType One of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @param string $toType One of the class type constants + * @return string translated name of the field. + */ + static public function translateFieldName($name, $fromType, $toType) + { + $toNames = self::getFieldNames($toType); + $key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null; + if ($key === null) { + throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true)); + } + return $toNames[$key]; + } + + /** + * Returns an array of of field names. + * + * @param string $type The type of fieldnames to return: + * One of the class type constants TYPE_PHPNAME, + * TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM + * @return array A list of field names + */ + + static public function getFieldNames($type = BasePeer::TYPE_PHPNAME) + { + if (!array_key_exists($type, self::$fieldNames)) { + throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.'); + } + return self::$fieldNames[$type]; + } + + /** + * Convenience method which changes table.column to alias.column. + * + * Using this method you can maintain SQL abstraction while using column aliases. + * + * $c->addAlias("alias1", TablePeer::TABLE_NAME); + * $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN); + * + * @param string $alias The alias for the current table. + * @param string $column The column name for current table. (i.e. GmailRelabelingPeer::COLUMN_NAME). + * @return string + */ + public static function alias($alias, $column) + { + return str_replace(GmailRelabelingPeer::TABLE_NAME.'.', $alias.'.', $column); + } + + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param criteria object containing the columns to add. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria) + { + + $criteria->addSelectColumn(GmailRelabelingPeer::LABELING_UID); + + $criteria->addSelectColumn(GmailRelabelingPeer::CREATE_DATE); + + $criteria->addSelectColumn(GmailRelabelingPeer::APP_UID); + + $criteria->addSelectColumn(GmailRelabelingPeer::DEL_INDEX); + + $criteria->addSelectColumn(GmailRelabelingPeer::CURRENT_LAST_INDEX); + + $criteria->addSelectColumn(GmailRelabelingPeer::UNASSIGNED); + + $criteria->addSelectColumn(GmailRelabelingPeer::STATUS); + + $criteria->addSelectColumn(GmailRelabelingPeer::MSG_ERROR); + + } + + const COUNT = 'COUNT(GMAIL_RELABELING.LABELING_UID)'; + const COUNT_DISTINCT = 'COUNT(DISTINCT GMAIL_RELABELING.LABELING_UID)'; + + /** + * Returns the number of rows matching criteria. + * + * @param Criteria $criteria + * @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria). + * @param Connection $con + * @return int Number of matching rows. + */ + public static function doCount(Criteria $criteria, $distinct = false, $con = null) + { + // we're going to modify criteria, so copy it first + $criteria = clone $criteria; + + // clear out anything that might confuse the ORDER BY clause + $criteria->clearSelectColumns()->clearOrderByColumns(); + if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { + $criteria->addSelectColumn(GmailRelabelingPeer::COUNT_DISTINCT); + } else { + $criteria->addSelectColumn(GmailRelabelingPeer::COUNT); + } + + // just in case we're grouping: add those columns to the select statement + foreach ($criteria->getGroupByColumns() as $column) { + $criteria->addSelectColumn($column); + } + + $rs = GmailRelabelingPeer::doSelectRS($criteria, $con); + if ($rs->next()) { + return $rs->getInt(1); + } else { + // no rows returned; we infer that means 0 matches. + return 0; + } + } + /** + * Method to select one object from the DB. + * + * @param Criteria $criteria object used to create the SELECT statement. + * @param Connection $con + * @return GmailRelabeling + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelectOne(Criteria $criteria, $con = null) + { + $critcopy = clone $criteria; + $critcopy->setLimit(1); + $objects = GmailRelabelingPeer::doSelect($critcopy, $con); + if ($objects) { + return $objects[0]; + } + return null; + } + /** + * Method to do selects. + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param Connection $con + * @return array Array of selected Objects + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doSelect(Criteria $criteria, $con = null) + { + return GmailRelabelingPeer::populateObjects(GmailRelabelingPeer::doSelectRS($criteria, $con)); + } + /** + * Prepares the Criteria object and uses the parent doSelect() + * method to get a ResultSet. + * + * Use this method directly if you want to just get the resultset + * (instead of an array of objects). + * + * @param Criteria $criteria The Criteria object used to build the SELECT statement. + * @param Connection $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return ResultSet The resultset object with numerically-indexed fields. + * @see BasePeer::doSelect() + */ + public static function doSelectRS(Criteria $criteria, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + if (!$criteria->getSelectColumns()) { + $criteria = clone $criteria; + GmailRelabelingPeer::addSelectColumns($criteria); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + // BasePeer returns a Creole ResultSet, set to return + // rows indexed numerically. + return BasePeer::doSelect($criteria, $con); + } + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(ResultSet $rs) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = GmailRelabelingPeer::getOMClass(); + $cls = Propel::import($cls); + // populate the object(s) + while ($rs->next()) { + + $obj = new $cls(); + $obj->hydrate($rs); + $results[] = $obj; + + } + return $results; + } + /** + * Returns the TableMap related to this peer. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME); + } + + /** + * The class that the Peer will make instances of. + * + * This uses a dot-path notation which is tranalted into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @return string path.to.ClassName + */ + public static function getOMClass() + { + return GmailRelabelingPeer::CLASS_DEFAULT; + } + + /** + * Method perform an INSERT on the database, given a GmailRelabeling or Criteria object. + * + * @param mixed $values Criteria or GmailRelabeling object containing data that is used to create the INSERT statement. + * @param Connection $con the connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($values, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } else { + $criteria = $values->buildCriteria(); // build Criteria from GmailRelabeling object + } + + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->begin(); + $pk = BasePeer::doInsert($criteria, $con); + $con->commit(); + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + + return $pk; + } + + /** + * Method perform an UPDATE on the database, given a GmailRelabeling or Criteria object. + * + * @param mixed $values Criteria or GmailRelabeling object containing data create the UPDATE statement. + * @param Connection $con The connection to use (specify Connection exert more control over transactions). + * @return int The number of affected rows (if supported by underlying database driver). + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doUpdate($values, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + $selectCriteria = new Criteria(self::DATABASE_NAME); + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + + $comparison = $criteria->getComparison(GmailRelabelingPeer::LABELING_UID); + $selectCriteria->add(GmailRelabelingPeer::LABELING_UID, $criteria->remove(GmailRelabelingPeer::LABELING_UID), $comparison); + + } else { + $criteria = $values->buildCriteria(); // gets full criteria + $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) + } + + // set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + return BasePeer::doUpdate($selectCriteria, $criteria, $con); + } + + /** + * Method to DELETE all rows from the GMAIL_RELABELING table. + * + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll($con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->begin(); + $affectedRows += BasePeer::doDeleteAll(GmailRelabelingPeer::TABLE_NAME, $con); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Method perform a DELETE on the database, given a GmailRelabeling or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or GmailRelabeling object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param Connection $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + * This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(GmailRelabelingPeer::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + $criteria = clone $values; // rename for clarity + } elseif ($values instanceof GmailRelabeling) { + + $criteria = $values->buildPkeyCriteria(); + } else { + // it must be the primary key + $criteria = new Criteria(self::DATABASE_NAME); + $criteria->add(GmailRelabelingPeer::LABELING_UID, (array) $values, Criteria::IN); + } + + // Set the correct dbName + $criteria->setDbName(self::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->begin(); + + $affectedRows += BasePeer::doDelete($criteria, $con); + $con->commit(); + return $affectedRows; + } catch (PropelException $e) { + $con->rollback(); + throw $e; + } + } + + /** + * Validates all modified columns of given GmailRelabeling object. + * If parameter $columns is either a single column name or an array of column names + * than only those columns are validated. + * + * NOTICE: This does not apply to primary or foreign keys for now. + * + * @param GmailRelabeling $obj The object to validate. + * @param mixed $cols Column name or array of column names. + * + * @return mixed TRUE if all columns are valid or the error message of the first invalid column. + */ + public static function doValidate(GmailRelabeling $obj, $cols = null) + { + $columns = array(); + + if ($cols) { + $dbMap = Propel::getDatabaseMap(GmailRelabelingPeer::DATABASE_NAME); + $tableMap = $dbMap->getTable(GmailRelabelingPeer::TABLE_NAME); + + if (! is_array($cols)) { + $cols = array($cols); + } + + foreach ($cols as $colName) { + if ($tableMap->containsColumn($colName)) { + $get = 'get' . $tableMap->getColumn($colName)->getPhpName(); + $columns[$colName] = $obj->$get(); + } + } + } else { + + } + + return BasePeer::doValidate(GmailRelabelingPeer::DATABASE_NAME, GmailRelabelingPeer::TABLE_NAME, $columns); + } + + /** + * Retrieve a single object by pkey. + * + * @param mixed $pk the primary key. + * @param Connection $con the connection to use + * @return GmailRelabeling + */ + public static function retrieveByPK($pk, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + $criteria = new Criteria(GmailRelabelingPeer::DATABASE_NAME); + + $criteria->add(GmailRelabelingPeer::LABELING_UID, $pk); + + + $v = GmailRelabelingPeer::doSelect($criteria, $con); + + return !empty($v) > 0 ? $v[0] : null; + } + + /** + * Retrieve multiple objects by pkey. + * + * @param array $pks List of primary keys + * @param Connection $con the connection to use + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function retrieveByPKs($pks, $con = null) + { + if ($con === null) { + $con = Propel::getConnection(self::DATABASE_NAME); + } + + $objs = null; + if (empty($pks)) { + $objs = array(); + } else { + $criteria = new Criteria(); + $criteria->add(GmailRelabelingPeer::LABELING_UID, $pks, Criteria::IN); + $objs = GmailRelabelingPeer::doSelect($criteria, $con); + } + return $objs; + } +} + + +// static code to register the map builder for this Peer with the main Propel class +if (Propel::isInit()) { + // the MapBuilder classes register themselves with Propel during initialization + // so we need to load them here. + try { + BaseGmailRelabelingPeer::getMapBuilder(); + } catch (Exception $e) { + Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR); + } +} else { + // even if Propel is not yet initialized, the map builder class can be registered + // now and then it will be loaded when Propel initializes. + require_once 'classes/model/map/GmailRelabelingMapBuilder.php'; + Propel::registerMapBuilder('classes.model.map.GmailRelabelingMapBuilder'); +} + diff --git a/workflow/engine/classes/model/om/BaseListParticipatedLast.php b/workflow/engine/classes/model/om/BaseListParticipatedLast.php index 4d7e2e499..2a9fa63a2 100644 --- a/workflow/engine/classes/model/om/BaseListParticipatedLast.php +++ b/workflow/engine/classes/model/om/BaseListParticipatedLast.php @@ -129,6 +129,12 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent */ protected $del_current_usr_lastname = ''; + /** + * The value for the del_current_tas_title field. + * @var string + */ + protected $del_current_tas_title = ''; + /** * The value for the del_delegate_date field. * @var int @@ -360,6 +366,17 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent return $this->del_current_usr_lastname; } + /** + * Get the [del_current_tas_title] column value. + * + * @return string + */ + public function getDelCurrentTasTitle() + { + + return $this->del_current_tas_title; + } + /** * Get the [optionally formatted] [del_delegate_date] column value. * @@ -852,6 +869,28 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent } // setDelCurrentUsrLastname() + /** + * Set the value of [del_current_tas_title] column. + * + * @param string $v new value + * @return void + */ + public function setDelCurrentTasTitle($v) + { + + // Since the native PHP type for this column is string, + // we will cast the input to a string (if it is not). + if ($v !== null && !is_string($v)) { + $v = (string) $v; + } + + if ($this->del_current_tas_title !== $v || $v === '') { + $this->del_current_tas_title = $v; + $this->modifiedColumns[] = ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE; + } + + } // setDelCurrentTasTitle() + /** * Set the value of [del_delegate_date] column. * @@ -1034,22 +1073,24 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent $this->del_current_usr_lastname = $rs->getString($startcol + 16); - $this->del_delegate_date = $rs->getTimestamp($startcol + 17, null); + $this->del_current_tas_title = $rs->getString($startcol + 17); - $this->del_init_date = $rs->getTimestamp($startcol + 18, null); + $this->del_delegate_date = $rs->getTimestamp($startcol + 18, null); - $this->del_due_date = $rs->getTimestamp($startcol + 19, null); + $this->del_init_date = $rs->getTimestamp($startcol + 19, null); - $this->del_priority = $rs->getString($startcol + 20); + $this->del_due_date = $rs->getTimestamp($startcol + 20, null); - $this->del_thread_status = $rs->getString($startcol + 21); + $this->del_priority = $rs->getString($startcol + 21); + + $this->del_thread_status = $rs->getString($startcol + 22); $this->resetModified(); $this->setNew(false); // FIXME - using NUM_COLUMNS may be clearer. - return $startcol + 22; // 22 = ListParticipatedLastPeer::NUM_COLUMNS - ListParticipatedLastPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 23; // 23 = ListParticipatedLastPeer::NUM_COLUMNS - ListParticipatedLastPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating ListParticipatedLast object", $e); @@ -1305,18 +1346,21 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent return $this->getDelCurrentUsrLastname(); break; case 17: - return $this->getDelDelegateDate(); + return $this->getDelCurrentTasTitle(); break; case 18: - return $this->getDelInitDate(); + return $this->getDelDelegateDate(); break; case 19: - return $this->getDelDueDate(); + return $this->getDelInitDate(); break; case 20: - return $this->getDelPriority(); + return $this->getDelDueDate(); break; case 21: + return $this->getDelPriority(); + break; + case 22: return $this->getDelThreadStatus(); break; default: @@ -1356,11 +1400,12 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent $keys[14] => $this->getDelCurrentUsrUsername(), $keys[15] => $this->getDelCurrentUsrFirstname(), $keys[16] => $this->getDelCurrentUsrLastname(), - $keys[17] => $this->getDelDelegateDate(), - $keys[18] => $this->getDelInitDate(), - $keys[19] => $this->getDelDueDate(), - $keys[20] => $this->getDelPriority(), - $keys[21] => $this->getDelThreadStatus(), + $keys[17] => $this->getDelCurrentTasTitle(), + $keys[18] => $this->getDelDelegateDate(), + $keys[19] => $this->getDelInitDate(), + $keys[20] => $this->getDelDueDate(), + $keys[21] => $this->getDelPriority(), + $keys[22] => $this->getDelThreadStatus(), ); return $result; } @@ -1444,18 +1489,21 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent $this->setDelCurrentUsrLastname($value); break; case 17: - $this->setDelDelegateDate($value); + $this->setDelCurrentTasTitle($value); break; case 18: - $this->setDelInitDate($value); + $this->setDelDelegateDate($value); break; case 19: - $this->setDelDueDate($value); + $this->setDelInitDate($value); break; case 20: - $this->setDelPriority($value); + $this->setDelDueDate($value); break; case 21: + $this->setDelPriority($value); + break; + case 22: $this->setDelThreadStatus($value); break; } // switch() @@ -1550,23 +1598,27 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent } if (array_key_exists($keys[17], $arr)) { - $this->setDelDelegateDate($arr[$keys[17]]); + $this->setDelCurrentTasTitle($arr[$keys[17]]); } if (array_key_exists($keys[18], $arr)) { - $this->setDelInitDate($arr[$keys[18]]); + $this->setDelDelegateDate($arr[$keys[18]]); } if (array_key_exists($keys[19], $arr)) { - $this->setDelDueDate($arr[$keys[19]]); + $this->setDelInitDate($arr[$keys[19]]); } if (array_key_exists($keys[20], $arr)) { - $this->setDelPriority($arr[$keys[20]]); + $this->setDelDueDate($arr[$keys[20]]); } if (array_key_exists($keys[21], $arr)) { - $this->setDelThreadStatus($arr[$keys[21]]); + $this->setDelPriority($arr[$keys[21]]); + } + + if (array_key_exists($keys[22], $arr)) { + $this->setDelThreadStatus($arr[$keys[22]]); } } @@ -1648,6 +1700,10 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent $criteria->add(ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME, $this->del_current_usr_lastname); } + if ($this->isColumnModified(ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE)) { + $criteria->add(ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE, $this->del_current_tas_title); + } + if ($this->isColumnModified(ListParticipatedLastPeer::DEL_DELEGATE_DATE)) { $criteria->add(ListParticipatedLastPeer::DEL_DELEGATE_DATE, $this->del_delegate_date); } @@ -1767,6 +1823,8 @@ abstract class BaseListParticipatedLast extends BaseObject implements Persistent $copyObj->setDelCurrentUsrLastname($this->del_current_usr_lastname); + $copyObj->setDelCurrentTasTitle($this->del_current_tas_title); + $copyObj->setDelDelegateDate($this->del_delegate_date); $copyObj->setDelInitDate($this->del_init_date); diff --git a/workflow/engine/classes/model/om/BaseListParticipatedLastPeer.php b/workflow/engine/classes/model/om/BaseListParticipatedLastPeer.php index 26fe8f6f3..04abd7170 100644 --- a/workflow/engine/classes/model/om/BaseListParticipatedLastPeer.php +++ b/workflow/engine/classes/model/om/BaseListParticipatedLastPeer.php @@ -25,7 +25,7 @@ abstract class BaseListParticipatedLastPeer const CLASS_DEFAULT = 'classes.model.ListParticipatedLast'; /** The total number of columns. */ - const NUM_COLUMNS = 22; + const NUM_COLUMNS = 23; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -82,6 +82,9 @@ abstract class BaseListParticipatedLastPeer /** the column name for the DEL_CURRENT_USR_LASTNAME field */ const DEL_CURRENT_USR_LASTNAME = 'LIST_PARTICIPATED_LAST.DEL_CURRENT_USR_LASTNAME'; + /** the column name for the DEL_CURRENT_TAS_TITLE field */ + const DEL_CURRENT_TAS_TITLE = 'LIST_PARTICIPATED_LAST.DEL_CURRENT_TAS_TITLE'; + /** the column name for the DEL_DELEGATE_DATE field */ const DEL_DELEGATE_DATE = 'LIST_PARTICIPATED_LAST.DEL_DELEGATE_DATE'; @@ -108,10 +111,10 @@ abstract class BaseListParticipatedLastPeer * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('AppUid', 'UsrUid', 'DelIndex', 'TasUid', 'ProUid', 'AppNumber', 'AppTitle', 'AppProTitle', 'AppTasTitle', 'AppStatus', 'DelPreviousUsrUid', 'DelPreviousUsrUsername', 'DelPreviousUsrFirstname', 'DelPreviousUsrLastname', 'DelCurrentUsrUsername', 'DelCurrentUsrFirstname', 'DelCurrentUsrLastname', 'DelDelegateDate', 'DelInitDate', 'DelDueDate', 'DelPriority', 'DelThreadStatus', ), - BasePeer::TYPE_COLNAME => array (ListParticipatedLastPeer::APP_UID, ListParticipatedLastPeer::USR_UID, ListParticipatedLastPeer::DEL_INDEX, ListParticipatedLastPeer::TAS_UID, ListParticipatedLastPeer::PRO_UID, ListParticipatedLastPeer::APP_NUMBER, ListParticipatedLastPeer::APP_TITLE, ListParticipatedLastPeer::APP_PRO_TITLE, ListParticipatedLastPeer::APP_TAS_TITLE, ListParticipatedLastPeer::APP_STATUS, ListParticipatedLastPeer::DEL_PREVIOUS_USR_UID, ListParticipatedLastPeer::DEL_PREVIOUS_USR_USERNAME, ListParticipatedLastPeer::DEL_PREVIOUS_USR_FIRSTNAME, ListParticipatedLastPeer::DEL_PREVIOUS_USR_LASTNAME, ListParticipatedLastPeer::DEL_CURRENT_USR_USERNAME, ListParticipatedLastPeer::DEL_CURRENT_USR_FIRSTNAME, ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME, ListParticipatedLastPeer::DEL_DELEGATE_DATE, ListParticipatedLastPeer::DEL_INIT_DATE, ListParticipatedLastPeer::DEL_DUE_DATE, ListParticipatedLastPeer::DEL_PRIORITY, ListParticipatedLastPeer::DEL_THREAD_STATUS, ), - BasePeer::TYPE_FIELDNAME => array ('APP_UID', 'USR_UID', 'DEL_INDEX', 'TAS_UID', 'PRO_UID', 'APP_NUMBER', 'APP_TITLE', 'APP_PRO_TITLE', 'APP_TAS_TITLE', 'APP_STATUS', 'DEL_PREVIOUS_USR_UID', 'DEL_PREVIOUS_USR_USERNAME', 'DEL_PREVIOUS_USR_FIRSTNAME', 'DEL_PREVIOUS_USR_LASTNAME', 'DEL_CURRENT_USR_USERNAME', 'DEL_CURRENT_USR_FIRSTNAME', 'DEL_CURRENT_USR_LASTNAME', 'DEL_DELEGATE_DATE', 'DEL_INIT_DATE', 'DEL_DUE_DATE', 'DEL_PRIORITY', 'DEL_THREAD_STATUS', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, ) + BasePeer::TYPE_PHPNAME => array ('AppUid', 'UsrUid', 'DelIndex', 'TasUid', 'ProUid', 'AppNumber', 'AppTitle', 'AppProTitle', 'AppTasTitle', 'AppStatus', 'DelPreviousUsrUid', 'DelPreviousUsrUsername', 'DelPreviousUsrFirstname', 'DelPreviousUsrLastname', 'DelCurrentUsrUsername', 'DelCurrentUsrFirstname', 'DelCurrentUsrLastname', 'DelCurrentTasTitle', 'DelDelegateDate', 'DelInitDate', 'DelDueDate', 'DelPriority', 'DelThreadStatus', ), + BasePeer::TYPE_COLNAME => array (ListParticipatedLastPeer::APP_UID, ListParticipatedLastPeer::USR_UID, ListParticipatedLastPeer::DEL_INDEX, ListParticipatedLastPeer::TAS_UID, ListParticipatedLastPeer::PRO_UID, ListParticipatedLastPeer::APP_NUMBER, ListParticipatedLastPeer::APP_TITLE, ListParticipatedLastPeer::APP_PRO_TITLE, ListParticipatedLastPeer::APP_TAS_TITLE, ListParticipatedLastPeer::APP_STATUS, ListParticipatedLastPeer::DEL_PREVIOUS_USR_UID, ListParticipatedLastPeer::DEL_PREVIOUS_USR_USERNAME, ListParticipatedLastPeer::DEL_PREVIOUS_USR_FIRSTNAME, ListParticipatedLastPeer::DEL_PREVIOUS_USR_LASTNAME, ListParticipatedLastPeer::DEL_CURRENT_USR_USERNAME, ListParticipatedLastPeer::DEL_CURRENT_USR_FIRSTNAME, ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME, ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE, ListParticipatedLastPeer::DEL_DELEGATE_DATE, ListParticipatedLastPeer::DEL_INIT_DATE, ListParticipatedLastPeer::DEL_DUE_DATE, ListParticipatedLastPeer::DEL_PRIORITY, ListParticipatedLastPeer::DEL_THREAD_STATUS, ), + BasePeer::TYPE_FIELDNAME => array ('APP_UID', 'USR_UID', 'DEL_INDEX', 'TAS_UID', 'PRO_UID', 'APP_NUMBER', 'APP_TITLE', 'APP_PRO_TITLE', 'APP_TAS_TITLE', 'APP_STATUS', 'DEL_PREVIOUS_USR_UID', 'DEL_PREVIOUS_USR_USERNAME', 'DEL_PREVIOUS_USR_FIRSTNAME', 'DEL_PREVIOUS_USR_LASTNAME', 'DEL_CURRENT_USR_USERNAME', 'DEL_CURRENT_USR_FIRSTNAME', 'DEL_CURRENT_USR_LASTNAME', 'DEL_CURRENT_TAS_TITLE', 'DEL_DELEGATE_DATE', 'DEL_INIT_DATE', 'DEL_DUE_DATE', 'DEL_PRIORITY', 'DEL_THREAD_STATUS', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, ) ); /** @@ -121,10 +124,10 @@ abstract class BaseListParticipatedLastPeer * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('AppUid' => 0, 'UsrUid' => 1, 'DelIndex' => 2, 'TasUid' => 3, 'ProUid' => 4, 'AppNumber' => 5, 'AppTitle' => 6, 'AppProTitle' => 7, 'AppTasTitle' => 8, 'AppStatus' => 9, 'DelPreviousUsrUid' => 10, 'DelPreviousUsrUsername' => 11, 'DelPreviousUsrFirstname' => 12, 'DelPreviousUsrLastname' => 13, 'DelCurrentUsrUsername' => 14, 'DelCurrentUsrFirstname' => 15, 'DelCurrentUsrLastname' => 16, 'DelDelegateDate' => 17, 'DelInitDate' => 18, 'DelDueDate' => 19, 'DelPriority' => 20, 'DelThreadStatus' => 21, ), - BasePeer::TYPE_COLNAME => array (ListParticipatedLastPeer::APP_UID => 0, ListParticipatedLastPeer::USR_UID => 1, ListParticipatedLastPeer::DEL_INDEX => 2, ListParticipatedLastPeer::TAS_UID => 3, ListParticipatedLastPeer::PRO_UID => 4, ListParticipatedLastPeer::APP_NUMBER => 5, ListParticipatedLastPeer::APP_TITLE => 6, ListParticipatedLastPeer::APP_PRO_TITLE => 7, ListParticipatedLastPeer::APP_TAS_TITLE => 8, ListParticipatedLastPeer::APP_STATUS => 9, ListParticipatedLastPeer::DEL_PREVIOUS_USR_UID => 10, ListParticipatedLastPeer::DEL_PREVIOUS_USR_USERNAME => 11, ListParticipatedLastPeer::DEL_PREVIOUS_USR_FIRSTNAME => 12, ListParticipatedLastPeer::DEL_PREVIOUS_USR_LASTNAME => 13, ListParticipatedLastPeer::DEL_CURRENT_USR_USERNAME => 14, ListParticipatedLastPeer::DEL_CURRENT_USR_FIRSTNAME => 15, ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME => 16, ListParticipatedLastPeer::DEL_DELEGATE_DATE => 17, ListParticipatedLastPeer::DEL_INIT_DATE => 18, ListParticipatedLastPeer::DEL_DUE_DATE => 19, ListParticipatedLastPeer::DEL_PRIORITY => 20, ListParticipatedLastPeer::DEL_THREAD_STATUS => 21, ), - BasePeer::TYPE_FIELDNAME => array ('APP_UID' => 0, 'USR_UID' => 1, 'DEL_INDEX' => 2, 'TAS_UID' => 3, 'PRO_UID' => 4, 'APP_NUMBER' => 5, 'APP_TITLE' => 6, 'APP_PRO_TITLE' => 7, 'APP_TAS_TITLE' => 8, 'APP_STATUS' => 9, 'DEL_PREVIOUS_USR_UID' => 10, 'DEL_PREVIOUS_USR_USERNAME' => 11, 'DEL_PREVIOUS_USR_FIRSTNAME' => 12, 'DEL_PREVIOUS_USR_LASTNAME' => 13, 'DEL_CURRENT_USR_USERNAME' => 14, 'DEL_CURRENT_USR_FIRSTNAME' => 15, 'DEL_CURRENT_USR_LASTNAME' => 16, 'DEL_DELEGATE_DATE' => 17, 'DEL_INIT_DATE' => 18, 'DEL_DUE_DATE' => 19, 'DEL_PRIORITY' => 20, 'DEL_THREAD_STATUS' => 21, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, ) + BasePeer::TYPE_PHPNAME => array ('AppUid' => 0, 'UsrUid' => 1, 'DelIndex' => 2, 'TasUid' => 3, 'ProUid' => 4, 'AppNumber' => 5, 'AppTitle' => 6, 'AppProTitle' => 7, 'AppTasTitle' => 8, 'AppStatus' => 9, 'DelPreviousUsrUid' => 10, 'DelPreviousUsrUsername' => 11, 'DelPreviousUsrFirstname' => 12, 'DelPreviousUsrLastname' => 13, 'DelCurrentUsrUsername' => 14, 'DelCurrentUsrFirstname' => 15, 'DelCurrentUsrLastname' => 16, 'DelCurrentTasTitle' => 17, 'DelDelegateDate' => 18, 'DelInitDate' => 19, 'DelDueDate' => 20, 'DelPriority' => 21, 'DelThreadStatus' => 22, ), + BasePeer::TYPE_COLNAME => array (ListParticipatedLastPeer::APP_UID => 0, ListParticipatedLastPeer::USR_UID => 1, ListParticipatedLastPeer::DEL_INDEX => 2, ListParticipatedLastPeer::TAS_UID => 3, ListParticipatedLastPeer::PRO_UID => 4, ListParticipatedLastPeer::APP_NUMBER => 5, ListParticipatedLastPeer::APP_TITLE => 6, ListParticipatedLastPeer::APP_PRO_TITLE => 7, ListParticipatedLastPeer::APP_TAS_TITLE => 8, ListParticipatedLastPeer::APP_STATUS => 9, ListParticipatedLastPeer::DEL_PREVIOUS_USR_UID => 10, ListParticipatedLastPeer::DEL_PREVIOUS_USR_USERNAME => 11, ListParticipatedLastPeer::DEL_PREVIOUS_USR_FIRSTNAME => 12, ListParticipatedLastPeer::DEL_PREVIOUS_USR_LASTNAME => 13, ListParticipatedLastPeer::DEL_CURRENT_USR_USERNAME => 14, ListParticipatedLastPeer::DEL_CURRENT_USR_FIRSTNAME => 15, ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME => 16, ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE => 17, ListParticipatedLastPeer::DEL_DELEGATE_DATE => 18, ListParticipatedLastPeer::DEL_INIT_DATE => 19, ListParticipatedLastPeer::DEL_DUE_DATE => 20, ListParticipatedLastPeer::DEL_PRIORITY => 21, ListParticipatedLastPeer::DEL_THREAD_STATUS => 22, ), + BasePeer::TYPE_FIELDNAME => array ('APP_UID' => 0, 'USR_UID' => 1, 'DEL_INDEX' => 2, 'TAS_UID' => 3, 'PRO_UID' => 4, 'APP_NUMBER' => 5, 'APP_TITLE' => 6, 'APP_PRO_TITLE' => 7, 'APP_TAS_TITLE' => 8, 'APP_STATUS' => 9, 'DEL_PREVIOUS_USR_UID' => 10, 'DEL_PREVIOUS_USR_USERNAME' => 11, 'DEL_PREVIOUS_USR_FIRSTNAME' => 12, 'DEL_PREVIOUS_USR_LASTNAME' => 13, 'DEL_CURRENT_USR_USERNAME' => 14, 'DEL_CURRENT_USR_FIRSTNAME' => 15, 'DEL_CURRENT_USR_LASTNAME' => 16, 'DEL_CURRENT_TAS_TITLE' => 17, 'DEL_DELEGATE_DATE' => 18, 'DEL_INIT_DATE' => 19, 'DEL_DUE_DATE' => 20, 'DEL_PRIORITY' => 21, 'DEL_THREAD_STATUS' => 22, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, ) ); /** @@ -259,6 +262,8 @@ abstract class BaseListParticipatedLastPeer $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_CURRENT_USR_LASTNAME); + $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_CURRENT_TAS_TITLE); + $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_DELEGATE_DATE); $criteria->addSelectColumn(ListParticipatedLastPeer::DEL_INIT_DATE); diff --git a/workflow/engine/classes/triggers/class.pmAlfrescoFunctions.php b/workflow/engine/classes/triggers/class.pmAlfrescoFunctions.php index f6d3a3065..28c328452 100755 --- a/workflow/engine/classes/triggers/class.pmAlfrescoFunctions.php +++ b/workflow/engine/classes/triggers/class.pmAlfrescoFunctions.php @@ -179,12 +179,15 @@ function createFolder($alfrescoServerUrl, $parentFolder, $folderName, $user, $pw */ function deleteObject($alfrescoServerUrl, $objetcId, $user, $pwd) { + $getResponse = true; $alfresco_url = "$alfrescoServerUrl/s/cmis/s/workspace:SpacesStore/i/$objetcId"; - $alfresco_exec = RestClient::delete($alfresco_url, $user, $pwd, "application/atom+xml"); - - $alfresco_res = G::json_decode($alfresco_exec->getResponse()); - - return $alfresco_res; + $alfresco_exec = RestClient::delete($alfresco_url, $user, $pwd, "application/atom+xml", $getResponse); + if($alfresco_exec->getResponseCode() === 204 && trim($alfresco_exec->getResponse()) === '') { + $alfresco_res = true; + } else { + $alfresco_res = false; + } + return $getResponse ? $alfresco_res : ''; } /** diff --git a/workflow/engine/config/execute-query-blacklist.ini b/workflow/engine/config/execute-query-blacklist.ini new file mode 100755 index 000000000..d2f7cfb57 --- /dev/null +++ b/workflow/engine/config/execute-query-blacklist.ini @@ -0,0 +1,6 @@ +;The separator parameter is | +;Setting statements - Statements can not allowed in the execution, example queries="INSERT|UPDATE|REPLACE|DELETE" +queries = "INSERT|UPDATE|REPLACE|DELETE" + +;Setting tables - Tables that can not apply sentences, pmtables="PMTABLE1|PMTABLE2" +pmtables = "" \ No newline at end of file diff --git a/workflow/engine/config/schema.xml b/workflow/engine/config/schema.xml index 80ad477e7..af799202f 100755 --- a/workflow/engine/config/schema.xml +++ b/workflow/engine/config/schema.xml @@ -191,6 +191,18 @@ + + + + + + + + + + + + @@ -222,6 +234,10 @@ + + + + @@ -365,6 +381,16 @@ + + + + + + + + + + @@ -2487,6 +2513,15 @@ + + + + + + + + + @@ -4004,6 +4039,15 @@ + + + + + + + + + @@ -4116,6 +4160,7 @@ + @@ -5239,4 +5284,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/workflow/engine/controllers/admin.php b/workflow/engine/controllers/admin.php index cae1cec9d..46ab93382 100644 --- a/workflow/engine/controllers/admin.php +++ b/workflow/engine/controllers/admin.php @@ -167,7 +167,7 @@ class Admin extends Controller public function pmLogo ($httpData) { global $RBAC; - $RBAC->requirePermissions( 'PM_SETUP_ADVANCE' ); + $RBAC->requirePermissions( 'PM_SETUP_ADVANCE', 'PM_SETUP_LOGO'); G::LoadClass( 'configuration' ); $c = new Configurations(); diff --git a/workflow/engine/controllers/adminProxy.php b/workflow/engine/controllers/adminProxy.php index 467cb39d0..c1e7e47d9 100644 --- a/workflow/engine/controllers/adminProxy.php +++ b/workflow/engine/controllers/adminProxy.php @@ -313,7 +313,7 @@ class adminProxy extends HttpProxyController public function testingOption($params) { $data['success'] = true; - $data['optionAuthS'] = $params->optionAuthS; + $data['optionAuthS'] = htmlspecialchars($params->optionAuthS); return $data; } diff --git a/workflow/engine/controllers/appProxy.php b/workflow/engine/controllers/appProxy.php index c8513ced4..b93389892 100644 --- a/workflow/engine/controllers/appProxy.php +++ b/workflow/engine/controllers/appProxy.php @@ -304,6 +304,8 @@ class AppProxy extends HttpProxyController $data[] = array ('label' => $labelsCurrentTaskProperties['DEL_TASK_DUE_DATE'],'value' => $applicationFields['DEL_TASK_DUE_DATE'],'section' => $labelTitleCurrentTasks['TITLE2']); $data[] = array ('label' => $labelsCurrentTaskProperties['DEL_FINISH_DATE'],'value' => $applicationFields['DEL_FINISH_DATE'],'section' => $labelTitleCurrentTasks['TITLE2']); //$data[] = array('label'=>$labelsCurrentTaskProperties['DYN_UID'] , 'value' => $processData['PRO_DYNAFORMS']['PROCESS'];, 'section'=>$labelsCurrentTaskProperties['DYN_UID']); + + $data = \ProcessMaker\Util\DateTime::convertUtcToTimeZone($data); return $data; } } diff --git a/workflow/engine/controllers/designer.php b/workflow/engine/controllers/designer.php index 2c126354f..606ba6a42 100644 --- a/workflow/engine/controllers/designer.php +++ b/workflow/engine/controllers/designer.php @@ -75,8 +75,8 @@ class Designer extends Controller } /*----------------------------------********---------------------------------*/ - $this->setVar('prj_uid', $proUid); - $this->setVar('app_uid', $appUid); + $this->setVar('prj_uid', htmlspecialchars($proUid)); + $this->setVar('app_uid', htmlspecialchars($appUid)); $this->setVar('consolidated', $consolidated); $this->setVar('enterprise', $enterprise); $this->setVar('prj_readonly', $proReadOnly); @@ -145,7 +145,7 @@ class Designer extends Controller $user = new \ProcessMaker\BusinessModel\User(); - if ($user->checkPermission($row['USER_ID'], 'PM_FACTORY')) { + if ($user->checkPermission($row['USER_ID'], 'PM_FACTORY') || $proReadOnly == 'true') { $this->setView('designer/index'); } else { $this->setVar('accessDenied', G::LoadTranslation('ID_ACCESS_DENIED')); diff --git a/workflow/engine/controllers/home.php b/workflow/engine/controllers/home.php index ba446fbe0..749193c59 100755 --- a/workflow/engine/controllers/home.php +++ b/workflow/engine/controllers/home.php @@ -410,28 +410,39 @@ class Home extends Controller $category ); } else { - G::LoadClass( 'applications' ); + $dataList['userId'] = $user; + $dataList['start'] = $start; + $dataList['limit'] = $limit; + $dataList['filter'] = $filter; + $dataList['search'] = $search; + $dataList['process'] = $process; + $dataList['status'] = $status; + $dataList['dateFrom'] = $dateFrom; + $dataList['dateTo'] = $dateTo; + $dataList['callback'] = $callback; + $dataList['dir'] = $dir; + $dataList['sort'] = $sort; + $dataList['category'] = $category; + /*----------------------------------********---------------------------------*/ + if (true) { + //In enterprise version this block of code should always be executed + //In community version this block of code is deleted and is executed the other + $list = new \ProcessMaker\BusinessModel\Lists(); + $cases = $list->getList('inbox', $dataList); + } else { + /*----------------------------------********---------------------------------*/ + $case = new \ProcessMaker\BusinessModel\Cases(); + $cases = $case->getList($dataList); + foreach ($cases['data'] as &$value) { + $value = array_change_key_case($value, CASE_UPPER); + } + if(!isset($cases['totalCount'])){ + $cases['totalCount'] = $cases['total']; + } + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ - $apps = new Applications(); - - $cases = $apps->getAll( - $user, - $start, - $limit, - $type, - $filter, - $search, - $process, - $status, - '', - $dateFrom, - $dateTo, - $callback, - $dir, - $sort, - $category, - false - ); } // formating & complitting apps data with 'Notes' diff --git a/workflow/engine/controllers/main.php b/workflow/engine/controllers/main.php index d181d35a8..15435cc52 100644 --- a/workflow/engine/controllers/main.php +++ b/workflow/engine/controllers/main.php @@ -40,7 +40,6 @@ class Main extends Controller $this->setVar( 'logout', G::LoadTranslation( 'ID_LOGOUT' ) ); $this->setVar( 'workspace', defined( 'SYS_SYS' ) ? ucfirst( SYS_SYS ) : '' ); $this->setVar( 'user_avatar', 'users/users_ViewPhotoGrid?pUID=' . $_SESSION['USER_LOGGED'] . '&h=' . rand() ); - $this->setVar( 'udate', G::getformatedDate( date( 'Y-m-d' ), 'M d, yyyy', SYS_LANG ) ); // license notification $expireInLabel = ''; diff --git a/workflow/engine/controllers/pmGmail.php b/workflow/engine/controllers/pmGmail.php index 767640f98..9a5b4b1f0 100644 --- a/workflow/engine/controllers/pmGmail.php +++ b/workflow/engine/controllers/pmGmail.php @@ -16,29 +16,28 @@ class pmGmail extends Controller $result = new StdClass(); $result->success = true; - if (!empty($httpData->status_pmgmail)) { - $httpData->status_pmgmail = $httpData->status_pmgmail == 1 ? true : false; - $pmGoogle->setStatusService($httpData->status_pmgmail); - $message = G::LoadTranslation('ID_ENABLE_PMGMAIL') . ': ' . ($httpData->status_pmgmail ? G::LoadTranslation('ID_ENABLE') : G::LoadTranslation('ID_DISABLE')); + $httpData->serviceGmailStatus = !empty($httpData->serviceGmailStatus) ? $httpData->serviceGmailStatus == 1 ? true : false : false; + $httpData->serviceDriveStatus = !empty($httpData->serviceDriveStatus) ? $httpData->serviceDriveStatus == 1 ? true : false : false; - $pmGoogle->setTypeAuthentication($httpData->typeAuth); + if ($httpData->serviceGmailStatus || $httpData->serviceDriveStatus) { - if (!empty($httpData->email_service_account)) { - $pmGoogle->setServiceAccountEmail($httpData->email_service_account); - $message .= ', ' . G::LoadTranslation('ID_PMG_EMAIL') . ': ' . $httpData->email_service_account; + + $pmGoogle->setServiceGmailStatus($httpData->serviceGmailStatus); + $pmGoogle->setServiceDriveStatus($httpData->serviceDriveStatus); + + $message = G::LoadTranslation('ID_ENABLE_PMGMAIL') . ': ' . ($httpData->serviceGmailStatus ? G::LoadTranslation('ID_ENABLE') : G::LoadTranslation('ID_DISABLE')); + $message .= G::LoadTranslation('ID_ENABLE_PMDRIVE') . ': ' . ($httpData->serviceDriveStatus ? G::LoadTranslation('ID_ENABLE') : G::LoadTranslation('ID_DISABLE')); + + if (!empty($httpData->emailServiceAccount)) { + $pmGoogle->setServiceAccountEmail($httpData->emailServiceAccount); + $message .= ', ' . G::LoadTranslation('ID_PMG_EMAIL') . ': ' . $httpData->emailServiceAccount; } if (!empty($_FILES)) { - if (!empty($_FILES['file_p12']) && $_FILES['file_p12']['error'] != 1) { - if ($_FILES['file_p12']['tmp_name'] != '') { - G::uploadFile($_FILES['file_p12']['tmp_name'], PATH_DATA_SITE, $_FILES['file_p12']['name']); - $pmGoogle->setServiceAccountP12($_FILES['file_p12']['name']); - $message .= ', ' . G::LoadTranslation('ID_PMG_FILE') . ': ' . $_FILES['file_p12']['name']; - } - } else if (!empty($_FILES['file_json']) && $_FILES['file_json']['error'] != 1) { - if ($_FILES['file_json']['tmp_name'] != '') { - G::uploadFile($_FILES['file_json']['tmp_name'], PATH_DATA_SITE, $_FILES['file_json']['name']); - $pmGoogle->setAccountJson($_FILES['file_json']['name']); - $message .= ', ' . G::LoadTranslation('ID_PMG_FILE') . ': ' . $_FILES['file_json']['name']; + if (!empty($_FILES['googleCertificate']) && $_FILES['googleCertificate']['error'] != 1) { + if ($_FILES['googleCertificate']['tmp_name'] != '') { + G::uploadFile($_FILES['googleCertificate']['tmp_name'], PATH_DATA_SITE, $_FILES['googleCertificate']['name']); + $pmGoogle->setServiceAccountCertificate($_FILES['googleCertificate']['name']); + $message .= ', ' . G::LoadTranslation('ID_PMG_FILE') . ': ' . $_FILES['googleCertificate']['name']; } } else { $result->success = false; @@ -48,7 +47,8 @@ class pmGmail extends Controller } } } else { - $pmGoogle->setStatusService(false); + $pmGoogle->setServiceGmailStatus(false); + $pmGoogle->setServiceDriveStatus(false); $message = G::LoadTranslation('ID_ENABLE_PMGMAIL') . ': ' . G::LoadTranslation('ID_DISABLE'); } G::auditLog("Update Settings Gmail", $message); @@ -64,20 +64,29 @@ class pmGmail extends Controller $this->setJSVar('__PMGMAIL_ERROR__', $_SESSION['__PMGMAIL_ERROR__']); unset($_SESSION['__PMGMAIL_ERROR__']); } - G::LoadClass( "pmGoogleApi" ); + G::LoadClass("pmGoogleApi"); $pmGoogle = new PMGoogleApi(); $accountEmail = $pmGoogle->getServiceAccountEmail(); - $fileP12 = $pmGoogle->getServiceAccountP12(); - $fileJson = $pmGoogle->getAccountJson(); - $fileJson = $fileJson == null ? '' : $fileJson; - $type = $pmGoogle->getTypeAuthentication(); - $enablePMGmail = $pmGoogle->getStatusService(); + $googleCertificate = $pmGoogle->getServiceAccountCertificate(); + $statusGmail = $pmGoogle->getServiceGmailStatus(); + $statusDrive = $pmGoogle->getServiceDriveStatus(); + $disableGmail = true; + $disableDrive = true; + + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + $disableGmail = false; + } + if ($licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M=')) { + $disableDrive = false; + } $this->setJSVar('accountEmail', $accountEmail); - $this->setJSVar('fileP12', $fileP12); - $this->setJSVar('enablePMGmail', $enablePMGmail); - $this->setJSVar('fileJson', $fileJson); - $this->setJSVar('typeAuthentication', $type); + $this->setJSVar('googleCertificate', $googleCertificate); + $this->setJSVar('statusGmail', $statusGmail); + $this->setJSVar('statusDrive', $statusDrive); + $this->setJSVar('disableGmail', $disableGmail); + $this->setJSVar('disableDrive', $disableDrive); G::RenderPage('publish', 'extJs'); @@ -97,13 +106,8 @@ class pmGmail extends Controller $result = new stdClass(); - $result->typeAuth = empty($httpData->typeAuth) ? $pmGoogle->getTypeAuthentication() : $httpData->typeAuth; - if ($result->typeAuth == 'webApplication') { - $result->pathFileJson = empty($_FILES['file_json']['tmp_name']) ? PATH_DATA_SITE . $pmGoogle->getAccountJson() : $_FILES['file_json']['tmp_name']; - } else { - $result->emailServiceAccount = empty($httpData->email_service_account) ? $pmGoogle->getServiceAccountEmail() : $httpData->email_service_account; - $result->pathServiceAccountP12 = empty($_FILES['file_p12']['tmp_name']) ? PATH_DATA_SITE . $pmGoogle->getserviceAccountP12() : $_FILES['file_p12']['tmp_name']; - } + $result->emailServiceAccount = empty($httpData->emailServiceAccount) ? $pmGoogle->getServiceAccountEmail() : $httpData->emailServiceAccount; + $result->pathServiceAccountCertificate = empty($_FILES['googleCertificate']['tmp_name']) ? PATH_DATA_SITE . $pmGoogle->getServiceAccountCertificate() : $_FILES['googleCertificate']['tmp_name']; print(G::json_encode($pmGoogle->testService($result))); } diff --git a/workflow/engine/controllers/pmTables.php b/workflow/engine/controllers/pmTables.php index b866c292c..031df068d 100755 --- a/workflow/engine/controllers/pmTables.php +++ b/workflow/engine/controllers/pmTables.php @@ -24,7 +24,7 @@ class pmTables extends Controller public function index ($httpData) { global $RBAC; - $RBAC->requirePermissions( 'PM_SETUP_ADVANCE' ); + $RBAC->requirePermissions( 'PM_SETUP_ADVANCE', 'PM_SETUP_PM_TABLES' ); G::LoadClass( 'configuration' ); $c = new Configurations(); diff --git a/workflow/engine/controllers/pmTablesProxy.php b/workflow/engine/controllers/pmTablesProxy.php index ad51c01f5..9199e3452 100755 --- a/workflow/engine/controllers/pmTablesProxy.php +++ b/workflow/engine/controllers/pmTablesProxy.php @@ -692,7 +692,7 @@ class pmTablesProxy extends HttpProxyController $sErrorMessages = ''; $i = 1; $conData = 0; - $insert = 'INSERT INTO ' . $aAdditionalTables['ADD_TAB_NAME'] . ' ('; + $insert = 'REPLACE INTO ' . $aAdditionalTables['ADD_TAB_NAME'] . ' ('; $query = ''; $swHead = false; while (($aAux = fgetcsv( $oFile, 4096, $_POST['form']['CSV_DELIMITER'] )) !== false) { @@ -720,7 +720,7 @@ class pmTablesProxy extends HttpProxyController $j = 0; foreach ($aAdditionalTables['FIELDS'] as $aField) { $conData++; - $temp = isset($aAux[$j]) ? '"'.addslashes($aAux[$j]).'"' : '""'; + $temp = isset($aAux[$j]) ? '"'.addslashes(stripslashes($aAux[$j])).'"' : '""'; if ($temp == '') { switch ($aField['FLD_TYPE']) { case 'DATE': @@ -885,11 +885,23 @@ class pmTablesProxy extends HttpProxyController $filename = $PUBLIC_ROOT_PATH . $filenameOnly; $fp = fopen( $filename, "wb" ); + $swColumns = true; foreach ($rows as $keyCol => $cols) { $SDATA = ""; - $cnt = count( $cols ); + $header = ""; + $cnt = $cntC = count( $cols ); foreach ($cols as $key => $val) { - $SDATA .= $val; + if($swColumns){ + $header .= $key; + if (-- $cntC > 0) { + $header .= $sDelimiter; + } else { + $header .= "\n"; + $bytesSaved += fwrite( $fp, $header ); + $swColumns = false; + } + } + $SDATA .= addslashes($val); if (-- $cnt > 0) { $SDATA .= $sDelimiter; } @@ -925,6 +937,11 @@ class pmTablesProxy extends HttpProxyController */ public function import ($httpData) { + define('ERROR_PM_TABLES_OVERWRITE', '1'); + define('ERROR_PROCESS_NOT_EXIST', '2'); + define('ERROR_RP_TABLES_OVERWRITE', '3'); + define('ERROR_NO_REPORT_TABLE', '4'); + define('ERROR_OVERWRITE_RELATED_PROCESS', '5'); $fromAdmin = false; if (isset( $_POST["form"]["TYPE_TABLE"] ) && ! empty( $_POST["form"]["TYPE_TABLE"] )) { if($_POST["form"]["TYPE_TABLE"] == 'admin') { @@ -974,21 +991,223 @@ class pmTablesProxy extends HttpProxyController throw new Exception( G::loadTranslation( 'ID_PMTABLE_INVALID_FILE' ) ); } - $fp = fopen( $PUBLIC_ROOT_PATH . $filename, "rb" ); - $fsData = intval( fread( $fp, 9 ) ); //reading the metadata - $sType = fread( $fp, $fsData ); + $currentProUid = ''; + if (isset( $_POST["form"]["PRO_UID_HELP"] ) && !empty($_POST["form"]["PRO_UID_HELP"])) { + $currentProUid = $_POST["form"]["PRO_UID_HELP"]; + } else { + if(isset( $_POST["form"]["PRO_UID"]) && !empty( $_POST["form"]["PRO_UID"])){ + $currentProUid = $_POST["form"]["PRO_UID"]; + $_SESSION['PROCESS'] = $currentProUid; + } else{ + $currentProUid = $_SESSION['PROCESS']; + } + } - //Ask for all Process - $processMap = new processMap(); - $aProcess = json_decode ($processMap->getAllProcesses()); - foreach($aProcess as $key => $val){ - if ($val->value != ''){ - $proUids[] = $val->value; - } - } - // first create the tables structures + //First Validate the file + $pathPmtableFile = $PUBLIC_ROOT_PATH . $filename; + $arrayOverwrite = array(); + $arrayRelated = array(); + $arrayMessage = array(); + $validationType = 0; + if(!$fromConfirm){ + $aErrors = $this->checkPmtFileThrowErrors($pathPmtableFile,$filename,$fromAdmin,$overWrite,$currentProUid); + $countC = 0; + $countM = 0; + $countI = 0; + foreach($aErrors as $row){ + if($row['ERROR_TYPE'] == ERROR_PM_TABLES_OVERWRITE || $row['ERROR_TYPE'] == ERROR_RP_TABLES_OVERWRITE){ + $arrayOverwrite[$countC] = $row; + $countC++; + } else { + if($row['ERROR_TYPE'] == ERROR_OVERWRITE_RELATED_PROCESS){ + $arrayRelated[$countI] = $row; + $countI++; + } else { + $arrayMessage[$countM] = $row; + $countM++; + } + } + } + if(sizeof($aErrors)){ + $validationType = 1; //Yes no + throw new Exception(G::loadTranslation( 'ID_PMTABLE_IMPORT_WITH_ERRORS', array ($filename))); + } + } + //Then create the tables + if(isset($_POST["form"]["TABLES_OF_NO"])){ + $arrayOfNo = $_POST["form"]["TABLES_OF_NO"]; + $arrayOfNew = $_POST["form"]["TABLES_OF_NEW"]; + $aTablesCreateNew = explode('|',$arrayOfNew); + $aTablesNoCreate = explode('|',$arrayOfNo); + $errors = $this->createStructureOfTables($pathPmtableFile, $fromAdmin, $currentProUid, true, $aTablesNoCreate, $aTablesCreateNew); + } else { + $errors = $this->createStructureOfTables($pathPmtableFile, $fromAdmin, $currentProUid, true); + } - while (! feof( $fp )) { + if ($errors == '') { + $result->success = true; + $msg = G::loadTranslation( 'ID_DONE' ); + } else { + $result->success = false; + $result->errorType = 'warning'; + $msg = G::loadTranslation( 'ID_PMTABLE_IMPORT_WITH_ERRORS', array ($filename) ) . "\n\n" . $errors; + } + + $result->message = $msg; + } catch (Exception $e) { + $result = new stdClass(); + $result->fromAdmin = $fromAdmin; + $result->arrayMessage = $arrayMessage; + $result->arrayRelated = $arrayRelated; + $result->arrayOverwrite = $arrayOverwrite; + $result->validationType = $validationType; + $result->errorType = 'error'; + $result->buildResult = ob_get_contents(); + ob_end_clean(); + $result->success = false; + + // if it is a propel exception message + if (preg_match( '/(.*)\s\[(.*):\s(.*)\]\s\[(.*):\s(.*)\]/', $e->getMessage(), $match )) { + $result->message = $match[3]; + $result->type = G::loadTranslation( 'ID_ERROR' ); + } else { + $result->message = $e->getMessage(); + $result->type = G::loadTranslation( 'ID_EXCEPTION' ); + } + } + + return $result; + } + /** + * Review the *.pmt file and Throw all errors + * @param string $tableFile + * @param string $fileName + * @param bool $fromAdmin + * @param bool $overWrite + * @param string $currentProUid + * @return string $aErrors + */ + public static function checkPmtFileThrowErrors($tableFile,$fileName,$fromAdmin,$overWrite,$currentProUid){ + $aErrors = array(); + //Ask for all Process + $processMap = new processMap(); + $aProcess = G::json_decode($processMap->getAllProcesses()); + foreach($aProcess as $key => $val){ + if ($val->value != ''){ + $proUids[] = $val->value; + } + } + + $fp = fopen( $tableFile, "rb" ); + $fsData = intval( fread( $fp, 9 ) ); //reading the metadata + $sType = fread( $fp, $fsData ); + $count = 0; + while (! feof( $fp )) { + $validationType = 0; + switch ($sType) { + case '@META': + $fsData = intval( fread( $fp, 9 ) ); + $METADATA = fread( $fp, $fsData ); + break; + case '@SCHEMA': + $fsUid = intval( fread( $fp, 9 ) ); + $uid = fread( $fp, $fsUid ); + $fsData = intval( fread( $fp, 9 ) ); + $schema = fread( $fp, $fsData ); + $contentSchema = unserialize( $schema ); + //The table exists? + $additionalTable = new additionalTables(); + $tableExists = $additionalTable->loadByName( $contentSchema['ADD_TAB_NAME'] ); + + $tableProUid = isset($contentSchema["PRO_UID"])?$contentSchema["PRO_UID"]:$_POST["form"]["PRO_UID"]; + $isPmTable = empty($contentSchema["PRO_UID"])? true : false; + + if($fromAdmin) { + if($isPmTable){ + if ($tableExists !== false && !$overWrite) { + $aErrors[$count]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME']; + $aErrors[$count]['ERROR_TYPE'] = ERROR_PM_TABLES_OVERWRITE; + $aErrors[$count]['ERROR_MESS'] = G::loadTranslation('ID_OVERWRITE_PMTABLE', array($contentSchema['ADD_TAB_NAME'])); + $aErrors[$count]['IS_PMTABLE'] = $isPmTable; + $aErrors[$count]['PRO_UID'] = $tableProUid; + } + } else { + if(!in_array($tableProUid, $proUids)){ + $aErrors[$count]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME']; + $aErrors[$count]['ERROR_TYPE'] = ERROR_PROCESS_NOT_EXIST; + $aErrors[$count]['ERROR_MESS'] = G::loadTranslation('ID_PROCESS_NOT_EXIST', array($contentSchema['ADD_TAB_NAME'])); + $aErrors[$count]['IS_PMTABLE'] = $isPmTable; + $aErrors[$count]['PRO_UID'] = $tableProUid; + } else { + $aErrors[$count]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME']; + $aErrors[$count]['ERROR_TYPE'] = ERROR_RP_TABLES_OVERWRITE; + $aErrors[$count]['ERROR_MESS'] = G::loadTranslation('ID_OVERWRITE_RPTABLE', array($contentSchema['ADD_TAB_NAME'])); + $aErrors[$count]['IS_PMTABLE'] = $isPmTable; + $aErrors[$count]['PRO_UID'] = $tableProUid; + } + } + } else { + if($isPmTable){ + $aErrors[$count]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME']; + $aErrors[$count]['ERROR_TYPE'] = ERROR_NO_REPORT_TABLE; + $aErrors[$count]['ERROR_MESS'] = G::loadTranslation('ID_NO_REPORT_TABLE', array($contentSchema['ADD_TAB_NAME'])); + $aErrors[$count]['IS_PMTABLE'] = $isPmTable; + $aErrors[$count]['PRO_UID'] = $tableProUid; + } else { + if(!$currentProUid != $tableProUid){ + $aErrors[$count]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME']; + $aErrors[$count]['ERROR_TYPE'] = ERROR_OVERWRITE_RELATED_PROCESS; + $aErrors[$count]['ERROR_MESS'] = G::loadTranslation('ID_OVERWRITE_RELATED_PROCESS', array($contentSchema['ADD_TAB_NAME'])); + $aErrors[$count]['IS_PMTABLE'] = $isPmTable; + $aErrors[$count]['PRO_UID'] = $tableProUid; + } else { + if ($tableExists !== false && !$overWrite) { + $aErrors[$count]['NAME_TABLE'] = $contentSchema['ADD_TAB_NAME']; + $aErrors[$count]['ERROR_TYPE'] = ERROR_RP_TABLES_OVERWRITE; + $aErrors[$count]['ERROR_MESS'] = G::loadTranslation('ID_OVERWRITE_RPTABLE', array($contentSchema['ADD_TAB_NAME'])); + $aErrors[$count]['IS_PMTABLE'] = $isPmTable; + $aErrors[$count]['PRO_UID'] = $tableProUid; + } + } + } + } + break; + case '@DATA': + break; + } + + $fsData = intval( fread( $fp, 9 ) ); + if ($fsData > 0) { + $sType = fread( $fp, $fsData ); + } else { + break; + } + $count++; + } + fclose( $fp ); + return $aErrors; + } + + /** + * Create the structure of tables + * @param string $tableFile, + * @param bool $fromAdmin + * @param string $currentProUid + * @param bool $overWrite + * @param array $aTables + * @return string $errors + */ + public function createStructureOfTables($tableFile,$fromAdmin,$currentProUid,$overWrite = true, $aTables=array(), $aTablesNew=array()){ + + $fp = fopen( $tableFile, "rb" ); + $fsData = intval( fread( $fp, 9 ) ); + $sType = fread( $fp, $fsData ); + $errors = ''; + $tableNameMap = array(); + $processQueue = array(); + $processQueueTables = array(); + while (! feof( $fp )) { + $validationType = 0; switch ($sType) { case '@META': $fsData = intval( fread( $fp, 9 ) ); @@ -1001,115 +1220,86 @@ class pmTablesProxy extends HttpProxyController $schema = fread( $fp, $fsData ); $contentSchema = unserialize( $schema ); $additionalTable = new additionalTables(); - $tableExists = $additionalTable->loadByName( $contentSchema['ADD_TAB_NAME'] ); - $tableNameMap[$contentSchema['ADD_TAB_NAME']] = $contentSchema['ADD_TAB_NAME']; - - $tableData = new stdClass(); - - if(isset( $contentSchema["PRO_UID"] )){ - $tableData->PRO_UID = $contentSchema["PRO_UID"]; - }else{ - $tableData->PRO_UID = $_POST["form"]["PRO_UID"]; - } - $isPmTable = false; /*is a report table*/ - if($contentSchema["PRO_UID"] == "" ) { - $isPmTable = true; - } - $currentPRO_UID = ''; - if (isset( $_POST["form"]["PRO_UID_HELP"] ) && !empty($_POST["form"]["PRO_UID_HELP"])) { - $currentPRO_UID = $_POST["form"]["PRO_UID_HELP"]; - } else { - if(isset( $_POST["form"]["PRO_UID"]) && !empty( $_POST["form"]["PRO_UID"])){ - $currentPRO_UID = $_POST["form"]["PRO_UID"]; - $_SESSION['PROCESS'] = $currentPRO_UID; - } else{ - $currentPRO_UID = $_SESSION['PROCESS']; - } - } + if(!in_array($contentSchema['ADD_TAB_NAME'],$aTables)){ + $tableExists = $additionalTable->loadByName( $contentSchema['ADD_TAB_NAME'] ); + $tableNameMap[$contentSchema['ADD_TAB_NAME']] = $contentSchema['ADD_TAB_NAME']; - if($fromAdmin) { /* from admin tab */ - if ($tableExists !== false && !$fromConfirm && !$overWrite) { - $validationType = 1; - throw new Exception( G::loadTranslation( 'ID_OVERWRITE_PMTABLE' ) ); - } - if(!in_array($tableData->PRO_UID, $proUids) && !$isPmTable) { - $validationType = 2; - throw new Exception( G::loadTranslation( 'ID_NO_RELATED_PROCESS' ) ); + $tableData = new stdClass(); + + if(isset( $contentSchema["PRO_UID"] )){ + $tableData->PRO_UID = $contentSchema["PRO_UID"]; + }else{ + $tableData->PRO_UID = $_POST["form"]["PRO_UID"]; } - } else { /* from designer tab */ - if($isPmTable){ - $validationType = ''; - throw new Exception( G::loadTranslation( 'ID_NO_REPORT_TABLE' ) ); + $isPmTable = false; /*is a report table*/ + if($contentSchema["PRO_UID"] === '' ) { + $isPmTable = true; } - if ($tableExists !== false && !$fromConfirm && !$overWrite) { - $validationType = 1; - throw new Exception( G::loadTranslation( 'ID_OVERWRITE_PMTABLE' ) ); + if(!$fromAdmin && !$isPmTable) { + $tableData->PRO_UID = $currentProUid; } - if($currentPRO_UID != $tableData->PRO_UID) { - if(!in_array($tableData->PRO_UID, $proUids)) { - $validationType = 2; - if(($fromConfirm == $validationType || !$fromConfirm) && !$isPmTable) { - throw new Exception( G::loadTranslation( 'ID_OVERWRITE_RELATED_PROCESS' ) ); - } else { - $tableData->PRO_UID = $currentPRO_UID; - } - } else { - $validationType = 3; - throw new Exception( G::loadTranslation( 'ID_ALREADY_RELATED_TABLE ' ) ); + if(in_array($contentSchema['ADD_TAB_NAME'],$aTablesNew)){ + $overWrite = false; + } + if ($overWrite) { + if ($tableExists !== false) { + $additionalTable->deleteAll( $tableExists['ADD_TAB_UID'] ); + } + } else { + if ($tableExists !== false) { + // some table exists with the same name + // renaming... + $tNameOld = $contentSchema['ADD_TAB_NAME']; + $newTableName = $contentSchema['ADD_TAB_NAME'] . '_' . date( 'YmdHis' ); + $contentSchema['ADD_TAB_UID'] = G::generateUniqueID(); + $contentSchema['ADD_TAB_NAME'] = $newTableName; + $contentSchema['ADD_TAB_CLASS_NAME'] = additionalTables::getPHPName( $newTableName ); + //mapping the table name for posterior uses + $tableNameMap[$tNameOld] = $contentSchema['ADD_TAB_NAME']; } } - } - - if ($overWrite) { - if ($tableExists !== false) { - $additionalTable->deleteAll( $tableExists['ADD_TAB_UID'] ); + + // validating invalid bds_uid in old tables definition -> mapped to workflow + if (! $contentSchema['DBS_UID'] || $contentSchema['DBS_UID'] == '0' || ! $contentSchema['DBS_UID']) { + $contentSchema['DBS_UID'] = 'workflow'; } - } else { - if ($tableExists !== false) { - // some table exists with the same name - // renaming... - $tNameOld = $contentSchema['ADD_TAB_NAME']; - $newTableName = $contentSchema['ADD_TAB_NAME'] . '_' . date( 'YmdHis' ); - $contentSchema['ADD_TAB_UID'] = G::generateUniqueID(); - $contentSchema['ADD_TAB_NAME'] = $newTableName; - $contentSchema['ADD_TAB_CLASS_NAME'] = additionalTables::getPHPName( $newTableName ); - //mapping the table name for posterior uses - $tableNameMap[$tNameOld] = $contentSchema['ADD_TAB_NAME']; + + $columns = array (); + foreach ($contentSchema['FIELDS'] as $field) { + $column = array ( + 'uid' => '', + 'field_uid' => '', + 'field_name' => $field['FLD_NAME'], + 'field_dyn' => isset( $field['FLD_DYN_NAME'] ) ? $field['FLD_DYN_NAME'] : '', + 'field_label' => isset( $field['FLD_DESCRIPTION'] ) ? $field['FLD_DESCRIPTION'] : '', + 'field_type' => $field['FLD_TYPE'],'field_size' => $field['FLD_SIZE'], + 'field_key' => isset( $field['FLD_KEY'] ) ? $field['FLD_KEY'] : 0, + 'field_null' => isset( $field['FLD_NULL'] ) ? $field['FLD_NULL'] : 1, + 'field_autoincrement' => isset( $field['FLD_AUTO_INCREMENT'] ) ? $field['FLD_AUTO_INCREMENT'] : 0 + ); + $columns[] = $column; + } + + $tableData->REP_TAB_UID = $contentSchema['ADD_TAB_UID']; + $tableData->REP_TAB_NAME = $contentSchema['ADD_TAB_NAME']; + $tableData->REP_TAB_DSC = $contentSchema['ADD_TAB_DESCRIPTION']; + $tableData->REP_TAB_CONNECTION = $contentSchema['DBS_UID']; + $tableData->REP_TAB_TYPE = isset( $contentSchema['ADD_TAB_TYPE'] ) ? $contentSchema['ADD_TAB_TYPE'] : ''; + $tableData->REP_TAB_GRID = isset( $contentSchema['ADD_TAB_GRID'] ) ? $contentSchema['ADD_TAB_GRID'] : ''; + $tableData->columns = G::json_encode( $columns ); + $tableData->forceUid = true; + + //save the table + $alterTable = false; + $result = $this->save( $tableData, $alterTable ); + + if ($result->success) { + G::auditLog("ImportTable", $contentSchema['ADD_TAB_NAME']." (".$contentSchema['ADD_TAB_UID'].") "); + $processQueueTables[$contentSchema['DBS_UID']][] = $contentSchema['ADD_TAB_NAME']; + } else { + $errors .= G::loadTranslation('ID_ERROR_CREATE_TABLE') . $tableData->REP_TAB_NAME . '-> ' . $result->message . "\n\n"; } } - - // validating invalid bds_uid in old tables definition -> mapped to workflow - if (! $contentSchema['DBS_UID'] || $contentSchema['DBS_UID'] == '0' || ! $contentSchema['DBS_UID']) { - $contentSchema['DBS_UID'] = 'workflow'; - } - - $columns = array (); - foreach ($contentSchema['FIELDS'] as $field) { - $column = array ('uid' => '','field_uid' => '','field_name' => $field['FLD_NAME'],'field_dyn' => isset( $field['FLD_DYN_NAME'] ) ? $field['FLD_DYN_NAME'] : '','field_label' => isset( $field['FLD_DESCRIPTION'] ) ? $field['FLD_DESCRIPTION'] : '','field_type' => $field['FLD_TYPE'],'field_size' => $field['FLD_SIZE'],'field_key' => isset( $field['FLD_KEY'] ) ? $field['FLD_KEY'] : 0,'field_null' => isset( $field['FLD_NULL'] ) ? $field['FLD_NULL'] : 1,'field_autoincrement' => isset( $field['FLD_AUTO_INCREMENT'] ) ? $field['FLD_AUTO_INCREMENT'] : 0 - ); - $columns[] = $column; - } - - $tableData->REP_TAB_UID = $contentSchema['ADD_TAB_UID']; - $tableData->REP_TAB_NAME = $contentSchema['ADD_TAB_NAME']; - $tableData->REP_TAB_DSC = $contentSchema['ADD_TAB_DESCRIPTION']; - $tableData->REP_TAB_CONNECTION = $contentSchema['DBS_UID']; - - $tableData->REP_TAB_TYPE = isset( $contentSchema['ADD_TAB_TYPE'] ) ? $contentSchema['ADD_TAB_TYPE'] : ''; - $tableData->REP_TAB_GRID = isset( $contentSchema['ADD_TAB_GRID'] ) ? $contentSchema['ADD_TAB_GRID'] : ''; - $tableData->columns = G::json_encode( $columns ); - $tableData->forceUid = true; - - //save the table - $alterTable = false; - $result = $this->save( $tableData, $alterTable ); - - if ($result->success) { - $processQueueTables[$contentSchema['DBS_UID']][] = $contentSchema['ADD_TAB_NAME']; - } else { - $errors .= 'Error creating table: ' . $tableData->REP_TAB_NAME . '-> ' . $result->message . "\n\n"; - } - break; case '@DATA': $fstName = intval( fread( $fp, 9 ) ); @@ -1128,79 +1318,73 @@ class pmTablesProxy extends HttpProxyController } else { break; } - } + } + fclose( $fp ); - fclose( $fp ); - G::loadClass( 'pmTable' ); - - foreach ($processQueueTables as $dbsUid => $tables) { + G::loadClass( 'pmTable' ); + foreach ($processQueueTables as $dbsUid => $tables) { $pmTable = new pmTable(); ob_start(); $pmTable->buildModelFor( $dbsUid, $tables ); $buildResult = ob_get_contents(); ob_end_clean(); $errors .= $pmTable->upgradeDatabaseFor( $pmTable->getDataSource(), $tables ); - } - - $fp = fopen( $PUBLIC_ROOT_PATH . $filename, "rb" ); - $fsData = intval( fread( $fp, 9 ) ); - $sType = fread( $fp, $fsData ); - - // data processing - while (! feof( $fp )) { - + } + if(sizeof($tableNameMap)>0){ + $errors = $this->dataProcessingOfTables($tableFile,$tableNameMap); + } + return $errors; + } + /** + * Review the *.pmt file and populate the data + * @param string $tableFile + * @param array $tableNameMap + * @return string errors + */ + public function dataProcessingOfTables($tableFile,$tableNameMap){ + $fp = fopen( $tableFile, "rb" ); + $fsData = intval( fread( $fp, 9 ) ); + $sType = fread( $fp, $fsData ); + $errors = ''; + while (! feof( $fp )) { switch ($sType) { case '@META': - $fsData = intval( fread( $fp, 9 ) ); - $METADATA = fread( $fp, $fsData ); - break; case '@SCHEMA': - $fsUid = intval( fread( $fp, 9 ) ); - $uid = fread( $fp, $fsUid ); - $fsData = intval( fread( $fp, 9 ) ); - $schema = fread( $fp, $fsData ); - $contentSchema = unserialize( $schema ); - $additionalTable = new additionalTables(); - $table = $additionalTable->loadByName( $tableNameMap[$contentSchema['ADD_TAB_NAME']] ); - if ($table['PRO_UID'] != '') { - // is a report table, try populate it - $additionalTable->populateReportTable( $table['ADD_TAB_NAME'], pmTable::resolveDbSource( $table['DBS_UID'] ), $table['ADD_TAB_TYPE'], $table['PRO_UID'], $table['ADD_TAB_GRID'], $table['ADD_TAB_UID'] ); - } - G::auditLog("ImportTable", $table['ADD_TAB_NAME']." (".$table['ADD_TAB_UID'].") "); break; case '@DATA': $fstName = intval( fread( $fp, 9 ) ); $tableName = fread( $fp, $fstName ); $fsData = intval( fread( $fp, 9 ) ); - if ($fsData > 0) { $data = fread( $fp, $fsData ); $contentData = unserialize( $data ); - $tableName = $tableNameMap[$tableName]; + if(isset($tableNameMap[$tableName])){ + $tableName = $tableNameMap[$tableName]; - $oAdditionalTables = new AdditionalTables(); - $table = $oAdditionalTables->loadByName( $tableName ); - $isReport = $table['PRO_UID'] !== '' ? true : false; + $oAdditionalTables = new AdditionalTables(); + $table = $oAdditionalTables->loadByName( $tableName ); + $isReport = $table['PRO_UID'] !== '' ? true : false; - if ($table !== false) { - if (! $isReport) { - if (count( $contentData ) > 0) { - $oAdditionalTables->load( $table['ADD_TAB_UID'], true ); - $primaryKeys = $oAdditionalTables->getPrimaryKeys(); - // Obtain a list of columns - $primaryKeyColumn = array(); - foreach ($contentData as $key => $row) { - $primaryKeyColumn[$key] = $row[$primaryKeys[0]['FLD_NAME']]; - } - unset($row); - array_multisort($primaryKeyColumn, SORT_ASC, $contentData); - foreach ($contentData as $row) { - $data = new StdClass(); - $data->id = $table['ADD_TAB_UID']; - $data->rows = base64_encode( serialize( $row ) ); - $res = $this->dataCreate( $data, 'base64' ); - if (! $res->success) { - $errors .= $res->message; + if ($table !== false) { + if (! $isReport) { + if (count( $contentData ) > 0) { + $oAdditionalTables->load( $table['ADD_TAB_UID'], true ); + $primaryKeys = $oAdditionalTables->getPrimaryKeys(); + // Obtain a list of columns + $primaryKeyColumn = array(); + foreach ($contentData as $key => $row) { + $primaryKeyColumn[$key] = $row[$primaryKeys[0]['FLD_NAME']]; + } + unset($row); + array_multisort($primaryKeyColumn, SORT_ASC, $contentData); + foreach ($contentData as $row) { + $data = new StdClass(); + $data->id = $table['ADD_TAB_UID']; + $data->rows = base64_encode( serialize( $row ) ); + $res = $this->dataCreate( $data, 'base64' ); + if (! $res->success) { + $errors .= $res->message; + } } } } @@ -1216,44 +1400,8 @@ class pmTablesProxy extends HttpProxyController } else { break; } - } - - //////////// - - - if ($errors == '') { - $result->success = true; - $msg = G::loadTranslation( 'ID_PMTABLE_IMPORT_SUCCESS', array ($filename - ) ); - } else { - $result->success = false; - $result->errorType = 'warning'; - $msg = G::loadTranslation( 'ID_PMTABLE_IMPORT_WITH_ERRORS', array ($filename - ) ) . "\n\n" . $errors; - } - - $result->message = $msg; - } catch (Exception $e) { - $result = new stdClass(); - $result->fromAdmin = $fromAdmin; - $result->validationType = $validationType; - $result->errorType = 'error'; - $result->buildResult = ob_get_contents(); - ob_end_clean(); - $result->success = false; - - // if it is a propel exception message - if (preg_match( '/(.*)\s\[(.*):\s(.*)\]\s\[(.*):\s(.*)\]/', $e->getMessage(), $match )) { - $result->message = $match[3]; - $result->type = G::loadTranslation( 'ID_ERROR' ); - } else { - $result->message = $e->getMessage(); - $result->type = G::loadTranslation( 'ID_EXCEPTION' ); - } - //$result->trace = $e->getTraceAsString(); } - - return $result; + return $errors; } /** @@ -1537,6 +1685,7 @@ class pmTablesProxy extends HttpProxyController $application->field_size = 32; $application->field_dyn = ''; $application->field_key = 1; + $application->field_index = 1; $application->field_null = 0; $application->field_filter = false; $application->field_autoincrement = false; @@ -1723,25 +1872,25 @@ class pmTablesProxy extends HttpProxyController $row = $oDataset->getRow(); if (isset($row["PRJ_UID"])) { $sProcessUID = $row["PRJ_UID"]; - - $arrayDataTypeToExclude = array("array", "grid"); - $arrayTypeToExclude = array("title", "subtitle", "link", "file", "button", "reset", "submit", "listbox", "grid", "array", "javascript", "location", "scannerCode"); - - $arrayControlSupported = array(); - - $dynaformAllControl = $this->getDynaformVariables($sProcessUID, $arrayTypeToExclude, true, "DATA"); - - foreach ($dynaformAllControl as $value) { - $arrayControl = array_change_key_case($value, CASE_UPPER); - - if(isset($arrayControl["DATATYPE"]) && isset($arrayControl["TYPE"])){ - if (!in_array($arrayControl["DATATYPE"], $arrayDataTypeToExclude) && !in_array($arrayControl["TYPE"], $arrayTypeToExclude)) { - $arrayControlSupported[$arrayControl["VAR_UID"]] = $arrayControl["TYPE"]; - } - } - } - - $dynaformNotAllowedVariables = $this->getDynaformVariables($sProcessUID,$arrayTypeToExclude,false); + + $arrayDataTypeToExclude = array("array", "grid"); + $arrayTypeToExclude = array("title", "subtitle", "link", "file", "button", "reset", "submit", "listbox", "grid", "array", "javascript", "location", "scannerCode"); + + $arrayControlSupported = array(); + + $dynaformAllControl = $this->getDynaformVariables($sProcessUID, $arrayTypeToExclude, true, "DATA"); + + foreach ($dynaformAllControl as $value) { + $arrayControl = array_change_key_case($value, CASE_UPPER); + + if(isset($arrayControl["DATATYPE"]) && isset($arrayControl["TYPE"])){ + if (!in_array($arrayControl["DATATYPE"], $arrayDataTypeToExclude) && !in_array($arrayControl["TYPE"], $arrayTypeToExclude)) { + $arrayControlSupported[$arrayControl["VAR_UID"]] = $arrayControl["TYPE"]; + } + } + } + + $dynaformNotAllowedVariables = $this->getDynaformVariables($sProcessUID,$arrayTypeToExclude,false); $oCriteria = new Criteria('workflow'); $oCriteria->addSelectColumn(ProcessVariablesPeer::VAR_UID); $oCriteria->addSelectColumn(ProcessVariablesPeer::VAR_NAME); @@ -1752,7 +1901,7 @@ class pmTablesProxy extends HttpProxyController $index = 0; while ($oDataset->next()) { $row = $oDataset->getRow(); - if(!in_array($row["VAR_NAME"], $dynaformNotAllowedVariables) && !in_array($row["VAR_FIELD_TYPE"], $arrayTypeToExclude) && !in_array($row["VAR_NAME"], $fieldsNames)) { + if(!in_array($row["VAR_NAME"], $dynaformNotAllowedVariables) && !in_array($row["VAR_FIELD_TYPE"], $arrayTypeToExclude) && !in_array($row["VAR_NAME"], $fieldsNames)) { array_push($fields, array( "FIELD_UID" => $row["VAR_NAME"] . "-" . $row["VAR_FIELD_TYPE"], "FIELD_NAME" => $row["VAR_NAME"], @@ -1761,20 +1910,20 @@ class pmTablesProxy extends HttpProxyController "_isset" => true )); } - - array_push($fieldsNames, $row["VAR_NAME"]); - - if (isset($arrayControlSupported[$row["VAR_UID"]]) && !in_array($row["VAR_NAME"] . "_label", $fieldsNames)) { - array_push($fields, array( - "FIELD_UID" => $row["VAR_NAME"] . "_label-" . $arrayControlSupported[$row["VAR_UID"]], - "FIELD_NAME" => $row["VAR_NAME"] . "_label", - "FIELD_VALIDATE" => "any", - "_index" => $index++, - "_isset" => true - )); - - array_push($fieldsNames, $row["VAR_NAME"] . "_label"); - } + + array_push($fieldsNames, $row["VAR_NAME"]); + + if (isset($arrayControlSupported[$row["VAR_UID"]]) && !in_array($row["VAR_NAME"] . "_label", $fieldsNames)) { + array_push($fields, array( + "FIELD_UID" => $row["VAR_NAME"] . "_label-" . $arrayControlSupported[$row["VAR_UID"]], + "FIELD_NAME" => $row["VAR_NAME"] . "_label", + "FIELD_VALIDATE" => "any", + "_index" => $index++, + "_isset" => true + )); + + array_push($fieldsNames, $row["VAR_NAME"] . "_label"); + } } } @@ -1919,7 +2068,7 @@ class pmTablesProxy extends HttpProxyController * * @param $sProcessUID */ - public function getDynaformVariables($sProcessUID, $excludeFieldsList, $allowed = true, $option = "VARIABLE") + public function getDynaformVariables($sProcessUID, $excludeFieldsList, $allowed = true, $option = "VARIABLE") { $dynaformVariables = array(); $oC = new Criteria( 'workflow' ); @@ -1936,33 +2085,33 @@ class pmTablesProxy extends HttpProxyController foreach($val as $column) { if($allowed) { if(isset($column['type']) && !in_array( $column['type'], $excludeFieldsList )){ - switch ($option) { - case "VARIABLE": - if (array_key_exists("variable", $column)) { - if($column["variable"] != "") { - $dynaformVariables[] = $column["variable"]; - } - } - break; - case "DATA": - $dynaformVariables[] = $column; - break; - } + switch ($option) { + case "VARIABLE": + if (array_key_exists("variable", $column)) { + if($column["variable"] != "") { + $dynaformVariables[] = $column["variable"]; + } + } + break; + case "DATA": + $dynaformVariables[] = $column; + break; + } } } else { if(isset($column['type']) && in_array( $column['type'], $excludeFieldsList )){ - switch ($option) { - case "VARIABLE": - if (array_key_exists("variable", $column)) { - if($column["variable"] != "") { - $dynaformVariables[] = $column["variable"]; - } - } - break; - case "DATA": - $dynaformVariables[] = $column; - break; - } + switch ($option) { + case "VARIABLE": + if (array_key_exists("variable", $column)) { + if($column["variable"] != "") { + $dynaformVariables[] = $column["variable"]; + } + } + break; + case "DATA": + $dynaformVariables[] = $column; + break; + } } } } @@ -1970,12 +2119,12 @@ class pmTablesProxy extends HttpProxyController } $oData->next(); } - - if ($option == "VARIABLE") { - return array_unique($dynaformVariables); - } else { - return $dynaformVariables; - } + + if ($option == "VARIABLE") { + return array_unique($dynaformVariables); + } else { + return $dynaformVariables; + } } } diff --git a/workflow/engine/controllers/processProxy.php b/workflow/engine/controllers/processProxy.php index 072ce56b5..3e3607644 100755 --- a/workflow/engine/controllers/processProxy.php +++ b/workflow/engine/controllers/processProxy.php @@ -118,7 +118,7 @@ class ProcessProxy extends HttpProxyController $oProcess = new Processes(); if (count( $ids ) > 0) { foreach ($ids as $id) { - $oProcess->changeStatus( $id ); + $oProcess->changeStatus( htmlspecialchars($id) ); } } } diff --git a/workflow/engine/data/mssql/insert.sql b/workflow/engine/data/mssql/insert.sql index c456c426a..04cec9c0f 100755 --- a/workflow/engine/data/mssql/insert.sql +++ b/workflow/engine/data/mssql/insert.sql @@ -11,6 +11,24 @@ SELECT 'PER_NAME','','00000000000000000000000000000016','en','Add Folders' UNION SELECT 'PER_NAME','','00000000000000000000000000000017','en','Add file in folders' UNION ALL SELECT 'PER_NAME','','00000000000000000000000000000018','en','Cancel cases' UNION ALL SELECT 'PER_NAME','','00000000000000000000000000000019','en','Delete folders' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000020','en','Setup Logo' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000021','en','Setup Email' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000022','en','Setup Calendar' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000023','en','Setup Process Categories' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000024','en','Setup Clear Cache' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000025','en','Setup Heart Beat' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000026','en','Setup Environment' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000027','en','Setup PM Tables' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000028','en','Setup Login' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000029','en','Setup Dashborads' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000030','en','Setup Language' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000031','en','Setup Skin' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000032','en','Setup Case List Cache Builder' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000033','en','Setup Plugins' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000034','en','Setup User Authentication Sources' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000035','en','Setup Logs' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000036','en','Delete process cases' UNION ALL +SELECT 'PER_NAME','','00000000000000000000000000000037','en','Edit personal info Calendar' UNION ALL SELECT 'PER_NAME','','00000000000000000000000000000013','en','Delete cases' UNION ALL SELECT 'PER_NAME','','00000000000000000000000000000012','en','WebDav' UNION ALL SELECT 'PER_NAME','','00000000000000000000000000000011','en','Dashboard' UNION ALL diff --git a/workflow/engine/data/mysql/insert.sql b/workflow/engine/data/mysql/insert.sql index 57d07b971..9f0d55ead 100644 --- a/workflow/engine/data/mysql/insert.sql +++ b/workflow/engine/data/mysql/insert.sql @@ -11,6 +11,24 @@ INSERT INTO CONTENT (CON_CATEGORY,CON_PARENT,CON_ID,CON_LANG,CON_VALUE) VALUES ('PER_NAME','','00000000000000000000000000000017','en','Add file in folders'), ('PER_NAME','','00000000000000000000000000000018','en','Cancel cases'), ('PER_NAME','','00000000000000000000000000000019','en','Delete folders'), +('PER_NAME','','00000000000000000000000000000020','en','Setup Logo'), +('PER_NAME','','00000000000000000000000000000021','en','Setup Email'), +('PER_NAME','','00000000000000000000000000000022','en','Setup Calendar'), +('PER_NAME','','00000000000000000000000000000023','en','Setup Process Categories'), +('PER_NAME','','00000000000000000000000000000024','en','Setup Clear Cache'), +('PER_NAME','','00000000000000000000000000000025','en','Setup Heart Beat'), +('PER_NAME','','00000000000000000000000000000026','en','Setup Environment'), +('PER_NAME','','00000000000000000000000000000027','en','Setup PM Tables'), +('PER_NAME','','00000000000000000000000000000028','en','Setup Login'), +('PER_NAME','','00000000000000000000000000000029','en','Setup Dashborads'), +('PER_NAME','','00000000000000000000000000000030','en','Setup Language'), +('PER_NAME','','00000000000000000000000000000031','en','Setup Skin'), +('PER_NAME','','00000000000000000000000000000032','en','Setup Case List Cache Builder'), +('PER_NAME','','00000000000000000000000000000033','en','Setup Plugins'), +('PER_NAME','','00000000000000000000000000000034','en','Setup User Authentication Sources'), +('PER_NAME','','00000000000000000000000000000035','en','Setup Logs'), +('PER_NAME','','00000000000000000000000000000036','en','Delete process cases'), +('PER_NAME','','00000000000000000000000000000037','en','Edit personal info Calendar'), ('PER_NAME','','00000000000000000000000000000013','en','Delete cases'), ('PER_NAME','','00000000000000000000000000000012','en','WebDav'), ('PER_NAME','','00000000000000000000000000000011','en','Dashboard'), diff --git a/workflow/engine/data/mysql/schema.sql b/workflow/engine/data/mysql/schema.sql index eab7c5a91..3ac42de52 100755 --- a/workflow/engine/data/mysql/schema.sql +++ b/workflow/engine/data/mysql/schema.sql @@ -96,7 +96,9 @@ CREATE TABLE `APP_DOCUMENT` `APP_DOC_STATUS` VARCHAR(32) default 'ACTIVE' NOT NULL, `APP_DOC_STATUS_DATE` DATETIME, `APP_DOC_FIELDNAME` VARCHAR(150), - `APP_DOC_DRIVE_DOWNLOAD` MEDIUMTEXT, + `APP_DOC_DRIVE_DOWNLOAD` MEDIUMTEXT, + `SYNC_WITH_DRIVE` VARCHAR(32) default 'UNSYNCHRONIZED' NOT NULL, + `SYNC_PERMISSIONS` MEDIUMTEXT, PRIMARY KEY (`APP_DOC_UID`,`DOC_VERSION`), KEY `indexAppDocument`(`FOLDER_UID`, `APP_DOC_UID`) )ENGINE=InnoDB DEFAULT CHARSET='utf8' COMMENT='Documents in an Application'; @@ -175,6 +177,8 @@ CREATE TABLE `CONTENT` `CON_LANG` VARCHAR(10) default '' NOT NULL, `CON_VALUE` MEDIUMTEXT NOT NULL, PRIMARY KEY (`CON_CATEGORY`,`CON_PARENT`,`CON_ID`,`CON_LANG`), + KEY `indexUidLang`(`CON_ID`, `CON_LANG`), + KEY `indexCatParUidLang`(`CON_CATEGORY`, `CON_PARENT`, `CON_ID`, `CON_LANG`), KEY `indexUid`(`CON_ID`, `CON_CATEGORY`, `CON_LANG`) )ENGINE=InnoDB DEFAULT CHARSET='utf8'; #----------------------------------------------------------------------------- @@ -1190,6 +1194,7 @@ CREATE TABLE `APP_CACHE_VIEW` `APP_UPDATE_DATE` DATETIME NOT NULL, `APP_OVERDUE_PERCENTAGE` DOUBLE NOT NULL, PRIMARY KEY (`APP_UID`,`DEL_INDEX`), + KEY `indexProUid`(`PRO_UID`), KEY `indexAppNumber`(`APP_NUMBER`), KEY `protitle`(`APP_PRO_TITLE`), KEY `appupdatedate`(`APP_UPDATE_DATE`), @@ -2258,6 +2263,7 @@ CREATE TABLE `LIST_INBOX` `DEL_RISK_DATE` DATETIME, `DEL_PRIORITY` VARCHAR(32) default '3' NOT NULL, PRIMARY KEY (`APP_UID`,`DEL_INDEX`), + KEY `indexUser`(`USR_UID`), KEY `indexInboxUser`(`USR_UID`, `DEL_DELEGATE_DATE`), KEY `indexInboxUserStatusUpdateDate`(`USR_UID`, `APP_STATUS`, `APP_UPDATE_DATE`) )ENGINE=InnoDB DEFAULT CHARSET='utf8' COMMENT='Inbox list'; @@ -2319,6 +2325,7 @@ CREATE TABLE `LIST_PARTICIPATED_LAST` `DEL_CURRENT_USR_USERNAME` VARCHAR(100) default '', `DEL_CURRENT_USR_FIRSTNAME` VARCHAR(50) default '', `DEL_CURRENT_USR_LASTNAME` VARCHAR(50) default '', + `DEL_CURRENT_TAS_TITLE` VARCHAR(255) default '' NOT NULL,) `DEL_DELEGATE_DATE` DATETIME NOT NULL, `DEL_INIT_DATE` DATETIME, `DEL_DUE_DATE` DATETIME, @@ -2919,4 +2926,28 @@ CREATE TABLE `NOTIFICATION_DEVICE` KEY `indexUserNotification`(`USR_UID`) )ENGINE=InnoDB DEFAULT CHARSET='utf8' COMMENT='Definitions Notification device.'; # This restores the fkey checks, after having unset them earlier +# SET FOREIGN_KEY_CHECKS = 1; + + + +#----------------------------------------------------------------------------- +#-- GMAIL_RELABELING +#----------------------------------------------------------------------------- +DROP TABLE IF EXISTS `GMAIL_RELABELING`; + +CREATE TABLE `GMAIL_RELABELING` ( + `LABELING_UID` VARCHAR(32) NOT NULL, + `CREATE_DATE` DATETIME NOT NULL, + `APP_UID` VARCHAR(32) NOT NULL DEFAULT '', + `DEL_INDEX` INT(11) NOT NULL DEFAULT '0', + `CURRENT_LAST_INDEX` INT(11) NOT NULL DEFAULT '0', + `UNASSIGNED` INT(11) NOT NULL DEFAULT '0', + `STATUS` VARCHAR(32) NOT NULL DEFAULT 'pending', + `MSG_ERROR` TEXT NULL, + PRIMARY KEY (`LABELING_UID`), + KEY `indexStatus` (`STATUS`) +)ENGINE=InnoDB DEFAULT CHARSET='utf8' COMMENT='Task to synchronize Gmail Labels'; + +# This restores the fkey checks, after having unset them earlier + SET FOREIGN_KEY_CHECKS = 1; diff --git a/workflow/engine/menus/caseOptions.php b/workflow/engine/menus/caseOptions.php index 905c52c47..8c683d07a 100755 --- a/workflow/engine/menus/caseOptions.php +++ b/workflow/engine/menus/caseOptions.php @@ -24,26 +24,59 @@ */ global $G_TMP_MENU; global $sStatus; +global $RBAC; +$statusSendAndUnassigned = false; -if ((($sStatus == 'DRAFT') || ($sStatus == 'TO_DO')) && ($_SESSION['TASK'] != -1)) { - if (isset($_SESSION['bNoShowSteps'])) { - unset($_SESSION['bNoShowSteps']); - } else { - $G_TMP_MENU->AddIdOption('STEPS' , G::LoadTranslation('ID_STEPS') , 'javascript:showSteps();' , 'absolute'); - $G_TMP_MENU->AddIdOption('INFO' , G::LoadTranslation('ID_INFORMATION'), 'javascript:showInformation();', 'absolute'); - } - $G_TMP_MENU->AddIdOption('ACTIONS' , G::LoadTranslation('ID_ACTIONS') , 'javascript:showActions();' , 'absolute'); -} else { - $G_TMP_MENU->AddIdOption('INFO' , G::LoadTranslation('ID_INFORMATION'), 'javascript:showInformation();', 'absolute'); +//caseOptions +switch ($_SESSION['actionCaseOptions']) { + case 'todo': + case 'draft': + if (isset($_SESSION['bNoShowSteps'])) { + unset($_SESSION['bNoShowSteps']); + } + break; + case 'sent': + case 'unassigned': + $_SESSION['TASK'] = -1; + $statusSendAndUnassigned = true; + break; + case 'paused': + $access = $RBAC->requirePermissions('PM_ALLCASES'); + if ($access) { + if (isset($_SESSION['bNoShowSteps'])) { + unset($_SESSION['bNoShowSteps']); + } + } else { + $_SESSION['TASK'] = -1; + } + break; + case 'to_revise': + case 'to_reassign': + $access = $RBAC->requirePermissions('PM_REASSIGNCASE', 'PM_SUPERVISOR'); + if ($access) { + if (isset($_SESSION['bNoShowSteps'])) { + unset($_SESSION['bNoShowSteps']); + } + } else { + $_SESSION['TASK'] = -1; + } + break; + default: + unset($_SESSION['bNoShowSteps']); + break; } -$G_TMP_MENU->AddIdOption('NOTES' , G::LoadTranslation('ID_NOTES'), 'javascript:showNotes();', 'absolute'); - - - - - - - - +unset($_SESSION['actionCaseOptions']); +if ((($sStatus === 'DRAFT') || ($sStatus === 'TO_DO')) && !$statusSendAndUnassigned) { + if (isset($_SESSION['bNoShowSteps'])) { + unset($_SESSION['bNoShowSteps']); + } else { + $G_TMP_MENU->AddIdOption('STEPS', G::LoadTranslation('ID_STEPS'), 'javascript:showSteps();', 'absolute'); + $G_TMP_MENU->AddIdOption('INFO', G::LoadTranslation('ID_INFORMATION'), 'javascript:showInformation();', 'absolute'); + } + $G_TMP_MENU->AddIdOption('ACTIONS', G::LoadTranslation('ID_ACTIONS'), 'javascript:showActions();', 'absolute'); +} else { + $G_TMP_MENU->AddIdOption('INFO', G::LoadTranslation('ID_INFORMATION'), 'javascript:showInformation();', 'absolute'); +} +$G_TMP_MENU->AddIdOption('NOTES', G::LoadTranslation('ID_NOTES'), 'javascript:showNotes();', 'absolute'); diff --git a/workflow/engine/menus/cases.php b/workflow/engine/menus/cases.php index 2ebf51b92..375568541 100755 --- a/workflow/engine/menus/cases.php +++ b/workflow/engine/menus/cases.php @@ -32,7 +32,8 @@ G::LoadTranslation('ID_NEW_CASE'), ''); /*----------------------------------********---------------------------------*/ $licensedFeatures = & PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7TTeDBQeWRoZTZKYjh4eFpYUlRDUUEyVERPU3FxellWank=')) { - $G_TMP_MENU->AddIdRawOption('CONSOLIDATED_CASES', 'casesConsolidatedListExtJs?action=consolidated', 'Batch Routing', ''); + $G_TMP_MENU->AddIdRawOption('CONSOLIDATED_CASES', 'casesConsolidatedListExtJs?action=consolidated', + G::LoadTranslation('ID_BATCH_ROUTING'), ''); } /*----------------------------------********---------------------------------*/ diff --git a/workflow/engine/menus/setup.php b/workflow/engine/menus/setup.php index b667de3ba..fad636ad4 100755 --- a/workflow/engine/menus/setup.php +++ b/workflow/engine/menus/setup.php @@ -27,101 +27,221 @@ global $RBAC; $partnerFlag = (defined('PARTNER_FLAG')) ? PARTNER_FLAG : false; /*----------------------------------********---------------------------------*/ -$oServerConf = & serverConf::getSingleton(); -$sAudit = $oServerConf->getAuditLogProperty( 'AL_OPTION', SYS_SYS ); -$licensedFeatures = & PMLicensedFeatures::getSingleton(); +$oServerConf = &serverConf::getSingleton(); +$sAudit = $oServerConf->getAuditLogProperty('AL_OPTION', SYS_SYS); +$licensedFeatures = &PMLicensedFeatures::getSingleton(); /*----------------------------------********---------------------------------*/ - -if ($RBAC->userCanAccess('PM_SETUP') == 1 ) { - //settings options - // $G_TMP_MENU->AddIdRawOption('LOGO', 'uplogo', G::LoadTranslation('ID_LOGO'), 'icon-pmlogo.png', '', 'settings'); - $G_TMP_MENU->AddIdRawOption('LOGO', '../admin/pmLogo', G::LoadTranslation('ID_LOGO'), 'icon-pmlogo.png','', 'settings'); - $G_TMP_MENU->AddIdRawOption("EMAIL_SERVER", "../emailServer/emailServer", G::LoadTranslation("ID_EMAIL_SERVER_TITLE"), "icon-email-settings1.png", "", "settings"); - $G_TMP_MENU->AddIdRawOption('CALENDAR', 'calendarList', G::LoadTranslation('ID_CALENDAR'), 'icon-calendar.png', '', 'settings' ); - //if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') == 1) - // $G_TMP_MENU->AddIdRawOption('CASES_LIST_SETUP', '../cases/casesListSetup', G::LoadTranslation('ID_CASES_LIST_SETUP'), "",'', 'settings'); - $G_TMP_MENU->AddIdRawOption('PROCESS_CATEGORY', '../processCategory/processCategoryList', G::LoadTranslation('ID_PROCESS_CATEGORY'), "rules.png",'', 'settings'); +if ($RBAC->userCanAccess('PM_SETUP') === 1) { + $pmSetupPermission = true; + if ($RBAC->userCanAccess('PM_SETUP_LOGO') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'LOGO', '../admin/pmLogo', + G::LoadTranslation('ID_LOGO'), + 'icon-pmlogo.png', '','settings' + ); + } + if ($RBAC->userCanAccess('PM_SETUP_EMAIL') === 1) { + $G_TMP_MENU->AddIdRawOption( + "EMAIL_SERVER", "../emailServer/emailServer", + G::LoadTranslation("ID_EMAIL_SERVER_TITLE"), + "icon-email-settings1.png", "", "settings" + ); + } + if ($RBAC->userCanAccess('PM_SETUP_CALENDAR') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'CALENDAR', 'calendarList', + G::LoadTranslation('ID_CALENDAR'), + 'icon-calendar.png', '', 'settings' + ); + } + if ($RBAC->userCanAccess('PM_SETUP_PROCESS_CATEGORIES') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'PROCESS_CATEGORY', '../processCategory/processCategoryList', + G::LoadTranslation('ID_PROCESS_CATEGORY'), + "rules.png", '', 'settings' + ); + } } -if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') == 1) { - $G_TMP_MENU->AddIdRawOption('LANGUAGES', 'languages', G::LoadTranslation('ID_LANGUAGES'), 'icon-language.png', '', 'settings'); +if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') === 1) { + if ($RBAC->userCanAccess('PM_SETUP_LANGUAGE') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'LANGUAGES', 'languages', + G::LoadTranslation('ID_LANGUAGES'), + 'icon-language.png','', 'settings' + ); + } } -if ($RBAC->userCanAccess('PM_SETUP') == 1 ) { - $G_TMP_MENU->AddIdRawOption('SKINS', 'skinsList', G::LoadTranslation('ID_SKINS'), 'icon-skins.png', '', 'settings'); +if ($RBAC->userCanAccess('PM_SETUP') === 1) { + if ($RBAC->userCanAccess('PM_SETUP_SKIN') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'SKINS', 'skinsList', + G::LoadTranslation('ID_SKINS'), + 'icon-skins.png', '', 'settings' + ); + } if (!$partnerFlag) { - $G_TMP_MENU->AddIdRawOption('HEARTBEAT', 'processHeartBeatConfig', G::LoadTranslation('ID_HEARTBEAT_CONFIG'), "heartBeat.jpg",'', 'settings'); + if ($RBAC->userCanAccess('PM_SETUP_HEART_BEAT') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'HEARTBEAT', 'processHeartBeatConfig', + G::LoadTranslation('ID_HEARTBEAT_CONFIG'), + "heartBeat.jpg", '', 'settings' + ); + } + } + if ($RBAC->userCanAccess('PM_SETUP_ENVIRONMENT') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'ENVIRONMENT_SETTINGS', 'environmentSettings', + G::LoadTranslation('ID_ENVIRONMENT_SETTINGS'), + "", '', 'settings' + ); } - - $G_TMP_MENU->AddIdRawOption('ENVIRONMENT_SETTINGS', 'environmentSettings', G::LoadTranslation('ID_ENVIRONMENT_SETTINGS'), "",'', 'settings'); } -if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') == 1) { - $G_TMP_MENU->AddIdRawOption('APPCACHEVIEW_SETUP', '../setup/appCacheViewConf', G::LoadTranslation('ID_APPCACHE_SETUP'), "",'', 'settings'); +if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'APPCACHEVIEW_SETUP', '../setup/appCacheViewConf', + G::LoadTranslation('ID_APPCACHE_SETUP'), + "", '', 'settings' + ); } -if ($RBAC->userCanAccess('PM_SETUP') == 1) { - $G_TMP_MENU->AddIdRawOption('CLEAR_CACHE', 'clearCompiled', G::LoadTranslation('ID_CLEAR_CACHE'), 'icon-rebuild-clean.png', "", 'settings' ); - //$G_TMP_MENU->AddIdRawOption('ADDITIONAL_TABLES', '../additionalTables/additionalTablesList', G::LoadTranslation('ID_ADDITIONAL_TABLES'), 'icon-tables.png','', 'settings'); - //$G_TMP_MENU->AddIdRawOption('REPORT_TABLES', '../reportTables/main', 'Report Tables', 'icon-tables.png','', 'settings'); - - $G_TMP_MENU->AddIdRawOption('PM_TABLES', '../pmTables', G::LoadTranslation('ID_ADDITIONAL_TABLES'), 'icon-tables.png','', 'settings'); - $G_TMP_MENU->AddIdRawOption('LOGIN', 'loginSettings', G::LoadTranslation('LOGIN'), "",'', 'settings'); - $G_TMP_MENU->AddIdRawOption('DASHBOARD', '../dashboard/dashletsList', ucfirst(G::LoadTranslation('ID_DASHBOARD')), '', '', 'settings'); - /*----------------------------------********---------------------------------*/ - - if ($licensedFeatures->verifyfeature('r19Vm5DK1UrT09MenlLYjZxejlhNUZ1b1NhV0JHWjBsZEJ6dnpJa3dTeWVLVT0=')) { - $G_TMP_MENU->AddIdRawOption('STRATEGIC_DASHBOARD', '../strategicDashboard/dashboardList', ucfirst(G::LoadTranslation('ID_STRATEGIC_DASHBOARD')), '', '', 'settings'); +if ($RBAC->userCanAccess('PM_SETUP') === 1) { + if ($RBAC->userCanAccess('PM_SETUP_CLEAR_CACHE') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'CLEAR_CACHE', 'clearCompiled', + G::LoadTranslation('ID_CLEAR_CACHE'), + 'icon-rebuild-clean.png', "", 'settings' + ); } - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - $G_TMP_MENU->AddIdRawOption('PMGMAIL', '../pmGmail/formPMGmail', ucfirst(G::LoadTranslation('ID_PMGMAIL')), '', '', 'settings'); + if ($RBAC->userCanAccess('PM_SETUP_PM_TABLES') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'PM_TABLES', '../pmTables', + G::LoadTranslation('ID_ADDITIONAL_TABLES'), + 'icon-tables.png', '', 'settings' + ); + } + if ($RBAC->userCanAccess('PM_SETUP_LOGIN') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'LOGIN', 'loginSettings', + G::LoadTranslation('LOGIN'), + "", '', 'settings' + ); + } + if ($RBAC->userCanAccess('PM_SETUP_DASHBOARDS') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'DASHBOARD', '../dashboard/dashletsList', + ucfirst(G::LoadTranslation('ID_DASHBOARD')), + '', '', 'settings' + ); + /*----------------------------------********---------------------------------*/ + if ($licensedFeatures->verifyfeature('r19Vm5DK1UrT09MenlLYjZxejlhNUZ1b1NhV0JHWjBsZEJ6dnpJa3dTeWVLVT0=')) { + $G_TMP_MENU->AddIdRawOption( + 'STRATEGIC_DASHBOARD', '../strategicDashboard/dashboardList', + ucfirst(G::LoadTranslation('ID_STRATEGIC_DASHBOARD')), + '', '', 'settings' + ); + } + if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + $G_TMP_MENU->AddIdRawOption( + 'PMGMAIL', '../pmGmail/formPMGmail', + ucfirst(G::LoadTranslation('ID_PMGMAIL')), + '', '', 'settings' + ); + } + /*----------------------------------********---------------------------------*/ } - - /*----------------------------------********---------------------------------*/ - } //tools options -if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') == 1 ) { +if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') === 1) { if (!$partnerFlag) { - $G_TMP_MENU->AddIdRawOption('PLUGINS', 'pluginsMain', G::LoadTranslation('ID_PLUGINS_MANAGER'), 'icon-plugins.png', '', 'plugins'); + if ($RBAC->userCanAccess('PM_SETUP_PLUGINS') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'PLUGINS', 'pluginsMain', + G::LoadTranslation('ID_PLUGINS_MANAGER'), + 'icon-plugins.png', '', 'plugins' + ); + } } } //users options -if ($RBAC->userCanAccess('PM_USERS') == 1) { - $G_TMP_MENU->AddIdRawOption('USERS', '../users/users_List', G::LoadTranslation('ID_USERS_LIST'), 'icon-webservices.png', '', 'users'); - +if ($RBAC->userCanAccess('PM_USERS') === 1) { + $G_TMP_MENU->AddIdRawOption('USERS', '../users/users_List', G::LoadTranslation('ID_USERS_LIST'), + 'icon-webservices.png', '', 'users'); $G_TMP_MENU->AddIdRawOption('GROUPS', '../groups/groups', G::LoadTranslation('ID_GROUPS'), '', '', 'users'); - $G_TMP_MENU->AddIdRawOption('DEPARTAMENTS', '../departments/departments', G::LoadTranslation('ID_DEPARTMENTS_USERS'), '', '', 'users'); - $G_TMP_MENU->AddIdRawOption('ROLES', '../roles/roles_List', G::LoadTranslation('ID_ROLES'), '', '', 'users'); + $G_TMP_MENU->AddIdRawOption( + 'DEPARTAMENTS', '../departments/departments', + G::LoadTranslation('ID_DEPARTMENTS_USERS'), + '', '', 'users' + ); + $G_TMP_MENU->AddIdRawOption('ROLES', '../roles/roles_List', + G::LoadTranslation('ID_ROLES'), + '', '', 'users' + ); } -if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') == 1 && $RBAC->userCanAccess('PM_USERS') == 1) { - $G_TMP_MENU->AddIdRawOption('AUTHSOURCES', '../authSources/authSources_List', G::LoadTranslation('ID_AUTH_SOURCES'), '', '', 'users'); +if ($RBAC->userCanAccess('PM_SETUP_ADVANCE') === 1 && $RBAC->userCanAccess('PM_USERS') === 1 && $RBAC->userCanAccess + ('PM_SETUP_USERS_AUTHENTICATION_SOURCES') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'AUTHSOURCES', '../authSources/authSources_List', + G::LoadTranslation('ID_AUTH_SOURCES'), + '', '', 'users' + ); $G_TMP_MENU->AddIdRawOption('UX', '../admin/uxList', G::LoadTranslation('ID_USER_EXPERIENCE'), '', '', 'users'); $G_TMP_MENU->AddIdRawOption('SYSTEM', '../admin/system', G::LoadTranslation('ID_SYSTEM'), '', '', 'settings'); - $G_TMP_MENU->AddIdRawOption('INFORMATION', '../setup/systemInfo?option=processInfo', G::LoadTranslation('ID_SYSTEM_INFO'), '', '', 'settings'); + $G_TMP_MENU->AddIdRawOption( + 'INFORMATION', '../setup/systemInfo?option=processInfo', + G::LoadTranslation('ID_SYSTEM_INFO'), + '', '', 'settings' + ); } -if ($RBAC->userCanAccess('PM_SETUP') == 1) { +if ($RBAC->userCanAccess('PM_SETUP') === 1 && $RBAC->userCanAccess('PM_SETUP_LOGS') === 1) { $G_TMP_MENU->AddIdRawOption('EVENT', '../events/eventList', G::LoadTranslation('ID_EVENTS'), '', '', 'logs'); - $G_TMP_MENU->AddIdRawOption('LOG_CASE_SCHEDULER', '../cases/cases_Scheduler_Log', G::LoadTranslation('ID_CASE_SCHEDULER'), "icon-logs-list.png",'', 'logs'); - $G_TMP_MENU->AddIdRawOption("CRON", "../setup/cron", G::LoadTranslation("ID_CRON_ACTIONS"), null, null, "logs"); - $G_TMP_MENU->AddIdRawOption('EMAILS', '../mails/emailList', ucfirst (strtolower ( G::LoadTranslation('ID_EMAILS'))), '', '', 'logs'); + $G_TMP_MENU->AddIdRawOption( + 'LOG_CASE_SCHEDULER', '../cases/cases_Scheduler_Log', + G::LoadTranslation('ID_CASE_SCHEDULER'), + "icon-logs-list.png", '', 'logs' + ); + $G_TMP_MENU->AddIdRawOption("CRON", "../setup/cron", G::LoadTranslation("ID_CRON_ACTIONS"), null, null, 'logs'); + $G_TMP_MENU->AddIdRawOption( + 'EMAILS', '../mails/emailList', + ucfirst(strtolower(G::LoadTranslation('ID_EMAILS'))), + '', '', 'logs' + ); /*----------------------------------********---------------------------------*/ - if (isset($sAudit) && $sAudit != false && $licensedFeatures->verifyfeature('vtSeHNhT0JnSmo1bTluUVlTYUxUbUFSVStEeXVqc1pEUG5EeXc0MGd2Q3ErYz0=')) { - $G_TMP_MENU->AddIdRawOption('AUDIT_LOG', '../setup/auditLog', ucfirst (G::LoadTranslation('ID_AUDITLOG_DISPLAY')), '', '', 'logs'); + if (isset($sAudit) && $sAudit !== false && $licensedFeatures->verifyfeature + ('vtSeHNhT0JnSmo1bTluUVlTYUxUbUFSVStEeXVqc1pEUG5EeXc0MGd2Q3ErYz0=') + ) { + $G_TMP_MENU->AddIdRawOption( + 'AUDIT_LOG', '../setup/auditLog', + ucfirst(G::LoadTranslation('ID_AUDITLOG_DISPLAY')), + '', '', 'logs' + ); } /*----------------------------------********---------------------------------*/ } -if ($RBAC->userCanAccess("PM_SETUP") == 1) { - $G_TMP_MENU->AddIdRawOption("PM_REQUIREMENTS", "../setup/systemInfo", G::LoadTranslation("ID_PROCESSMAKER_REQUIREMENTS_CHECK"), "", "", "settings"); - $G_TMP_MENU->AddIdRawOption("PHP_INFO", "../setup/systemInfo?option=php", G::LoadTranslation("ID_PHP_INFO"), "", "", "settings"); - //$G_TMP_MENU->AddIdRawOption("PHP_MAINTENANCE", "../admin/maintenance", 'Maintenance', "", "", "settings"); +if ($RBAC->userCanAccess('PM_SETUP') === 1) { + $G_TMP_MENU->AddIdRawOption( + 'PM_REQUIREMENTS', '../setup/systemInfo', + G::LoadTranslation('ID_PROCESSMAKER_REQUIREMENTS_CHECK'), + '', '', 'settings' + ); + $G_TMP_MENU->AddIdRawOption( + 'PHP_INFO', '../setup/systemInfo?option=php', + G::LoadTranslation('ID_PHP_INFO'), + '','', 'settings' + ); /*----------------------------------********---------------------------------*/ if ($licensedFeatures->verifyfeature('vtSeHNhT0JnSmo1bTluUVlTYUxUbUFSVStEeXVqc1pEUG5EeXc0MGd2Q3ErYz0=')) { - $G_TMP_MENU->AddIdRawOption("AUDIT_LOG", "auditLogConfig", G::LoadTranslation("ID_AUDITLOG_DISPLAY"), "", "", "settings"); + $G_TMP_MENU->AddIdRawOption( + "AUDIT_LOG", "auditLogConfig", + G::LoadTranslation("ID_AUDITLOG_DISPLAY"), + "", "","settings" + ); } /*----------------------------------********---------------------------------*/ } @@ -151,9 +271,35 @@ if ($licenseStatusInfo["message"] != "") { $licStatusMsg = " (" . $licenseStatusInfo["message"] . ")"; } /*----------------------------------********---------------------------------*/ -if ($RBAC->userCanAccess("PM_SETUP") == 1) { +if ($RBAC->userCanAccess('PM_SETUP') == 1) { /*----------------------------------********---------------------------------*/ - $G_TMP_MENU->AddIdRawOption("PMENTERPRISE", "../enterprise/addonsStore", G::LoadTranslation('ID_MENU_NAME') . $licStatusMsg, "", "", "plugins"); + if ($RBAC->userCanAccess('PM_SETUP_CASES_LIST_CACHE_BUILDER') == 1) { + $G_TMP_MENU->AddIdRawOption( + 'PMENTERPRISE', '../enterprise/addonsStore', + G::LoadTranslation('ID_MENU_NAME') .$licStatusMsg, + '', '', 'plugins' + ); + $G_TMP_MENU->AddIdRawOption( + 'CASES_LIST_SETUP', '../cases/casesListSetup', + G::LoadTranslation('ID_CUSTOM_CASES_LISTS'), + '', '', 'settings'); + } /*----------------------------------********---------------------------------*/ - $G_TMP_MENU->AddIdRawOption("CASES_LIST_SETUP", "../cases/casesListSetup", G::LoadTranslation("ID_CUSTOM_CASES_LISTS"), "", "", "settings"); } + +/*----------------------------------********---------------------------------*/ +$pluginRegistry = &PMPluginRegistry::getSingleton(); //lsl +$status = $pluginRegistry->getStatusPlugin('actionsByEmail'); + +if ((string)($status) !== 'enabled' && + $licensedFeatures->verifyfeature('zLhSk5TeEQrNFI2RXFEVktyUGpnczV1WEJNWVp6cjYxbTU3R29mVXVZNWhZQT0=') && + $RBAC->userCanAccess('PM_SETUP_LOGS') == 1 +) { + $G_TMP_MENU->AddIdRawOption( + 'PM_ACTIONS_BY_EMAIL_LOGS', + '../actionsByEmail/ActionByEmail.php', + G::LoadTranslation("ID_ACTIONS_BY_EMAIL_LOG"), + '', '', 'logs' + ); +} +/*----------------------------------********---------------------------------*/ diff --git a/workflow/engine/methods/actionsByEmail/ActionByEmail.php b/workflow/engine/methods/actionsByEmail/ActionByEmail.php new file mode 100644 index 000000000..450b99aa7 --- /dev/null +++ b/workflow/engine/methods/actionsByEmail/ActionByEmail.php @@ -0,0 +1,4 @@ +addExtJsScript('actionsByEmail/report', false); //adding a javascript file .js + +G::RenderPage('publish', 'extJs'); diff --git a/workflow/engine/methods/actionsByEmail/actionsByEmailAjax.php b/workflow/engine/methods/actionsByEmail/actionsByEmailAjax.php new file mode 100644 index 000000000..8a8079f64 --- /dev/null +++ b/workflow/engine/methods/actionsByEmail/actionsByEmailAjax.php @@ -0,0 +1,57 @@ +status = 'OK'; + +//Main switch +try { + $actionsByEmail = new \ProcessMaker\BusinessModel\ActionsByEmail(); + + switch ($_REQUEST['action']) { + case 'editTemplate': + $actionsByEmail->editTemplate($_REQUEST); + die(); + break; + case 'updateTemplate': + $actionsByEmail->updateTemplate($_REQUEST); + break; + case 'loadFields': + $actionsByEmail->loadFields($_REQUEST); + break; + case 'saveConfiguration': + $actionsByEmail->saveConfiguration2($_REQUEST); + break; + case 'loadActionByEmail': + $actionsByEmail->loadActionByEmail($_REQUEST); + break; + case 'forwardMail': + $actionsByEmail->forwardMail($_REQUEST); + die; + break; + case 'viewForm': + $actionsByEmail->viewForm($_REQUEST); + die; + break; + } +} catch (Exception $error) { + $response = new stdclass(); + $response->status = 'ERROR'; + $response->message = $error->getMessage(); +} + +header('Content-Type: application/json;'); + +die(G::json_encode($response)); diff --git a/workflow/engine/methods/cases/ajaxListener.php b/workflow/engine/methods/cases/ajaxListener.php index 0e49b524f..8cb426f07 100755 --- a/workflow/engine/methods/cases/ajaxListener.php +++ b/workflow/engine/methods/cases/ajaxListener.php @@ -200,7 +200,7 @@ class Ajax } else { $options[] = Array('text' => G::LoadTranslation('ID_UNPAUSE'), 'fn' => 'unpauseCase'); } - if ($RBAC->userCanAccess('PM_REASSIGNCASE') == 1) { + if ($RBAC->userCanAccess('PM_REASSIGNCASE') == 1 || $RBAC->userCanAccess('PM_SUPERVISOR') == 1) { $options[] = Array('text' => G::LoadTranslation('ID_REASSIGN'), 'fn' => 'getUsersToReassign'); } break; @@ -363,6 +363,8 @@ class Ajax } $taskData = $task->getDelegatedTaskData($_SESSION['TASK'], $_SESSION['APPLICATION'], $_SESSION['INDEX']); + $taskData = \ProcessMaker\Util\DateTime::convertUtcToTimeZone($taskData); + print (G::json_encode($taskData)); } @@ -518,14 +520,37 @@ class Ajax print G::json_encode( $response ); die(); } - G::LoadClass( 'tasks' ); - $task = new Task(); - $tasks = $task->load($_SESSION['TASK']); - $case = new Cases(); - $result = new stdclass(); - $result->data = $case->getUsersToReassign($_SESSION['TASK'], $_SESSION['USER_LOGGED'], $tasks['PRO_UID']); - print G::json_encode($result); + if(isset($_SESSION['TASK']) && $_SESSION['TASK'] != '-1'){ + $taskUid = $_SESSION['TASK']; + } else { + $taskUid = $_SESSION['CURRENT_TASK']; + } + $search = $_POST['search']; + $pageSize = $_POST['pageSize']; + + $sortField = (isset($_POST['sort']))? $_POST['sort'] : ''; + $sortDir = (isset($_POST['dir']))? $_POST['dir'] : ''; + $start = (isset($_POST['start']))? $_POST['start'] : 0; + $limit = (isset($_POST['limit']))? $_POST['limit'] : $pageSize; + + $response = []; + + try { + $case = new \ProcessMaker\BusinessModel\Cases(); + + $result = $case->getUsersToReassign($_SESSION['USER_LOGGED'], $taskUid, ['filter' => $search], $sortField, $sortDir, $start, $limit); + + $response['status'] = 'OK'; + $response['success'] = true; + $response['resultTotal'] = $result['total']; + $response['resultRoot'] = $result['data']; + } catch (Exception $e) { + $response['status'] = 'ERROR'; + $response['message'] = $e->getMessage(); + } + + echo G::json_encode($response); } public function reassignCase() diff --git a/workflow/engine/methods/cases/caseHistory_Ajax.php b/workflow/engine/methods/cases/caseHistory_Ajax.php index 052298332..abb067dc5 100644 --- a/workflow/engine/methods/cases/caseHistory_Ajax.php +++ b/workflow/engine/methods/cases/caseHistory_Ajax.php @@ -48,7 +48,7 @@ if ($actionAjax == 'historyGridList_JXP') { $newDir = '/tmp/test/directory'; G::verifyPath( $newDir ); $r = new stdclass(); - $r->data = $aProcesses; + $r->data = \ProcessMaker\Util\DateTime::convertUtcToTimeZone($aProcesses); $r->totalCount = 2; echo G::json_encode( $r ); diff --git a/workflow/engine/methods/cases/caseMessageHistory_Ajax.php b/workflow/engine/methods/cases/caseMessageHistory_Ajax.php index 9c360f572..5a466f1e0 100755 --- a/workflow/engine/methods/cases/caseMessageHistory_Ajax.php +++ b/workflow/engine/methods/cases/caseMessageHistory_Ajax.php @@ -122,11 +122,15 @@ if ($actionAjax == 'messageHistoryGridList_JXP') { $r->data = $aProcesses; $r->totalCount = $totalCount; - if (!isset($r->data[0])) { - $r->data[0] = array('APP_MSG_TYPE' => ''); - } + if (!empty($aProcesses)) { + if (!isset($r->data[0])) { + $r->data[0] = array('APP_MSG_TYPE' => ''); + } - $r->data[0]["APP_MSG_TYPE"] = (array_key_exists($r->data[0]["APP_MSG_TYPE"], $arrayToTranslation))? $arrayToTranslation[$r->data[0]["APP_MSG_TYPE"]] : $r->data[0]["APP_MSG_TYPE"]; + $r->data[0]["APP_MSG_TYPE"] = (array_key_exists($r->data[0]["APP_MSG_TYPE"], $arrayToTranslation)) ? + $arrayToTranslation[$r->data[0]["APP_MSG_TYPE"]] : + $r->data[0]["APP_MSG_TYPE"]; + } echo G::json_encode( $r ); } diff --git a/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php b/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php index 498b738a2..0a0d1cc2f 100644 --- a/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php +++ b/workflow/engine/methods/cases/casesHistoryDynaformPage_Ajax.php @@ -49,7 +49,7 @@ if ($actionAjax == 'historyDynaformGrid_Ajax') { $oCase = new Cases(); $aProcesses = Array (); - $c = $oCase->getallDynaformsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['TASK'], $_SESSION['USER_LOGGED'] ); + $c = $oCase->getallDynaformsCriteria( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['CURRENT_TASK'], $_SESSION['USER_LOGGED'] ); if ($c->getDbName() == 'dbarray') { $rs = ArrayBasePeer::doSelectRs( $c ); diff --git a/workflow/engine/methods/cases/casesListExtJs.php b/workflow/engine/methods/cases/casesListExtJs.php index 2abf2df5e..487e51660 100755 --- a/workflow/engine/methods/cases/casesListExtJs.php +++ b/workflow/engine/methods/cases/casesListExtJs.php @@ -222,6 +222,7 @@ $oHeadPublisher->addExtJsScript( 'app/main', true ); $oHeadPublisher->addExtJsScript( 'cases/casesList', false ); //adding a javascript file .js $oHeadPublisher->addContent( 'cases/casesListExtJs' ); //adding a html file .html. $oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); +$oHeadPublisher->assign('extJsViewState', $oHeadPublisher->getExtJsViewState()); $ieVersion = null; if(preg_match("/^.*\(.*MSIE (\d+)\..+\).*$/", $_SERVER["HTTP_USER_AGENT"], $arrayMatch) || preg_match("/^.*\(.*rv.(\d+)\..+\).*$/", $_SERVER["HTTP_USER_AGENT"], $arrayMatch)){ $ieVersion = intval($arrayMatch[1]); diff --git a/workflow/engine/methods/cases/casesListExtJsRedirector.php b/workflow/engine/methods/cases/casesListExtJsRedirector.php index 42efa294e..969709b57 100755 --- a/workflow/engine/methods/cases/casesListExtJsRedirector.php +++ b/workflow/engine/methods/cases/casesListExtJsRedirector.php @@ -2,12 +2,12 @@ if (typeof window.parent != 'undefined') { verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); + G::LoadClass( "pmGoogleApi" ); + $pmGoogle = new PMGoogleApi(); + $statusPMGmail = $pmGoogle->getServiceGmailStatus(); } /*----------------------------------********---------------------------------*/ if (isset( $_GET['ux'] )) { @@ -20,7 +20,7 @@ if (isset( $_GET['ux'] )) { default: $url = 'casesListExtJs'; } -} else if( key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && !empty($enablePMGmail) && $enablePMGmail==1 ){ +} else if( key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && $statusPMGmail ){ $url = 'derivatedGmail'; } else { $url = 'casesListExtJs'; @@ -31,8 +31,8 @@ if (isset( $_GET['ux'] )) { echo " window.parent.location.href = '$url';"; if (isset( $_GET['ux'] )) { /*----------------------------------********---------------------------------*/ - if(PMLicensedFeatures::getSingleton()->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09') && !empty($enablePMGmail) && $enablePMGmail==1){ - echo '} else { window.parent.location.href = \'derivatedGmail\'; }'; + if(PMLicensedFeatures::getSingleton()->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09') && $statusPMGmail){ + echo '} else { window.parent.location.href = \'derivatedGmail\'; }'; } else { /*----------------------------------********---------------------------------*/ echo '} else { window.parent.location.href = \'casesListExtJs\'; }'; diff --git a/workflow/engine/methods/cases/casesList_Ajax.php b/workflow/engine/methods/cases/casesList_Ajax.php index 95469bf44..8ebbeb84c 100755 --- a/workflow/engine/methods/cases/casesList_Ajax.php +++ b/workflow/engine/methods/cases/casesList_Ajax.php @@ -85,7 +85,7 @@ if ($actionAjax == "userValues") { $cUsers->addSelectColumn(UsersPeer::USR_FIRSTNAME); $cUsers->addSelectColumn(UsersPeer::USR_LASTNAME); $cUsers->add( UsersPeer::USR_STATUS, 'CLOSED', Criteria::NOT_EQUAL ); - + if (!is_null($query)) { $filters = $cUsers->getNewCriterion( UsersPeer::USR_FIRSTNAME, '%'.$query.'%', Criteria::LIKE )->addOr( $cUsers->getNewCriterion( UsersPeer::USR_LASTNAME, '%'.$query.'%', Criteria::LIKE )->addOr( @@ -217,14 +217,32 @@ if ($actionAjax == "processListExtJs") { } if ($actionAjax == "getUsersToReassign") { - $_SESSION['TASK'] = $_REQUEST['TAS_UID']; - $case = new Cases(); - G::LoadClass( 'tasks' ); - $task = new Task(); - $tasks = $task->load($_SESSION['TASK']); - $result = new stdclass(); - $result->data = $case->getUsersToReassign( $_SESSION['TASK'], $_SESSION['USER_LOGGED'], $tasks['PRO_UID'] ); - print G::json_encode( $result ); + $taskUid = $_POST['taskUid']; + $search = $_POST['search']; + $pageSize = $_POST['pageSize']; + + $sortField = (isset($_POST['sort']))? $_POST['sort'] : ''; + $sortDir = (isset($_POST['dir']))? $_POST['dir'] : ''; + $start = (isset($_POST['start']))? $_POST['start'] : 0; + $limit = (isset($_POST['limit']))? $_POST['limit'] : $pageSize; + + $response = []; + + try { + $case = new \ProcessMaker\BusinessModel\Cases(); + + $result = $case->getUsersToReassign($_SESSION['USER_LOGGED'], $taskUid, ['filter' => $search], $sortField, $sortDir, $start, $limit); + + $response['status'] = 'OK'; + $response['success'] = true; + $response['resultTotal'] = $result['total']; + $response['resultRoot'] = $result['data']; + } catch (Exception $e) { + $response['status'] = 'ERROR'; + $response['message'] = $e->getMessage(); + } + + echo G::json_encode($response); } if ($actionAjax == 'reassignCase') { diff --git a/workflow/engine/methods/cases/casesMenuLoader.php b/workflow/engine/methods/cases/casesMenuLoader.php index 425f6560e..df87147e0 100755 --- a/workflow/engine/methods/cases/casesMenuLoader.php +++ b/workflow/engine/methods/cases/casesMenuLoader.php @@ -80,7 +80,7 @@ function getLoadTreeMenuData () $index = $i; list($childs, $index) = getChilds($oMenu, ++$index); - + $menuCases[$CurrentBlockID]['blockItems'][$oMenu->Id[$i]]['childs'] = $childs; $i = $index; @@ -274,7 +274,7 @@ function getProcess () function getAllCounters () { $userUid = (isset( $_SESSION['USER_LOGGED'] ) && $_SESSION['USER_LOGGED'] != '') ? $_SESSION['USER_LOGGED'] : null; - $oAppCache = new AppCacheView(); + $aTypes = Array (); $aTypes['to_do'] = 'CASES_INBOX'; $aTypes['draft'] = 'CASES_DRAFT'; @@ -285,29 +285,9 @@ function getAllCounters () $aTypes['selfservice'] = 'CASES_SELFSERVICE'; //$aTypes['to_revise'] = 'CASES_TO_REVISE'; //$aTypes['to_reassign'] = 'CASES_TO_REASSIGN'; - $solrEnabled = false; - if ((($solrConf = System::solrEnv()) !== false)) { - G::LoadClass( 'AppSolr' ); - $ApplicationSolrIndex = new AppSolr( $solrConf['solr_enabled'], $solrConf['solr_host'], $solrConf['solr_instance'] ); - - if ($ApplicationSolrIndex->isSolrEnabled() && $solrConf['solr_enabled'] == true) { - $solrEnabled = true; - } - } - - if ($solrEnabled) { - $aCount = $ApplicationSolrIndex->getCasesCount( $userUid ); - - //get paused count - $aCountMissing = $oAppCache->getAllCounters( array ('completed','cancelled'), $userUid ); - - $aCount = array_merge( $aCount, $aCountMissing ); - } else { - - $aCount = $oAppCache->getAllCounters( array_keys( $aTypes ), $userUid ); - - } + $case = new \ProcessMaker\BusinessModel\Cases(); + $aCount = $case->getListCounters($userUid, array_keys($aTypes)); $response = Array (); $i = 0; @@ -326,7 +306,7 @@ function getChilds($menu, $index) for ($i = $index; $i < count($menu->Options); $i++) { if ($menu->Types[$i] == 'childNode') { - + $childs[$menu->Id[$i]] = array( 'label' => $menu->Labels[$i], 'link' => $menu->Options[$i], diff --git a/workflow/engine/methods/cases/casesStartPage_Ajax.php b/workflow/engine/methods/cases/casesStartPage_Ajax.php index b98077be8..0f10ca2f5 100755 --- a/workflow/engine/methods/cases/casesStartPage_Ajax.php +++ b/workflow/engine/methods/cases/casesStartPage_Ajax.php @@ -262,19 +262,17 @@ function startCase () $_SESSION['CASES_REFRESH'] = true; /*----------------------------------********---------------------------------*/ - //sending the email for gmail integration if the option es available - $licensedFeatures = &PMLicensedFeatures::getSingleton(); + //sending the email for gmail integration if the option is available + $licensedFeatures = &PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + G::LoadClass( "pmGoogleApi" ); + $pmGoogle = new PMGoogleApi(); - $enablePMGmail = false; - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - if(!empty($enablePMGmail) && $enablePMGmail==1){ - require_once 'src/ProcessMaker/BusinessModel/Pmgmail.php'; - $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); - $response = $Pmgmail->sendEmail($aData['APPLICATION'], "", $aData['INDEX']); - } + if($pmGoogle->getServiceGmailStatus()){ + require_once 'src/ProcessMaker/BusinessModel/Pmgmail.php'; + $Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail(); + $response = $Pmgmail->sendEmail($aData['APPLICATION'], "", $aData['INDEX']); + } } /*----------------------------------********---------------------------------*/ diff --git a/workflow/engine/methods/cases/casesStreamingFile.php b/workflow/engine/methods/cases/casesStreamingFile.php index 77116077d..f4def7ef6 100644 --- a/workflow/engine/methods/cases/casesStreamingFile.php +++ b/workflow/engine/methods/cases/casesStreamingFile.php @@ -6,7 +6,7 @@ $actionAjax = isset( $_REQUEST['actionAjax'] ) ? $_REQUEST['actionAjax'] : null; if ($actionAjax == "streaming") { $app_uid = isset( $_REQUEST['a'] ) ? $_REQUEST['a'] : null; - $inp_doc_uid = isset( $_REQUEST['d'] ) ? $_REQUEST['d'] : null; + $inp_doc_uid = isset( $_REQUEST['d'] ) ? htmlspecialchars($_REQUEST['d']) : null; $oAppDocument = new \AppDocument(); if (! isset( $fileData['version'] )) { @@ -52,7 +52,7 @@ if ($actionAjax == "streaming") { if ($actionAjax == "fileMobile") { $app_uid = isset( $_REQUEST['a'] ) ? $_REQUEST['a'] : null; - $inp_doc_uid = isset( $_REQUEST['d'] ) ? $_REQUEST['d'] : null; + $inp_doc_uid = isset( $_REQUEST['d'] ) ? htmlspecialchars($_REQUEST['d']) : null; $structure = file_get_contents(PATH_HTML ."/mobile/index.json"); $structure = json_decode($structure); diff --git a/workflow/engine/methods/cases/cases_CatchExecute.php b/workflow/engine/methods/cases/cases_CatchExecute.php index 060a09d5e..1caf658f6 100755 --- a/workflow/engine/methods/cases/cases_CatchExecute.php +++ b/workflow/engine/methods/cases/cases_CatchExecute.php @@ -67,12 +67,19 @@ $aDelegation = $oAppDelegation->load( $sAppUid, $iDelIndex ); //if there are no user in the delegation row, this case is still in selfservice if ($aDelegation['USR_UID'] == "") { $oCase->setCatchUser( $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['USER_LOGGED'] ); + /*----------------------------------********---------------------------------*/ + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { + require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.labelsGmail.php"); + $pmGoogle = new PMGoogleApi(); + if($pmGoogle->getServiceGmailStatus()) { + $labGmail = new labelsGmail(); + $labGmail->addRelabelingToQueue($sAppUid, $iDelIndex, -1, true); + } + } + /*----------------------------------********---------------------------------*/ //changing email labels if the claim comes from gmail if(array_key_exists('gmail',$_SESSION) && $_SESSION['gmail'] == 1){ - require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.labelsGmail.php"); - $labGmail = new labelsGmail(); - $oResponse = $labGmail->setLabels($sAppUid, $iDelIndex, -1, true); - die( '' ); diff --git a/workflow/engine/methods/cases/cases_Derivate.php b/workflow/engine/methods/cases/cases_Derivate.php index b8f7b4af6..06426bc68 100755 --- a/workflow/engine/methods/cases/cases_Derivate.php +++ b/workflow/engine/methods/cases/cases_Derivate.php @@ -208,13 +208,28 @@ try { } } //Events - End + + /*----------------------------------********---------------------------------*/ + // Set users drive - start + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + if ($licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M=')) { + G::LoadClass("AppDocumentDrive"); + $drive = new AppDocumentDrive(); + if ($drive->getStatusDrive()) { + //add users email next task + $drive->addUsersDocumentDrive($appFields['APP_UID']); + } + } + // Set users drive - End + /*----------------------------------********---------------------------------*/ + $debuggerAvailable = true; if (isset( $_SESSION['user_experience'] )) { $aNextStep['PAGE'] = 'casesListExtJsRedirector?ux=' . $_SESSION['user_experience']; $debuggerAvailable = false; } else if( isset( $_SESSION['gmail'] ) ){ - $aNextStep['PAGE'] = 'casesListExtJsRedirector?gmail='.$_SESSION['gmail']; + $aNextStep['PAGE'] = 'casesListExtJsRedirector?gmail='.$_SESSION['gmail']; } else { $aNextStep['PAGE'] = 'casesListExtJsRedirector'; } diff --git a/workflow/engine/methods/cases/cases_Redirect.php b/workflow/engine/methods/cases/cases_Redirect.php index a6cb95f65..3ab1bd579 100755 --- a/workflow/engine/methods/cases/cases_Redirect.php +++ b/workflow/engine/methods/cases/cases_Redirect.php @@ -32,7 +32,7 @@ $aFields = $oAppDocument->load( $_GET['a'] ); require_once 'classes/model/OutputDocument.php'; $oOutputDocument = new OutputDocument(); $aOD = $oOutputDocument->load( $aFields['DOC_UID'] ); -$a = $_GET['a']; +$a = htmlspecialchars($_GET['a']); $ext = strtolower( $aOD['OUT_DOC_GENERATE'] ); G::header( 'location: cases_ShowOutputDocument?a=' . $a . '&ext=' . $ext ); diff --git a/workflow/engine/methods/cases/cases_SaveData.php b/workflow/engine/methods/cases/cases_SaveData.php index c714f69a8..1cb1fc46e 100755 --- a/workflow/engine/methods/cases/cases_SaveData.php +++ b/workflow/engine/methods/cases/cases_SaveData.php @@ -90,6 +90,13 @@ try { $Fields = $oCase->loadCase( $_SESSION["APPLICATION"] ); if ($swpmdynaform) { + $dataFields = $Fields["APP_DATA"]; + $dataFields["CURRENT_DYNAFORM"] = $_GET['UID']; + + G::LoadClass('pmDynaform'); + $oPmDynaform = new pmDynaform($dataFields); + $pmdynaform = $oPmDynaform->validatePost($pmdynaform); + $Fields["APP_DATA"] = array_merge( $Fields["APP_DATA"], $pmdynaform ); } @@ -360,91 +367,6 @@ try { $sPathName = PATH_DOCUMENT . $pathUID . PATH_SEP; $sFileName = $sAppDocUid . "_" . $iDocVersion . "." . $sExtension; - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - if ($pmDrive->getStatusService()) { - $app = new Application(); - $user = new Users(); - $dataUser = $user->load($_SESSION['USER_LOGGED']); - $pmDrive->setDriveUser($dataUser['USR_EMAIL']); - - $appData = $app->Load($_SESSION['APPLICATION']); - if ($appData['APP_DRIVE_FOLDER_UID'] == null) { - $process = new Process(); - $process->setProUid($appData['PRO_UID']); - - $result = $pmDrive->createFolder($process->getProTitle() . ' - ' . G::LoadTranslation("ID_CASE") . ' #' . $appData['APP_NUMBER'], - $pmDrive->getFolderIdPMDrive($_SESSION['USER_LOGGED'])); - $appData['APP_DRIVE_FOLDER_UID'] = $result->id; - $app->update($appData); - } - - $result = $pmDrive->uploadFile('application/' . $sExtension, $arrayFileTmpName[$i], - $arrayFileName[$i], $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('ATTACHED', $result->webContentLink); - $fileIdDrive = $result->id; - $aFields['DOC_VERSION'] = $iDocVersion; - $aFields['APP_DOC_UID'] = $sAppDocUid; - - $oAppDocument->update($aFields); - - //add permissions - $criteria = new Criteria('workflow'); - $criteria->addSelectColumn(ApplicationPeer::PRO_UID); - $criteria->addSelectColumn(TaskUserPeer::TAS_UID); - $criteria->addSelectColumn(TaskUserPeer::USR_UID); - $criteria->addSelectColumn(TaskUserPeer::TU_RELATION); - - $criteria->add(ApplicationPeer::APP_UID, $_SESSION['APPLICATION']); - $criteria->addJoin(ApplicationPeer::PRO_UID, TaskPeer::PRO_UID, Criteria::LEFT_JOIN); - $criteria->addJoin(TaskPeer::TAS_UID, TaskUserPeer::TAS_UID, Criteria::LEFT_JOIN); - - $dataset = TaskUserPeer::doSelectRs($criteria); - $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $userPermission = array(); - $case = new Cases(); - - while ($dataset->next()) { - $row = $dataset->getRow(); - if ($row['TU_RELATION'] == 1) { - //users - $dataUser = $user->load($row['USR_UID']); - if (array_search($dataUser['USR_EMAIL'], $userPermission) === false) { - $userPermission[] = $dataUser['USR_EMAIL']; - } - } else { - //Groups - $criteria = new Criteria('workflow'); - $criteria->addSelectColumn(UsersPeer::USR_EMAIL); - $criteria->addSelectColumn(UsersPeer::USR_UID); - $criteria->add(GroupUserPeer::GRP_UID, $row['USR_UID']); - $criteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); - - $oDataset = AppDelegationPeer::doSelectRs($criteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($oDataset->next()) { - $aRow = $oDataset->getRow(); - if (array_search($aRow['USR_EMAIL'], $userPermission) === false) { - $userPermission[] = $aRow['USR_EMAIL']; - } - - } - } - - } - $userPermission = array_unique($userPermission); - - foreach ($userPermission as $key => $value) { - $pmDrive->setPermission($appData['APP_DRIVE_FOLDER_UID'], $value, 'user', 'writer'); - $pmDrive->setPermission($fileIdDrive, $value); - } - } - } - /*----------------------------------********---------------------------------*/ - G::uploadFile( $arrayFileTmpName[$i], $sPathName, $sFileName ); //Plugin Hook PM_UPLOAD_DOCUMENT for upload document diff --git a/workflow/engine/methods/cases/cases_ShowDocument.php b/workflow/engine/methods/cases/cases_ShowDocument.php index 3a7db552e..73fbc0329 100755 --- a/workflow/engine/methods/cases/cases_ShowDocument.php +++ b/workflow/engine/methods/cases/cases_ShowDocument.php @@ -107,7 +107,34 @@ if (! $sw_file_exists) { $res['message'] = $oAppDocument->Fields['APP_DOC_FILENAME']; print G::json_encode( $res ); } else { - G::streamFile( $realPath, $bDownload, $oAppDocument->Fields['APP_DOC_FILENAME'] ); //download + $nameFile = $oAppDocument->Fields['APP_DOC_FILENAME']; + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + $downloadStatus = false; + if ($licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M=')) { + G::LoadClass( "AppDocumentDrive" ); + $drive = new AppDocumentDrive(); + if ($drive->getStatusDrive()) { + $fieldDrive = $oAppDocument->getAppDocDriveDownload(); + $drive->loadUser($_SESSION['USER_LOGGED']); + $uidDrive = $drive->changeUrlDrive($oAppDocument->Fields, $oAppDocument->getAppDocType()); + $fileContent = $drive->download($uidDrive); + if ($fileContent !== null) { + $downloadStatus = true; + header('Content-Description: File Transfer'); + header('Content-Disposition: attachment; filename='.$nameFile); + header('Content-Transfer-Encoding: binary'); + header('Set-Cookie: fileLoading=true'); + echo $fileContent; + exit(); + } + } + } + if (!$downloadStatus) { + G::streamFile( $realPath, $bDownload, $nameFile ); //download + } + + + } } diff --git a/workflow/engine/methods/cases/cases_ShowOutputDocument.php b/workflow/engine/methods/cases/cases_ShowOutputDocument.php index 61e7e667c..b300b5da8 100755 --- a/workflow/engine/methods/cases/cases_ShowOutputDocument.php +++ b/workflow/engine/methods/cases/cases_ShowOutputDocument.php @@ -109,7 +109,35 @@ if (! $sw_file_exists) { $res['message'] = $info['basename'] . $ver . '.' . $ext; print G::json_encode( $res ); } else { - G::streamFile( $realPath, $download, $info['basename'] . $ver . '.' . $ext ); + $nameFile = $info['basename'] . $ver . '.' . $ext; + $licensedFeatures = &PMLicensedFeatures::getSingleton(); + $downloadStatus = false; + if ($licensedFeatures->verifyfeature('AhKNjBEVXZlWUFpWE8wVTREQ0FObmo0aTdhVzhvalFic1M=')) { + G::LoadClass( "AppDocumentDrive" ); + $drive = new AppDocumentDrive(); + if ($drive->getStatusDrive()) { + $fieldDrive = $oAppDocument->getAppDocDriveDownload(); + $drive->loadUser($_SESSION['USER_LOGGED']); + $type = $ext == 'doc' ? 'OUTPUT_DOC' : 'OUTPUT_PDF'; + $uidDrive = $drive->changeUrlDrive($oAppDocument->Fields, $type); + $fileContent = $drive->download($uidDrive); + if ($fileContent !== null) { + $downloadStatus = true; + header('Content-Description: File Transfer'); + header('Content-Disposition: attachment; filename='.$nameFile); + header('Content-Transfer-Encoding: binary'); + header('Set-Cookie: fileLoading=true'); + echo $fileContent; + exit(); + } + } + } + if (!$downloadStatus) { + G::streamFile( $realPath, $download, $nameFile); //download + } + + //die($realPath); + //G::streamFile( $realPath, $download, $info['basename'] . $ver . '.' . $ext ); } } //G::streamFile ( $realPath, true); diff --git a/workflow/engine/methods/cases/cases_Step.php b/workflow/engine/methods/cases/cases_Step.php index 6afaf0d2f..a5f8962c4 100755 --- a/workflow/engine/methods/cases/cases_Step.php +++ b/workflow/engine/methods/cases/cases_Step.php @@ -628,130 +628,6 @@ try { $oCase->updateCase( $_SESSION['APPLICATION'], $Fields ); //Save data - End - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - if ($pmDrive->getStatusService()) { - $app = new Application(); - $user = new Users(); - $dataUser = $user->load($_SESSION['USER_LOGGED']); - $pmDrive->setDriveUser($dataUser['USR_EMAIL']); - - $applicationUid = $_SESSION['APPLICATION']; - $appData = $app->Load($applicationUid); - if ($appData['APP_DRIVE_FOLDER_UID'] == null) { - $process = new Process(); - $process->setProUid($appData['PRO_UID']); - - $result = $pmDrive->createFolder($process->getProTitle() . ' - ' . G::LoadTranslation("ID_CASE") . ' #' . $appData['APP_NUMBER'], - $pmDrive->getFolderIdPMDrive($_SESSION['USER_LOGGED'])); - $appData['APP_DRIVE_FOLDER_UID'] = $result->id; - $app->update($appData); - } - - $fileIdDriveDoc = ''; - $fileIdDrivePdf = ''; - switch ($aOD['OUT_DOC_GENERATE']) { - case "BOTH": - $result = $pmDrive->uploadFile('application/pdf', $pathOutput . $sFilename . '.pdf', - $sFilenameOriginal . '.pdf', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_PDF', $result->webContentLink); - $fileIdDrivePdf = $result->id; - $result = $pmDrive->uploadFile('application/doc', $pathOutput . $sFilename . '.doc', - $sFilenameOriginal . '.doc', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_DOC', $result->webContentLink); - $fileIdDriveDoc = $result->id; - break; - case "PDF": - $result = $pmDrive->uploadFile('application/pdf', $pathOutput . $sFilename . '.pdf', - $sFilenameOriginal . '.pdf', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_PDF', $result->webContentLink); - $fileIdDrivePdf = $result->id; - break; - case "DOC": - $result = $pmDrive->uploadFile('application/doc', $pathOutput . $sFilename . '.doc', - $sFilenameOriginal . '.doc', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_DOC', $result->webContentLink); - $fileIdDriveDoc = $result->id; - break; - } - $aFields['DOC_VERSION'] = $oAppDocument->getDocVersion();// $docVersion; - $aFields['APP_DOC_UID'] = $oAppDocument->getAppDocUid();//$appDocUid; - $appDocUid = $aFields['APP_DOC_UID']; - - $oAppDocument->update($aFields); - //$option = 'pmDrive'; - - - //add permissions - $criteria = new Criteria('workflow'); - $criteria->addSelectColumn(ApplicationPeer::PRO_UID); - $criteria->addSelectColumn(TaskUserPeer::TAS_UID); - $criteria->addSelectColumn(TaskUserPeer::USR_UID); - $criteria->addSelectColumn(TaskUserPeer::TU_RELATION); - - $criteria->add(ApplicationPeer::APP_UID, $applicationUid); - $criteria->addJoin(ApplicationPeer::PRO_UID, TaskPeer::PRO_UID, Criteria::LEFT_JOIN); - $criteria->addJoin(TaskPeer::TAS_UID, TaskUserPeer::TAS_UID, Criteria::LEFT_JOIN); - - - $dataset = ApplicationPeer::doSelectRs($criteria); - $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - - $userPermission = array(); - $case = new Cases(); - - while ($dataset->next()) { - $row = $dataset->getRow(); - if ($row['TU_RELATION'] == 1) { - //users - $dataUser = $user->load($row['USR_UID']); - if (array_search($dataUser['USR_EMAIL'], $userPermission) === false) { - $objectPermissions = $case->getAllObjects($row['PRO_UID'], $applicationUid, - $row['TAS_UID'], $row['USR_UID']); - if (array_search($appDocUid, $objectPermissions['OUTPUT_DOCUMENTS']) !== false) { - $userPermission[] = $dataUser['USR_EMAIL']; - } - } - } else { - //Groups - $criteria = new Criteria('workflow'); - $criteria->addSelectColumn(UsersPeer::USR_EMAIL); - $criteria->addSelectColumn(UsersPeer::USR_UID); - $criteria->add(GroupUserPeer::GRP_UID, $row['USR_UID']); - $criteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); - - $oDataset = AppDelegationPeer::doSelectRs($criteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - while ($oDataset->next()) { - $aRow = $oDataset->getRow(); - if (array_search($aRow['USR_EMAIL'], $userPermission) === false) { - $objectPermissions = $case->getAllObjects($row['PRO_UID'], $applicationUid, - $row['TAS_UID'], $aRow['USR_UID']); - if (array_search($appDocUid, - $objectPermissions['OUTPUT_DOCUMENTS']) !== false - ) { - $userPermission[] = $aRow['USR_EMAIL']; - } - } - - } - } - - } - $userPermission = array_unique($userPermission); - - foreach ($userPermission as $key => $val) { - $pmDrive->setPermission($appData['APP_DRIVE_FOLDER_UID'], $val, 'user', 'writer'); - $pmDrive->setPermission($fileIdDrivePdf, $val); - $pmDrive->setPermission($fileIdDriveDoc, $val); - } - } - } - /*----------------------------------********---------------------------------*/ - //Plugin Hook PM_UPLOAD_DOCUMENT for upload document $oPluginRegistry = & PMPluginRegistry::getSingleton(); if ($oPluginRegistry->existsTrigger( PM_UPLOAD_DOCUMENT ) && class_exists( 'uploadDocumentData' )) { @@ -867,29 +743,6 @@ try { } } - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - if ($pmDrive->getStatusService()) { - //change donwload link - drive - $driveDownload = @unserialize($aFields['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_DOC', - $driveDownload) - ) { - $aFields['FILE1'] = $driveDownload['OUTPUT_DOC']; - } - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_PDF', - $driveDownload) - ) { - $aFields['FILE2'] = $driveDownload['OUTPUT_PDF']; - } - } - } - /*----------------------------------********---------------------------------*/ - if (($aGields['OUT_DOC_GENERATE'] == 'BOTH') || ($aGields['OUT_DOC_GENERATE'] == '')) { $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'cases/cases_ViewOutputDocument1', '', G::array_merges( $aOD, $aFields ), '' ); } diff --git a/workflow/engine/methods/cases/derivatedGmail.php b/workflow/engine/methods/cases/derivatedGmail.php index d2fbff684..1a576f977 100644 --- a/workflow/engine/methods/cases/derivatedGmail.php +++ b/workflow/engine/methods/cases/derivatedGmail.php @@ -32,16 +32,14 @@ foreach ($appDelPrev as $app){ require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.labelsGmail.php"); $oLabels = new labelsGmail(); -$oResponse = $oLabels->setLabels($caseId, $actualIndex, $actualLastIndex, false); +$oLabels->addRelabelingToQueue($caseId, $actualIndex, $actualLastIndex, false); -$enablePMGmail = false; -G::LoadClass( "pmDrive" ); -$pmDrive = new PMDrive(); -$enablePMGmail = $pmDrive->getStatusService(); -if(key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && !empty($enablePMGmail) && $enablePMGmail==1 ){ +G::LoadClass( "pmGoogleApi" ); +$pmGoogle = new PMGoogleApi(); +if(array_key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && $pmGoogle->getServiceGmailStatus() ){ $_SESSION['gmail'] = 0; unset($_SESSION['gmail']); //cleaning session - $mUrl = '/sys'. $_SESSION['WORKSPACE'] .'/en/neoclassic/cases/cases_Open?APP_UID='.$caseId.'&DEL_INDEX='.$actualIndex.'&action=sent'; + $mUrl = '/sys'. $_SESSION['WORKSPACE'] .'/en/'.$_SESSION['currentSkin'].'/cases/cases_Open?APP_UID='.$caseId.'&DEL_INDEX='.$actualIndex.'&action=sent'; } else{ $mUrl = 'casesListExtJs'; } diff --git a/workflow/engine/methods/cases/open.php b/workflow/engine/methods/cases/open.php index 06c064616..b3c2107b1 100755 --- a/workflow/engine/methods/cases/open.php +++ b/workflow/engine/methods/cases/open.php @@ -38,17 +38,20 @@ if (! isset( $_GET['APP_UID'] ) || ! isset( $_GET['DEL_INDEX'] )) { if (isset( $_GET['APP_NUMBER'] )) { G::LoadClass( 'case' ); $oCase = new Cases(); - $_GET['APP_UID'] = $oCase->getApplicationUIDByNumber( $_GET['APP_NUMBER'] ); - $_GET['DEL_INDEX'] = $oCase->getCurrentDelegation( $_GET['APP_UID'], $_SESSION['USER_LOGGED'] ); - if (is_null( $_GET['APP_UID'] )) { + $appUid = $oCase->getApplicationUIDByNumber( htmlspecialchars($_GET['APP_NUMBER']) ); + $delIndex = $oCase->getCurrentDelegation( $appUid, $_SESSION['USER_LOGGED'] ); + if (is_null( $appUid )) { throw new Exception( G::LoadTranslation( 'ID_CASE_DOES_NOT_EXISTS' ) ); } - if (is_null( $_GET['DEL_INDEX'] )) { + if (is_null( $delIndex )) { throw new Exception( G::LoadTranslation( 'ID_CASE_IS_CURRENTLY_WITH_ANOTHER_USER' ) ); } } else { throw new Exception( "Application ID or Delegation Index is missing!. The System can't open the case." ); } +} else { + $appUid = htmlspecialchars($_GET['APP_UID']); + $delIndex = htmlspecialchars($_GET['DEL_INDEX']); } require_once ("classes/model/Step.php"); @@ -61,18 +64,17 @@ $oHeadPublisher = & headPublisher::getSingleton(); $urlToRedirectAfterPause = 'casesListExtJs'; - /*----------------------------------********---------------------------------*/ +/*----------------------------------********---------------------------------*/ $licensedFeatures = &PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - if (key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && !empty($enablePMGmail) && $enablePMGmail == 1) { + G::LoadClass( "pmGoogleApi" ); + $pmGoogle = new PMGoogleApi(); + if (array_key_exists('gmail', $_SESSION) && $_SESSION['gmail'] == 1 && $pmGoogle->getServiceGmailStatus()) { $_SESSION['gmail'] = 0; $urlToRedirectAfterPause = '/sys'. $_SESSION['WORKSPACE'] .'/en/neoclassic/cases/cases_Open?APP_UID='.$_SESSION['APPLICATION'].'&DEL_INDEX='.$_SESSION['INDEX'].'&action=sent'; } } - /*----------------------------------********---------------------------------*/ +/*----------------------------------********---------------------------------*/ $oHeadPublisher->assign( 'urlToRedirectAfterPause', $urlToRedirectAfterPause ); @@ -86,19 +88,16 @@ foreach ($_GET as $k => $v) { $uri .= ($uri == '') ? "$k=$v" : "&$k=$v"; } -//$case = $oCase->loadCase( $_GET['APP_UID'], $_GET['DEL_INDEX'] ); if( isset($_GET['action']) && ($_GET['action'] == 'jump') ) { - $case = $oCase->loadCase( $_GET['APP_UID'], $_GET['DEL_INDEX'], $_GET['action']); + $case = $oCase->loadCase( $appUid, $delIndex, $_GET['action']); } else { - $case = $oCase->loadCase( $_GET['APP_UID'], $_GET['DEL_INDEX'] ); + $case = $oCase->loadCase( $appUid, $delIndex ); } if (! isset( $_GET['to_revise'] )) { $script = 'cases_Open?'; } else { $script = 'cases_OpenToRevise?'; - $delIndex = $_GET['DEL_INDEX']; - $appUid = $_GET['APP_UID']; $oHeadPublisher->assign( 'treeToReviseTitle', G::loadtranslation( 'ID_STEP_LIST' ) ); $casesPanelUrl = 'casesToReviseTreeContent?APP_UID=' . $appUid . '&DEL_INDEX=' . $delIndex; $oHeadPublisher->assign( 'casesPanelUrl', $casesPanelUrl ); //translations @@ -122,7 +121,7 @@ $oHeadPublisher->assign( 'uri', $script . $uri ); $oHeadPublisher->assign( '_APP_NUM', '#: ' . $case['APP_NUMBER'] ); $oHeadPublisher->assign( '_PROJECT_TYPE', in_array($case['PRO_UID'], $bpmnProjects) ? 'bpmn' : 'classic' ); $oHeadPublisher->assign( '_PRO_UID', $case['PRO_UID']); -$oHeadPublisher->assign( '_APP_UID', $_GET['APP_UID']); +$oHeadPublisher->assign( '_APP_UID', $appUid); $oHeadPublisher->assign( '_ENV_CURRENT_DATE', $conf->getSystemDate( date( 'Y-m-d' ) ) ); $oHeadPublisher->assign( '_ENV_CURRENT_DATE_NO_FORMAT', date( 'Y-m-d-h-i-A' ) ); $oHeadPublisher->assign( 'idfirstform', is_null( $oStep ) ? '' : $oStep->getStepUidObj() ); @@ -133,12 +132,7 @@ if(!isset($_SESSION['APPLICATION']) || !isset($_SESSION['TASK']) || !isset($_SES $_SESSION['APPLICATION'] = $case['APP_UID']; $_SESSION['TASK'] = $case['TAS_UID']; $_SESSION['INDEX'] = $case['DEL_INDEX']; -} -$_SESSION['TASK'] = ($_GET['action'] == "unassigned" || $_GET['action'] == "sent" ) ? -1 : $_SESSION['TASK']; -if($_GET['action'] == "todo" || $_GET['action'] == "draft") { - if (isset($_SESSION['bNoShowSteps'])) { - unset($_SESSION['bNoShowSteps']); - } } +$_SESSION['actionCaseOptions'] = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : ''; G::RenderPage( 'publish', 'extJs' ); diff --git a/workflow/engine/methods/cases/proxyDataCombobox.php b/workflow/engine/methods/cases/proxyDataCombobox.php index 4d086afc9..a0d65d2df 100755 --- a/workflow/engine/methods/cases/proxyDataCombobox.php +++ b/workflow/engine/methods/cases/proxyDataCombobox.php @@ -5,12 +5,11 @@ */ $appUid = isset($_POST["appUid"])? $_POST["appUid"] : ""; -$dynUid = isset($_POST["dynUid"])? $_POST["dynUid"] : ""; -$proUid = isset($_POST["proUid"])? $_POST["proUid"] : ""; +$dynUid = isset($_POST["dynUid"])? htmlspecialchars($_POST["dynUid"]) : ""; +$proUid = isset($_POST["proUid"])? htmlspecialchars($_POST["proUid"]) : ""; $fieldName = isset($_POST["fieldName"])? $_POST["fieldName"] : ""; $filename = $proUid . PATH_SEP . $dynUid . ".xml"; - $G_FORM = new xmlform(); $G_FORM->home = PATH_DYNAFORM; $G_FORM->parseFile($filename, SYS_LANG, true); @@ -72,4 +71,4 @@ foreach ($aResult as $field) { $response["records"] = $array; -echo G::json_encode($response); \ No newline at end of file +echo G::json_encode($response); diff --git a/workflow/engine/methods/cases/proxyNewCasesList.php b/workflow/engine/methods/cases/proxyNewCasesList.php index a20198e70..384a8c9b8 100644 --- a/workflow/engine/methods/cases/proxyNewCasesList.php +++ b/workflow/engine/methods/cases/proxyNewCasesList.php @@ -153,6 +153,10 @@ try { $record["APP_UPDATE_DATE"] = $record["DEL_DELEGATE_DATE"]; } + if (isset($record['DEL_CURRENT_TAS_TITLE'])) { + $record['APP_TAS_TITLE'] = $record['DEL_CURRENT_TAS_TITLE']; + } + if (isset($record["APP_STATUS"])) { $record["APP_STATUS_LABEL"] = G::LoadTranslation("ID_" . $record["APP_STATUS"]); } diff --git a/workflow/engine/methods/cases/proxyPMTablesSaveFields.php b/workflow/engine/methods/cases/proxyPMTablesSaveFields.php deleted file mode 100644 index d79fcd15a..000000000 --- a/workflow/engine/methods/cases/proxyPMTablesSaveFields.php +++ /dev/null @@ -1,171 +0,0 @@ -xssFilterHard($callback); -$dir = isset($_POST['dir']) ? $_POST['dir'] : 'DESC'; -$dir = $filter->xssFilterHard($dir); -$sort = isset($_POST['sort']) ? $_POST['sort'] : ''; -$sort = $filter->xssFilterHard($sort); -$query = isset($_POST['query']) ? $_POST['query'] : ''; -$query = $filter->xssFilterHard($query); -$tabUid = isset($_POST['table']) ? $_POST['table'] : ''; -$tabUid = $filter->xssFilterHard($tabUid); -$action = isset($_POST['action']) ? $_POST['action'] : 'todo'; -$action = $filter->xssFilterHard($action); - -try { - G::LoadClass("BasePeer" ); - require_once ( "classes/model/Fields.php" ); - //$sUIDUserLogged = $_SESSION['USER_LOGGED']; - $oCriteria = new Criteria('workflow'); - $oCriteria->clearSelectColumns(); - $oCriteria->setDistinct(); - $oCriteria->addSelectColumn (FieldsPeer::FLD_NAME); - $oCriteria->addSelectColumn (FieldsPeer::FLD_UID); - $oCriteria->addSelectColumn (FieldsPeer::FLD_INDEX); - - if ($query != '') { - $oCriteria->add (FieldsPeer::FLD_NAME, $query . '%', Criteria::LIKE); - } - //$oCriteria->addJoin(AdditionalTablesPeer::ADD_TAB_UID, FieldsPeer::ADD_TAB_UID); - $oCriteria->add (FieldsPeer::ADD_TAB_UID, $tabUid , CRITERIA::EQUAL ); - $oCriteria->add (FieldsPeer::FLD_NAME, 'APP_UID' , CRITERIA::NOT_EQUAL ); - //$oCriteria->add (AppCacheViewPeer::APP_STATUS, "TO_DO" , CRITERIA::EQUAL ); - //$oCriteria->add (AppCacheViewPeer::USR_UID, $sUIDUserLogged); - //$totalCount = AppCacheViewPeer::doCount( $Criteria ); - //if ( isset($limit) ) $oCriteria->setLimit ( $limit ); - //if ( isset($start) ) $oCriteria->setOffset ( $start ); - if ($sort != '') { - if ($dir == 'DESC') { - $oCriteria->addDescendingOrderByColumn( $sort ); - } else { - $oCriteria->addAscendingOrderByColumn( $sort ); - } //else { - // $oCriteria->addDescendingOrderByColumn('FLD_INDEX'); - //} - $oDataset = FieldsPeer::doSelectRS($oCriteria); - $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $oDataset->next(); - - $result = array(); - $rows = array(); - switch ($action) { - case 'todo': - // #, Case, task, process, sent by, due date, Last Modify, Priority - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '6', 'column2' => '6' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '5', 'column2' => '5' ); - $rows[] = array( 'name' => 'APP_DEL_PREVIOUS_USER', 'gridIndex' => '7', 'column2' => '7' ); - $rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '8', 'column2' => '8' ); - $rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '9', 'column2' => '9' ); - $rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '10', 'column2' =>'10' ); - break; - case 'draft': - //#, Case, task, process, due date, Last Modify, Priority }, - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '6', 'column2' => '6' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '5', 'column2' => '5' ); - $rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '8', 'column2' => '8' ); - $rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '9', 'column2' => '9' ); - $rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '10', 'column2' =>'10' ); - break; - case 'sent': - // #, Case, task, process, current user, sent by, Last Modify, Status - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - $rows[] = array( 'name' => 'APP_STATUS', 'gridIndex' => '2', 'column2' => '2' ); - $rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '5', 'column2' => '5' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '6', 'column2' => '6' ); - $rows[] = array( 'name' => 'APP_DEL_PREVIOUS_USER', 'gridIndex' => '7', 'column2' => '7' ); - $rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '8', 'column2' => '8' ); - $rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '9', 'column2' => '9' ); - $rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '10', 'column2' =>'10' ); - break; - case 'unassigned': - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - //$rows[] = array( 'name' => 'APP_STATUS', 'gridIndex' => '2', 'column2' => '2' ); - //$rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '2', 'column2' => '2' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - $rows[] = array( 'name' => 'APP_DEL_PREVIOUS_USER', 'gridIndex' => '5', 'column2' => '5' ); - //$rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '8', 'column2' => '8' ); - $rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '6', 'column2' => '6' ); - //$rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '10', 'column2' =>'10' ); - break; - case 'paused': - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - //$rows[] = array( 'name' => 'APP_STATUS', 'gridIndex' => '2', 'column2' => '2' ); - //$rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '2', 'column2' => '2' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - $rows[] = array( 'name' => 'APP_DEL_PREVIOUS_USER', 'gridIndex' => '5', 'column2' => '5' ); - //$rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '8', 'column2' => '8' ); - //$rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '9', 'column2' => '9' ); - //$rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '10', 'column2' =>'10' ); - break; - case 'completed': - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - //$rows[] = array( 'name' => 'APP_STATUS', 'gridIndex' => '2', 'column2' => '2' ); - //$rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '2', 'column2' => '2' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - $rows[] = array( 'name' => 'APP_DEL_PREVIOUS_USER', 'gridIndex' => '5', 'column2' => '5' ); - //$rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '8', 'column2' => '8' ); - $rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '6', 'column2' => '6' ); - //$rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '10', 'column2' =>'10' ); - break; - case 'cancelled': - $rows[] = array( 'name' => 'APP_UID', 'gridIndex' => '0', 'column2' => '0' ); - $rows[] = array( 'name' => 'APP_NUMBER', 'gridIndex' => '1', 'column2' => '1' ); - //$rows[] = array( 'name' => 'APP_STATUS', 'gridIndex' => '2', 'column2' => '2' ); - //$rows[] = array( 'name' => 'DEL_INDEX', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TITLE', 'gridIndex' => '2', 'column2' => '2' ); - $rows[] = array( 'name' => 'APP_PRO_TITLE', 'gridIndex' => '3', 'column2' => '3' ); - $rows[] = array( 'name' => 'APP_TAS_TITLE', 'gridIndex' => '4', 'column2' => '4' ); - //$rows[] = array( 'name' => 'APP_DEL_PREVIOUS_USER', 'gridIndex' => '7', 'column2' => '7' ); - $rows[] = array( 'name' => 'DEL_TASK_DUE_DATE', 'gridIndex' => '5', 'column2' => '5' ); - $rows[] = array( 'name' => 'APP_UPDATE_DATE', 'gridIndex' => '6', 'column2' => '6' ); - $rows[] = array( 'name' => 'DEL_PRIORITY', 'gridIndex' => '7', 'column2' =>'7' ); - break; - } - } - $index = count($rows); - - while ($aRow = $oDataset->getRow()) { - $aRow['index'] = ++$index; - $aTempRow['name'] = $aRow['FLD_NAME']; - $aTempRow['gridIndex'] = $aRow['index']; - $aTempRow['column2'] = $aTempRow['gridIndex']; - $rows[] = $aTempRow; - $oDataset->next(); - } - $result['totalCount'] = count($rows); - $result['data'] = $rows; - //$jsonResult['records'] = $result; - print G::json_encode( $result ) ; -} catch (Exception $e) { - print G::json_encode ($e->getMessage()); -} - diff --git a/workflow/engine/methods/cases/proxyProcessList.php b/workflow/engine/methods/cases/proxyProcessList.php index c522a6732..6e2c91f9f 100755 --- a/workflow/engine/methods/cases/proxyProcessList.php +++ b/workflow/engine/methods/cases/proxyProcessList.php @@ -44,6 +44,37 @@ try { if (isset( $start )) { $Criteria->setOffset( $start ); } + + + // The $sort field is arbitrary + // This can result in ORDER BY + // SQL injection + + // This ensures that ORDER BY will ONLY + // use a known good sort field. + // There is a matching list on the javascript side at + // workflow/engine/templates/processes/main.js + + $allowedSortField = array( + "PRO_TITLE", + "PROJECT_TYPE", + "PRO_CATEGORY_LABEL", + "PRO_STATUS_LABEL", + "PRO_CREATE_USER_LABEL", + "PRO_CREATE_DATE", + "CASES_COUNT_TO_DO", + "CASES_COUNT_DRAFT", + "CASES_COUNT_COMPLETED", + "CASES_COUNT_CANCELLED", + "CASES_COUNT", + "PRO_DEBUG_LABEL", + "PRO_TYPE_PROCESS", + "PRO_UPDATE_DATE", + ); + + if(!in_array($sort, $allowedSortField)) { + $sort = ''; + } if ($sort != '') { if ($dir == 'DESC') { diff --git a/workflow/engine/methods/cases/proxyReassignCasesList.php b/workflow/engine/methods/cases/proxyReassignCasesList.php index def13a50d..eeeb34e19 100755 --- a/workflow/engine/methods/cases/proxyReassignCasesList.php +++ b/workflow/engine/methods/cases/proxyReassignCasesList.php @@ -6,19 +6,9 @@ if (!isset($_SESSION['USER_LOGGED'])) { print G::json_encode( $response ); die(); } -$callback = isset( $_POST['callback'] ) ? $_POST['callback'] : 'stcCallback1001'; -$dir = isset( $_POST['dir'] ) ? $_POST['dir'] : 'DESC'; -$sort = isset( $_POST['sort'] ) ? $_POST['sort'] : ''; + $start = isset( $_POST['start'] ) ? $_POST['start'] : '0'; $limit = isset( $_POST['limit'] ) ? $_POST['limit'] : '25'; -$filter = isset( $_POST['filter'] ) ? $_POST['filter'] : ''; -$search = isset( $_POST['search'] ) ? $_POST['search'] : ''; -$process = isset( $_POST['process'] ) ? $_POST['process'] : ''; -$user = isset( $_POST['user'] ) ? $_POST['user'] : ''; -$status = isset( $_POST['status'] ) ? strtoupper( $_POST['status'] ) : ''; -$action = isset( $_GET['action'] ) ? $_GET['action'] : (isset( $_POST['action'] ) ? $_POST['action'] : 'todo'); -$type = isset( $_GET['type'] ) ? $_GET['type'] : (isset( $_POST['type'] ) ? $_POST['type'] : 'extjs'); -$user = isset( $_POST['user'] ) ? $_POST['user'] : ''; if (isset($_POST['APP_UIDS'])) { $sentUids = explode( ',', $_POST['APP_UIDS'] ); @@ -27,7 +17,6 @@ if (isset($_POST['APP_UIDS'])) { } $allUidsRecords = array (); -$allTasUids = array (); // getting all App Uids and task Uids foreach ($sentUids as $sentUid) { @@ -35,52 +24,16 @@ foreach ($sentUids as $sentUid) { $allUidsRecords[] = array ('APP_UID' => $aItem[0],'TAS_UID' => $aItem[1],'DEL_INDEX' => $aItem[2]); } -$sReassignFromUser = isset( $_POST['user'] ) ? $_POST['user'] : ''; -$sProcessUid = isset( $_POST['process'] ) ? $_POST['process'] : ''; - -G::LoadClass( 'tasks' ); -G::LoadClass( 'groups' ); -G::LoadClass( 'case' ); -G::LoadClass( 'users' ); -require_once ("classes/model/AppCacheView.php"); - -$oTasks = new Tasks(); -$oGroups = new Groups(); -$oUser = new Users(); $oCases = new Cases(); $aCasesList = Array (); -$vard = 0; + foreach ($allUidsRecords as $aRecord) { - $vard = $vard + 1; $APP_UID = $aRecord['APP_UID']; $delIndex = $aRecord['DEL_INDEX']; $aCase = $oCases->loadCaseByDelegation( $APP_UID, $delIndex ); - $aUsersInvolved = Array (); - $aCaseGroups = $oTasks->getGroupsOfTask( $aCase['TAS_UID'], 1 ); - - foreach ($aCaseGroups as $aCaseGroup) { - $aCaseUsers = $oGroups->getUsersOfGroup( $aCaseGroup['GRP_UID'] ); - foreach ($aCaseUsers as $aCaseUser) { - if ($aCaseUser['USR_UID'] != $sReassignFromUser) { - $aCaseUserRecord = $oUser->load( $aCaseUser['USR_UID'] ); - $aUsersInvolved[] = array ('userUid' => $aCaseUser['USR_UID'],'userFullname' => $aCaseUserRecord['USR_FIRSTNAME'] . ' ' . $aCaseUserRecord['USR_LASTNAME']); - // . ' (' . $aCaseUserRecord['USR_USERNAME'] - } - } - } - - $aCaseUsers = $oTasks->getUsersOfTask( $aCase['TAS_UID'], 1 ); - foreach ($aCaseUsers as $aCaseUser) { - if ($aCaseUser['USR_UID'] != $sReassignFromUser) { - $aCaseUserRecord = $oUser->load( $aCaseUser['USR_UID'] ); - $aUsersInvolved[] = array ('userUid' => $aCaseUser['USR_UID'],'userFullname' => $aCaseUserRecord['USR_FIRSTNAME'] . ' ' . $aCaseUserRecord['USR_LASTNAME'] - ); - } - } - $oTmp = $aUsersInvolved; - $aCase['USERS'] = $oTmp; + $aCase['USERS'] = []; array_push( $aCasesList, $aCase ); } diff --git a/workflow/engine/methods/cases/proxyReassignUsersList.php b/workflow/engine/methods/cases/proxyReassignUsersList.php index ae662cbd5..67e119bf5 100755 --- a/workflow/engine/methods/cases/proxyReassignUsersList.php +++ b/workflow/engine/methods/cases/proxyReassignUsersList.php @@ -1,91 +1,34 @@ 0) { - foreach ($array as $k => $v) { - if (is_array( $v )) { - foreach ($v as $k2 => $v2) { - if ($k2 == $on) { - $sortable_array[$k] = $v2; - } - } - } else { - $sortable_array[$k] = $v; - } - } - - switch ($order) { - case SORT_ASC: - asort( $sortable_array ); - break; - case SORT_DESC: - arsort( $sortable_array ); - break; - } - - foreach ($sortable_array as $k => $v) { - if ($query == '') { - $new_array[] = $array[$k]; - } else { - if (preg_match( "/" . preg_quote($query, '/') . "/i", $array[$k]['userFullname'] )) { - $new_array[] = $array[$k]; - } - } - } - } - - return $new_array; -} -// $APP_UIDS = explode(',', $_POST['APP_UID']); - - $appUid = isset( $_POST['application'] ) ? $_POST['application'] : ''; -//$processUid = isset($_POST['process']) ? $_POST['process'] : ''; $TaskUid = isset( $_POST['task'] ) ? $_POST['task'] : ''; $sReassignFromUser = isset( $_POST['currentUser'] ) ? $_POST['currentUser'] : ''; +$query = (isset($_POST['query']))? $_POST['query'] : ''; -G::LoadClass( 'case' ); - -$oCases = new Cases(); $oConf = new Configurations(); -$aUsersInvolved = Array(); - +$arrayUsersToReassign = []; $ConfEnv = $oConf->getFormats(); + if ($TaskUid != '') { - G::LoadClass( 'tasks' ); - $task = new Task(); - $tasks = $task->load($TaskUid); - $rows = $oCases->getUsersToReassign($TaskUid, $_SESSION['USER_LOGGED'], $tasks['PRO_UID']); - foreach ($rows as $row) { + $case = new \ProcessMaker\BusinessModel\Cases(); + + $result = $case->getUsersToReassign( + $_SESSION['USER_LOGGED'], + $TaskUid, + ['filter' => $query], + $oConf->userNameFormatGetFirstFieldByUsersTable(), + 'ASC', + null, + 25 + ); + + foreach ($result['data'] as $row) { $sCaseUser = G::getFormatUserList( $ConfEnv['format'], $row ); - $aUsersInvolved[] = array ('userUid' => $row['USR_UID'], 'userFullname' => $sCaseUser); + $arrayUsersToReassign[] = ['userUid' => $row['USR_UID'], 'userFullname' => $sCaseUser]; } } -// $oTmp = new stdClass(); -// $oTmp->items = $aUsersInvolved; $result = array (); -$aUsersInvolved = array_sort( $aUsersInvolved, 'userFullname', SORT_ASC, $query ); -$result['data'] = $aUsersInvolved; +$result['data'] = $arrayUsersToReassign; print G::json_encode( $result ); diff --git a/workflow/engine/methods/cases/saveFormSupervisor.php b/workflow/engine/methods/cases/saveFormSupervisor.php deleted file mode 100644 index 4a8525aae..000000000 --- a/workflow/engine/methods/cases/saveFormSupervisor.php +++ /dev/null @@ -1,135 +0,0 @@ -. - * - * For more information, contact Colosa Inc, 2566 Le Jeune Rd., - * Coral Gables, FL, 33134, USA, or email info@colosa.com. - */ - - -try { - - $oForm = new Form( $_SESSION["PROCESS"] . "/" . $_GET["UID"], PATH_DYNAFORM ); - $oForm->validatePost(); - - //Includes - G::LoadClass( "case" ); - - //Load the variables - $oCase = new Cases(); - $Fields = $oCase->loadCase( $_SESSION["APPLICATION"] ); - - $Fields["APP_DATA"] = array_merge( $Fields["APP_DATA"], G::getSystemConstants() ); - $Fields["APP_DATA"] = array_merge( $Fields["APP_DATA"], $_POST["form"] ); - - //save data in PM Tables if necessary - $newValues = array (); - foreach ($_POST['form'] as $sField => $sAux) { - if (isset( $oForm->fields[$sField]->pmconnection ) && isset( $oForm->fields[$sField]->pmfield )) { - if (($oForm->fields[$sField]->pmconnection != '') && ($oForm->fields[$sField]->pmfield != '')) { - if (isset( $oForm->fields[$oForm->fields[$sField]->pmconnection] )) { - require_once PATH_CORE . 'classes' . PATH_SEP . 'model' . PATH_SEP . 'AdditionalTables.php'; - $oAdditionalTables = new AdditionalTables(); - try { - $aData = $oAdditionalTables->load( $oForm->fields[$oForm->fields[$sField]->pmconnection]->pmtable, true ); - } catch (Exception $oError) { - $aData = array ('FIELDS' => array () - ); - } - $aKeys = array (); - $aAux = explode( '|', $oForm->fields[$oForm->fields[$sField]->pmconnection]->keys ); - $i = 0; - $aValues = array (); - foreach ($aData['FIELDS'] as $aField) { - if ($aField['FLD_KEY'] == '1') { - $aKeys[$aField['FLD_NAME']] = (isset( $aAux[$i] ) ? G::replaceDataField( $aAux[$i], $Fields['APP_DATA'] ) : ''); - $i ++; - } - if ($aField['FLD_NAME'] == $oForm->fields[$sField]->pmfield) { - $aValues[$aField['FLD_NAME']] = $Fields['APP_DATA'][$sField]; - } else { - $aValues[$aField['FLD_NAME']] = ''; - } - } - try { - $aRow = $oAdditionalTables->getDataTable( $oForm->fields[$oForm->fields[$sField]->pmconnection]->pmtable, $aKeys ); - } catch (Exception $oError) { - $aRow = false; - } - if ($aRow) { - foreach ($aValues as $sKey => $sValue) { - if ($sKey != $oForm->fields[$sField]->pmfield) { - $aValues[$sKey] = $aRow[$sKey]; - } - } - try { - $oAdditionalTables->updateDataInTable( $oForm->fields[$oForm->fields[$sField]->pmconnection]->pmtable, $aValues ); - } catch (Exception $oError) { - //Nothing - } - } else { - try { - // assembling the field list in order to save the data ina new record of a pm table - if (empty( $newValues )) { - $newValues = $aValues; - } else { - foreach ($aValues as $aValueKey => $aValueCont) { - if (trim( $newValues[$aValueKey] ) == '') { - $newValues[$aValueKey] = $aValueCont; - } - } - } - //$oAdditionalTables->saveDataInTable ( $oForm->fields [$oForm->fields [$sField]->pmconnection]->pmtable, $aValues ); - } catch (Exception $oError) { - //Nothing - } - } - } - } - } - } - - //save data - $aData = array (); - $aData['APP_NUMBER'] = $Fields['APP_NUMBER']; - $aData['APP_PROC_STATUS'] = $Fields['APP_PROC_STATUS']; - $aData['APP_DATA'] = $Fields['APP_DATA']; - $aData['DEL_INDEX'] = $_SESSION['INDEX']; - $aData['TAS_UID'] = $_SESSION['TASK']; - $aData['CURRENT_DYNAFORM'] = $_GET['UID']; - $aData['USER_UID'] = $_SESSION['USER_LOGGED']; - $aData['APP_STATUS'] = $Fields['APP_STATUS']; - $aData['PRO_UID'] = $_SESSION['PROCESS']; - - $oCase->updateCase( $_SESSION['APPLICATION'], $aData ); - - // saving the data ina pm table in case that is a new record - if (! empty( $newValues )) { - $id = key( $newValues ); - if (! $oAdditionalTables->updateDataInTable( $oForm->fields[$oForm->fields[$id]->pmconnection]->pmtable, $newValues )) { - //<--This is to know if it is a new registry on the PM Table - $oAdditionalTables->saveDataInTable( $oForm->fields[$oForm->fields[$id]->pmconnection]->pmtable, $newValues ); - } - } - - die('OK'); - -} catch (Exception $e) { - die($e->getMessage()); -} diff --git a/workflow/engine/methods/departments/departments.php b/workflow/engine/methods/departments/departments.php index aff81e959..f9376ad1e 100755 --- a/workflow/engine/methods/departments/departments.php +++ b/workflow/engine/methods/departments/departments.php @@ -25,7 +25,7 @@ G::LoadClass( 'configuration' ); $c = new Configurations(); -$access = $RBAC->userCanAccess( 'PM_USERS' ); +$access = $RBAC->requirePermissions( 'PM_USERS' ); if ($access != 1) { switch ($access) { case - 1: diff --git a/workflow/engine/methods/emailServer/emailServer.php b/workflow/engine/methods/emailServer/emailServer.php index 237f9e136..f877daf43 100644 --- a/workflow/engine/methods/emailServer/emailServer.php +++ b/workflow/engine/methods/emailServer/emailServer.php @@ -1,9 +1,11 @@ userCanAccess("PM_SETUP") != 1) { - G::SendTemporalMessage("ID_USER_HAVENT_RIGHTS_PAGE", "error", "labels"); - exit(0); +$resultRbac = $RBAC->requirePermissions('PM_SETUP_EMAIL'); +if (!$resultRbac) { + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); + die(); } //Data diff --git a/workflow/engine/methods/events/eventList.php b/workflow/engine/methods/events/eventList.php index dc98cce45..951881eb5 100644 --- a/workflow/engine/methods/events/eventList.php +++ b/workflow/engine/methods/events/eventList.php @@ -23,16 +23,17 @@ */ global $RBAC; -if ($RBAC->userCanAccess( 'PM_SETUP_ADVANCE' ) != 1) { - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); +$resultRbac = $RBAC->requirePermissions('PM_SETUP_ADVANCE', 'PM_SETUP_LOGS'); +if (!$resultRbac) { + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); } -G::LoadClass( 'configuration' ); +G::LoadClass('configuration'); $c = new Configurations(); -$configPage = $c->getConfiguration( 'eventList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); -$Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; +$configPage = $c->getConfiguration('eventList', 'pageSize', '', $_SESSION['USER_LOGGED']); +$Config['pageSize'] = isset($configPage['pageSize']) ? $configPage['pageSize'] : 20; $G_MAIN_MENU = 'processmaker'; $G_SUB_MENU = 'logs'; @@ -40,52 +41,51 @@ $G_ID_MENU_SELECTED = 'logs'; $G_ID_SUB_MENU_SELECTED = 'EVENT'; //get values for the comboBoxes -$userUid = (isset( $_SESSION['USER_LOGGED'] ) && $_SESSION['USER_LOGGED'] != '') ? $_SESSION['USER_LOGGED'] : null; -$status = array (array ('',G::LoadTranslation( 'ID_ALL' ) -),array ("PENDING",G::LoadTranslation( 'ID_OPEN' ) -),array ("COMPLETED",G::LoadTranslation( 'ID_CLOSE' ) +$userUid = (isset($_SESSION['USER_LOGGED']) && $_SESSION['USER_LOGGED'] != '') ? $_SESSION['USER_LOGGED'] : null; +$status = array(array('', G::LoadTranslation('ID_ALL') +), array("PENDING", G::LoadTranslation('ID_OPEN') +), array("COMPLETED", G::LoadTranslation('ID_CLOSE') ) ); -$type = array (array ('',G::LoadTranslation( 'ID_ALL' ) -),array ('SEND_MESSAGE',G::LoadTranslation( 'ID_EVENT_MESSAGE' ) -),array ('EXECUTE_TRIGGER',G::LoadTranslation( 'ID_EVENT_TIMER' ) -),array ('EXECUTE_CONDITIONAL_TRIGGER',G::LoadTranslation( 'ID_EVENT_CONDITIONAL' ) +$type = array(array('', G::LoadTranslation('ID_ALL') +), array('SEND_MESSAGE', G::LoadTranslation('ID_EVENT_MESSAGE') +), array('EXECUTE_TRIGGER', G::LoadTranslation('ID_EVENT_TIMER') +), array('EXECUTE_CONDITIONAL_TRIGGER', G::LoadTranslation('ID_EVENT_CONDITIONAL') ) ); $processes = getProcessArray( $userUid ); $G_PUBLISH = new Publisher(); -$oHeadPublisher = & headPublisher::getSingleton(); -$oHeadPublisher->addExtJsScript( 'events/eventList', false ); //adding a javascript file .js -$oHeadPublisher->addContent( 'events/eventList' ); //adding a html file .html. +$oHeadPublisher = &headPublisher::getSingleton(); +$oHeadPublisher->addExtJsScript('events/eventList', false); //adding a javascript file .js +$oHeadPublisher->addContent('events/eventList'); //adding a html file .html. //sending the columns to display in grid -$oHeadPublisher->assign( 'typeValues', $type ); -$oHeadPublisher->assign( 'statusValues', $status ); -$oHeadPublisher->assign( 'processValues', $processes ); +$oHeadPublisher->assign('typeValues', $type); +$oHeadPublisher->assign('statusValues', $status); +$oHeadPublisher->assign('processValues', $processes); -function getProcessArray ($userUid) -{ +function getProcessArray($userUid) { global $oAppCache; - require_once ("classes/model/AppCacheView.php"); + require_once("classes/model/AppCacheView.php"); - $processes = Array (); - $processes[] = array ('',G::LoadTranslation( 'ID_ALL_PROCESS' )); + $processes = array(); + $processes[] = array('', G::LoadTranslation('ID_ALL_PROCESS')); - $cProcess = new Criteria( 'workflow' ); + $cProcess = new Criteria('workflow'); $cProcess->clearSelectColumns(); - $cProcess->addSelectColumn( AppCacheViewPeer::PRO_UID ); - $cProcess->addSelectColumn( AppCacheViewPeer::APP_PRO_TITLE ); - $cProcess->setDistinct( AppCacheViewPeer::PRO_UID ); + $cProcess->addSelectColumn(AppCacheViewPeer::PRO_UID); + $cProcess->addSelectColumn(AppCacheViewPeer::APP_PRO_TITLE); + $cProcess->setDistinct(AppCacheViewPeer::PRO_UID); - $cProcess->addAscendingOrderByColumn( AppCacheViewPeer::APP_PRO_TITLE ); + $cProcess->addAscendingOrderByColumn(AppCacheViewPeer::APP_PRO_TITLE); - $oDataset = AppCacheViewPeer::doSelectRS( $cProcess ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset = AppCacheViewPeer::doSelectRS($cProcess); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $processes[] = array ($aRow['PRO_UID'],$aRow['APP_PRO_TITLE']); + $processes[] = array($aRow['PRO_UID'], $aRow['APP_PRO_TITLE']); $oDataset->next(); } diff --git a/workflow/engine/methods/events/eventsAjax.php b/workflow/engine/methods/events/eventsAjax.php index c301f030e..48567b6ca 100755 --- a/workflow/engine/methods/events/eventsAjax.php +++ b/workflow/engine/methods/events/eventsAjax.php @@ -109,6 +109,19 @@ switch($req){ $criteria = new Criteria(); $criteria = $oAppEvent->getAppEventsCriteria($proUid, $evenStatus, $evenType); + + $allowedSortField = array( + 'PRO_TITLE', + 'TAS_TITLE', + 'APP_TITLE', + 'APP_EVN_ACTION_DATE', + 'APP_EVN_LAST_EXECUTION_DATE', + ); + + if (!in_array($sort, $allowedSortField)) { + $sort = ""; + } + if ($sort != '') { if ($dir == 'ASC') { $criteria->addAscendingOrderByColumn($sort); @@ -116,12 +129,13 @@ switch($req){ $criteria->addDescendingOrderByColumn($sort); } } else { - $oCriteria->addDescendingOrderByColumn(AppEventPeer::APP_EVN_ACTION_DATE); + $criteria->addDescendingOrderByColumn(AppEventPeer::APP_EVN_ACTION_DATE); } if ($limit != '') { $criteria->setLimit($limit); $criteria->setOffset($start); } + $result = AppEventPeer::doSelectRS($criteria); $result->setFetchmode(ResultSet::FETCHMODE_ASSOC); $data = Array(); diff --git a/workflow/engine/methods/groups/groups.php b/workflow/engine/methods/groups/groups.php index 1347f7328..1a336477b 100755 --- a/workflow/engine/methods/groups/groups.php +++ b/workflow/engine/methods/groups/groups.php @@ -21,29 +21,33 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ - -$access = $RBAC->userCanAccess( 'PM_USERS' ); -if ($access != 1) { +$resultRbac = $RBAC_Response = $RBAC->requirePermissions("PM_USERS"); +if (!$resultRbac) { + return $RBAC_Response; +} +global $RBAC; +$access = $RBAC->userCanAccess('PM_USERS'); +if ($access !== 1) { switch ($access) { - case - 1: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + case -1: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; - case - 2: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + case -2: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; default: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; } } -if (($RBAC_Response = $RBAC->userCanAccess( "PM_USERS" )) != 1) { +if (($RBAC_Response = $RBAC->userCanAccess("PM_USERS")) != 1) { return $RBAC_Response; } @@ -54,16 +58,16 @@ $G_ID_SUB_MENU_SELECTED = 'GROUPS'; $G_PUBLISH = new Publisher(); -G::LoadClass( 'configuration' ); +G::LoadClass('configuration'); $c = new Configurations(); -$configPage = $c->getConfiguration( 'groupList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); -$configEnv = $c->getConfiguration( 'ENVIRONMENT_SETTINGS', '' ); -$Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; +$configPage = $c->getConfiguration('groupList', 'pageSize', '', $_SESSION['USER_LOGGED']); +$configEnv = $c->getConfiguration('ENVIRONMENT_SETTINGS', ''); +$Config['pageSize'] = isset($configPage['pageSize']) ? $configPage['pageSize'] : 20; -$oHeadPublisher = & headPublisher::getSingleton(); -$oHeadPublisher->addExtJsScript( 'groups/groupsList', false ); //adding a javascript file .js -$oHeadPublisher->addContent( 'groups/groupsList' ); //adding a html file .html. -$oHeadPublisher->assign( 'CONFIG', $Config ); +$oHeadPublisher = &headPublisher::getSingleton(); +$oHeadPublisher->addExtJsScript('groups/groupsList', false); //adding a javascript file .js +$oHeadPublisher->addContent('groups/groupsList'); //adding a html file .html. +$oHeadPublisher->assign('CONFIG', $Config); -G::RenderPage( 'publish', 'extJs' ); +G::RenderPage('publish', 'extJs'); diff --git a/workflow/engine/methods/mails/emailList.php b/workflow/engine/methods/mails/emailList.php index 1379a514a..b69ef8a8d 100644 --- a/workflow/engine/methods/mails/emailList.php +++ b/workflow/engine/methods/mails/emailList.php @@ -23,16 +23,17 @@ */ global $RBAC; -if ($RBAC->userCanAccess( 'PM_SETUP_ADVANCE' ) != 1) { - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); +$resultRbac = $RBAC->requirePermissions('PM_SETUP_ADVANCE', 'PM_SETUP_LOGS'); +if (!$resultRbac) { + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); } -G::LoadClass( 'configuration' ); +G::LoadClass('configuration'); $c = new Configurations(); -$configPage = $c->getConfiguration( 'eventList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); -$Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; +$configPage = $c->getConfiguration('eventList', 'pageSize', '', $_SESSION['USER_LOGGED']); +$Config['pageSize'] = isset($configPage['pageSize']) ? $configPage['pageSize'] : 20; $G_MAIN_MENU = 'processmaker'; $G_SUB_MENU = 'logs'; @@ -40,46 +41,45 @@ $G_ID_MENU_SELECTED = 'logs'; $G_ID_SUB_MENU_SELECTED = 'EMAILS'; //get values for the comboBoxes -$userUid = (isset( $_SESSION['USER_LOGGED'] ) && $_SESSION['USER_LOGGED'] != '') ? $_SESSION['USER_LOGGED'] : null; -$status = array ( - array ('',G::LoadTranslation( 'ID_ALL' )), - array ("sent", G::LoadTranslation( 'ID_SENT' )), - array ("pending", G::LoadTranslation( 'ID_PENDING' )) +$userUid = (isset($_SESSION['USER_LOGGED']) && $_SESSION['USER_LOGGED'] != '') ? $_SESSION['USER_LOGGED'] : null; +$status = array( + array('', G::LoadTranslation('ID_ALL')), + array("sent", G::LoadTranslation('ID_SENT')), + array("pending", G::LoadTranslation('ID_PENDING')) ); -$processes = getProcessArray( $userUid ); +$processes = getProcessArray($userUid); $G_PUBLISH = new Publisher(); -$oHeadPublisher = & headPublisher::getSingleton(); -$oHeadPublisher->addExtJsScript( 'mails/emailList', false ); //adding a javascript file .js -$oHeadPublisher->addContent( 'mails/emailList' ); //adding a html file .html. +$oHeadPublisher = &headPublisher::getSingleton(); +$oHeadPublisher->addExtJsScript('mails/emailList', false); //adding a javascript file .js +$oHeadPublisher->addContent('mails/emailList'); //adding a html file .html. //sending the columns to display in grid -$oHeadPublisher->assign( 'statusValues', $status ); -$oHeadPublisher->assign( 'processValues', $processes ); +$oHeadPublisher->assign('statusValues', $status); +$oHeadPublisher->assign('processValues', $processes); -function getProcessArray ($userUid) -{ +function getProcessArray($userUid) { global $oAppCache; - require_once ("classes/model/AppCacheView.php"); + require_once("classes/model/AppCacheView.php"); - $processes = Array (); - $processes[] = array ('',G::LoadTranslation( 'ID_ALL_PROCESS' )); + $processes = array(); + $processes[] = array('', G::LoadTranslation('ID_ALL_PROCESS')); - $cProcess = new Criteria( 'workflow' ); + $cProcess = new Criteria('workflow'); $cProcess->clearSelectColumns(); - $cProcess->addSelectColumn( AppCacheViewPeer::PRO_UID ); - $cProcess->addSelectColumn( AppCacheViewPeer::APP_PRO_TITLE ); - $cProcess->setDistinct( AppCacheViewPeer::PRO_UID ); + $cProcess->addSelectColumn(AppCacheViewPeer::PRO_UID); + $cProcess->addSelectColumn(AppCacheViewPeer::APP_PRO_TITLE); + $cProcess->setDistinct(AppCacheViewPeer::PRO_UID); - $cProcess->addAscendingOrderByColumn( AppCacheViewPeer::APP_PRO_TITLE ); + $cProcess->addAscendingOrderByColumn(AppCacheViewPeer::APP_PRO_TITLE); - $oDataset = AppCacheViewPeer::doSelectRS( $cProcess ); - $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); + $oDataset = AppCacheViewPeer::doSelectRS($cProcess); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $oDataset->next(); while ($aRow = $oDataset->getRow()) { - $processes[] = array ($aRow['PRO_UID'],$aRow['APP_PRO_TITLE']); + $processes[] = array($aRow['PRO_UID'], $aRow['APP_PRO_TITLE']); $oDataset->next(); } diff --git a/workflow/engine/methods/mails/emailsAjax.php b/workflow/engine/methods/mails/emailsAjax.php index 69fc6f7ce..45bc34cc5 100644 --- a/workflow/engine/methods/mails/emailsAjax.php +++ b/workflow/engine/methods/mails/emailsAjax.php @@ -51,13 +51,19 @@ switch($req){ $criteria->add( AppMessagePeer::APP_MSG_DATE, $dateTo, Criteria::LESS_EQUAL ); } - $result = AppMessagePeer::doSelectRS($criteria); - $result->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $data = Array(); - while ( $result->next() ) { - $data[] = $result->getRow(); - } - $totalCount = count($data); + //Number records total + $criteriaCount = clone $criteria; + + $criteriaCount->clearSelectColumns(); + $criteriaCount->addSelectColumn('COUNT(' . AppMessagePeer::APP_MSG_UID . ') AS NUM_REC'); + + $rsCriteriaCount = AppMessagePeer::doSelectRS($criteriaCount); + $rsCriteriaCount->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $resultCount = $rsCriteriaCount->next(); + $rowCount = $rsCriteriaCount->getRow(); + + $totalCount = (int)($rowCount['NUM_REC']); $criteria = new Criteria(); $criteria->addSelectColumn(AppMessagePeer::APP_MSG_UID); diff --git a/workflow/engine/methods/processes/mainInit.php b/workflow/engine/methods/processes/mainInit.php index 13ee39b79..70f96ee8f 100755 --- a/workflow/engine/methods/processes/mainInit.php +++ b/workflow/engine/methods/processes/mainInit.php @@ -78,6 +78,14 @@ $oHeadPublisher->assign("arrayFlagImportFileExtension", $arrayFlagImportFileExte $oHeadPublisher->assign("arrayFlagMenuNewOption", $arrayFlagMenuNewOption); $oHeadPublisher->assign("arrayMenuNewOptionPlugin", $arrayMenuNewOptionPlugin); $oHeadPublisher->assign("arrayContextMenuOptionPlugin", $arrayContextMenuOptionPlugin); +$oHeadPublisher->assign('extJsViewState', $oHeadPublisher->getExtJsViewState()); + +$deleteCasesFlag = false; +global $RBAC; +if($RBAC->userCanAccess('DELETE_PROCESS_CASES') === 1) { + $deleteCasesFlag = true; +} +$oHeadPublisher->assign('deleteCasesFlag', $deleteCasesFlag); $oPluginRegistry = & PMPluginRegistry::getSingleton(); $callBackFile = $oPluginRegistry->getImportProcessCallback(); diff --git a/workflow/engine/methods/processes/processesList.php b/workflow/engine/methods/processes/processesList.php index 141c64a1f..fc441d0e8 100755 --- a/workflow/engine/methods/processes/processesList.php +++ b/workflow/engine/methods/processes/processesList.php @@ -78,7 +78,7 @@ if (isset( $_POST['category'] ) && $_POST['category'] !== '') { } } $r = new stdclass(); -$r->memkey = $memkey; +$r->memkey = htmlspecialchars($memkey); $r->memcache = $memcacheUsed; $r->data = \ProcessMaker\Util\DateTime::convertUtcToTimeZone($proData); $r->totalCount = $totalCount; diff --git a/workflow/engine/methods/processes/processes_DeleteCases.php b/workflow/engine/methods/processes/processes_DeleteCases.php new file mode 100644 index 000000000..d90bf3810 --- /dev/null +++ b/workflow/engine/methods/processes/processes_DeleteCases.php @@ -0,0 +1,25 @@ +requirePermissions( 'DELETE_PROCESS_CASES', 'PM_FACTORY' ); + +try { + $uids = explode(',', $_POST['PRO_UIDS']); + $oProcess = new Process(); + foreach ($uids as $uid) { + $oProcess->deleteProcessCases($uid); + } + $oProcess->refreshUserAllCountersByProcessesGroupUid($uids); + + $resp = new StdClass(); + $resp->status = true; + $resp->msg = G::LoadTranslation('ID_ALL_RECORDS_DELETED_SUCESSFULLY'); + + echo G::json_encode($resp); + +} catch (Exception $e) { + $resp->status = false; + $resp->msg = $e->getMessage(); + echo G::json_encode($resp); +} + + diff --git a/workflow/engine/methods/processes/processes_Import_Ajax.php b/workflow/engine/methods/processes/processes_Import_Ajax.php index 3ca27a1c7..6028c1ef5 100644 --- a/workflow/engine/methods/processes/processes_Import_Ajax.php +++ b/workflow/engine/methods/processes/processes_Import_Ajax.php @@ -117,7 +117,17 @@ if (isset($_FILES["PROCESS_FILENAME"]) && $importer->setSourceFromGlobals("PROCESS_FILENAME"); try { - $prjUid = $importer->import(); + $opt1 = XmlImporter::IMPORT_OPTION_CREATE_NEW; + $opt2 = XmlImporter::GROUP_IMPORT_OPTION_CREATE_NEW; + if($_POST['generateUid'] === 'generate') { + $generateUid = true; + $prjUid = $importer->import($opt1,$opt2,$generateUid); + } elseif($_POST['generateUid'] === 'keep') { + $generateUid = false; + $prjUid = $importer->import($opt1,$opt2,$generateUid); + } else { + $prjUid = $importer->import(); + } G::LoadClass( 'Process' ); $oProcess = new Process(); @@ -126,19 +136,37 @@ if (isset($_FILES["PROCESS_FILENAME"]) && $result = array( "success" => true, - "catchMessage" => "", + "catchMessage" => '', "ExistProcessInDatabase" => 0, "ExistGroupsInDatabase" => 0, + "notExistProcessInDatabase" => 0, + "affectedGroups" => '', "sNewProUid" => $prjUid, - "project_type" => "bpmn", + "project_type" => 'bpmn', "project_type_aux" => $proType ); } catch (Exception $e) { + $groupsExists = ($e->getCode() == XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS)? 1 : 0; + if($groupsExists === 1) { + $arrayGroups = XmlImporter::$affectedGroups; + if(sizeof($arrayGroups)) { + foreach ($arrayGroups as $group) { + $affectedGroups[] = $group["GRP_TITLE"]; + } + $affectedGroups = implode(', ', $affectedGroups); + } + } $result = array( "success" => true, - "catchMessage" => (in_array($e->getCode(), array(XmlImporter::IMPORT_STAT_TARGET_ALREADY_EXISTS, XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS)))? "" : $e->getMessage(), + "catchMessage" => (in_array($e->getCode(), array( + XmlImporter::IMPORT_STAT_TARGET_ALREADY_EXISTS, + XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS, + XmlImporter::IMPORTED_PROJECT_DOES_NOT_EXISTS + )))? "" : $e->getMessage(), "ExistProcessInDatabase" => ($e->getCode() == XmlImporter::IMPORT_STAT_TARGET_ALREADY_EXISTS)? 1 : 0, - "ExistGroupsInDatabase" => ($e->getCode() == XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS)? 1 : 0, + "ExistGroupsInDatabase" => $groupsExists, + "notExistProcessInDatabase" => ($e->getCode() == XmlImporter::IMPORTED_PROJECT_DOES_NOT_EXISTS) ? 1 : 0, + "affectedGroups" => !empty($affectedGroups)? $affectedGroups : '', "sNewProUid" => "", "project_type" => "bpmn", @@ -195,19 +223,31 @@ if (isset($_POST["PRO_FILENAME"]) && $result = array( "success" => true, - "catchMessage" => "", + "catchMessage" => '', "ExistProcessInDatabase" => 0, "ExistGroupsInDatabase" => 0, + "ExistGroupsInDatabase" => '', "sNewProUid" => $prjUid, - "project_type" => "bpmn", + "project_type" => 'bpmn', "project_type_aux" => $proType ); } catch (Exception $e) { + $groupsExists = ($e->getCode() == XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS)? 1 : 0; + if($groupsExists === 1) { + $arrayGroups = XmlImporter::$affectedGroups; + if(sizeof($arrayGroups)) { + foreach($arrayGroups as $group){ + $affectedGroups[] = $group["GRP_TITLE"]; + } + $affectedGroups = implode(', ', $affectedGroups); + } + } $result = array( "success" => true, "catchMessage" => (in_array($e->getCode(), array(XmlImporter::IMPORT_STAT_TARGET_ALREADY_EXISTS, XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS)))? "" : $e->getMessage(), "ExistProcessInDatabase" => ($e->getCode() == XmlImporter::IMPORT_STAT_TARGET_ALREADY_EXISTS)? 1 : 0, - "ExistGroupsInDatabase" => ($e->getCode() == XmlImporter::IMPORT_STAT_GROUP_ALREADY_EXISTS)? 1 : 0, + "ExistGroupsInDatabase" => $groupsExists, + "affectedGroups" => !empty($affectedGroups)? $affectedGroups : '', "sNewProUid" => "", "project_type" => "bpmn", @@ -341,6 +381,17 @@ if ($action == "uploadFileNewProcess") { //!data ouput $result->sNewProUid = $sProUid; $result->proFileName = $Fields['PRO_FILENAME']; + $result->affectedGroups = ''; + if($result->ExistGroupsInDatabase === 1) { + $arrayGroups = XmlImporter::$affectedGroups; + if(sizeof($arrayGroups)) { + foreach ($arrayGroups as $group) { + $affectedGroups[] = $group["GRP_TITLE"]; + } + $affectedGroups = implode(', ', $affectedGroups); + } + } + $result->affectedGroups = $affectedGroups; //Add Audit Log $process = new Process(); @@ -473,6 +524,18 @@ if ($action == "uploadFileNewProcessExist") { $result->success = true; $result->ExistGroupsInDatabase = $result->ExistGroupsInDatabase; $result->groupBeforeAccion = $action; + $result->affectedGroups = ''; + if($result->ExistGroupsInDatabase === 1) { + $arrayGroups = XmlImporter::$affectedGroups; + if(sizeof($arrayGroups)) { + foreach ($arrayGroups as $group) { + $affectedGroups[] = $group["GRP_TITLE"]; + } + $affectedGroups = implode(', ', $affectedGroups); + } + } + $result->affectedGroups = $affectedGroups; + //!data ouput } catch (Exception $e) { $result->response = $e->getMessage(); diff --git a/workflow/engine/methods/roles/roles_List.php b/workflow/engine/methods/roles/roles_List.php index e668463c3..f7c63e6cf 100755 --- a/workflow/engine/methods/roles/roles_List.php +++ b/workflow/engine/methods/roles/roles_List.php @@ -21,21 +21,26 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ +$RBAC_Response = $RBAC->requirePermissions('PM_USERS'); +if (!$RBAC_Response) { + return $RBAC_Response; +} global $RBAC; -switch ($RBAC->userCanAccess( 'PM_USERS' )) { - case - 2: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels' ); - G::header( 'location: ../login/login' ); +$access = $RBAC->userCanAccess('PM_USERS'); +switch ($access !== 1) { + case -2: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; - case - 1: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + case -1: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; - case - 3: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + case -3: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; } @@ -47,17 +52,17 @@ $G_ID_SUB_MENU_SELECTED = 'ROLES'; $G_PUBLISH = new Publisher(); -G::LoadClass( 'configuration' ); +G::LoadClass('configuration'); $c = new Configurations(); -$configPage = $c->getConfiguration( 'rolesList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); -$Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; +$configPage = $c->getConfiguration('rolesList', 'pageSize', '', $_SESSION['USER_LOGGED']); +$Config['pageSize'] = isset($configPage['pageSize']) ? $configPage['pageSize'] : 20; -$oHeadPublisher = & headPublisher::getSingleton(); +$oHeadPublisher = &headPublisher::getSingleton(); -$oHeadPublisher->addExtJsScript( 'roles/rolesList', false ); //adding a javascript file .js -$oHeadPublisher->addContent( 'roles/rolesList' ); //adding a html file .html. -$oHeadPublisher->assign( 'PARTNER_FLAG', (defined('PARTNER_FLAG')) ? PARTNER_FLAG : false); -$oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); -$oHeadPublisher->assign( 'CONFIG', $Config ); -G::RenderPage( 'publish', 'extJs' ); +$oHeadPublisher->addExtJsScript('roles/rolesList', false); //adding a javascript file .js +$oHeadPublisher->addContent('roles/rolesList'); //adding a html file .html. +$oHeadPublisher->assign('PARTNER_FLAG', (defined('PARTNER_FLAG')) ? PARTNER_FLAG : false); +$oHeadPublisher->assign('FORMATS', $c->getFormats()); +$oHeadPublisher->assign('CONFIG', $Config); +G::RenderPage('publish', 'extJs'); diff --git a/workflow/engine/methods/setup/appCacheViewAjax.php b/workflow/engine/methods/setup/appCacheViewAjax.php index bb17fc2ff..4af621a0d 100755 --- a/workflow/engine/methods/setup/appCacheViewAjax.php +++ b/workflow/engine/methods/setup/appCacheViewAjax.php @@ -1,10 +1,10 @@ xssFilterHard($_POST); $_GET = $filter->xssFilterHard($_GET); -$request = isset( $_POST['request'] ) ? $_POST['request'] : (isset( $_GET['request'] ) ? $_GET['request'] : null); +$request = isset($_POST['request']) ? $_POST['request'] : (isset($_GET['request']) ? $_GET['request'] : null); function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName = "") { @@ -44,7 +44,7 @@ function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName $message = ""; $response = $Server->tryConnectServer($type); $server = $filter->validateInput($server); - $user = $filter->validateInput($user); + $user = $filter->validateInput($user); $passwd = $filter->validateInput($passwd); $connDatabase = @mysql_connect($server, $user, $passwd); $dbNameTest = "PROCESSMAKERTESTDC"; @@ -58,14 +58,14 @@ function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName } else { $usrTest = "wfrbtest"; $chkG = "GRANT ALL PRIVILEGES ON `%s`.* TO %s@'%%' IDENTIFIED BY 'sample' WITH GRANT OPTION"; - $chkG = $filter->preventSqlInjection($chkG, array($dbNameTest,$usrTest), $connDatabase); + $chkG = $filter->preventSqlInjection($chkG, array($dbNameTest, $usrTest), $connDatabase); $ch = @mysql_query($chkG, $connDatabase); if (!$ch) { $message = mysql_error(); } else { $sqlCreateUser = "CREATE USER '%s'@'%%' IDENTIFIED BY '%s'"; $user = $filter->validateInput($user, 'nosql'); - $sqlCreateUser = $filter->preventSqlInjection($sqlCreateUser, array($user."_usertest","sample"), $connDatabase); + $sqlCreateUser = $filter->preventSqlInjection($sqlCreateUser, array($user . "_usertest", "sample"), $connDatabase); $result = @mysql_query($sqlCreateUser, $connDatabase); if (!$result) { $message = mysql_error(); @@ -75,9 +75,9 @@ function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName } $sqlDropUser = "DROP USER '%s'@'%%'"; $user = $filter->validateInput($user, 'nosql'); - $sqlDropUser = $filter->preventSqlInjection($sqlDropUser, array($user."_usertest"), $connDatabase); + $sqlDropUser = $filter->preventSqlInjection($sqlDropUser, array($user . "_usertest"), $connDatabase); @mysql_query($sqlDropUser, $connDatabase); - + $sqlDropUser = "DROP USER %s@'%%'"; $usrTest = $filter->validateInput($usrTest, 'nosql'); $sqlDropUser = $filter->preventSqlInjection($sqlDropUser, array($usrTest), $connDatabase); @@ -88,7 +88,7 @@ function testConnection($type, $server, $user, $passwd, $port = 'none', $dbName $sqlDropDb = $filter->preventSqlInjection($sqlDropDb, array($dbNameTest), $connDatabase); @mysql_query($sqlDropDb, $connDatabase); } - return array($success, ($message != "")? $message : $Server->error); + return array($success, ($message != "") ? $message : $Server->error); } else { return array(false, $Server->error); } @@ -110,65 +110,65 @@ switch ($request) { //check if the APP_CACHE VIEW table and their triggers are installed case 'info': $result = new stdClass(); - $result->info = Array (); + $result->info = array(); //check the language, if no info in config about language, the default is 'en' - G::loadClass( 'configuration' ); + G::loadClass('configuration'); $oConf = new Configurations(); - $oConf->loadConfig( $x, 'APP_CACHE_VIEW_ENGINE', '', '', '', '' ); + $oConf->loadConfig($x, 'APP_CACHE_VIEW_ENGINE', '', '', '', ''); $appCacheViewEngine = $oConf->aConfig; - if (isset( $appCacheViewEngine['LANG'] )) { + if (isset($appCacheViewEngine['LANG'])) { $lang = (defined('SYS_LANG')) ? SYS_LANG : $appCacheViewEngine['LANG']; - $status = strtoupper( $appCacheViewEngine['STATUS'] ); + $status = strtoupper($appCacheViewEngine['STATUS']); } else { - $confParams = Array ('LANG' => (defined('SYS_LANG')) ? SYS_LANG : 'en','STATUS' => ''); + $confParams = array('LANG' => (defined('SYS_LANG')) ? SYS_LANG : 'en', 'STATUS' => ''); $oConf->aConfig = $confParams; - $oConf->saveConfig( 'APP_CACHE_VIEW_ENGINE', '', '', '' ); + $oConf->saveConfig('APP_CACHE_VIEW_ENGINE', '', '', ''); $lang = (defined('SYS_LANG')) ? SYS_LANG : 'en'; $status = ''; } //get user Root from hash - $result->info = array (); + $result->info = array(); $result->error = false; //setup the appcacheview object, and the path for the sql files $appCache = new AppCacheView(); - $appCache->setPathToAppCacheFiles( PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP ); + $appCache->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP); $res = $appCache->getMySQLVersion(); //load translations G::LoadTranslation - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_MYSQL_VERSION' ) ,'value' => $res); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_MYSQL_VERSION'), 'value' => $res); - $res = $appCache->checkGrantsForUser( false ); + $res = $appCache->checkGrantsForUser(false); $currentUser = $res['user']; $currentUserIsSuper = $res['super']; - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_CURRENT_USER' ) ,'value' => $currentUser); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_USER_SUPER_PRIVILEGE' ) ,'value' => $currentUserIsSuper); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_CURRENT_USER'), 'value' => $currentUser); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_USER_SUPER_PRIVILEGE'), 'value' => $currentUserIsSuper); try { - PROPEL::Init( PATH_METHODS . 'dbConnections/rootDbConnections.php' ); - $con = Propel::getConnection( "root" ); + PROPEL::Init(PATH_METHODS . 'dbConnections/rootDbConnections.php'); + $con = Propel::getConnection("root"); } catch (Exception $e) { - $result->info[] = array ('name' => 'Checking MySql Root user','value' => 'failed'); + $result->info[] = array('name' => 'Checking MySql Root user', 'value' => 'failed'); $result->error = true; $result->errorMsg = $e->getMessage(); } //if user does not have the SUPER privilege we need to use the root user and grant the SUPER priv. to normal user. - if (! $currentUserIsSuper && ! $result->error) { - $res = $appCache->checkGrantsForUser( true ); - if (! isset( $res['error'] )) { - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_ROOT_USER' ), 'value' => $res['user']); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_ROOT_USER_SUPER' ), 'value' => $res['super']); + if (!$currentUserIsSuper && !$result->error) { + $res = $appCache->checkGrantsForUser(true); + if (!isset($res['error'])) { + $result->info[] = array('name' => G::LoadTranslation('ID_ROOT_USER'), 'value' => $res['user']); + $result->info[] = array('name' => G::LoadTranslation('ID_ROOT_USER_SUPER'), 'value' => $res['super']); } else { - $result->info[] = array ('name' => 'Error','value' => $res['msg']); + $result->info[] = array('name' => 'Error', 'value' => $res['msg']); } - $res = $appCache->setSuperForUser( $currentUser ); - if (! isset( $res['error'] )) { - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_SETTING_SUPER' ), 'value' => G::LoadTranslation ( 'ID_SUCCESSFULLY' )); + $res = $appCache->setSuperForUser($currentUser); + if (!isset($res['error'])) { + $result->info[] = array('name' => G::LoadTranslation('ID_SETTING_SUPER'), 'value' => G::LoadTranslation('ID_SUCCESSFULLY')); } else { $result->error = true; $result->errorMsg = $res['msg']; @@ -179,55 +179,54 @@ switch ($request) { //now check if table APPCACHEVIEW exists, and it have correct number of fields, etc. $res = $appCache->checkAppCacheView(); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_TABLE' ),'value' => $res['found']); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_TABLE'), 'value' => $res['found']); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_ROWS' ),'value' => $res['count']); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_ROWS'), 'value' => $res['count']); //now check if we have the triggers installed //APP_DELEGATION INSERT - $res = $appCache->triggerAppDelegationInsert( $lang, false ); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_TRIGGER_INSERT' ),'value' => $res); + $res = $appCache->triggerAppDelegationInsert($lang, false); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_TRIGGER_INSERT'), 'value' => $res); //APP_DELEGATION Update - $res = $appCache->triggerAppDelegationUpdate( $lang, false ); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_TRIGGER_UPDATE' ),'value' => $res); + $res = $appCache->triggerAppDelegationUpdate($lang, false); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_TRIGGER_UPDATE'), 'value' => $res); //APPLICATION UPDATE - $res = $appCache->triggerApplicationUpdate( $lang, false ); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_TRIGGER_APPLICATION_UPDATE' ),'value' => $res); + $res = $appCache->triggerApplicationUpdate($lang, false); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_TRIGGER_APPLICATION_UPDATE'), 'value' => $res); //APPLICATION DELETE - $res = $appCache->triggerApplicationDelete( $lang, false ); - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_TRIGGER_APPLICATION_DELETE' ),'value' => $res); + $res = $appCache->triggerApplicationDelete($lang, false); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_TRIGGER_APPLICATION_DELETE'), 'value' => $res); //SUB_APPLICATION INSERT $res = $appCache->triggerSubApplicationInsert($lang, false); //CONTENT UPDATE - $res = $appCache->triggerContentUpdate( $lang, false ); - $result->info[] = array ("name" => G::LoadTranslation ( 'ID_CACHE_BUILDER_TRIGGER_CONTENT_UPDATE' ),"value" => $res); + $res = $appCache->triggerContentUpdate($lang, false); + $result->info[] = array("name" => G::LoadTranslation('ID_CACHE_BUILDER_TRIGGER_CONTENT_UPDATE'), "value" => $res); //show language - $result->info[] = array ('name' => G::LoadTranslation ( 'ID_CACHE_BUILDER_LANGUAGE' ),'value' => $lang); + $result->info[] = array('name' => G::LoadTranslation('ID_CACHE_BUILDER_LANGUAGE'), 'value' => $lang); - echo G::json_encode( $result ); + echo G::json_encode($result); break; case 'getLangList': - - $Translations = G::getModel( 'Translation' ); + $Translations = G::getModel('Translation'); $result = new stdClass(); - $result->rows = Array (); + $result->rows = array(); $langs = $Translations->getTranslationEnvironments(); foreach ($langs as $lang) { - $result->rows[] = Array ('LAN_ID' => $lang['LOCALE'],'LAN_NAME' => $lang['LANGUAGE']); + $result->rows[] = array('LAN_ID' => $lang['LOCALE'], 'LAN_NAME' => $lang['LANGUAGE']); } - print (G::json_encode( $result )) ; + print (G::json_encode($result)); break; case 'build': - $sqlToExe = Array (); - G::LoadClass( 'configuration' ); + $sqlToExe = array(); + G::LoadClass('configuration'); $conf = new Configurations(); //DEPRECATED $lang = $_POST['lang']; @@ -237,57 +236,57 @@ switch ($request) { try { //setup the appcacheview object, and the path for the sql files $appCache = new AppCacheView(); - $appCache->setPathToAppCacheFiles( PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP ); + $appCache->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP); //Update APP_DELEGATION.DEL_LAST_INDEX data $res = $appCache->updateAppDelegationDelLastIndex($lang, true); //$result->info[] = array("name" => "update APP_DELEGATION.DEL_LAST_INDEX", "value" => $res); //APP_DELEGATION INSERT - $res = $appCache->triggerAppDelegationInsert( $lang, true ); + $res = $appCache->triggerAppDelegationInsert($lang, true); //$result->info[] = array ('name' => 'Trigger APP_DELEGATION INSERT', 'value'=> $res); //APP_DELEGATION Update - $res = $appCache->triggerAppDelegationUpdate( $lang, true ); + $res = $appCache->triggerAppDelegationUpdate($lang, true); //$result->info[] = array ('name' => 'Trigger APP_DELEGATION UPDATE', 'value'=> $res); //APPLICATION UPDATE - $res = $appCache->triggerApplicationUpdate( $lang, true ); + $res = $appCache->triggerApplicationUpdate($lang, true); //$result->info[] = array ('name' => 'Trigger APPLICATION UPDATE', 'value'=> $res); //APPLICATION DELETE - $res = $appCache->triggerApplicationDelete( $lang, true ); + $res = $appCache->triggerApplicationDelete($lang, true); //$result->info[] = array ('name' => 'Trigger APPLICATION DELETE', 'value'=> $res); //SUB_APPLICATION INSERT $res = $appCache->triggerSubApplicationInsert($lang, false); //CONTENT UPDATE - $res = $appCache->triggerContentUpdate( $lang, true ); + $res = $appCache->triggerContentUpdate($lang, true); //$result->info[] = array("name" => "Trigger CONTENT UPDATE", "value" => $res); //build using the method in AppCacheView Class - $res = $appCache->fillAppCacheView( $lang ); + $res = $appCache->fillAppCacheView($lang); //$result->info[] = array ('name' => 'build APP_CACHE_VIEW', 'value'=> $res); //set status in config table - $confParams = Array ('LANG' => $lang,'STATUS' => 'active'); + $confParams = array('LANG' => $lang, 'STATUS' => 'active'); $conf->aConfig = $confParams; - $conf->saveConfig( 'APP_CACHE_VIEW_ENGINE', '', '', '' ); + $conf->saveConfig('APP_CACHE_VIEW_ENGINE', '', '', ''); $result = new StdClass(); $result->success = true; $result->msg = G::LoadTranslation('ID_TITLE_COMPLETED'); G::auditLog("BuildCache"); - echo G::json_encode( $result ); + echo G::json_encode($result); } catch (Exception $e) { - $confParams = Array ('lang' => $lang,'status' => 'failed'); - $appCacheViewEngine = $oServerConf->setProperty( 'APP_CACHE_VIEW_ENGINE', $confParams ); + $confParams = array('lang' => $lang, 'status' => 'failed'); + $appCacheViewEngine = $oServerConf->setProperty('APP_CACHE_VIEW_ENGINE', $confParams); echo '{success: false, msg:"' . $e->getMessage() . '"}'; } @@ -296,37 +295,48 @@ switch ($request) { $user = $_POST['user']; $passwd = $_POST['password']; $server = $_POST['host']; + $code = $_POST['codeCaptcha']; $aServer = split(":", $server); $serverName = $aServer[0]; - $port = (count($aServer)>1) ? $aServer[1] : "none"; + $port = (count($aServer) > 1) ? $aServer[1] : "none"; + + if ($code !== $_SESSION['securimage_code_disp']['default']) { + echo G::loadTranslation('ID_CAPTCHA_CODE_INCORRECT'); + break; + } + list($sucess, $msgErr) = testConnection(DB_ADAPTER, $serverName, $user, $passwd, $port); if ($sucess) { - $sh = G::encryptOld( filemtime( PATH_GULLIVER . "/class.g.php" ) ); - $h = G::encrypt( $_POST['host'] . $sh . $_POST['user'] . $sh . $_POST['password'] . $sh . (1), $sh ); + $sh = G::encryptOld(filemtime(PATH_GULLIVER . "/class.g.php")); + $h = G::encrypt($_POST['host'] . $sh . $_POST['user'] . $sh . $_POST['password'] . $sh . (1), $sh); $insertStatements = "define ( 'HASH_INSTALLATION','{$h}' ); \ndefine ( 'SYSTEM_HASH', '{$sh}' ); \n"; - $lines = array (); + $lines = array(); $content = ''; $filename = PATH_HOME . 'engine' . PATH_SEP . 'config' . PATH_SEP . 'paths_installed.php'; - $lines = file( $filename ); + $lines = file($filename); $count = 1; foreach ($lines as $line_num => $line) { - $pos = strpos( $line, "define" ); + $pos = strpos($line, "define"); if ($pos !== false && $count < 3) { $content = $content . $line; - $count ++; + $count++; } } $content = "show(); + break; } - diff --git a/workflow/engine/methods/setup/calendarList.php b/workflow/engine/methods/setup/calendarList.php index 8204f4120..86f298160 100755 --- a/workflow/engine/methods/setup/calendarList.php +++ b/workflow/engine/methods/setup/calendarList.php @@ -21,10 +21,11 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ - -if ($RBAC->userCanAccess( 'PM_SETUP' ) != 1 && $RBAC->userCanAccess( 'PM_SETUP_ADVANCE' ) != 1) { - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - //G::header('location: ../login/login'); +global $RBAC; +$resultRbac = $RBAC->requirePermissions('PM_SETUP_CALENDAR'); +if (!$resultRbac) { + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); } diff --git a/workflow/engine/methods/setup/clearCompiled.php b/workflow/engine/methods/setup/clearCompiled.php index a2115ef99..9c8e715b3 100755 --- a/workflow/engine/methods/setup/clearCompiled.php +++ b/workflow/engine/methods/setup/clearCompiled.php @@ -22,7 +22,12 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ global $RBAC; -$RBAC->requirePermissions( 'PM_SETUP' ); +$resultRbac = $RBAC->requirePermissions('PM_SETUP_CLEAR_CACHE'); +if (!$resultRbac) { + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); + die(); +} $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'setup/clearCompiled', true ); //adding a javascript file .js diff --git a/workflow/engine/methods/setup/jasper.php b/workflow/engine/methods/setup/jasper.php deleted file mode 100755 index b4a94cbd0..000000000 --- a/workflow/engine/methods/setup/jasper.php +++ /dev/null @@ -1,136 +0,0 @@ -ws_list( "/" ); - -if (is_object( $response ) && get_class( $response ) == 'SOAP_Fault') { - $errorMessage = $response->getFault()->faultstring; -} else { - $folders = $oJasper->getResourceDescriptors( $response ); -} - -//$result = $oJasper->ws_put(); -krumo( $response ); - -//execute a report - - -$currentUri = "/reports/samples/Employees"; -$result = $oJasper->ws_get( $currentUri ); - -$folders = $oJasper->getResourceDescriptors( $result ); - -if (count( $folders ) != 1 || $folders[0]['type'] != 'reportUnit') { - echo "

Invalid RU ($currentUri)

"; - echo "
$result
"; - exit(); -} - -$reportUnit = $folders[0]; - -// 2. Prepare the parameters array looking in the $_GET for params -// starting with PARAM_ ... -// - - -$report_params = array (); - -$moveToPage = "jasper?uri=$currentUri"; - -foreach (array_keys( $_GET ) as $param_name) { - if (strncmp( "PARAM_", $param_name, 6 ) == 0) { - $report_params[substr( $param_name, 6 )] = $_GET[$param_name]; - } - - // if ($param_name != "page" && $param_name != "uri") { - // $moveToPage .= "&".urlencode($param_name)."=". urlencode($_GET[$param_name]); - // } -} - -$formatReport = RUN_OUTPUT_FORMAT_XML; -$formatReport = RUN_OUTPUT_FORMAT_CSV; -$formatReport = RUN_OUTPUT_FORMAT_RTF; -$formatReport = RUN_OUTPUT_FORMAT_PDF; -$formatReport = RUN_OUTPUT_FORMAT_HTML; -$moveToPage .= "&page="; - -// 3. Execute the report -$output_params = array (); -$output_params[RUN_OUTPUT_FORMAT] = $formatReport; - -if ($formatReport == RUN_OUTPUT_FORMAT_HTML) { - //$pageReport = isset ( $_GET['page'] ) ? $_GET['page'] : 1; - //$output_params[RUN_OUTPUT_PAGE] = $pageReport; - //$output_params[RUN_OUTPUT_IMAGES_URI] = '/sysos/'. SYS_LANG. '/classic'; -} - -$result = $oJasper->ws_runReport( $currentUri, $report_params, $output_params, $attachments ); - -// 4. -if (is_object( $result ) && get_class( $result ) == 'SOAP_Fault') { - $errorMessage = $result->getFault()->faultstring; - - echo $errorMessage; - exit(); -} - -$operationResult = $oJasper->getOperationResult( $result ); - -if ($operationResult['returnCode'] != '0') { - echo "Error executing the report:
" . $operationResult['returnMessage'] . ""; - exit(); -} - -if (is_array( $attachments )) { - //krumo ($attachments); - - - switch ($formatReport) { - case RUN_OUTPUT_FORMAT_PDF: - header( "Content-type: application/pdf" ); - echo ($attachments["cid:report"]); - break; - case RUN_OUTPUT_FORMAT_HTML: - // 1. Save attachments.... - // 2. Print the report.... - header( "Content-type: text/html" ); - foreach (array_keys( $attachments ) as $key) { - if ($key != "cid:report") { - $f = fopen( "images/" . substr( $key, 4 ), "w" ); - fwrite( $f, $attachments[$key] ); - fclose( $f ); - } - } - - echo "
"; - $prevpage = ($pageReport > 0) ? $pageReport - 1 : 0; - $nextpage = $pageReport + 1; - - echo "Prev page | Next page"; - echo "

"; - - echo $attachments["cid:report"]; - //print_r(array_keys($attachments)); - break; - case RUN_OUTPUT_FORMAT_CSV: - case RUN_OUTPUT_FORMAT_XLS: - header( 'Content-type: application/xls' ); - header( 'Content-Disposition: attachment; filename="report.xls"' ); - echo ($attachments["cid:report"]); - break; - case RUN_OUTPUT_FORMAT_RTF: - header( 'Content-type: text/rtf' ); - header( 'Content-Disposition: attachment; filename="report.rtf"' ); - echo ($attachments["cid:report"]); - break; - default: - //header ( 'Content-type: application/xls' ); - //header ( 'Content-Disposition: attachment; filename="report.xls"'); - echo ($attachments["cid:report"]); - break; - } - exit(); -} else - echo "No attachment found!"; - diff --git a/workflow/engine/methods/setup/languages.php b/workflow/engine/methods/setup/languages.php index fad45b1a1..2a98db4e2 100755 --- a/workflow/engine/methods/setup/languages.php +++ b/workflow/engine/methods/setup/languages.php @@ -21,7 +21,7 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ -$RBAC->requirePermissions( 'PM_SETUP_ADVANCE' ); +$RBAC->requirePermissions( 'PM_SETUP_ADVANCE', 'PM_SETUP_LANGUAGE'); $oHeadPublisher->addExtJsScript( 'setup/languages', false ); //adding a javascript file .js $oHeadPublisher->addContent( 'setup/languages' ); //adding a html file .html. diff --git a/workflow/engine/methods/setup/processHeartBeatConfig.php b/workflow/engine/methods/setup/processHeartBeatConfig.php index 2eacc4eaf..696efe798 100755 --- a/workflow/engine/methods/setup/processHeartBeatConfig.php +++ b/workflow/engine/methods/setup/processHeartBeatConfig.php @@ -22,7 +22,7 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ global $RBAC; -$RBAC->requirePermissions( 'PM_SETUP' ); +$RBAC->requirePermissions( 'PM_SETUP', 'PM_SETUP_HEART_BEAT'); $oHeadPublisher = & headPublisher::getSingleton(); G::LoadClass( 'serverConfiguration' ); diff --git a/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql b/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql index d0fd9b856..809608aa0 100755 --- a/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql +++ b/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationInsert.sql @@ -5,6 +5,7 @@ BEGIN DECLARE APP_NUMBER INT; DECLARE APP_STATUS VARCHAR(32); DECLARE APP_CREATE_DATE DATETIME; + DECLARE APP_UPDATE_DATE DATETIME; DECLARE APP_TITLE VARCHAR(255); DECLARE APP_PRO_TITLE VARCHAR(255); DECLARE APP_TAS_TITLE VARCHAR(255); @@ -17,6 +18,8 @@ BEGIN SELECT APPLICATION.APP_NUMBER into @APP_NUMBER FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; SELECT APPLICATION.APP_STATUS into @APP_STATUS FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; SELECT APPLICATION.APP_CREATE_DATE into @APP_CREATE_DATE FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; + SELECT APPLICATION.APP_UPDATE_DATE into @APP_UPDATE_DATE FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; + SELECT CONTENT.CON_VALUE into @APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = '{lang}' LIMIT 1; IF ( @APP_TITLE IS NULL ) THEN SET @APP_TITLE = ''; @@ -108,7 +111,7 @@ BEGIN NEW.DEL_DELAYED, @APP_CREATE_DATE, NULL, - NOW(), + @APP_UPDATE_DATE, NEW.APP_OVERDUE_PERCENTAGE, NEW.DEL_LAST_INDEX ); diff --git a/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql b/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql index 1a492caab..dce6833fe 100755 --- a/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql +++ b/workflow/engine/methods/setup/setupSchemas/triggerAppDelegationUpdate.sql @@ -5,6 +5,7 @@ BEGIN DECLARE APP_NUMBER INT; DECLARE APP_STATUS VARCHAR(32); DECLARE APP_CREATE_DATE DATETIME; + DECLARE APP_UPDATE_DATE DATETIME; DECLARE APP_TITLE VARCHAR(255); DECLARE APP_PRO_TITLE VARCHAR(255); DECLARE APP_TAS_TITLE VARCHAR(255); @@ -17,6 +18,8 @@ BEGIN SELECT APPLICATION.APP_NUMBER into @APP_NUMBER FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; SELECT APPLICATION.APP_STATUS into @APP_STATUS FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; SELECT APPLICATION.APP_CREATE_DATE into @APP_CREATE_DATE FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; + SELECT APPLICATION.APP_UPDATE_DATE into @APP_UPDATE_DATE FROM APPLICATION WHERE APP_UID = NEW.APP_UID LIMIT 1; + SELECT CONTENT.CON_VALUE into @APP_TITLE FROM CONTENT WHERE NEW.APP_UID=CON_ID AND CON_CATEGORY='APP_TITLE' and CON_LANG = '{lang}' LIMIT 1; IF ( @APP_TITLE IS NULL ) THEN SET @APP_TITLE = ''; @@ -71,6 +74,7 @@ BEGIN DEL_FINISHED = NEW.DEL_FINISHED, DEL_DELAYED = NEW.DEL_DELAYED, APP_FINISH_DATE = NULL, + APP_UPDATE_DATE = @APP_UPDATE_DATE, APP_OVERDUE_PERCENTAGE = NEW.APP_OVERDUE_PERCENTAGE, DEL_LAST_INDEX = NEW.DEL_LAST_INDEX WHERE diff --git a/workflow/engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql b/workflow/engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql index a0ad8adf5..686c6f619 100755 --- a/workflow/engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql +++ b/workflow/engine/methods/setup/setupSchemas/triggerApplicationUpdate.sql @@ -14,10 +14,11 @@ BEGIN END IF; IF(OLD.APP_DATA<>NEW.APP_DATA) THEN - UPDATE APP_CACHE_VIEW SET APP_UPDATE_DATE = NOW() WHERE APP_UID = NEW.APP_UID; + UPDATE APP_CACHE_VIEW SET APP_UPDATE_DATE = NEW.APP_UPDATE_DATE WHERE APP_UID = NEW.APP_UID; END IF; IF (NEW.APP_STATUS = 'COMPLETED') THEN - UPDATE APP_CACHE_VIEW SET APP_FINISH_DATE = NEW.APP_FINISH_DATE WHERE APP_UID = NEW.APP_UID; + UPDATE APP_CACHE_VIEW SET APP_FINISH_DATE = NEW.APP_FINISH_DATE WHERE APP_UID = NEW.APP_UID; + UPDATE APP_CACHE_VIEW SET APP_UPDATE_DATE = NEW.APP_UPDATE_DATE WHERE APP_UID = NEW.APP_UID; END IF; END diff --git a/workflow/engine/methods/tools/ajaxListener.php b/workflow/engine/methods/tools/ajaxListener.php index 963b9c82b..687b6e62c 100755 --- a/workflow/engine/methods/tools/ajaxListener.php +++ b/workflow/engine/methods/tools/ajaxListener.php @@ -67,11 +67,11 @@ class Ajax $result->msg = $res['message']; } else { $result->success = true; - $result->msg = 'Label ' . $id . ' saved Successfully!'; + $result->msg = 'Label ' . htmlspecialchars($id) . ' saved Successfully!'; } } catch (Exception $e) { $result->success = false; - $result->msg = $e->getMessage(); + $result->msg = htmlspecialchars($e->getMessage()); } print G::json_encode($result); } @@ -93,7 +93,7 @@ class Ajax $result->msg = 'Deleted Successfully!'; } catch (Exception $e) { $result->success = false; - $result->msg = $e->getMessage(); + $result->msg = htmlspecialchars($e->getMessage()); } print G::json_encode($result); } @@ -106,7 +106,7 @@ class Ajax $result['success'] = true; } catch (Exception $e) { $result->success = false; - $result->msg = $e->getMessage(); + $result->msg = htmlspecialchars($e->getMessage()); } print G::json_encode($result); } diff --git a/workflow/engine/methods/tools/translationsAjax.php b/workflow/engine/methods/tools/translationsAjax.php index 9d2544357..eead4afa1 100755 --- a/workflow/engine/methods/tools/translationsAjax.php +++ b/workflow/engine/methods/tools/translationsAjax.php @@ -37,11 +37,11 @@ switch ($function) { case "changeLabel": $query = $ses->execute( "select * from $table where TRN_CATEGORY='$cat' and TRN_ID='$node' and TRN_LANG='$lang'", false ); if ($query->count() === 0) { - echo ("Not found $cat:$node:$lang in table '$table'"); + echo ("Not found ".htmlspecialchars("$cat:$node:$lang")." in table '".htmlspecialchars($table)."'"); return; } if ($query->count() > 1) { - echo ("The $cat:$node:$lang in table '$table' is not unique"); + echo ("The $".htmlspecialchars("$cat:$node:$lang")." in table '".htmlspecialchars($table)."' is not unique"); return; } $res = $query->read(); @@ -55,11 +55,11 @@ switch ($function) { $update = $ses->execute( "update $table set TRN_VALUE='$langLabel' where TRN_CATEGORY='$cat' and TRN_ID='$node' and TRN_LANG='$lang'", false ); $query = $ses->execute( "select * from $table where TRN_CATEGORY='$cat' and TRN_ID='$node' and TRN_LANG='$lang'", false ); if ($query->count() === 0) { - echo ("Not found $cat:$node:$lang in table '$table'"); + echo ("Not found ".htmlspecialchars("$cat:$node:$lang")." in table '".htmlspecialchars($table)."'"); return; } if ($query->count() > 1) { - echo ("The $cat:$node:$lang in table '$table' is not unique"); + echo ("The ".htmlspecialchars("$cat:$node:$lang")." in table '".htmlspecialchars($table)."' is not unique"); return; } $res = $query->read(); diff --git a/workflow/engine/methods/users/usersInit.php b/workflow/engine/methods/users/usersInit.php index 3a53ed036..fbb7fae72 100644 --- a/workflow/engine/methods/users/usersInit.php +++ b/workflow/engine/methods/users/usersInit.php @@ -11,6 +11,8 @@ if ($RBAC->userCanAccess( 'PM_EDITPERSONALINFO' ) == 1) { //he has permitions fo } else { //he has not permitions for edit his profile, so just view mode will be displayed $canEdit = true; } +$canEditCalendar = $RBAC->userCanAccess('PM_EDITPERSONALINFO') == 1 && + $RBAC->userCanAccess('PM_EDITPERSONALINFO_CALENDAR') == 1; //calculating the max upload file size; $POST_MAX_SIZE = ini_get( 'post_max_size' ); @@ -43,6 +45,7 @@ $oHeadPublisher->assign( 'USR_UID', $aFields['USR_UID'] ); $oHeadPublisher->assign( 'infoMode', true ); $oHeadPublisher->assign( 'EDITPROFILE', 1); $oHeadPublisher->assign( 'canEdit', $canEdit ); +$oHeadPublisher->assign('canEditCalendar', $canEditCalendar); $oHeadPublisher->assign( 'MAX_FILES_SIZE', ' (' . $UPLOAD_MAX_SIZE . ') ' ); $oHeadPublisher->assign( 'MODE', '' ); $oHeadPublisher->assign('SYSTEM_TIME_ZONE', $arraySystemConfiguration['time_zone']); diff --git a/workflow/engine/methods/users/users_List.php b/workflow/engine/methods/users/users_List.php index 3b2ecd488..3deb38aeb 100755 --- a/workflow/engine/methods/users/users_List.php +++ b/workflow/engine/methods/users/users_List.php @@ -21,26 +21,27 @@ * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ -if (($RBAC_Response = $RBAC->userCanAccess( "PM_LOGIN" )) != 1) +$RBAC_Response = $RBAC->requirePermissions('PM_USERS'); +if (!$RBAC_Response) return $RBAC_Response; global $RBAC; -$access = $RBAC->userCanAccess( 'PM_USERS' ); +$access = $RBAC->userCanAccess('PM_USERS'); if ($access != 1) { switch ($access) { - case - 1: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + case -1: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; - case - 2: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + case -2: + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_SYSTEM', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; default: - G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' ); - G::header( 'location: ../login/login' ); + G::SendTemporalMessage('ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels'); + G::header('location: ../login/login'); die(); break; } @@ -53,16 +54,16 @@ $G_ID_SUB_MENU_SELECTED = 'USERS'; $G_PUBLISH = new Publisher(); -G::LoadClass( 'configuration' ); +G::LoadClass('configuration'); $c = new Configurations(); -$configPage = $c->getConfiguration( 'usersList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); -$Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; +$configPage = $c->getConfiguration('usersList', 'pageSize', '', $_SESSION['USER_LOGGED']); +$Config['pageSize'] = isset($configPage['pageSize']) ? $configPage['pageSize'] : 20; -$oHeadPublisher = & headPublisher::getSingleton(); -$oHeadPublisher->addExtJsScript( 'users/usersList', false ); //adding a javascript file .js -$oHeadPublisher->addContent( 'users/usersList' ); //adding a html file .html. -$oHeadPublisher->assign( 'CONFIG', $Config ); -$oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); +$oHeadPublisher = &headPublisher::getSingleton(); +$oHeadPublisher->addExtJsScript('users/usersList', false); //adding a javascript file .js +$oHeadPublisher->addContent('users/usersList'); //adding a html file .html. +$oHeadPublisher->assign('CONFIG', $Config); +$oHeadPublisher->assign('FORMATS', $c->getFormats()); G::RenderPage( 'publish', 'extJs' ); diff --git a/workflow/engine/skinEngine/base/error404.php b/workflow/engine/skinEngine/base/error404.php index 5972ede39..c34ca9902 100644 --- a/workflow/engine/skinEngine/base/error404.php +++ b/workflow/engine/skinEngine/base/error404.php @@ -13,17 +13,33 @@ if (isset($_GET["url"]) && $_GET["url"] != "") { $sysSys = ""; $sysLang = ""; $sysSkin = ""; - + if (isset($url[1]) && preg_match("/^sys(.+)$/", $url[1], $match)) { $sysSys = $match[1]; - } + // Check if sys path exists + $checkDir = PATH_DATA."sites/".$sysSys; + if(!is_dir($checkDir)) { + $sysSys = ''; + } + } + if (isset($url[2])) { $sysLang = $url[2]; } if (isset($url[3])) { $sysSkin = $url[3]; + + // Check if sys path exists + $checkDir = PATH_SKIN_ENGINE.$sysSkin; + if(!is_dir($checkDir)) { + // Try this again + $checkDir = PATH_CUSTOM_SKINS.$sysSkin; + if(!is_dir($checkDir)) { + $sysSkin = ''; + } + } } if ($sysSys != "" && $sysLang != "" && $sysSkin != "") { @@ -84,8 +100,8 @@ if (isset($_GET["url"]) && $_GET["url"] != "") {
  • You might try retyping the URL and trying again.
  • -
  • Or we could take you back to the home page.
  • -
  • Or you could start again from the login page.
  • +
  • Or we could take you back to the home page.
  • +
  • Or you could start again from the login page.
@@ -125,4 +141,4 @@ if (isset($_GET["url"]) && $_GET["url"] != "") { - \ No newline at end of file + diff --git a/workflow/engine/skinEngine/base/layout.html b/workflow/engine/skinEngine/base/layout.html index 13b89edfc..ea2b8ddaa 100755 --- a/workflow/engine/skinEngine/base/layout.html +++ b/workflow/engine/skinEngine/base/layout.html @@ -21,8 +21,7 @@ {/if} {$logout}  
-     +     {else} {if $tracker eq 1} {$logout}   diff --git a/workflow/engine/skinEngine/neoclassic/error404.php b/workflow/engine/skinEngine/neoclassic/error404.php index 79a4ec960..fc695a3d5 100644 --- a/workflow/engine/skinEngine/neoclassic/error404.php +++ b/workflow/engine/skinEngine/neoclassic/error404.php @@ -9,23 +9,41 @@ $urlLogin = $http . "://" . $host . "/sys/en/neoclassic/login/login"; $urlHome = $urlLogin; if (isset($_GET["url"]) && $_GET["url"] != "") { + $url = urldecode($_GET["url"]); $url = explode("/", $url); $sysSys = ""; $sysLang = ""; $sysSkin = ""; - + if (isset($url[1]) && preg_match("/^sys(.+)$/", $url[1], $match)) { $sysSys = $match[1]; + + // Check if sys path exists + $checkDir = PATH_DATA."sites/".$sysSys; + if(!is_dir($checkDir)) { + $sysSys = ''; + } } + if (isset($url[2])) { $sysLang = $url[2]; } if (isset($url[3])) { $sysSkin = $url[3]; + + // Check if sys path exists + $checkDir = PATH_SKIN_ENGINE.$sysSkin; + if(!is_dir($checkDir)) { + // Try this again + $checkDir = PATH_CUSTOM_SKINS.$sysSkin; + if(!is_dir($checkDir)) { + $sysSkin = ''; + } + } } if ($sysSys != "" && $sysLang != "" && $sysSkin != "") { @@ -85,8 +103,8 @@ if (isset($_GET["url"]) && $_GET["url"] != "") {
  • You might try retyping the URL and trying again.
  • -
  • Or we could take you back to the home page.
  • -
  • Or you could start again from the login page.
  • +
  • Or we could take you back to the home page.
  • +
  • Or you could start again from the login page.
@@ -126,4 +144,4 @@ if (isset($_GET["url"]) && $_GET["url"] != "") { - \ No newline at end of file + diff --git a/workflow/engine/skinEngine/neoclassic/layout.html b/workflow/engine/skinEngine/neoclassic/layout.html index be5bbd643..e5ad8fc07 100644 --- a/workflow/engine/skinEngine/neoclassic/layout.html +++ b/workflow/engine/skinEngine/neoclassic/layout.html @@ -31,8 +31,7 @@ {/if} {$logout}  
-     +     {else} {if $tracker eq 1} {$logout}   diff --git a/workflow/engine/skinEngine/simplified/layout.html b/workflow/engine/skinEngine/simplified/layout.html index a7479c297..88f413ea8 100644 --- a/workflow/engine/skinEngine/simplified/layout.html +++ b/workflow/engine/skinEngine/simplified/layout.html @@ -18,8 +18,7 @@ {php}if ((int)$_SESSION['USER_LOGGED'] != 0) {{/php} {$msgVer} {$logout}  
-     +     {php}}{/php} diff --git a/workflow/engine/skinEngine/skinEngine.php b/workflow/engine/skinEngine/skinEngine.php index 91d402859..36ea2be41 100755 --- a/workflow/engine/skinEngine/skinEngine.php +++ b/workflow/engine/skinEngine/skinEngine.php @@ -434,11 +434,6 @@ class SkinEngine G::LoadClass( "configuration" ); $conf = new Configurations(); $conf->getFormats(); - if (defined('SYS_SYS')) { - $smarty->assign('udate', $conf->getSystemDate(date('Y-m-d H:i:s'))); - } else { - $smarty->assign('udate', G::getformatedDate(date('Y-m-d'), 'M d, yyyy', SYS_LANG)); - } $name = $conf->userNameFormat(isset($_SESSION['USR_USERNAME']) ? $_SESSION['USR_USERNAME']: '', isset($_SESSION['USR_FULLNAME']) ? htmlentities($_SESSION['USR_FULLNAME'] , ENT_QUOTES, 'UTF-8'): '', isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : ''); $smarty->assign('user',$name); } @@ -758,11 +753,6 @@ class SkinEngine G::LoadClass( "configuration" ); $conf = new Configurations(); $conf->getFormats(); - if ( defined('SYS_SYS')) { - $smarty->assign('udate', $conf->getSystemDate(\ProcessMaker\Util\DateTime::convertUtcToTimeZone(date('Y-m-d H:i:s')))); - } else { - $smarty->assign('udate', G::getformatedDate(\ProcessMaker\Util\DateTime::convertUtcToTimeZone(date('Y-m-d H:i:s')), 'M d, yyyy', SYS_LANG)); - } $name = $conf->userNameFormat(isset($_SESSION['USR_USERNAME']) ? $_SESSION['USR_USERNAME']: '', isset($_SESSION['USR_FULLNAME']) ? htmlentities($_SESSION['USR_FULLNAME'] , ENT_QUOTES, 'UTF-8'): '', isset($_SESSION['USER_LOGGED']) ? $_SESSION['USER_LOGGED'] : ''); $smarty->assign('user',$name); } diff --git a/workflow/engine/skinEngine/uxmodern/layout.html b/workflow/engine/skinEngine/uxmodern/layout.html index 66fc025a1..25e7d032a 100644 --- a/workflow/engine/skinEngine/uxmodern/layout.html +++ b/workflow/engine/skinEngine/uxmodern/layout.html @@ -21,8 +21,7 @@ {/if} {$logout}  
-     +     {/if} diff --git a/workflow/engine/skinEngine/uxs/layout.html b/workflow/engine/skinEngine/uxs/layout.html index e19068311..57e40b3d8 100644 --- a/workflow/engine/skinEngine/uxs/layout.html +++ b/workflow/engine/skinEngine/uxs/layout.html @@ -21,8 +21,7 @@ {/if} {$logout}  
-     +     {/if} diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php b/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php index d8acd1351..be0427d10 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/ActionsByEmail.php @@ -4,7 +4,7 @@ namespace ProcessMaker\BusinessModel; /** * Description of ActionsByEmailService - * + * */ class ActionsByEmail { @@ -35,7 +35,7 @@ class ActionsByEmail public function loadConfiguration($params) { - if ($params['type'] != 'activity' + if ($params['type'] != 'activity' || !\PMLicensedFeatures ::getSingleton() ->verifyfeature('zLhSk5TeEQrNFI2RXFEVktyUGpnczV1WEJNWVp6cjYxbTU3R29mVXVZNWhZQT0=')) @@ -71,4 +71,464 @@ class ActionsByEmail return $configuration; } + public function editTemplate(array $arrayData) + { + //Action Validations + if (!isset($arrayData['TEMPLATE'])) { + $arrayData['TEMPLATE'] = ''; + } + + if ($arrayData['TEMPLATE'] == '') { + throw new Exception(\G::LoadTranslation('ID_TEMPLATE_PARAMETER_EMPTY')); + } + + $data = array( + 'CONTENT' => file_get_contents( + PATH_DATA_MAILTEMPLATES . $arrayData['PRO_UID'] . PATH_SEP . $arrayData['TEMPLATE'] + ), + 'TEMPLATE' => $arrayData['TEMPLATE'], + ); + + global $G_PUBLISH; + + $G_PUBLISH = new \Publisher(); + $G_PUBLISH->AddContent('xmlform', 'xmlform', 'actionsByEmail/actionsByEmail_FileEdit', '', $data); + + \G::RenderPage('publish', 'raw'); + die(); + } + + public function updateTemplate(array $arrayData) + { + //Action Validations + if (!isset($arrayData['TEMPLATE'])) { + $arrayData['TEMPLATE'] = ''; + } + + if (!isset($arrayData['CONTENT'])) { + $arrayData['CONTENT'] = ''; + } + + if ($arrayData['TEMPLATE'] == '') { + throw new Exception(\G::LoadTranslation('ID_TEMPLATE_PARAMETER_EMPTY')); + } + + $templateFile = fopen(PATH_DATA_MAILTEMPLATES . $arrayData['PRO_UID'] . PATH_SEP . $arrayData['TEMPLATE'], 'w'); + $content = stripslashes($arrayData['CONTENT']); + $content = str_replace('@amp@', '&', $content); + $content = base64_decode($content); + + fwrite($templateFile, $content); + fclose($templateFile); + } + + public function loadFields(array $arrayData) + { + if (!isset($arrayData['DYN_UID'])) { + $arrayData['DYN_UID'] = ''; + } + + if (!isset($arrayData['PRO_UID'])) { + $arrayData['PRO_UID'] = ''; + } + + $response->emailFields = array(); + $response->actionFields = array(); + + if ($arrayData['PRO_UID'] != '' && $arrayData['DYN_UID']) { + $dynaform = new Form($arrayData['PRO_UID'] . PATH_SEP . $arrayData['DYN_UID'], PATH_DYNAFORM, SYS_LANG, false); + + foreach ($dynaform->fields as $fieldName => $data) { + switch ($data->type) { + case 'text': + case 'suggest': + case 'hidden': + case 'textarea': + $response->emailFields[] = array('value' => $data->name, 'label' => $data->label . ' (@@' . $data->name . ')'); + break; + case 'dropdown': + case 'radiogroup': + case 'yesno': + case 'checkbox': + $response->actionFields[] = array('value' => $data->name, 'label' => $data->label . ' (@@' . $data->name . ')'); + break; + } + } + } + + //Return + return $response; + } + + public function saveConfiguration2(array $arrayData) + { + if (!isset($arrayData['ABE_UID'])) { + $arrayData['ABE_UID'] = ''; + } + + if (!isset($arrayData['PRO_UID'])) { + $arrayData['PRO_UID'] = ''; + } + + if (!isset($arrayData['TAS_UID'])) { + $arrayData['TAS_UID'] = ''; + } + + if (!isset($arrayData['ABE_TYPE'])) { + $arrayData['ABE_TYPE'] = ''; + } + + if (!isset($arrayData['ABE_TEMPLATE'])) { + $arrayData['ABE_TEMPLATE'] = ''; + } + + if (!isset($arrayData['DYN_UID'])) { + $arrayData['DYN_UID'] = ''; + } + + if (!isset($arrayData['ABE_EMAIL_FIELD'])) { + $arrayData['ABE_EMAIL_FIELD'] = ''; + } + + if (!isset($arrayData['ABE_ACTION_FIELD'])) { + $arrayData['ABE_ACTION_FIELD'] = ''; + } + + if (!isset($arrayData['ABE_CASE_NOTE_IN_RESPONSE'])) { + $arrayData['ABE_CASE_NOTE_IN_RESPONSE'] = 0; + } + + if ($arrayData['PRO_UID'] == '') { + throw new Exception(\G::LoadTranslation('ID_PRO_UID_PARAMETER_IS_EMPTY')); + } + + if ($arrayData['TAS_UID'] == '') { + throw new Exception(\G::LoadTranslation('ID_TAS_UID_PARAMETER_IS_EMPTY')); + } + + $abeConfigurationInstance = new \AbeConfiguration(); + + if ($arrayData['ABE_TYPE'] != '') { + if ($arrayData['DYN_UID'] == '') { + throw new Exception(\G::LoadTranslation('ID_DYN_UID_PARAMETER_IS_EMPTY')); + } + + try { + $response->ABE_UID = $abeConfigurationInstance->createOrUpdate($arrayData); + } catch (\Exception $error) { + throw $error; + } + } else { + try { + $abeConfigurationInstance->deleteByTasUid($arrayData['TAS_UID']); + $response->ABE_UID = ''; + } catch (\Exception $error) { + throw $error; + } + } + + //Return + return $response; + } + + public function loadActionByEmail(array $arrayData) + { + $criteria = new \Criteria(); + $criteria->addSelectColumn('COUNT(*)'); + + $criteria->addJoin(\AbeConfigurationPeer::ABE_UID, \AbeRequestsPeer::ABE_UID); + $criteria->addJoin(\AppDelegationPeer::APP_UID, \AbeRequestsPeer::APP_UID); + $criteria->addJoin(\AppDelegationPeer::DEL_INDEX, \AbeRequestsPeer::DEL_INDEX); + $result = \AbeConfigurationPeer::doSelectRS($criteria); + $result->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $result->next(); + $totalCount = $result->getRow(); + $totalCount = $totalCount['COUNT(*)']; + + $criteria = new \Criteria(); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::PRO_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::TAS_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_UPDATE_DATE); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_TEMPLATE); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_ACTION_FIELD); + $criteria->addSelectColumn(\AbeConfigurationPeer::DYN_UID); + + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_UID); + $criteria->addSelectColumn(\AbeRequestsPeer::APP_UID); + $criteria->addSelectColumn(\AbeRequestsPeer::DEL_INDEX); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_SENT_TO); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_STATUS); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_SUBJECT); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_ANSWERED); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_BODY); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_DATE); + + $criteria->addSelectColumn(\ApplicationPeer::APP_NUMBER); + + $criteria->addSelectColumn(\AppDelegationPeer::DEL_PREVIOUS); + + $criteria->addJoin(\AbeConfigurationPeer::ABE_UID, \AbeRequestsPeer::ABE_UID); + $criteria->addJoin(\ApplicationPeer::APP_UID, \AbeRequestsPeer::APP_UID); + + $criteria->addJoin(\AppDelegationPeer::APP_UID, \AbeRequestsPeer::APP_UID); + $criteria->addJoin(\AppDelegationPeer::DEL_INDEX, \AbeRequestsPeer::DEL_INDEX); + $criteria->addDescendingOrderByColumn(\AbeRequestsPeer::ABE_REQ_DATE); + $criteria->setLimit($arrayData['limit']); + $criteria->setOffset($arrayData['start']); + $result = \AbeConfigurationPeer::doSelectRS($criteria); + $result->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $data = Array(); + $arrayPro = Array(); + $arrayTAS = Array(); + $index = 0; + + while ($result->next()) { + $data[] = $result->getRow(); + $criteriaRes = new \Criteria(); + + $criteriaRes->addSelectColumn(\AbeResponsesPeer::ABE_RES_UID); + $criteriaRes->addSelectColumn(\AbeResponsesPeer::ABE_RES_CLIENT_IP); + $criteriaRes->addSelectColumn(\AbeResponsesPeer::ABE_RES_DATA); + $criteriaRes->addSelectColumn(\AbeResponsesPeer::ABE_RES_STATUS); + $criteriaRes->addSelectColumn(\AbeResponsesPeer::ABE_RES_MESSAGE); + + $criteriaRes->add(\AbeResponsesPeer::ABE_REQ_UID, $data[$index]['ABE_REQ_UID']); + + $resultRes = \AbeResponsesPeer::doSelectRS($criteriaRes); + $resultRes->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $resultRes->next(); + $dataRes = Array(); + + if ($dataRes = $resultRes->getRow()) { + $data[$index]['ABE_RES_UID'] = $dataRes['ABE_RES_UID']; + $data[$index]['ABE_RES_CLIENT_IP'] = $dataRes['ABE_RES_CLIENT_IP']; + $data[$index]['ABE_RES_DATA'] = $dataRes['ABE_RES_DATA']; + $data[$index]['ABE_RES_STATUS'] = $dataRes['ABE_RES_STATUS']; + $data[$index]['ABE_RES_MESSAGE'] = $dataRes['ABE_RES_MESSAGE']; + } else { + $data[$index]['ABE_RES_UID'] = ''; + $data[$index]['ABE_RES_CLIENT_IP'] = ''; + $data[$index]['ABE_RES_DATA'] = ''; + $data[$index]['ABE_RES_STATUS'] = ''; + $data[$index]['ABE_RES_MESSAGE'] = ''; + } + + $criteriaRes = new \Criteria(); + + $criteriaRes->addSelectColumn(\AppDelegationPeer::USR_UID); + $criteriaRes->addSelectColumn(\UsersPeer::USR_FIRSTNAME); + $criteriaRes->addSelectColumn(\UsersPeer::USR_LASTNAME); + + $criteria->addJoin(\AppDelegationPeer::APP_UID, $data[$index]['APP_UID']); + $criteria->addJoin(\AppDelegationPeer::DEL_INDEX, $data[$index]['DEL_PREVIOUS']); + $criteria->addJoin(\AppDelegationPeer::USR_UID, \UsersPeer::USR_UID); + $resultRes = \AppDelegationPeer::doSelectRS($criteriaRes); + $resultRes->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $resultRes->next(); + + if ($dataRes = $resultRes->getRow()) { + $data[$index]['USER'] = $dataRes['USR_FIRSTNAME'] . ' ' . $dataRes['USR_LASTNAME']; + } else { + $data[$index]['USER'] = ''; + } + + $data[$index]['ABE_REQ_ANSWERED'] = ($data[$index]['ABE_REQ_ANSWERED'] == 1) ? 'YES' : 'NO'; + $index++; + } + + $response = array(); + $response['totalCount'] = $totalCount; + $response['data'] = $data; + + //Return + return $response; + } + + public function forwardMail(array $arrayData) + { + if (!isset($arrayData['REQ_UID'])) { + $arrayData['REQ_UID'] = ''; + } + + $criteria = new \Criteria(); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::PRO_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::TAS_UID); + + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_UID); + $criteria->addSelectColumn(\AbeRequestsPeer::APP_UID); + $criteria->addSelectColumn(\AbeRequestsPeer::DEL_INDEX); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_SENT_TO); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_SUBJECT); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_BODY); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_ANSWERED); + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_STATUS); + + $criteria->addSelectColumn(\AppDelegationPeer::DEL_FINISH_DATE); + + $criteria->add(\AbeRequestsPeer::ABE_REQ_UID, $arrayData['REQ_UID']); + $criteria->addJoin(\AbeRequestsPeer::ABE_UID, \AbeConfigurationPeer::ABE_UID); + $criteria->addJoin(\AppDelegationPeer::APP_UID, \AbeRequestsPeer::APP_UID); + $criteria->addJoin(\AppDelegationPeer::DEL_INDEX, \AbeRequestsPeer::DEL_INDEX); + $resultRes = AbeRequestsPeer::doSelectRS($criteria); + $resultRes->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + $resultRes->next(); + $dataRes = Array(); + + if ($dataRes = $resultRes->getRow()) { + if (is_null($dataRes['DEL_FINISH_DATE'])) { + \G::LoadClass('spool'); + + $configuration = new \Configuration(); + $sDelimiter = \DBAdapter::getStringDelimiter(); + $criteria = new \Criteria('workflow'); + $criteria->add(\ConfigurationPeer::CFG_UID, 'Emails'); + $criteria->add(\ConfigurationPeer::OBJ_UID, ''); + $criteria->add(\ConfigurationPeer::PRO_UID, ''); + $criteria->add(\ConfigurationPeer::USR_UID, ''); + $criteria->add(\ConfigurationPeer::APP_UID, ''); + + if (\ConfigurationPeer::doCount($criteria) == 0) { + $configuration->create(array('CFG_UID' => 'Emails', 'OBJ_UID' => '', 'CFG_VALUE' => '', 'PRO_UID' => '', 'USR_UID' => '', 'APP_UID' => '')); + $newConfiguration = array(); + } else { + $newConfiguration = $configuration->load('Emails', '', '', '', ''); + + if ($newConfiguration['CFG_VALUE'] != '') { + $newConfiguration = unserialize($newConfiguration['CFG_VALUE']); + } else { + $newConfiguration = array(); + } + } + + $spool = new \spoolRun(); + $spool->setConfig(array( + 'MESS_ENGINE' => $newConfiguration['MESS_ENGINE'], + 'MESS_SERVER' => $newConfiguration['MESS_SERVER'], + 'MESS_PORT' => $newConfiguration['MESS_PORT'], + 'MESS_ACCOUNT' => $newConfiguration['MESS_ACCOUNT'], + 'MESS_PASSWORD' => $newConfiguration['MESS_PASSWORD'], + 'SMTPAuth' => $newConfiguration['MESS_RAUTH'] + )); + + $spool->create(array( + 'msg_uid' => '', + 'app_uid' => $dataRes['APP_UID'], + 'del_index' => $dataRes['DEL_INDEX'], + 'app_msg_type' => 'TEST', + 'app_msg_subject' => $dataRes['ABE_REQ_SUBJECT'], + 'app_msg_from' => $newConfiguration['MESS_ACCOUNT'], + 'app_msg_to' => $dataRes['ABE_REQ_SENT_TO'], + 'app_msg_body' => $dataRes['ABE_REQ_BODY'], + 'app_msg_cc' => '', + 'app_msg_bcc' => '', + 'app_msg_attach' => '', + 'app_msg_template' => '', + 'app_msg_status' => 'pending' + )); + + if ($spool->sendMail()) { + $dataRes['ABE_REQ_STATUS'] = 'SENT'; + + $message = G::LoadTranslation('ID_EMAIL_RESENT_TO') . ': '. $dataRes['ABE_REQ_SENT_TO']; + } else { + $dataRes['ABE_REQ_STATUS'] = 'ERROR'; + $message = G::LoadTranslation('ID_THERE_PROBLEM_SENDING_EMAIL') . ': '. $dataRes['ABE_REQ_SENT_TO'] . ', ' . G::LoadTranslation('ID_PLEASE_TRY_LATER'); + } + + try { + $abeRequestsInstance = new \AbeRequests(); + $abeRequestsInstance->createOrUpdate($dataRes); + } catch (\Exception $error) { + throw $error; + } + } else { + $message = \G::LoadTranslation('ID_UNABLE_TO_SEND_EMAIL'); + } + } else { + $message = \G::LoadTranslation('ID_UNEXPECTED_ERROR_OCCURRED_PLEASE'); + } + + //Return + return $message; + } + + public function viewForm(array $arrayData) + { + //coment + if (!isset($arrayData['REQ_UID'])) { + $arrayData['REQ_UID'] = ''; + } + + $criteria = new \Criteria(); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::PRO_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::TAS_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::DYN_UID); + $criteria->addSelectColumn(\AbeConfigurationPeer::ABE_ACTION_FIELD); + + $criteria->addSelectColumn(\AbeRequestsPeer::ABE_REQ_UID); + $criteria->addSelectColumn(\AbeRequestsPeer::APP_UID); + $criteria->addSelectColumn(\AbeRequestsPeer::DEL_INDEX); + + $criteria->addSelectColumn(\AbeResponsesPeer::ABE_RES_UID); + $criteria->addSelectColumn(\AbeResponsesPeer::ABE_RES_DATA); + + $criteria->add(\AbeRequestsPeer::ABE_REQ_UID, $arrayData['REQ_UID']); + $criteria->addJoin(\AbeRequestsPeer::ABE_UID, \AbeConfigurationPeer::ABE_UID); + $criteria->addJoin(\AbeResponsesPeer::ABE_REQ_UID, \AbeRequestsPeer::ABE_REQ_UID); + $resultRes = AbeRequestsPeer::doSelectRS($criteria); + $resultRes->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + $resultRes->next(); + $dataRes = Array(); + $message = \G::LoadTranslation('ID_USER_NOT_RESPONDED_REQUEST'); + + if ($dataRes = $resultRes->getRow()) { + $_SESSION['CURRENT_DYN_UID'] = trim($dataRes['DYN_UID']); + $dynaform = new \Form($dataRes['PRO_UID'] . PATH_SEP . trim($dataRes['DYN_UID']), PATH_DYNAFORM, SYS_LANG, false); + $dynaform->mode = 'view'; + + if ($dataRes['ABE_RES_DATA'] != '') { + $value = unserialize($dataRes['ABE_RES_DATA']); + + if (is_array($value)) { + $dynaform->values = $value; + + foreach ($dynaform->fields as $fieldName => $field) { + if ($field->type == 'submit') { + unset($dynaform->fields[$fieldName]); + } + } + + $message = $dynaform->render(PATH_CORE . 'templates/xmlform.html', $scriptCode); + } else { + $response = $dynaform->render(PATH_CORE . 'templates/xmlform.html', $scriptCode); + $field = $dynaform->fields[$dataRes['ABE_ACTION_FIELD']]; + $message = 'Type: ' . $field->type . '
'; + + switch ($field->type) { + case 'dropdown': + case 'radiogroup': + $message .=$field->label . ' - '; + $message .= $field->options[$value]; + break; + case 'yesno': + $message .= '' . $field->label . ' - '; + $message .= ($value == 1) ? 'Yes' : 'No'; + break; + case 'checkbox': + $message .= '' . $field->label . ' - '; + $message .= ($value == 'On') ? 'Check' : 'Uncheck'; + break; + } + } + } + } + + //Return + return $message; + } } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php b/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php index 802cc7e5a..cdfa9fd8b 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Cases.php @@ -45,6 +45,21 @@ class Cases } } + /** + * Throw the exception "The Case doesn't exist" + * + * @param string $applicationUid Unique id of Case + * @param string $fieldNameForException Field name for the exception + * + * @return void + */ + private function throwExceptionCaseDoesNotExist($applicationUid, $fieldNameForException) + { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_DOES_NOT_EXIST2', [$fieldNameForException, $applicationUid] + )); + } + /** * Verify if does not exist the Case in table APPLICATION * @@ -68,13 +83,135 @@ class Cases } if ($flag) { - throw new \Exception(\G::LoadTranslation("ID_CASE_DOES_NOT_EXIST2", array($fieldNameForException, $applicationUid))); + $this->throwExceptionCaseDoesNotExist($applicationUid, $fieldNameForException); } } catch (\Exception $e) { throw $e; } } + /** + * Get Application record + * + * @param string $applicationUid Unique id of Case + * @param array $arrayVariableNameForException Variable name for exception + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Application record, ThrowTheException/FALSE otherwise + */ + public function getApplicationRecordByPk( + $applicationUid, + array $arrayVariableNameForException, + $throwException = true + ) { + try { + $obj = \ApplicationPeer::retrieveByPK($applicationUid); + + if (is_null($obj)) { + if ($throwException) { + $this->throwExceptionCaseDoesNotExist( + $applicationUid, $arrayVariableNameForException['$applicationUid'] + ); + } else { + return false; + } + } + + //Return + return $obj->toArray(\BasePeer::TYPE_FIELDNAME); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get AppDelegation record + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param array $arrayVariableNameForException Variable name for exception + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with AppDelegation record, ThrowTheException/FALSE otherwise + */ + public function getAppDelegationRecordByPk( + $applicationUid, + $delIndex, + array $arrayVariableNameForException, + $throwException = true + ) { + try { + $obj = \AppDelegationPeer::retrieveByPK($applicationUid, $delIndex); + + if (is_null($obj)) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_DEL_INDEX_DOES_NOT_EXIST', + [ + $arrayVariableNameForException['$applicationUid'], + $applicationUid, + $arrayVariableNameForException['$delIndex'], + $delIndex + ] + )); + } else { + return false; + } + } + + //Return + return $obj->toArray(\BasePeer::TYPE_FIELDNAME); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get list counters + * + * @param string $userUid Unique id of User + * @param array $arrayType Type lists + * + * @return array Return the list counters + */ + public function getListCounters($userUid, array $arrayType) + { + try { + $solrEnabled = false; + $solrConf = \System::solrEnv(); + + if ($solrConf !== false) { + $ApplicationSolrIndex = new \AppSolr( + $solrConf['solr_enabled'], + $solrConf['solr_host'], + $solrConf['solr_instance'] + ); + + if ($ApplicationSolrIndex->isSolrEnabled() && $solrConf['solr_enabled'] == true) { + $solrEnabled = true; + } + } + + $appCacheView = new \AppCacheView(); + + if ($solrEnabled) { + $arrayListCounter = array_merge( + $ApplicationSolrIndex->getCasesCount($userUid), + $appCacheView->getAllCounters(['completed', 'cancelled'], $userUid) + ); + } else { + $arrayListCounter = $appCacheView->getAllCounters($arrayType, $userUid); + } + + //Return + return $arrayListCounter; + } catch (\Exception $e) { + throw $e; + } + } + /** * Get list for Cases * @@ -113,6 +250,8 @@ class Cases $type = "extjs"; $dateFrom = (!empty( $dataList["dateFrom"] )) ? substr( $dataList["dateFrom"], 0, 10 ) : ""; $dateTo = (!empty( $dataList["dateTo"] )) ? substr( $dataList["dateTo"], 0, 10 ) : ""; + $newerThan = (!empty($dataList['newerThan']))? $dataList['newerThan'] : ''; + $oldestThan = (!empty($dataList['oldestthan']))? $dataList['oldestthan'] : ''; $first = isset( $dataList["first"] ) ? true :false; $u = new \ProcessMaker\BusinessModel\User(); @@ -154,7 +293,7 @@ class Cases } $dir = G::toUpper($dir); if (!($dir == 'DESC' || $dir == 'ASC')) { - $dir = 'DESC'; + $dir = 'ASC'; } if ($process != '') { Validator::proUid($process, '$pro_uid'); @@ -246,7 +385,9 @@ class Cases (strpos($sort, ".") !== false)? $sort : "APP_CACHE_VIEW." . $sort, $category, true, - $paged + $paged, + $newerThan, + $oldestThan ); } if (!empty($result['data'])) { @@ -1042,15 +1183,6 @@ class Cases //$oPluginRegistry = & PMPluginRegistry::getSingleton(); $listing = $oPluginRegistry->executeTriggers(PM_CASE_DOCUMENT_LIST, $folderData); } - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &\PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new \PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ $aObjectPermissions = $cases->getAllObjects($sProcessUID, $sApplicationUID, $sTasKUID, $sUserUID); if (!is_array($aObjectPermissions)) { $aObjectPermissions = array( @@ -1126,12 +1258,15 @@ class Cases $aAux = $oAppDocument->load($aRow['APP_DOC_UID'], $aRow['DOC_VERSION']); $lastVersion = $oAppDocument->getLastAppDocVersion($aRow['APP_DOC_UID'], $sApplicationUID); - try { - $aAux1 = $oUser->load($aAux['USR_UID']); + if ($aAux['USR_UID'] !== "-1") { + try { + $aAux1 = $oUser->load($aAux['USR_UID']); - $sUser = $conf->usersNameFormatBySetParameters($confEnvSetting["format"], $aAux1["USR_USERNAME"], $aAux1["USR_FIRSTNAME"], $aAux1["USR_LASTNAME"]); - } catch (Exception $oException) { - //$sUser = '(USER DELETED)'; + $sUser = $conf->usersNameFormatBySetParameters($confEnvSetting["format"], $aAux1["USR_USERNAME"], $aAux1["USR_FIRSTNAME"], $aAux1["USR_LASTNAME"]); + } catch (Exception $oException) { + $sUser = '***'; + } + } else { $sUser = '***'; } $aFields = array( @@ -1167,15 +1302,6 @@ class Cases } } } - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('INPUT', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['INPUT']; - } - /*----------------------------------********---------------------------------*/ if ($lastVersion == $aRow['DOC_VERSION']) { //Show only last version $aInputDocuments[] = $aFields; @@ -1247,15 +1373,7 @@ class Cases } $aFields['DOWNLOAD_LABEL'] = G::LoadTranslation('ID_DOWNLOAD'); $aFields['DOWNLOAD_LINK'] = "cases/cases_ShowDocument?a=" . $aRow['APP_DOC_UID']; - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('ATTACHED', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['ATTACHED']; - } - /*----------------------------------********---------------------------------*/ + if ($lastVersion == $aRow['DOC_VERSION']) { //Show only last version $aInputDocuments[] = $aFields; @@ -1319,15 +1437,7 @@ class Cases } } } - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('INPUT', - $driveDownload) && $enablePMGmail - ) { - $aFields['DOWNLOAD_LINK'] = $driveDownload['INPUT']; - } - /*----------------------------------********---------------------------------*/ + if ($lastVersion == $aRow['DOC_VERSION']) { //Show only last version $aInputDocuments[] = $aFields; @@ -1371,15 +1481,6 @@ class Cases //$oPluginRegistry = & PMPluginRegistry::getSingleton(); $listing = $oPluginRegistry->executeTriggers(PM_CASE_DOCUMENT_LIST, $folderData); } - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &\PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - G::LoadClass( "pmDrive" ); - $pmDrive = new \PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ $aObjectPermissions = $cases->getAllObjects($sProcessUID, $sApplicationUID, $sTasKUID, $sUserUID); if (!is_array($aObjectPermissions)) { $aObjectPermissions = array('DYNAFORMS' => array(-1),'INPUT_DOCUMENTS' => array(-1),'OUTPUT_DOCUMENTS' => array(-1)); @@ -1525,20 +1626,6 @@ class Cases } catch (\Exception $oException) { $sUser = '(USER DELETED)'; } - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($aRow['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_DOC', - $driveDownload) && $enablePMGmail - ) { - $fileDoc = $driveDownload['OUTPUT_DOC']; - } - if ($driveDownload !== false && is_array($driveDownload) && array_key_exists('OUTPUT_PDF', - $driveDownload) && $enablePMGmail - ) { - $filePdf = $driveDownload['OUTPUT_PDF']; - } - /*----------------------------------********---------------------------------*/ //if both documents were generated, we choose the pdf one, only if doc was //generate then choose the doc file. $firstDocLink = $filePdf; @@ -2477,4 +2564,196 @@ class Cases throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); } } + + /** + * Get Users to reassign + * + * @param string $userUid Unique id of User (User logged) + * @param string $taskUid Unique id of Task + * @param array $arrayFilterData Data of the filters + * @param string $sortField Field name to sort + * @param string $sortDir Direction of sorting (ASC, DESC) + * @param int $start Start + * @param int $limit Limit + * + * @return array Return Users to reassign + */ + public function getUsersToReassign($userUid, $taskUid, $arrayFilterData = null, $sortField = null, $sortDir = null, $start = null, $limit = null) + { + try { + $arrayUser = []; + + $numRecTotal = 0; + + //Set variables + $task = \TaskPeer::retrieveByPK($taskUid); + + $processUid = $task->getProUid(); + + $user = new \ProcessMaker\BusinessModel\User(); + $task = new \Tasks(); + $group = new \Groups(); + + //Set variables + $filterName = 'filter'; + + if (!is_null($arrayFilterData) && is_array($arrayFilterData) && isset($arrayFilterData['filter'])) { + $arrayAux = [ + '' => 'filter', + 'LEFT' => 'lfilter', + 'RIGHT' => 'rfilter' + ]; + + $filterName = $arrayAux[(isset($arrayFilterData['filterOption']))? $arrayFilterData['filterOption'] : '']; + } + + //Get data + if (!is_null($limit) && $limit . '' == '0') { + //Return + return [ + 'total' => $numRecTotal, + 'start' => (int)((!is_null($start))? $start : 0), + 'limit' => (int)((!is_null($limit))? $limit : 0), + $filterName => (!is_null($arrayFilterData) && is_array($arrayFilterData) && isset($arrayFilterData['filter']))? $arrayFilterData['filter'] : '', + 'data' => $arrayUser + ]; + } + + //Set variables + $processSupervisor = new \ProcessMaker\BusinessModel\ProcessSupervisor(); + + $arrayResult = $processSupervisor->getProcessSupervisors($processUid, 'ASSIGNED', null, null, null, 'group'); + + $arrayGroupUid = array_merge( + array_map(function ($value) { return $value['GRP_UID']; }, $task->getGroupsOfTask($taskUid, 1)), //Groups + array_map(function ($value) { return $value['GRP_UID']; }, $task->getGroupsOfTask($taskUid, 2)), //AdHoc Groups + array_map(function ($value) { return $value['grp_uid']; }, $arrayResult['data']) //ProcessSupervisor Groups + ); + + $sqlTaskUser = ' + SELECT ' . \TaskUserPeer::USR_UID . ' + FROM ' . \TaskUserPeer::TABLE_NAME . ' + WHERE ' . \TaskUserPeer::TAS_UID . ' = \'%s\' AND + ' . \TaskUserPeer::TU_TYPE . ' IN (1, 2) AND + ' . \TaskUserPeer::TU_RELATION . ' = 1 + '; + + $sqlGroupUser = ' + SELECT ' . \GroupUserPeer::USR_UID . ' + FROM ' . \GroupUserPeer::TABLE_NAME . ' + WHERE ' . \GroupUserPeer::GRP_UID . ' IN (%s) + '; + + $sqlProcessSupervisor = ' + SELECT ' . \ProcessUserPeer::USR_UID . ' + FROM ' . \ProcessUserPeer::TABLE_NAME . ' + WHERE ' . \ProcessUserPeer::PRO_UID . ' = \'%s\' AND + ' . \ProcessUserPeer::PU_TYPE . ' = \'%s\' + '; + + $sqlUserToReassign = '(' . sprintf($sqlTaskUser, $taskUid) . ')'; + + if (!empty($arrayGroupUid)) { + $sqlUserToReassign .= ' UNION (' . sprintf($sqlGroupUser, '\'' . implode('\', \'', $arrayGroupUid) . '\'') . ')'; + } + + $sqlUserToReassign .= ' UNION (' . sprintf($sqlProcessSupervisor, $processUid, 'SUPERVISOR') . ')'; + + //Query + $criteria = new \Criteria('workflow'); + + $criteria->addSelectColumn(\UsersPeer::USR_UID); + $criteria->addSelectColumn(\UsersPeer::USR_USERNAME); + $criteria->addSelectColumn(\UsersPeer::USR_FIRSTNAME); + $criteria->addSelectColumn(\UsersPeer::USR_LASTNAME); + + $criteria->addAlias('USER_TO_REASSIGN', '(' . $sqlUserToReassign . ')'); + + $criteria->addJoin(\UsersPeer::USR_UID, 'USER_TO_REASSIGN.USR_UID', \Criteria::INNER_JOIN); + + if (!is_null($arrayFilterData) && is_array($arrayFilterData) && isset($arrayFilterData['filter']) && trim($arrayFilterData['filter']) != '') { + $arraySearch = [ + '' => '%' . $arrayFilterData['filter'] . '%', + 'LEFT' => $arrayFilterData['filter'] . '%', + 'RIGHT' => '%' . $arrayFilterData['filter'] + ]; + + $search = $arraySearch[(isset($arrayFilterData['filterOption']))? $arrayFilterData['filterOption'] : '']; + + $criteria->add( + $criteria->getNewCriterion(\UsersPeer::USR_USERNAME, $search, \Criteria::LIKE)->addOr( + $criteria->getNewCriterion(\UsersPeer::USR_FIRSTNAME, $search, \Criteria::LIKE))->addOr( + $criteria->getNewCriterion(\UsersPeer::USR_LASTNAME, $search, \Criteria::LIKE)) + ); + } + + $criteria->add(\UsersPeer::USR_STATUS, 'ACTIVE', \Criteria::EQUAL); + + if (!$user->checkPermission($userUid, 'PM_SUPERVISOR')) { + $criteria->add(\UsersPeer::USR_UID, $userUid, \Criteria::NOT_EQUAL); + } + + //Number records total + $criteriaCount = clone $criteria; + + $criteriaCount->clearSelectColumns(); + $criteriaCount->addSelectColumn('COUNT(' . \UsersPeer::USR_UID . ') AS NUM_REC'); + + $rsCriteriaCount = \UsersPeer::doSelectRS($criteriaCount); + $rsCriteriaCount->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + $result = $rsCriteriaCount->next(); + $row = $rsCriteriaCount->getRow(); + + $numRecTotal = (int)($row['NUM_REC']); + + //Query + if (!is_null($sortField) && trim($sortField) != '') { + $sortField = strtoupper($sortField); + + if (in_array(\UsersPeer::TABLE_NAME . '.' . $sortField, $criteria->getSelectColumns())) { + $sortField = \UsersPeer::TABLE_NAME . '.' . $sortField; + } else { + $sortField = \UsersPeer::USR_FIRSTNAME; + } + } else { + $sortField = \UsersPeer::USR_FIRSTNAME; + } + + if (!is_null($sortDir) && trim($sortDir) != '' && strtoupper($sortDir) == 'DESC') { + $criteria->addDescendingOrderByColumn($sortField); + } else { + $criteria->addAscendingOrderByColumn($sortField); + } + + if (!is_null($start)) { + $criteria->setOffset((int)($start)); + } + + if (!is_null($limit)) { + $criteria->setLimit((int)($limit)); + } + + $rsCriteria = \UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $arrayUser[] = $row; + } + + //Return + return [ + 'total' => $numRecTotal, + 'start' => (int)((!is_null($start))? $start : 0), + 'limit' => (int)((!is_null($limit))? $limit : 0), + $filterName => (!is_null($arrayFilterData) && is_array($arrayFilterData) && isset($arrayFilterData['filter']))? $arrayFilterData['filter'] : '', + 'data' => $arrayUser + ]; + } catch (\Exception $e) { + throw $e; + } + } } + diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php index 454695576..6d110c40e 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/InputDocument.php @@ -3,6 +3,26 @@ namespace ProcessMaker\BusinessModel\Cases; class InputDocument { + /** + * Verify exists app_doc_uid in table APP_DOCUMENT + * + * @param string $applicationUid + * + * return void Throw exception + */ + private function throwExceptionIfNotExistsAppDocument($appDocumentUid) + { + try { + $appDocument = \AppDocumentPeer::retrieveByPK($appDocumentUid, 1); + + if (is_null($appDocument)) { + throw new \Exception(\G::LoadTranslation("ID_CASES_INPUT_DOES_NOT_EXIST", array($appDocumentUid))); + } + } catch (\Exception $e) { + throw $e; + } + } + /** * Check if the user has permissions * @@ -47,6 +67,9 @@ class InputDocument throw new \Exception(\G::LoadTranslation("ID_USER_NOT_HAVE_PERMISSION_DELETE_INPUT_DOCUMENT", array($userUid))); } + //verfiry exists $appDocumentUid + $this->throwExceptionIfNotExistsAppDocument($appDocumentUid); + //Verify data permission $flagPermission = 0; @@ -284,16 +307,6 @@ class InputDocument $rsCriteria = \AppDocumentPeer::doSelectRS($criteria); $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &\PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - \G::LoadClass( "pmDrive" ); - $pmDrive = new \PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ - while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); @@ -304,19 +317,6 @@ class InputDocument $row["APP_DOC_FILENAME"] = $arrayAppDocument["APP_DOC_FILENAME"]; $row["APP_DOC_CREATE_USER"] = $configuraction->usersNameFormatBySetParameters($confEnvSetting["format"], $arrayUserData["USR_USERNAME"], $arrayUserData["USR_FIRSTNAME"], $arrayUserData["USR_LASTNAME"]); $row["APP_DOC_LINK"] = "cases/cases_ShowDocument?a=" . $row["APP_DOC_UID"] . "&v=" . $row["DOC_VERSION"]; - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($arrayAppDocument['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && $enablePMGmail - ) { - if (array_key_exists('INPUT', $driveDownload)) { - $row['APP_DOC_LINK'] = $driveDownload['INPUT']; - } else if (array_key_exists('ATTACHED', $driveDownload)) { - $row['APP_DOC_LINK'] = $driveDownload['ATTACHED']; - } - - } - /*----------------------------------********---------------------------------*/ $arrayInputDocument[] = $this->getAppDocumentDataFromRecord($row); } @@ -371,39 +371,20 @@ class InputDocument $rsCriteria = \AppDocumentPeer::doSelectRS($criteria); $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &\PMLicensedFeatures::getSingleton(); - $enablePMGmail = false; - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - \G::LoadClass( "pmDrive" ); - $pmDrive = new \PMDrive(); - $enablePMGmail = $pmDrive->getStatusService(); - } - /*----------------------------------********---------------------------------*/ while ($rsCriteria->next()) { $row = $rsCriteria->getRow(); - $arrayUserData = $user->load($row["USR_UID"]); - + $sUser = '***'; + if ($row["USR_UID"] !== '-1') { + $arrayUserData = $user->load($row["USR_UID"]); + $sUser = $configuraction->usersNameFormatBySetParameters($confEnvSetting["format"], $arrayUserData["USR_USERNAME"], $arrayUserData["USR_FIRSTNAME"], $arrayUserData["USR_LASTNAME"]); + } $arrayAppDocument = $appDocument->load($row["APP_DOC_UID"], $row["DOC_VERSION"]); $row["APP_DOC_FILENAME"] = $arrayAppDocument["APP_DOC_FILENAME"]; - $row["APP_DOC_CREATE_USER"] = $configuraction->usersNameFormatBySetParameters($confEnvSetting["format"], $arrayUserData["USR_USERNAME"], $arrayUserData["USR_FIRSTNAME"], $arrayUserData["USR_LASTNAME"]); + $row["APP_DOC_CREATE_USER"] = $sUser; $row["APP_DOC_LINK"] = "cases/cases_ShowDocument?a=" . $row["APP_DOC_UID"] . "&v=" . $row["DOC_VERSION"]; - /*----------------------------------********---------------------------------*/ - //change donwload link - drive - $driveDownload = @unserialize($arrayAppDocument['APP_DOC_DRIVE_DOWNLOAD']); - if ($driveDownload !== false && is_array($driveDownload) && $enablePMGmail - ) { - if (array_key_exists('INPUT', $driveDownload)) { - $row['APP_DOC_LINK'] = $driveDownload['INPUT']; - } else if (array_key_exists('ATTACHED', $driveDownload)) { - $row['APP_DOC_LINK'] = $driveDownload['ATTACHED']; - } - - } - /*----------------------------------********---------------------------------*/ $arrayInputDocument[] = $this->getAppDocumentDataFromRecord($row); } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/OutputDocument.php b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/OutputDocument.php index 6c166cc31..f8c59a53e 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/OutputDocument.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/OutputDocument.php @@ -3,6 +3,26 @@ namespace ProcessMaker\BusinessModel\Cases; class OutputDocument { + /** + * Verify exists app_doc_uid in table APP_DOCUMENT when is output + * + * @param string $applicationUid + * + * return void Throw exception output not exists + */ + private function throwExceptionIfNotExistsAppDocument($appDocumentUid) + { + try { + $appDocument = \AppDocumentPeer::retrieveByPK($appDocumentUid, 1); + + if (is_null($appDocument)) { + throw new \Exception(\G::LoadTranslation("ID_CASES_OUTPUT_DOES_NOT_EXIST", array($appDocumentUid))); + } + } catch (\Exception $e) { + throw $e; + } + } + /** * Check if the user has permissions * @@ -26,6 +46,9 @@ class OutputDocument $flagInbox = 0; } + //Verfiry exists $appDocumentUid + $this->throwExceptionIfNotExistsAppDocument($appDocumentUid); + //Verify data permission $flagPermission = 0; @@ -381,128 +404,6 @@ class OutputDocument } $this->generate( $outputID, $Fields['APP_DATA'], $pathOutput, $sFilename, $aOD['OUT_DOC_TEMPLATE'], (boolean) $aOD['OUT_DOC_LANDSCAPE'], $aOD['OUT_DOC_GENERATE'], $aProperties , $applicationUid); - /*----------------------------------********---------------------------------*/ - $licensedFeatures = &\PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) { - \G::LoadClass( "pmDrive" ); - $pmDrive = new \PMDrive(); - if ($pmDrive->getStatusService()) { - $app = new \Application(); - $user = new \Users(); - $dataUser = $user->load($userUid); - $pmDrive->setDriveUser($dataUser['USR_EMAIL']); - - $appData = $app->Load($applicationUid); - if ($appData['APP_DRIVE_FOLDER_UID'] == null) { - $process = new \Process(); - $process->setProUid($appData['PRO_UID']); - - $result = $pmDrive->createFolder($process->getProTitle() . ' - ' . G::LoadTranslation("ID_CASE") . ' #' . $appData['APP_NUMBER'], - $pmDrive->getFolderIdPMDrive($userUid)); - $appData['APP_DRIVE_FOLDER_UID'] = $result->id; - $app->update($appData); - } - - $fileIdDriveDoc = ''; - $fileIdDrivePdf = ''; - $sFilenameOriginal = preg_replace('[^A-Za-z0-9_]', '_', - \G::replaceDataField($aOD['OUT_DOC_FILENAME'], $Fields['APP_DATA'])); - switch ($aOD['OUT_DOC_GENERATE']) { - case "BOTH": - $result = $pmDrive->uploadFile('application/pdf', $pathOutput . $sFilename . '.pdf', - $sFilenameOriginal . '.pdf', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_PDF', $result->webContentLink); - $fileIdDrivePdf = $result->id; - $result = $pmDrive->uploadFile('application/doc', $pathOutput . $sFilename . '.doc', - $sFilenameOriginal . '.doc', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_DOC', $result->webContentLink); - $fileIdDriveDoc = $result->id; - break; - case "PDF": - $result = $pmDrive->uploadFile('application/pdf', $pathOutput . $sFilename . '.pdf', - $sFilenameOriginal . '.pdf', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_PDF', $result->webContentLink); - $fileIdDrivePdf = $result->id; - break; - case "DOC": - $result = $pmDrive->uploadFile('application/doc', $pathOutput . $sFilename . '.doc', - $sFilenameOriginal . '.doc', $appData['APP_DRIVE_FOLDER_UID']); - $oAppDocument->setDriveDownload('OUTPUT_DOC', $result->webContentLink); - $fileIdDriveDoc = $result->id; - break; - } - $aFields['DOC_VERSION'] = $oAppDocument->getDocVersion();// $docVersion; - $aFields['APP_DOC_UID'] = $oAppDocument->getAppDocUid();//$appDocUid; - $appDocUid = $aFields['APP_DOC_UID']; - - $oAppDocument->update($aFields); - //$option = 'pmDrive'; - - - //add permissions - $criteria = new \Criteria('workflow'); - $criteria->addSelectColumn(\ApplicationPeer::PRO_UID); - $criteria->addSelectColumn(\TaskUserPeer::TAS_UID); - $criteria->addSelectColumn(\TaskUserPeer::USR_UID); - $criteria->addSelectColumn(\TaskUserPeer::TU_RELATION); - - $criteria->add(\ApplicationPeer::APP_UID, $applicationUid); - $criteria->addJoin(\ApplicationPeer::PRO_UID, \TaskPeer::PRO_UID, \Criteria::LEFT_JOIN); - $criteria->addJoin(\TaskPeer::TAS_UID, \TaskUserPeer::TAS_UID, \Criteria::LEFT_JOIN); - - - $dataset = \ApplicationPeer::doSelectRS($criteria); - $dataset->setFetchmode(\ResultSet::FETCHMODE_ASSOC); - - $userPermission = array(); - $case = new \Cases(); - - while ($dataset->next()) { - $row = $dataset->getRow(); - if ($row['TU_RELATION'] == 1) { - //users - $dataUser = $user->load($row['USR_UID']); - if (array_search($dataUser['USR_EMAIL'], $userPermission) === false) { - $objectPermissions = $case->getAllObjects($row['PRO_UID'], $applicationUid, - $row['TAS_UID'], $row['USR_UID']); - if (array_search($appDocUid, $objectPermissions['OUTPUT_DOCUMENTS']) !== false) { - $userPermission[] = $dataUser['USR_EMAIL']; - } - } - } else { - //Groups - $criteria = new \Criteria('workflow'); - $criteria->addSelectColumn(\UsersPeer::USR_EMAIL); - $criteria->addSelectColumn(\UsersPeer::USR_UID); - $criteria->add(\GroupUserPeer::GRP_UID, $row['USR_UID']); - $criteria->addJoin(\GroupUserPeer::USR_UID, \UsersPeer::USR_UID, \Criteria::LEFT_JOIN); - - $oDataset = \AppDelegationPeer::doSelectRS($criteria); - $oDataset->setFetchmode(\ResultSet::FETCHMODE_ASSOC); - - while ( $oDataset->next()) { - $aRow = $oDataset->getRow(); - if (array_search($aRow['USR_EMAIL'], $userPermission) === false) { - $objectPermissions = $case->getAllObjects($row['PRO_UID'], $applicationUid, - $row['TAS_UID'], $aRow['USR_UID']); - if (array_search($appDocUid, $objectPermissions['OUTPUT_DOCUMENTS']) !== false) { - $userPermission[] = $aRow['USR_EMAIL']; - } - } - } - } - } - $userPermission = array_unique($userPermission); - - foreach ($userPermission as $key => $val) { - $pmDrive->setPermission($appData['APP_DRIVE_FOLDER_UID'], $val, 'user', 'writer'); - $pmDrive->setPermission($fileIdDrivePdf, $val); - $pmDrive->setPermission($fileIdDriveDoc, $val); - } - } - } - /*----------------------------------********---------------------------------*/ - //Plugin Hook PM_UPLOAD_DOCUMENT for upload document //G::LoadClass('plugin'); $oPluginRegistry = & \PMPluginRegistry::getSingleton(); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Cases/Variable.php b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/Variable.php new file mode 100644 index 000000000..cd5f831bf --- /dev/null +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Cases/Variable.php @@ -0,0 +1,804 @@ +runningWorkflow, $this->arrayFieldDefinition, $this->arrayVariableNameForException + ); + + $this->arrayFieldNameForException = $this->getArrayFieldNameForException(); + $this->arrayVariableNameForException = $this->getArrayVariableNameForException(); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set runningWorkflow atributte + * + * @param bool $flag + * + * @return void + */ + public function setRunningWorkflow($flag) + { + try { + parent::setRunningWorkflow($flag); + + $this->runningWorkflow = $flag; + + $this->arrayFieldNameForException = $this->getArrayFieldNameForException(); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set arrayVariableNameForException atributte by data + * + * @param array $arrayData + * + * @return void + */ + public function setArrayVariableNameForException(array $arrayData) + { + try { + foreach ($arrayData as $key => $value) { + $this->arrayVariableNameForException[$key] = $value; + } + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get Application, AppDelegation and Variable record by data + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param string $variableName Variable name + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return mixed Returns array with Application, AppDelegation and Variable record, + * ThrowTheException/FALSE otherwise + */ + private function __getApplicationAppDelegationAndVariableRecordByData( + $applicationUid, + $delIndex, + $variableName, + $throwException = true + ) { + try { + $case = new \ProcessMaker\BusinessModel\Cases(); + + $arrayApplicationData = $case->getApplicationRecordByPk( + $applicationUid, $this->arrayVariableNameForException, $throwException + ); + + if ($arrayApplicationData === false) { + return false; + } + + $arrayAppDelegationData = $case->getAppDelegationRecordByPk( + $applicationUid, $delIndex, $this->arrayVariableNameForException, $throwException + ); + + if ($arrayAppDelegationData === false) { + return false; + } + + $variable = new \ProcessMaker\BusinessModel\Variable(); + + $arrayVariableData = $variable->getVariableRecordByName( + $arrayApplicationData['PRO_UID'], $variableName, $this->arrayVariableNameForException, $throwException + ); + + if ($arrayVariableData === false) { + return false; + } + + $case = new \Cases(); + + $arrayApplicationData['APP_DATA'] = $case->unserializeData($arrayApplicationData['APP_DATA']); + + //Return + return [$arrayApplicationData, $arrayAppDelegationData, $arrayVariableData]; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get Fields of a Grid + * + * @param string $projectUid Unique id of Project + * @param string $gridName Grid name (Variable name) + * + * @return array Returns an array with Fields of a Grid + */ + private function __getGridFieldDefinitions($projectUid, $gridName) + { + try { + $arrayGridField = []; + + //Get data + $criteria = new \Criteria('workflow'); + + $criteria->addSelectColumn(\DynaformPeer::DYN_CONTENT); + + $criteria->add(\DynaformPeer::PRO_UID, $projectUid, \Criteria::EQUAL); + $criteria->add(\DynaformPeer::DYN_CONTENT, '%' . $gridName . '%', \Criteria::LIKE); + + $rsCriteria = \DynaformPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $dynaFormContent = \G::json_decode($row['DYN_CONTENT']); + + foreach ($dynaFormContent->items[0]->items as $value) { + $arrayField = $value; + + foreach ($arrayField as $value2) { + $fld = $value2; + + if ($fld->type == 'grid' && $fld->variable == $gridName) { + foreach ($fld->columns as $value3) { + $col = $value3; + + if (!isset($arrayGridField[$col->id])) { + $arrayGridField[$col->id] = $col; + } + } + break 2; + } + } + } + } + + //Return + return $arrayGridField; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Validate data + * + * @param array $arrayData Data + * @param array $arrayVariableData Variable data + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return bool Returns TRUE when array data is valid, ThrowTheException/FALSE otherwise + */ + private function __validateData(array $arrayData, array $arrayVariableData, $throwException = true) + { + try { + if (empty($arrayData)) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation('ID_INVALID_DATA')); + } else { + return false; + } + } + + if (isset($arrayVariableData['arrayGridField']) && empty($arrayVariableData['arrayGridField'])) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_GRID_DOES_NOT_HAVE_FIELDS', + [$this->arrayVariableNameForException['$variableName'], $arrayVariableData['VAR_NAME']] + )); + } else { + return false; + } + } + + $msgException = ''; + + switch ($arrayVariableData['VAR_FIELD_TYPE']) { + case 'grid': + foreach ($arrayData as $key => $value) { + $row = $value; + + if (is_array($row)) { + foreach ($arrayVariableData['arrayGridField'] as $value2) { + $field = $value2; + + if (isset($row[$field->id])) { + if (isset($row[$field->id . '_label'])) { + unset($row[$field->id], $row[$field->id . '_label']); + } else { + $msgException = $key . ': ' . $field->id . '_label' . ' ' . + \G::LoadTranslation('ID_DOES_NOT_EXIST'); + break 2; + } + } + } + + if (!empty($row)) { + $msgException = $key . ': ' . \G::LoadTranslation('ID_FIELD_INVALID') . + ' (' . implode(', ', array_keys($row)) . ')'; + break; + } + } else { + $msgException = $key . ': ' . \G::LoadTranslation('ID_INVALID_DATA'); + break; + } + } + break; + default: + $arrayFieldName = [ + $arrayVariableData['VAR_NAME'], + $arrayVariableData['VAR_NAME'] . '_label' + ]; + + foreach ($arrayFieldName as $value) { + if (!isset($arrayData[$value])) { + $msgException = $value . ' ' . \G::LoadTranslation('ID_DOES_NOT_EXIST'); + break; + } + } + break; + } + + if ($msgException != '') { + if ($throwException) { + throw new \Exception($msgException); + } else { + return false; + } + } + + //Return + return true; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Create Variable for the Case + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param string $variableName Variable name + * @param array $arrayData Data + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns data of the new Variable created, ThrowTheException/FALSE otherwise + */ + public function create($applicationUid, $delIndex, $variableName, array $arrayData, $throwException = true) + { + try { + //Verify data and Set variables + $result = $this->__getApplicationAppDelegationAndVariableRecordByData( + $applicationUid, $delIndex, $variableName, $throwException + ); + + if ($result === false) { + return false; + } + + $arrayApplicationData = $result[0]; + $arrayAppDelegationData = $result[1]; + $arrayVariableData = $result[2]; + + if ($arrayVariableData['VAR_FIELD_TYPE'] != 'grid' && + isset($arrayApplicationData['APP_DATA'][$variableName]) + ) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_VARIABLE_ALREADY_EXISTS', + [$this->arrayVariableNameForException['$variableName'], $variableName] + )); + } else { + return false; + } + } + + if ($arrayVariableData['VAR_FIELD_TYPE'] == 'grid') { + $arrayVariableData['arrayGridField'] = $this->__getGridFieldDefinitions( + $arrayVariableData['PRJ_UID'], $arrayVariableData['VAR_NAME'] + ); + } + + $result = $this->__validateData($arrayData, $arrayVariableData, $throwException); + + if ($result === false) { + return false; + } + + //Create + $arrayVariable = []; + + switch ($arrayVariableData['VAR_FIELD_TYPE']) { + case 'grid': + $arrayGridData = (isset($arrayApplicationData['APP_DATA'][$variableName]))? + $arrayApplicationData['APP_DATA'][$variableName] : []; + + $i1 = $i2 = count($arrayGridData); + + foreach ($arrayData as $value) { + $i1++; + $arrayGridData[$i1] = $value; + } + + $arrayVariable = array_slice($arrayGridData, $i2, null, true); + + $arrayApplicationData['APP_DATA'][$variableName] = $arrayGridData; + break; + default: + $arrayVariable = [ + $variableName => $arrayData[$variableName], + $variableName . '_label' => $arrayData[$variableName . '_label'] + ]; + + $arrayApplicationData['APP_DATA'] = array_merge($arrayApplicationData['APP_DATA'], $arrayVariable); + break; + } + + $case = new \Cases(); + + $result = $case->updateCase($applicationUid, $arrayApplicationData); + + //Return + return $arrayVariable; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Update Variable for the Case + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param string $variableName Variable name + * @param array $arrayData Data + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return bool Returns TRUE when Variable is updated, ThrowTheException/FALSE otherwise + */ + public function update($applicationUid, $delIndex, $variableName, array $arrayData, $throwException = true) + { + try { + //Verify data and Set variables + $result = $this->__getApplicationAppDelegationAndVariableRecordByData( + $applicationUid, $delIndex, $variableName, $throwException + ); + + if ($result === false) { + return false; + } + + $arrayApplicationData = $result[0]; + $arrayAppDelegationData = $result[1]; + $arrayVariableData = $result[2]; + + if (!isset($arrayApplicationData['APP_DATA'][$variableName])) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_VARIABLE_DOES_NOT_EXIST', + [$this->arrayVariableNameForException['$variableName'], $variableName] + )); + } else { + return false; + } + } + + if ($arrayVariableData['VAR_FIELD_TYPE'] == 'grid') { + $arrayVariableData['arrayGridField'] = $this->__getGridFieldDefinitions( + $arrayVariableData['PRJ_UID'], $arrayVariableData['VAR_NAME'] + ); + } + + $result = $this->__validateData($arrayData, $arrayVariableData, $throwException); + + if ($result === false) { + return false; + } + + if ($arrayVariableData['VAR_FIELD_TYPE'] == 'grid') { + foreach ($arrayData as $key => $value) { + if (!isset($arrayApplicationData['APP_DATA'][$variableName][$key])) { + if ($throwException) { + throw new \Exception($key . ': ' . \G::LoadTranslation('ID_NO_EXIST')); + } else { + return false; + } + } + } + } + + //Update + switch ($arrayVariableData['VAR_FIELD_TYPE']) { + case 'grid': + foreach ($arrayData as $key => $value) { + $arrayApplicationData['APP_DATA'][$variableName][$key] = array_merge( + $arrayApplicationData['APP_DATA'][$variableName][$key], $value + ); + } + break; + default: + $arrayApplicationData['APP_DATA'] = array_merge( + $arrayApplicationData['APP_DATA'], + [ + $variableName => $arrayData[$variableName], + $variableName . '_label' => $arrayData[$variableName . '_label'] + ] + ); + break; + } + + $case = new \Cases(); + + $result = $case->updateCase($applicationUid, $arrayApplicationData); + + //Return + return true; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Delete Variable of the Case + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param string $variableName Variable name + * @param array $arrayKey Keys to delete (Only for Grids) + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return bool Returns TRUE when Variable is deleted, ThrowTheException/FALSE otherwise + */ + public function delete($applicationUid, $delIndex, $variableName, array $arrayKey = null, $throwException = true) + { + try { + //Verify data and Set variables + $result = $this->__getApplicationAppDelegationAndVariableRecordByData( + $applicationUid, $delIndex, $variableName, $throwException + ); + + if ($result === false) { + return false; + } + + $arrayApplicationData = $result[0]; + $arrayAppDelegationData = $result[1]; + $arrayVariableData = $result[2]; + + if (!isset($arrayApplicationData['APP_DATA'][$variableName])) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_VARIABLE_DOES_NOT_EXIST', + [$this->arrayVariableNameForException['$variableName'], $variableName] + )); + } else { + return false; + } + } + + if ($arrayVariableData['VAR_FIELD_TYPE'] == 'grid' && !is_null($arrayKey)) { + $msgException = ''; + + if (!empty($arrayKey)) { + foreach ($arrayKey as $value) { + $key = $value; + + if (!isset($arrayApplicationData['APP_DATA'][$variableName][$key])) { + $msgException = $key . ': ' . \G::LoadTranslation('ID_NO_EXIST'); + break; + } + } + } else { + $msgException = \G::LoadTranslation( + 'ID_INVALID_VALUE_CAN_NOT_BE_EMPTY', [$this->arrayVariableNameForException['$arrayKey']] + ); + } + + if ($msgException != '') { + if ($throwException) { + throw new \Exception($msgException); + } else { + return false; + } + } + } + + //Delete + switch ($arrayVariableData['VAR_FIELD_TYPE']) { + case 'grid': + if (!is_null($arrayKey)) { + //Delete keys + foreach ($arrayKey as $value) { + $key = $value; + + unset($arrayApplicationData['APP_DATA'][$variableName][$key]); + } + + //Reset keys + $arrayGridData = []; + $i = 1; + + foreach ($arrayApplicationData['APP_DATA'][$variableName] as $value) { + $arrayGridData[$i] = $value; + $i++; + } + + $arrayApplicationData['APP_DATA'][$variableName] = $arrayGridData; + } else { + unset($arrayApplicationData['APP_DATA'][$variableName]); + } + break; + default: + unset( + $arrayApplicationData['APP_DATA'][$variableName], + $arrayApplicationData['APP_DATA'][$variableName . '_label'] + ); + break; + } + + $case = new \Cases(); + + $result = $case->updateCase($applicationUid, $arrayApplicationData); + + //Return + return true; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get Variable of a Case + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param string $variableName Variable name + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Variable of a Case, ThrowTheException/FALSE otherwise + */ + public function getVariableByName( + $applicationUid, + $delIndex, + $variableName, + $throwException = true + ) { + try { + $arrayVariable = []; + + //Verify data and Set variables + $result = $this->__getApplicationAppDelegationAndVariableRecordByData( + $applicationUid, $delIndex, $variableName, $throwException + ); + + if ($result === false) { + return false; + } + + $arrayApplicationData = $result[0]; + $arrayAppDelegationData = $result[1]; + $arrayVariableData = $result[2]; + + if (!isset($arrayApplicationData['APP_DATA'][$variableName])) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_VARIABLE_DOES_NOT_EXIST', + [$this->arrayVariableNameForException['$variableName'], $variableName] + )); + } else { + return false; + } + } + + //Get Variable + switch ($arrayVariableData['VAR_FIELD_TYPE']) { + case 'grid': + $arrayVariable = $arrayApplicationData['APP_DATA'][$variableName]; + break; + default: + $arrayVariable = [ + $variableName => $arrayApplicationData['APP_DATA'][$variableName], + $variableName . '_label' => isset($arrayApplicationData['APP_DATA'][$variableName . '_label'])? + $arrayApplicationData['APP_DATA'][$variableName . '_label'] : '' + ]; + break; + } + + //Return + return $arrayVariable; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get Variable of a Case (Only for Grids) + * + * @param string $applicationUid Unique id of Case + * @param int $delIndex Delegation index + * @param string $variableName Variable name + * @param array $arrayFilterData Data of the filters + * @param int $start Start + * @param int $limit Limit + * @param bool $throwException Flag to throw the exception (This only if the parameters are invalid) + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Variable of a Case, ThrowTheException/FALSE otherwise + */ + public function getVariableByNamePaged( + $applicationUid, + $delIndex, + $variableName, + $arrayFilterData = null, + $start = null, + $limit = null, + $throwException = true + ) { + try { + $arrayVariable = []; + + $numRecTotal = 0; + + //Verify data and Set variables + $flagFilter = !is_null($arrayFilterData) && is_array($arrayFilterData) && isset($arrayFilterData['filter']); + + $result = \ProcessMaker\BusinessModel\Validator::validatePagerDataByPagerDefinition( + [ + $this->arrayVariableNameForException['$start'] => $start, + $this->arrayVariableNameForException['$limit'] => $limit + ], + $this->arrayVariableNameForException + ); + + if ($result !== true) { + if ($throwException) { + throw new \Exception($result); + } else { + return false; + } + } + + $result = $this->__getApplicationAppDelegationAndVariableRecordByData( + $applicationUid, $delIndex, $variableName, $throwException + ); + + if ($result === false) { + return false; + } + + $arrayApplicationData = $result[0]; + $arrayAppDelegationData = $result[1]; + $arrayVariableData = $result[2]; + + if (!isset($arrayApplicationData['APP_DATA'][$variableName])) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_CASE_VARIABLE_DOES_NOT_EXIST', + [$this->arrayVariableNameForException['$variableName'], $variableName] + )); + } else { + return false; + } + } + + if ($arrayVariableData['VAR_FIELD_TYPE'] != 'grid') { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_VARIABLE_NO_IS_GRID', + [$this->arrayVariableNameForException['$variableName'], $variableName] + )); + } else { + return false; + } + } + + //Set variables + $filterName = 'filter'; + + if ($flagFilter) { + $arrayAux = [ + '' => 'filter', + 'LEFT' => 'lfilter', + 'RIGHT' => 'rfilter' + ]; + + $filterName = $arrayAux[ + (isset($arrayFilterData['filterOption']))? $arrayFilterData['filterOption'] : '' + ]; + } + + //Get Variable + if (!is_null($limit) && (string)($limit) == '0') { + return [ + 'total' => $numRecTotal, + 'start' => (int)((!is_null($start))? $start : 0), + 'limit' => (int)((!is_null($limit))? $limit : 0), + $filterName => ($flagFilter)? $arrayFilterData['filter'] : '', + 'data' => $arrayVariable + ]; + } + + $arraySearch = [ + '' => '.*' . $arrayFilterData['filter'] . '.*', + 'LEFT' => $arrayFilterData['filter'] . '.*', + 'RIGHT' => '.*' . $arrayFilterData['filter'] + ]; + + $search = $arraySearch[ + (isset($arrayFilterData['filterOption']))? $arrayFilterData['filterOption'] : '' + ]; + + foreach ($arrayApplicationData['APP_DATA'][$variableName] as $key => $value) { + if ($flagFilter && trim($arrayFilterData['filter']) != '') { + foreach ($value as $key2 => $value2) { + if (preg_match('/^' . $search . '$/i', $value2)) { + $arrayVariable[$key] = $value; + $numRecTotal++; + break; + } + } + } else { + $arrayVariable[$key] = $value; + $numRecTotal++; + } + } + + $arrayVariable = array_slice( + $arrayVariable, + (!is_null($start))? (int)($start) : 0, + (!is_null($limit))? (int)($limit) : null, + true + ); + + //Return + return [ + 'total' => $numRecTotal, + 'start' => (int)((!is_null($start))? $start : 0), + 'limit' => (int)((!is_null($limit))? $limit : 0), + $filterName => ($flagFilter)? $arrayFilterData['filter'] : '', + 'data' => $arrayVariable + ]; + } catch (\Exception $e) { + throw $e; + } + } +} + diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php b/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php index 63e9b684c..1b2ba2187 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Consolidated.php @@ -121,7 +121,9 @@ class Consolidated $response["casesNumRec"] = \Library::getCasesNumRec($usr_uid); if (is_array($res)) { - $response ["message"] = "" . G::LoadTranslation("ID_CASE") . " " . $app_number . " Summary of Derivations:
" . $messageDerivateCase; + $response ["message"] = "" . G::LoadTranslation("ID_CASE") . " " . $app_number . " " . + G::LoadTranslation("ID_SUMMARY_DERIVATION_BATCH_ROUTING") . ' :' . "
" . + $messageDerivateCase; } else { $response ["message"] = G::LoadTranslation("ID_CASE") . " " . $app_number . " " . $res->message; } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php b/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php index 0dfa0dc71..80af715d6 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/DataBaseConnection.php @@ -70,6 +70,32 @@ class DataBaseConnection } $aFields['DBS_PASSWORD'] = $dbs->getPassWithoutEncrypt($aFields); + $aFields['DBS_DATABASE_DESCRIPTION'] = ''; + + $dbDescription = ''; + + $criteria2 = new \Criteria('workflow'); + + $criteria2->addSelectColumn(\ContentPeer::CON_VALUE); + $criteria2->add(\ContentPeer::CON_ID, $aFields['DBS_UID'], \Criteria::EQUAL); + + $rsCriteria2 = \ContentPeer::doSelectRS($criteria2); + $rsCriteria2->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria2->next()) { + $row2 = $rsCriteria2->getRow(); + + if ($row2['CON_VALUE'] != '') { + $dbDescription = ' - [' . $row2['CON_VALUE'] . ']'; + } + } + + if($aFields['DBS_TYPE'] == 'oracle' && $aFields['DBS_CONNECTION_TYPE'] == 'TNS') { + $aFields['DBS_DATABASE_DESCRIPTION'] = '[' . $aFields['DBS_TNS'] . ']' . $dbDescription; + } else { + $aFields['DBS_DATABASE_DESCRIPTION'] = $dbDescription; + } + $response = array_change_key_case($aFields, CASE_LOWER); return $response; } catch (\Exception $e) { diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Department.php b/workflow/engine/src/ProcessMaker/BusinessModel/Department.php index 0c19e55c7..0d1149873 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Department.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Department.php @@ -50,6 +50,27 @@ class Department } } + /** + * Verify if the User is not in a Department + * + * @param string $departmentUid + * @param string $userUid + * + * return void Throw exception user not exists + */ + private function throwExceptionUserNotExistsInDepartment($departmentUid, $userUid) + { + try { + $user = \UsersPeer::retrieveByPK($userUid); + + if (is_null($user) || $user->getDepUid() != $departmentUid) { + throw new \Exception(\G::LoadTranslation('ID_USER_NOT_EXIST_DEPARTMENT', [$userUid])); + } + } catch (\Exception $e) { + throw $e; + } + } + /** * Verify if exists the title of a Department * @@ -70,6 +91,41 @@ class Department } } + /** + * Get Department record + * + * @param string $departmentUid Unique id of Department + * @param array $arrayVariableNameForException Variable name for exception + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Department record, ThrowTheException/FALSE otherwise + */ + public function getDepartmentRecordByPk( + $departmentUid, + array $arrayVariableNameForException, + $throwException = true + ) { + try { + $obj = \DepartmentPeer::retrieveByPK($departmentUid); + + if (is_null($obj)) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_DEPARTMENT_NOT_EXIST', [$arrayVariableNameForException['$departmentUid'], $departmentUid] + )); + } else { + return false; + } + } + + //Return + return $obj->toArray(\BasePeer::TYPE_FIELDNAME); + } catch (\Exception $e) { + throw $e; + } + } + /** * Get list for Departments * @@ -166,7 +222,7 @@ class Department $oCriteria->setOffset( $start ); if ($search != '') { - $oCriteria->add( $oCriteria->getNewCriterion( UsersPeer::USR_USERNAME, '%' . $search . '%', \Criteria::LIKE )->addOr( $oCriteria->getNewCriterion( UsersPeer::USR_FIRSTNAME, '%' . $search . '%', \Criteria::LIKE )->addOr( $oCriteria->getNewCriterion( UsersPeer::USR_LASTNAME, '%' . $search . '%', \Criteria::LIKE ) ) ) ); + $oCriteria->add( $oCriteria->getNewCriterion( UsersPeer::USR_USERNAME, '%' . $search . '%', \Criteria::LIKE )->addOr( $oCriteria->getNewCriterion( UsersPeer::USR_FIRSTNAME, '%' . $search . '%', \Criteria::LIKE )->addOr( $oCriteria->getNewCriterion( UsersPeer::USR_LASTNAME, '%' . $search . '%', \Criteria::LIKE ) ) ) ); } $oDataset = UsersPeer::doSelectRS( $oCriteria ); @@ -253,6 +309,8 @@ class Department $dep_uid = Validator::depUid($dep_uid); $usr_uid = Validator::usrUid($usr_uid); + $this->throwExceptionUserNotExistsInDepartment($dep_uid, $usr_uid); + $dep = new \Department(); $dep->load( $dep_uid ); $manager = $dep->getDepManager(); diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm.php b/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm.php index bc3c58435..0b891f7c2 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm.php @@ -268,6 +268,21 @@ class DynaForm } } + /** + * Throw the exception "The DynaForm doesn't exist" + * + * @param string $dynaFormUid Unique id of DynaForm + * @param string $fieldNameForException Field name for the exception + * + * @return void + */ + private function throwExceptionDynaFormDoesNotExist($dynaFormUid, $fieldNameForException) + { + throw new \Exception(\G::LoadTranslation( + 'ID_DYNAFORM_DOES_NOT_EXIST', [$fieldNameForException, $dynaFormUid] + )); + } + /** * Verify if doesn't exists the DynaForm in table DYNAFORM * @@ -293,7 +308,7 @@ class DynaForm $rsCriteria = \DynaformPeer::doSelectRS($criteria); if (!$rsCriteria->next()) { - throw new \Exception(\G::LoadTranslation("ID_DYNAFORM_DOES_NOT_EXIST", array($fieldNameForException, $dynaFormUid))); + $this->throwExceptionDynaFormDoesNotExist($dynaFormUid, $fieldNameForException); } } catch (\Exception $e) { throw $e; @@ -345,6 +360,38 @@ class DynaForm } } + /** + * Get DynaForm record + * + * @param string $dynaFormUid Unique id of DynaForm + * @param array $arrayVariableNameForException Variable name for exception + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with DynaForm record, ThrowTheException/FALSE otherwise + */ + public function getDynaFormRecordByPk($dynaFormUid, array $arrayVariableNameForException, $throwException = true) + { + try { + $obj = \DynaformPeer::retrieveByPK($dynaFormUid); + + if (is_null($obj)) { + if ($throwException) { + $this->throwExceptionDynaFormDoesNotExist( + $dynaFormUid, $arrayVariableNameForException['$dynaFormUid'] + ); + } else { + return false; + } + } + + //Return + return $obj->toArray(\BasePeer::TYPE_FIELDNAME); + } catch (\Exception $e) { + throw $e; + } + } + /** * Create DynaForm for a Process * @@ -553,7 +600,7 @@ class DynaForm $this->throwExceptionIfNotExistsDynaForm($dynaFormUidCopyImport, $processUidCopyImport, $this->getFieldNameByFormatFieldName("COPY_IMPORT.DYN_UID")); //Copy/Import - + //Copy content if version is 2 if ($arrayData["DYN_VERSION"] === 2) { $dynaFormOld = new \Dynaform(); @@ -562,7 +609,7 @@ class DynaForm $arrayData["DYN_CONTENT"] = $arrayDynaFormData["DYN_CONTENT"]; } - + //Create $arrayData = $this->create($processUid, $arrayData); @@ -976,7 +1023,7 @@ class DynaForm if ($record["DYN_VERSION"] == 0) { $record["DYN_VERSION"] = 1; } - + $record["DYN_CONTENT"] = preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", $record["DYN_CONTENT"]); return array( @@ -1147,7 +1194,7 @@ class DynaForm throw $e; } } - + /** * Get data of a DynaForm History * diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm/Grid.php b/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm/Grid.php new file mode 100644 index 000000000..318c88517 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/BusinessModel/DynaForm/Grid.php @@ -0,0 +1,193 @@ +runningWorkflow, $this->arrayFieldDefinition, $this->arrayVariableNameForException + ); + + $this->arrayFieldNameForException = $this->getArrayFieldNameForException(); + $this->arrayVariableNameForException = $this->getArrayVariableNameForException(); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set runningWorkflow atributte + * + * @param bool $flag + * + * @return void + */ + public function setRunningWorkflow($flag) + { + try { + parent::setRunningWorkflow($flag); + + $this->runningWorkflow = $flag; + + $this->arrayFieldNameForException = $this->getArrayFieldNameForException(); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set arrayVariableNameForException atributte by data + * + * @param array $arrayData + * + * @return void + */ + public function setArrayVariableNameForException(array $arrayData) + { + try { + foreach ($arrayData as $key => $value) { + $this->arrayVariableNameForException[$key] = $value; + } + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get Fields of a Grid + * + * @param string $dynaFormUid Unique id of DynaForm + * @param string $gridName Grid name (Variable name) + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Fields of a Grid, ThrowTheException/FALSE otherwise + */ + public function getGridFieldDefinitions($dynaFormUid, $gridName, $throwException = true) + { + try { + //Verify data and Set variables + $dynaForm = new \ProcessMaker\BusinessModel\DynaForm(); + + $arrayDynaFormData = $dynaForm->getDynaFormRecordByPk( + $dynaFormUid, $this->arrayVariableNameForException, $throwException + ); + + if ($arrayDynaFormData === false) { + return false; + } + + //Get data + $dynaFormContent = \G::json_decode($arrayDynaFormData['DYN_CONTENT']); + + $arrayGridField = []; + $flagFound = false; + + foreach ($dynaFormContent->items[0]->items as $value) { + $arrayField = $value; + + foreach ($arrayField as $value2) { + $fld = $value2; + + if ($fld->type == 'grid' && $fld->variable == $gridName) { + $arrayGridField = $fld->columns; + $flagFound = true; + break 2; + } + } + } + + if (!$flagFound) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_GRID_DOES_NOT_EXIST_IN_DYNAFORM', + [$this->arrayVariableNameForException['$gridName'], $gridName] + )); + } else { + return false; + } + } + + //Return + return $arrayGridField; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get Field of a Grid + * + * @param string $dynaFormUid Unique id of DynaForm + * @param string $gridName Grid name (Variable name) + * @param string $fieldId Field id + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Field of a Grid, ThrowTheException/FALSE otherwise + */ + public function getGridFieldDefinition($dynaFormUid, $gridName, $fieldId, $throwException = true) + { + try { + //Verify data and Set variables + $arrayGridField = $this->getGridFieldDefinitions($dynaFormUid, $gridName, $throwException); + + if ($arrayGridField === false) { + return false; + } + + //Get data + $field = null; + $flagFound = false; + + foreach ($arrayGridField as $value) { + $fld = $value; + + if ($fld->id == $fieldId) { + $field = $fld; + $flagFound = true; + break; + } + } + + if (!$flagFound) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_GRID_FIELD_DOES_NOT_EXIST', + [$this->arrayVariableNameForException['$fieldId'], $fieldId] + )); + } else { + return false; + } + } + + //Return + return $field; + } catch (\Exception $e) { + throw $e; + } + } +} + diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light.php index bd3084763..1b77dba0a 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light.php @@ -22,6 +22,18 @@ class Light { $response = null; try { + // getting bpmn projects + $c = new Criteria('workflow'); + $c->addSelectColumn(\BpmnProjectPeer::PRJ_UID); + $ds = \ProcessPeer::doSelectRS($c, \Propel::getDbConnection('workflow_ro')); + $ds->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $bpmnProjects = array(); + + while ($ds->next()) { + $row = $ds->getRow(); + $bpmnProjects[] = $row['PRJ_UID']; + } + $oProcess = new \Process(); $oCase = new \Cases(); @@ -65,7 +77,7 @@ class Light $tempTreeChildren = array (); foreach ($processList[$key] as $keyChild => $processInfoChild) { $webEntryEventStart = $webEntryEvent->getWebEntryEvents($processInfoChild['pro_uid']); - if(empty($webEntryEventStart)){ + if (empty($webEntryEventStart) && in_array($processInfoChild['pro_uid'], $bpmnProjects)) { $tempTreeChild['text'] = $keyChild; //ellipsis ( $keyChild, 50 ); $tempTreeChild['processId'] = $processInfoChild['pro_uid']; $tempTreeChild['taskId'] = $processInfoChild['uid']; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php b/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php index fd885fd57..88c32255a 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Light/NotificationDevice.php @@ -152,11 +152,13 @@ class NotificationDevice { try { $response = array(); + $typeList = 'todo'; foreach ($aTasks as $aTask) { $arrayTaskUser = array(); switch ($aTask["TAS_ASSIGN_TYPE"]) { case "SELF_SERVICE": $arrayTaskUser = $this->getTaskUserSelfService($aTask["TAS_UID"], $appFields); + $typeList = 'unassigned'; break; default: if (isset($aTask["USR_UID"]) && !empty($aTask["USR_UID"])) { @@ -181,7 +183,7 @@ class NotificationDevice 'caseId' => $appFields['APP_UID'], 'caseTitle' => $appFields['APP_TITLE'], 'delIndex' => $delIndex, - 'typeList' => 'todo' + 'typeList' => $typeList ); if ($userIds) { diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php b/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php index c20eadcac..c6c1ae32d 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php @@ -188,11 +188,14 @@ class Pmgmail { $subject = "[PM] " .$proName. " (" . $index . ") Case: ". $appNumber; + //getting the default email server + $defaultEmail = $this->emailAccount(); + require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.wsBase.php"); $ws = new \wsBase(); $resultMail = $ws->sendMessage( $app_uid, - 'inbox.pm@processmaker.com', //From, + $defaultEmail, //From, $mail,//To, '', '', diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Process.php b/workflow/engine/src/ProcessMaker/BusinessModel/Process.php index 5352373b9..991d9776d 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Process.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Process.php @@ -325,12 +325,12 @@ class Process public function throwExceptionIfDataNotMetPagerVarDefinition($arrayData, $arrayFieldNameForException) { try { - foreach ($arrayData as $key => $value) { - $nameForException = (isset($arrayFieldNameForException[$key]))? $arrayFieldNameForException[$key] : $key; + $result = \ProcessMaker\BusinessModel\Validator::validatePagerDataByPagerDefinition( + $arrayData, $arrayFieldNameForException + ); - if (!is_null($value) && ($value . "" == "" || !preg_match("/^(?:\+|\-)?(?:0|[1-9]\d*)$/", $value . "") || (int)($value) < 0)) { - throw new \Exception(\G::LoadTranslation('ID_INVALID_VALUE_EXPECTING_POSITIVE_INTEGER', [$nameForException])); - } + if ($result !== true) { + throw new \Exception($result); } } catch (\Exception $e) { throw $e; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/ProcessSupervisor.php b/workflow/engine/src/ProcessMaker/BusinessModel/ProcessSupervisor.php index 47f71ddb6..e0b809835 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/ProcessSupervisor.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/ProcessSupervisor.php @@ -2,7 +2,6 @@ namespace ProcessMaker\BusinessModel; use \G; -use Luracast\Restler\User; class ProcessSupervisor { diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Table.php b/workflow/engine/src/ProcessMaker/BusinessModel/Table.php index 244619e69..71991aa45 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Table.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Table.php @@ -497,7 +497,9 @@ class Table } $index = G::encrypt( implode( ',', $primaryKeysValues ), 'pmtable' ); - $rep = $this->getTableData($pmt_uid); + $rep = $obj->toArray(\BasePeer::TYPE_FIELDNAME); + $rep = array_change_key_case($rep, CASE_LOWER); + $rep['__index__'] = $index; return $rep; } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/User.php b/workflow/engine/src/ProcessMaker/BusinessModel/User.php index 2449e92d7..368f07422 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/User.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/User.php @@ -328,6 +328,38 @@ class User } } + /** + * Get User record + * + * @param string $userUid Unique id of User + * @param array $arrayVariableNameForException Variable name for exception + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with User record, ThrowTheException/FALSE otherwise + */ + public function getUserRecordByPk($userUid, array $arrayVariableNameForException, $throwException = true) + { + try { + $obj = \UsersPeer::retrieveByPK($userUid); + + if (is_null($obj)) { + if ($throwException) { + throw new \Exception(\G::LoadTranslation( + 'ID_USER_DOES_NOT_EXIST', [$arrayVariableNameForException['$userUid'], $userUid] + )); + } else { + return false; + } + } + + //Return + return $obj->toArray(\BasePeer::TYPE_FIELDNAME); + } catch (\Exception $e) { + throw $e; + } + } + /** * Get data of a from a record * @@ -1288,5 +1320,68 @@ class User throw $e; } } -} + /** + * Get the User's Manager + * + * @param string $userUid Unique id of User + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return string Returns an string with Unique id of User (Manager), ThrowTheException/FALSE otherwise + */ + public function getUsersManager($userUid, $throwException = true) + { + try { + //Verify data and Set variables + $arrayUserData = $this->getUserRecordByPk($userUid, ['$userUid' => '$userUid'], $throwException); + + if ($arrayUserData === false) { + return false; + } + + //Set variables + $department = new \ProcessMaker\BusinessModel\Department(); + + //Get Manager + if ((string)($arrayUserData['USR_REPORTS_TO']) == '' || + (string)($arrayUserData['USR_REPORTS_TO']) == $userUid + ) { + if ((string)($arrayUserData['DEP_UID']) != '') { + $departmentUid = $arrayUserData['DEP_UID']; + + do { + $flagd = false; + + $arrayDepartmentData = $department->getDepartmentRecordByPk( + $departmentUid, ['$departmentUid' => '$departmentUid'], $throwException + ); + + if ($arrayDepartmentData === false) { + return false; + } + + if ((string)($arrayDepartmentData['DEP_MANAGER']) == '' || + (string)($arrayDepartmentData['DEP_MANAGER']) == $userUid + ) { + if ((string)($arrayDepartmentData['DEP_PARENT']) != '') { + $departmentUid = $arrayDepartmentData['DEP_PARENT']; + $flagd = true; + } else { + return false; + } + } else { + return $arrayDepartmentData['DEP_MANAGER']; + } + } while ($flagd); + } else { + return false; + } + } else { + return $arrayUserData['USR_REPORTS_TO']; + } + } catch (\Exception $e) { + throw $e; + } + } +} diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Util/Attribute.php b/workflow/engine/src/ProcessMaker/BusinessModel/Util/Attribute.php new file mode 100644 index 000000000..ed48ab343 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Util/Attribute.php @@ -0,0 +1,141 @@ +runningWorkflow = $runningWorkflow; + $this->arrayFieldDefinition = $arrayFieldDefinition; + + foreach ($arrayFieldDefinition as $key => $value) { + if (isset($value['fieldNameAux'])) { + $this->arrayFieldNameForException[$value['fieldNameAux']] = $key; + } + } + + foreach ($arrayVariableNameForException as $value) { + $this->arrayVariableNameForException[$value] = $value; + } + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set runningWorkflow atributte + * + * @param bool $flag + * + * @return void + */ + public function setRunningWorkflow($flag) + { + try { + $this->runningWorkflow = $flag; + + $this->setArrayFieldNameForException($this->arrayFieldNameForException); + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set arrayFieldNameForException atributte by data + * + * @param array $arrayData + * + * @return void + */ + public function setArrayFieldNameForException(array $arrayData) + { + try { + foreach ($arrayData as $key => $value) { + $this->arrayFieldNameForException[$key] = $this->convertFieldNameByRunningWorkflow($value); + } + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Set arrayVariableNameForException atributte by data + * + * @param array $arrayData + * + * @return void + */ + public function setArrayVariableNameForException(array $arrayData) + { + try { + foreach ($arrayData as $key => $value) { + $this->arrayVariableNameForException[$key] = $value; + } + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get arrayFieldNameForException atributte + * + * @return array + */ + public function getArrayFieldNameForException() + { + try { + return $this->arrayFieldNameForException; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Get arrayVariableNameForException atributte + * + * @return array + */ + public function getArrayVariableNameForException() + { + try { + return $this->arrayVariableNameForException; + } catch (\Exception $e) { + throw $e; + } + } + + /** + * Convert field name by runningWorkflow + * + * @param string $fieldName + * + * @return string + */ + public function convertFieldNameByRunningWorkflow($fieldName) + { + try { + return ($this->runningWorkflow)? strtoupper($fieldName) : strtolower($fieldName); + } catch (\Exception $e) { + throw $e; + } + } +} + diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Validator.php b/workflow/engine/src/ProcessMaker/BusinessModel/Validator.php index bb622755c..5c61055ae 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Validator.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Validator.php @@ -374,5 +374,38 @@ class Validator throw $e; } } + + /** + * Validate pager data + * + * @param array $arrayData Data + * @param array $arrayVariableNameForException Variable name for exception + * + * @return mixed Returns TRUE when pager data is valid, Message Error otherwise + */ + public static function validatePagerDataByPagerDefinition($arrayPagerData, $arrayVariableNameForException) + { + try { + foreach ($arrayPagerData as $key => $value) { + $nameForException = (isset($arrayVariableNameForException[$key]))? + $arrayVariableNameForException[$key] : $key; + + if (!is_null($value) && + ( + (string)($value) == '' || + !preg_match('/^(?:\+|\-)?(?:0|[1-9]\d*)$/', $value . '') || + (int)($value) < 0 + ) + ) { + return \G::LoadTranslation('ID_INVALID_VALUE_EXPECTING_POSITIVE_INTEGER', [$nameForException]); + } + } + + //Return + return true; + } catch (\Exception $e) { + throw $e; + } + } } diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php b/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php index a54718871..766957119 100755 --- a/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Variable.php @@ -231,6 +231,9 @@ class Variable $this->throwExceptionIfNotExistsVariable($variableUid); + //Verify variable + $this->throwExceptionIfVariableIsAssociatedAditionalTable($variableUid); + $variable = $this->getVariable($processUid, $variableUid); \G::LoadClass('pmDynaform'); $pmDynaform = new \pmDynaform(); @@ -556,13 +559,16 @@ class Variable \G::LoadClass('pmDynaform'); $pmDynaform = new \pmDynaform(); $field = $pmDynaform->searchField($arrayVariable["dyn_uid"], $arrayVariable["field_id"]); - $variableDbConnectionUid = $field !== null ? $field->dbConnection : ""; + $dbConnection = "workflow"; + if ($field !== null && !empty($field->dbConnection)) { + $dbConnection = $field->dbConnection; + } $variableSql = $field !== null ? $field->sql : ""; //Get data $_SESSION["PROCESS"] = $processUid; - $cnn = \Propel::getConnection(($variableDbConnectionUid . "" != "")? $variableDbConnectionUid : "workflow"); + $cnn = \Propel::getConnection($dbConnection); $stmt = $cnn->createStatement(); $replaceFields = G::replaceDataField($variableSql, $arrayVariable); @@ -605,6 +611,40 @@ class Variable } } + /** + * Check if the variable is associated to Report Table + * + * @param string $variableUid Unique id of variable + * + * @return void Throw exception + */ + public function throwExceptionIfVariableIsAssociatedAditionalTable($variableUid) + { + try { + $criteria = new \Criteria('workflow'); + + $criteria->addSelectColumn(\ProcessVariablesPeer::VAR_UID); + + $criteria->addJoin(\ProcessVariablesPeer::PRJ_UID, \AdditionalTablesPeer::PRO_UID, \Criteria::INNER_JOIN); + + $arrayCondition = []; + $arrayCondition[] = array(\AdditionalTablesPeer::ADD_TAB_UID, \FieldsPeer::ADD_TAB_UID, \Criteria::EQUAL); + $arrayCondition[] = array(\ProcessVariablesPeer::VAR_NAME, \FieldsPeer::FLD_NAME, \Criteria::EQUAL); + $criteria->addJoinMC($arrayCondition, \Criteria::INNER_JOIN); + + $criteria->add(\ProcessVariablesPeer::VAR_UID, $variableUid, \Criteria::EQUAL); + + $rsCriteria = \ProcessVariablesPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + throw new \Exception(\G::LoadTranslation('ID_VARIABLE_ASSOCIATED_WITH_REPORT_TABLE', array($variableUid))); + } + } catch (\Exception $e) { + throw $e; + } + } + /** * Verify if the variable is being used in a Dynaform * @@ -677,41 +717,85 @@ class Variable \G::LoadClass('pmDynaform'); $pmDynaform = new \pmDynaform(); $field = $pmDynaform->searchField($arrayVariable["dyn_uid"], $variableName); - $variableDbConnectionUid = $field !== null ? $field->dbConnection : ""; - $variableSql = $field !== null ? $field->sql : ""; //Get data - $_SESSION["PROCESS"] = $processUid; + $filter = str_replace('\'', '\'\'', (isset($arrayVariable['filter']))? $arrayVariable['filter'] : ''); + $start = (isset($arrayVariable['start']))? $arrayVariable['start'] : 0; + $limit = (isset($arrayVariable['limit']))? $arrayVariable['limit'] : ''; - $cnn = \Propel::getConnection(($variableDbConnectionUid . "" != "") ? $variableDbConnectionUid : "workflow"); - $stmt = $cnn->createStatement(); + switch (($field !== null && isset($field->datasource))? $field->datasource : 'database') { + case 'dataVariable': + if (!isset($arrayVariable['app_uid'])) { + return []; + } - $replaceFields = G::replaceDataField($variableSql, $arrayVariable); - - $filter = ""; - if (isset($arrayVariable["filter"])) { - $filter = $arrayVariable["filter"]; - } - $start = 0; - if (isset($arrayVariable["start"])) { - $start = $arrayVariable["start"]; - } - $limit = ""; - if (isset($arrayVariable["limit"])) { - $limit = $arrayVariable["limit"]; - } - $parser = new \PHPSQLParser($replaceFields); - $filter = str_replace("'", "''", $filter); - $replaceFields = $this->queryModified($parser->parsed, $filter, "*searchtype*", $start, $limit); - $rs = $stmt->executeQuery($replaceFields, \ResultSet::FETCHMODE_NUM); + $applicationUid = $arrayVariable['app_uid']; - while ($rs->next()) { - $row = $rs->getRow(); + $case = new \ProcessMaker\BusinessModel\Cases(); - $arrayRecord[] = array( - strtolower("VALUE") => $row[0], - strtolower("TEXT") => isset($row[1]) ? $row[1] : $row[0] - ); + $arrayApplicationData = $case->getApplicationRecordByPk( + $applicationUid, ['$applicationUid' => 'app_uid'] + ); + + $case = new \Cases(); + + $arrayApplicationData['APP_DATA'] = $case->unserializeData($arrayApplicationData['APP_DATA']); + + $dataVariable = (preg_match('/^\s*@.(.+)\s*$/', $field->dataVariable, $arrayMatch))? + $arrayMatch[1] : $field->dataVariable; + + if (isset($arrayApplicationData['APP_DATA'][$dataVariable]) && + is_array($arrayApplicationData['APP_DATA'][$dataVariable]) && + !empty($arrayApplicationData['APP_DATA'][$dataVariable]) + ) { + foreach ($arrayApplicationData['APP_DATA'][$dataVariable] as $row) { + $value = $row[0]; + $text = (isset($row[1]))? $row[1] : $row[0]; + + if ($filter !== '') { + if (preg_match('/^.*' . $filter . '.*$/i', $text)) { + $arrayRecord[] = [strtolower('VALUE') => $value, strtolower('TEXT') => $text]; + } + } else { + $arrayRecord[] = [strtolower('VALUE') => $value, strtolower('TEXT') => $text]; + } + } + + $arrayRecord = array_slice( + $arrayRecord, + (int)($start), + ($limit !== '')? (int)($limit) : null + ); + } + break; + default: + //database + $dbConnection = ($field !== null && !empty($field->dbConnection))? $field->dbConnection : 'workflow'; + $variableSql = ($field !== null)? $field->sql : ''; + + $_SESSION['PROCESS'] = $processUid; + + $cnn = \Propel::getConnection($dbConnection); + $stmt = $cnn->createStatement(); + + $replaceFields = \G::replaceDataField($variableSql, $arrayVariable); + + $parser = new \PHPSQLParser($replaceFields); + + $replaceFields = $this->queryModified( + $parser->parsed, $filter, '*searchtype*', $start, $limit, $dbConnection + ); + $rs = $stmt->executeQuery($replaceFields, \ResultSet::FETCHMODE_NUM); + + while ($rs->next()) { + $row = $rs->getRow(); + + $value = $row[0]; + $text = (isset($row[1]))? $row[1] : $row[0]; + + $arrayRecord[] = [strtolower('VALUE') => $value, strtolower('TEXT') => $text]; + } + break; } //Return @@ -720,8 +804,8 @@ class Variable throw $e; } } - - public function queryModified($sqlParsed, $inputSel = "", $searchType, $start, $limit) + + public function queryModified($sqlParsed, $inputSel = "", $searchType = "*searchtype*", $start = 0, $limit = "", $dbConnection = "workflow") { if (!empty($sqlParsed['SELECT'])) { $sqlSelectOptions = (isset($sqlParsed["OPTIONS"]) && count($sqlParsed["OPTIONS"]) > 0) ? implode(" ", $sqlParsed["OPTIONS"]) : null; @@ -833,7 +917,7 @@ class Variable } else { $sqlOrderBy = " ORDER BY " . $sFieldSel; } - + $sqlLimit = ""; if ($start >= 0) { $sqlLimit = " LIMIT " . $start; @@ -845,6 +929,26 @@ class Variable $sqlLimit = " LIMIT " . $sqlParsed['LIMIT']['start'] . ", " . $sqlParsed['LIMIT']['end']; } + //get database provider + $a = new \Criteria("workflow"); + $a->addSelectColumn(\DbSourcePeer::DBS_TYPE); + $a->add(\DbSourcePeer::DBS_UID, $dbConnection, \Criteria::EQUAL); + $ds = \DbSourcePeer::doSelectRS($a); + $ds->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $ds->next(); + $row = $ds->getRow(); + if (isset($row["DBS_TYPE"])) { + if ($row["DBS_TYPE"] === "pgsql") { + $sqlLimit = $this->limitPgsql($start, $limit); + } + if ($row["DBS_TYPE"] === "mssql") { + return $this->limitMssqlOracle($sqlSelect, $sqlFrom, $sqlWhere, $sqlGroupBy, $sqlHaving, $sqlOrderBy, $start, $limit, true); + } + if ($row["DBS_TYPE"] === "oracle") { + return $this->limitMssqlOracle($sqlSelect, $sqlFrom, $sqlWhere, $sqlGroupBy, $sqlHaving, $sqlOrderBy, $start, $limit, false); + } + } + return $sqlSelect . $sqlFrom . $sqlWhere . $sqlGroupBy . $sqlHaving . $sqlOrderBy . $sqlLimit; } if (!empty($sqlParsed['CALL'])) { @@ -872,7 +976,37 @@ class Variable return $sCall; } } - + + public function limitPgsql($start = 0, $limit = "") + { + $sqlLimit = ""; + if ($start >= 0) { + $sqlLimit = " OFFSET " . $start; + } + if ($limit !== "") { + $sqlLimit = $sqlLimit . " LIMIT " . $limit; + } + return $sqlLimit; + } + + public function limitMssqlOracle($sqlSelect = "", $sqlFrom = "", $sqlWhere = "", $sqlGroupBy = "", $sqlHaving = "", $sqlOrderBy = "", $start = 0, $limit = "", $isMssql = true) + { + $sqlLimit = ""; + if ($start >= 0) { + $sqlLimit = "WHERE rn >= " . $start; + } + if ($start >= 0 && $limit != "") { + $sqlLimit = "WHERE rn BETWEEN " . $start . " AND " . $limit; + } + $sql = "" + . "SELECT * FROM (" + . " " . $sqlSelect . ", ROW_NUMBER() OVER( " . $sqlOrderBy . " desc )-1 " . ($isMssql ? " AS " : "") . " rn " + . " " . $sqlFrom . $sqlWhere . $sqlGroupBy . $sqlHaving + . ")" . ($isMssql ? " AS A " : "") + . $sqlLimit; + return $sql; + } + public function getVariableTypeByName($processUid, $variableName) { try { @@ -897,4 +1031,49 @@ class Variable } } -} \ No newline at end of file + /** + * Get Variable record by name + * + * @param string $projectUid Unique id of Project + * @param string $variableName Variable name + * @param array $arrayVariableNameForException Variable name for exception + * @param bool $throwException Flag to throw the exception if the main parameters are invalid or do not exist + * (TRUE: throw the exception; FALSE: returns FALSE) + * + * @return array Returns an array with Variable record, ThrowTheException/FALSE otherwise + */ + public function getVariableRecordByName( + $projectUid, + $variableName, + array $arrayVariableNameForException, + $throwException = true + ) { + try { + $criteria = new \Criteria('workflow'); + + $criteria->add(\ProcessVariablesPeer::PRJ_UID, $projectUid, \Criteria::EQUAL); + $criteria->add(\ProcessVariablesPeer::VAR_NAME, $variableName, \Criteria::EQUAL); + + $rsCriteria = \ProcessVariablesPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + $arrayVariableData = $rsCriteria->getRow(); + } else { + if ($throwException) { + throw new \Exception( + $arrayVariableNameForException['$variableName'] . ': ' . $variableName. ' ' . + \G::LoadTranslation('ID_DOES_NOT_EXIST') + ); + } else { + return false; + } + } + + //Return + return $arrayVariableData; + } catch (\Exception $e) { + throw $e; + } + } +} diff --git a/workflow/engine/src/ProcessMaker/Importer/Importer.php b/workflow/engine/src/ProcessMaker/Importer/Importer.php index 59f593cd7..afa53a949 100755 --- a/workflow/engine/src/ProcessMaker/Importer/Importer.php +++ b/workflow/engine/src/ProcessMaker/Importer/Importer.php @@ -12,6 +12,7 @@ abstract class Importer protected $filename = ""; protected $saveDir = ""; protected $metadata = array(); + public static $affectedGroups = array(); const IMPORT_OPTION_OVERWRITE = "project.import.override"; const IMPORT_OPTION_DISABLE_AND_CREATE_NEW = "project.import.disable_and_create_new"; @@ -26,6 +27,7 @@ abstract class Importer const IMPORT_STAT_TARGET_ALREADY_EXISTS = 101; //Error, Target Project already exists. const IMPORT_STAT_INVALID_SOURCE_FILE = 102; //Error, Invalid file type or the file have corrupt data. const IMPORT_STAT_GROUP_ALREADY_EXISTS = 105; //Error, Group already exists. + const IMPORTED_PROJECT_DOES_NOT_EXISTS = 106; public abstract function load($filename = null); @@ -69,7 +71,7 @@ abstract class Importer } } - public function import($option = self::IMPORT_OPTION_CREATE_NEW, $optionGroup = self::GROUP_IMPORT_OPTION_CREATE_NEW) + public function import($option = self::IMPORT_OPTION_CREATE_NEW, $optionGroup = self::GROUP_IMPORT_OPTION_CREATE_NEW, $generateUidFromJs = null) { $this->prepare(); @@ -92,6 +94,15 @@ abstract class Importer ), self::IMPORT_STAT_TARGET_ALREADY_EXISTS ); + } else { + if(is_null($generateUidFromJs)) { + throw new \Exception( + \G::LoadTranslation( + "ID_IMPORTER_PROJECT_DOES_NOT_EXISTS_SET_ACTION_TO_CONTINUE" + ), + self::IMPORTED_PROJECT_DOES_NOT_EXISTS + ); + } } break; case self::IMPORT_OPTION_OVERWRITE: @@ -109,6 +120,7 @@ abstract class Importer $arrayAux = $processes->checkExistingGroups($this->importData["tables"]["workflow"]["groupwfs"]); if (is_array($arrayAux) && count($arrayAux) > 0) { + self::$affectedGroups = $arrayAux; throw new \Exception( \G::LoadTranslation( "ID_IMPORTER_GROUP_ALREADY_EXISTS_SET_ACTION_TO_CONTINUE", @@ -140,6 +152,11 @@ abstract class Importer //Import $name = $this->importData["tables"]["bpmn"]["project"][0]["prj_name"]; + + if (\Process::existsByProTitle($name) && !is_null($generateUidFromJs)) { + $name = $name . ' ' . date('Y-m-d H:i:s'); + } + switch ($option) { case self::IMPORT_OPTION_CREATE_NEW: //Shouldn't generate new UID for all objects @@ -179,6 +196,9 @@ abstract class Importer $this->importData["tables"]["workflow"]["process"] = $this->importData["tables"]["workflow"]["process"][0]; //Import + if(!empty($generateUidFromJs)) { + $generateUid = $generateUidFromJs; + } $result = $this->doImport($generateUid); //Return diff --git a/workflow/engine/src/ProcessMaker/Project/Workflow.php b/workflow/engine/src/ProcessMaker/Project/Workflow.php index c3d5666e9..f49e9c925 100755 --- a/workflow/engine/src/ProcessMaker/Project/Workflow.php +++ b/workflow/engine/src/ProcessMaker/Project/Workflow.php @@ -66,6 +66,15 @@ class Workflow extends Handler $data['PRO_CATEGORY'] = array_key_exists('PRO_CATEGORY', $data) ? $data['PRO_CATEGORY'] : ""; try { + + // Check to make sure that there aren't any html sneaking into process titles. + + $testTitle = htmlspecialchars($data['PRO_TITLE']); + + if($testTitle != $data['PRO_TITLE']) { + $data['PRO_TITLE'] = $testTitle; + } + self::log("Create Process with data:", $data); //validate if process with specified name already exists diff --git a/workflow/engine/src/ProcessMaker/Services/Api/ActionsByEmail.php b/workflow/engine/src/ProcessMaker/Services/Api/ActionsByEmail.php index 266080f4a..ee6f24a36 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/ActionsByEmail.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/ActionsByEmail.php @@ -24,6 +24,21 @@ require_once 'classes/model/Users.php'; */ class ActionsByEmail extends Api { + private $actionsByEmail; + + /** + * Constructor of the class + * + * return void + */ + public function __construct() + { + try { + $this->actionsByEmail = new \ProcessMaker\BusinessModel\ActionsByEmail(); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } /** * @url GET @@ -39,489 +54,70 @@ class ActionsByEmail extends Api } /** - * + * * @url GET /editTemplate */ public function editTemplate($params) { - // Action Validations - if (!isset($_REQUEST['TEMPLATE'])) { - $_REQUEST['TEMPLATE'] = ''; - } - - if ($_REQUEST['TEMPLATE'] == '') { - throw new Exception('The TEMPLATE parameter is empty.'); - } - - $data = array( - 'CONTENT' => file_get_contents(PATH_DATA_MAILTEMPLATES . $_REQUEST['PRO_UID'] . PATH_SEP . $_REQUEST['TEMPLATE']), - 'TEMPLATE' => $_REQUEST['TEMPLATE'], - ); - - global $G_PUBLISH; - - $G_PUBLISH = new Publisher(); - $G_PUBLISH->AddContent('xmlform', 'xmlform', 'actionsByEmail/actionsByEmail_FileEdit', '', $data); - - G::RenderPage('publish', 'raw'); - die(); + $this->actionsByEmail->editTemplate($_REQUEST); } /** - * + * * @url PUT /updateTemplate */ public function updateTemplate($params) { - // Action Validations - if (!isset($_REQUEST['TEMPLATE'])) { - $_REQUEST['TEMPLATE'] = ''; - } - - if (!isset($_REQUEST['CONTENT'])) { - $_REQUEST['CONTENT'] = ''; - } - - if ($_REQUEST['TEMPLATE'] == '') { - throw new Exception('The TEMPLATE parameter is empty.'); - } - - $templateFile = fopen(PATH_DATA_MAILTEMPLATES . $_REQUEST['PRO_UID'] . PATH_SEP . $_REQUEST['TEMPLATE'], 'w'); - $content = stripslashes($_REQUEST['CONTENT']); - $content = str_replace('@amp@', '&', $content); - $content = base64_decode($content); - - fwrite($templateFile, $content); - fclose($templateFile); + $this->actionsByEmail->updateTemplate($_REQUEST); } /** - * + * * @url GET /loadFields */ public function loadFields($params) { - if (!isset($_REQUEST['DYN_UID'])) { - $_REQUEST['DYN_UID'] = ''; - } - - if (!isset($_REQUEST['PRO_UID'])) { - $_REQUEST['PRO_UID'] = ''; - } - - $response->emailFields = array(); - $response->actionFields = array(); - - if ($_REQUEST['PRO_UID'] != '' && $_REQUEST['DYN_UID']) { - $dynaform = new Form($_REQUEST['PRO_UID'] . PATH_SEP . $_REQUEST['DYN_UID'], PATH_DYNAFORM, SYS_LANG, false); - - foreach ($dynaform->fields as $fieldName => $data) { - switch ($data->type) { - case 'text': - case 'suggest': - case 'hidden': - case 'textarea': - $response->emailFields[] = array('value' => $data->name, 'label' => $data->label . ' (@@' . $data->name . ')'); - break; - case 'dropdown': - case 'radiogroup': - case 'yesno': - case 'checkbox': - $response->actionFields[] = array('value' => $data->name, 'label' => $data->label . ' (@@' . $data->name . ')'); - break; - } - } - } - return $response; + return $this->actionsByEmail->loadFields($_REQUEST); } /** - * + * * @url PUT /saveConfiguration */ public function saveConfiguration($params) { - if (!isset($_REQUEST['ABE_UID'])) { - $_REQUEST['ABE_UID'] = ''; - } - - if (!isset($_REQUEST['PRO_UID'])) { - $_REQUEST['PRO_UID'] = ''; - } - - if (!isset($_REQUEST['TAS_UID'])) { - $_REQUEST['TAS_UID'] = ''; - } - - if (!isset($_REQUEST['ABE_TYPE'])) { - $_REQUEST['ABE_TYPE'] = ''; - } - - if (!isset($_REQUEST['ABE_TEMPLATE'])) { - $_REQUEST['ABE_TEMPLATE'] = ''; - } - - if (!isset($_REQUEST['DYN_UID'])) { - $_REQUEST['DYN_UID'] = ''; - } - - if (!isset($_REQUEST['ABE_EMAIL_FIELD'])) { - $_REQUEST['ABE_EMAIL_FIELD'] = ''; - } - - if (!isset($_REQUEST['ABE_ACTION_FIELD'])) { - $_REQUEST['ABE_ACTION_FIELD'] = ''; - } - - if (!isset($_REQUEST['ABE_CASE_NOTE_IN_RESPONSE'])) { - $_REQUEST['ABE_CASE_NOTE_IN_RESPONSE'] = 0; - } - - if ($_REQUEST['PRO_UID'] == '') { - throw new Exception('The PRO_UID parameter is empty.'); - } - - if ($_REQUEST['TAS_UID'] == '') { - throw new Exception('The TAS_UID parameter is empty.'); - } - - require_once 'classes/model/AbeConfiguration.php'; - - $abeConfigurationInstance = new AbeConfiguration(); - - if ($_REQUEST['ABE_TYPE'] != '') { - if ($_REQUEST['DYN_UID'] == '') { - throw new Exception('The DYN_UID parameter is empty.'); - } - - try { - $response->ABE_UID = $abeConfigurationInstance->createOrUpdate($_REQUEST); - } catch (Exception $error) { - throw $error; - } - } else { - try { - $abeConfigurationInstance->deleteByTasUid($_REQUEST['TAS_UID']); - $response->ABE_UID = ''; - } catch (Exception $error) { - throw $error; - } - } - return $response; + return $this->actionsByEmail->saveConfiguration2($_REQUEST); } /** - * + * * @url GET /loadActionByEmail */ public function loadActionByEmail($params) { - $criteria = new Criteria(); - $criteria->addSelectColumn('COUNT(*)'); - - $criteria->addJoin(AbeConfigurationPeer::ABE_UID, AbeRequestsPeer::ABE_UID); - $criteria->addJoin(AppDelegationPeer::APP_UID, AbeRequestsPeer::APP_UID); - $criteria->addJoin(AppDelegationPeer::DEL_INDEX, AbeRequestsPeer::DEL_INDEX); - $result = AbeConfigurationPeer::doSelectRS($criteria); - $result->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $result->next(); - $totalCount = $result->getRow(); - $totalCount = $totalCount['COUNT(*)']; - - $criteria = new Criteria(); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::PRO_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::TAS_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_UPDATE_DATE); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_TEMPLATE); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_ACTION_FIELD); - $criteria->addSelectColumn(AbeConfigurationPeer::DYN_UID); - - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_UID); - $criteria->addSelectColumn(AbeRequestsPeer::APP_UID); - $criteria->addSelectColumn(AbeRequestsPeer::DEL_INDEX); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_SENT_TO); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_STATUS); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_SUBJECT); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_ANSWERED); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_BODY); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_DATE); - - $criteria->addSelectColumn(ApplicationPeer::APP_NUMBER); - - $criteria->addSelectColumn(AppDelegationPeer::DEL_PREVIOUS); - - $criteria->addJoin(AbeConfigurationPeer::ABE_UID, AbeRequestsPeer::ABE_UID); - $criteria->addJoin(ApplicationPeer::APP_UID, AbeRequestsPeer::APP_UID); - - $criteria->addJoin(AppDelegationPeer::APP_UID, AbeRequestsPeer::APP_UID); - $criteria->addJoin(AppDelegationPeer::DEL_INDEX, AbeRequestsPeer::DEL_INDEX); - $criteria->addDescendingOrderByColumn(AbeRequestsPeer::ABE_REQ_DATE); - $criteria->setLimit($_REQUEST['limit']); - $criteria->setOffset($_REQUEST['start']); - $result = AbeConfigurationPeer::doSelectRS($criteria); - $result->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $data = Array(); - $arrayPro = Array(); - $arrayTAS = Array(); - $index = 0; - - while ($result->next()) { - $data[] = $result->getRow(); - $criteriaRes = new Criteria(); - - $criteriaRes->addSelectColumn(AbeResponsesPeer::ABE_RES_UID); - $criteriaRes->addSelectColumn(AbeResponsesPeer::ABE_RES_CLIENT_IP); - $criteriaRes->addSelectColumn(AbeResponsesPeer::ABE_RES_DATA); - $criteriaRes->addSelectColumn(AbeResponsesPeer::ABE_RES_STATUS); - $criteriaRes->addSelectColumn(AbeResponsesPeer::ABE_RES_MESSAGE); - - $criteriaRes->add(AbeResponsesPeer::ABE_REQ_UID, $data[$index]['ABE_REQ_UID']); - - $resultRes = AbeResponsesPeer::doSelectRS($criteriaRes); - $resultRes->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $resultRes->next(); - $dataRes = Array(); - - if ($dataRes = $resultRes->getRow()) { - $data[$index]['ABE_RES_UID'] = $dataRes['ABE_RES_UID']; - $data[$index]['ABE_RES_CLIENT_IP'] = $dataRes['ABE_RES_CLIENT_IP']; - $data[$index]['ABE_RES_DATA'] = $dataRes['ABE_RES_DATA']; - $data[$index]['ABE_RES_STATUS'] = $dataRes['ABE_RES_STATUS']; - $data[$index]['ABE_RES_MESSAGE'] = $dataRes['ABE_RES_MESSAGE']; - } else { - $data[$index]['ABE_RES_UID'] = ''; - $data[$index]['ABE_RES_CLIENT_IP'] = ''; - $data[$index]['ABE_RES_DATA'] = ''; - $data[$index]['ABE_RES_STATUS'] = ''; - $data[$index]['ABE_RES_MESSAGE'] = ''; - } - - $criteriaRes = new Criteria(); - - $criteriaRes->addSelectColumn(AppDelegationPeer::USR_UID); - $criteriaRes->addSelectColumn(UsersPeer::USR_FIRSTNAME); - $criteriaRes->addSelectColumn(UsersPeer::USR_LASTNAME); - - $criteria->addJoin(AppDelegationPeer::APP_UID, $data[$index]['APP_UID']); - $criteria->addJoin(AppDelegationPeer::DEL_INDEX, $data[$index]['DEL_PREVIOUS']); - $criteria->addJoin(AppDelegationPeer::USR_UID, UsersPeer::USR_UID); - $resultRes = AppDelegationPeer::doSelectRS($criteriaRes); - $resultRes->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $resultRes->next(); - - if ($dataRes = $resultRes->getRow()) { - $data[$index]['USER'] = $dataRes['USR_FIRSTNAME'] . ' ' . $dataRes['USR_LASTNAME']; - } else { - $data[$index]['USER'] = ''; - } - - $data[$index]['ABE_REQ_ANSWERED'] = ($data[$index]['ABE_REQ_ANSWERED'] == 1) ? 'YES' : 'NO'; - $index++; - } - - $response = array(); - $response['totalCount'] = $totalCount; - $response['data'] = $data; - return $response; + return $this->actionsByEmail->loadActionByEmail($_REQUEST); } /** - * + * * @url POST /forwardMail */ public function forwardMail($params) { - if (!isset($_REQUEST['REQ_UID'])) { - $_REQUEST['REQ_UID'] = ''; - } - - $criteria = new Criteria(); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::PRO_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::TAS_UID); - - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_UID); - $criteria->addSelectColumn(AbeRequestsPeer::APP_UID); - $criteria->addSelectColumn(AbeRequestsPeer::DEL_INDEX); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_SENT_TO); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_SUBJECT); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_BODY); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_ANSWERED); - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_STATUS); - - $criteria->addSelectColumn(AppDelegationPeer::DEL_FINISH_DATE); - - $criteria->add(AbeRequestsPeer::ABE_REQ_UID, $_REQUEST['REQ_UID']); - $criteria->addJoin(AbeRequestsPeer::ABE_UID, AbeConfigurationPeer::ABE_UID); - $criteria->addJoin(AppDelegationPeer::APP_UID, AbeRequestsPeer::APP_UID); - $criteria->addJoin(AppDelegationPeer::DEL_INDEX, AbeRequestsPeer::DEL_INDEX); - $resultRes = AbeRequestsPeer::doSelectRS($criteria); - $resultRes->setFetchmode(ResultSet::FETCHMODE_ASSOC); - - $resultRes->next(); - $dataRes = Array(); - - if ($dataRes = $resultRes->getRow()) { - if (is_null($dataRes['DEL_FINISH_DATE'])) { - require_once 'classes/model/Configuration.php'; - G::LoadClass('spool'); - - $configuration = new Configuration(); - $sDelimiter = DBAdapter::getStringDelimiter(); - $criteria = new Criteria('workflow'); - $criteria->add(ConfigurationPeer::CFG_UID, 'Emails'); - $criteria->add(ConfigurationPeer::OBJ_UID, ''); - $criteria->add(ConfigurationPeer::PRO_UID, ''); - $criteria->add(ConfigurationPeer::USR_UID, ''); - $criteria->add(ConfigurationPeer::APP_UID, ''); - - if (ConfigurationPeer::doCount($criteria) == 0) { - $configuration->create(array('CFG_UID' => 'Emails', 'OBJ_UID' => '', 'CFG_VALUE' => '', 'PRO_UID' => '', 'USR_UID' => '', 'APP_UID' => '')); - $newConfiguration = array(); - } else { - $newConfiguration = $configuration->load('Emails', '', '', '', ''); - - if ($newConfiguration['CFG_VALUE'] != '') { - $newConfiguration = unserialize($newConfiguration['CFG_VALUE']); - } else { - $newConfiguration = array(); - } - } - - $spool = new spoolRun(); - $spool->setConfig(array( - 'MESS_ENGINE' => $newConfiguration['MESS_ENGINE'], - 'MESS_SERVER' => $newConfiguration['MESS_SERVER'], - 'MESS_PORT' => $newConfiguration['MESS_PORT'], - 'MESS_ACCOUNT' => $newConfiguration['MESS_ACCOUNT'], - 'MESS_PASSWORD' => $newConfiguration['MESS_PASSWORD'], - 'SMTPAuth' => $newConfiguration['MESS_RAUTH'] - )); - - $spool->create(array( - 'msg_uid' => '', - 'app_uid' => $dataRes['APP_UID'], - 'del_index' => $dataRes['DEL_INDEX'], - 'app_msg_type' => 'TEST', - 'app_msg_subject' => $dataRes['ABE_REQ_SUBJECT'], - 'app_msg_from' => $newConfiguration['MESS_ACCOUNT'], - 'app_msg_to' => $dataRes['ABE_REQ_SENT_TO'], - 'app_msg_body' => $dataRes['ABE_REQ_BODY'], - 'app_msg_cc' => '', - 'app_msg_bcc' => '', - 'app_msg_attach' => '', - 'app_msg_template' => '', - 'app_msg_status' => 'pending' - )); - - if ($spool->sendMail()) { - $dataRes['ABE_REQ_STATUS'] = 'SENT'; - - $message = 'The email was resend to: ' . $dataRes['ABE_REQ_SENT_TO']; - } else { - $dataRes['ABE_REQ_STATUS'] = 'ERROR'; - $message = 'There was a problem sending the email to: ' . $dataRes['ABE_REQ_SENT_TO'] . ', please try later.'; - } - - try { - $abeRequestsInstance = new AbeRequests(); - $abeRequestsInstance->createOrUpdate($dataRes); - } catch (Exception $error) { - throw $error; - } - } else { - $message = 'Unable to send email, the task is closed.'; - } - } else { - $message = 'An unexpected error occurred please try again later.'; - } - - return $message; + return $this->actionsByEmail->forwardMail($_REQUEST); } /** - * + * * @url GET /viewForm */ public function viewForm($params) { - //coment - if (!isset($_REQUEST['REQ_UID'])) { - $_REQUEST['REQ_UID'] = ''; - } - - $criteria = new Criteria(); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::PRO_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::TAS_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::DYN_UID); - $criteria->addSelectColumn(AbeConfigurationPeer::ABE_ACTION_FIELD); - - $criteria->addSelectColumn(AbeRequestsPeer::ABE_REQ_UID); - $criteria->addSelectColumn(AbeRequestsPeer::APP_UID); - $criteria->addSelectColumn(AbeRequestsPeer::DEL_INDEX); - - $criteria->addSelectColumn(AbeResponsesPeer::ABE_RES_UID); - $criteria->addSelectColumn(AbeResponsesPeer::ABE_RES_DATA); - - - $criteria->add(AbeRequestsPeer::ABE_REQ_UID, $_REQUEST['REQ_UID']); - $criteria->addJoin(AbeRequestsPeer::ABE_UID, AbeConfigurationPeer::ABE_UID); - $criteria->addJoin(AbeResponsesPeer::ABE_REQ_UID, AbeRequestsPeer::ABE_REQ_UID); - $resultRes = AbeRequestsPeer::doSelectRS($criteria); - $resultRes->setFetchmode(ResultSet::FETCHMODE_ASSOC); - - $resultRes->next(); - $dataRes = Array(); - $message = 'The user has not responded to this request.'; - - if ($dataRes = $resultRes->getRow()) { - $_SESSION['CURRENT_DYN_UID'] = trim($dataRes['DYN_UID']); - $dynaform = new Form($dataRes['PRO_UID'] . PATH_SEP . trim($dataRes['DYN_UID']), PATH_DYNAFORM, SYS_LANG, false); - $dynaform->mode = 'view'; - - if ($dataRes['ABE_RES_DATA'] != '') { - $value = unserialize($dataRes['ABE_RES_DATA']); - - if (is_array($value)) { - $dynaform->values = $value; - - foreach ($dynaform->fields as $fieldName => $field) { - if ($field->type == 'submit') { - unset($dynaform->fields[$fieldName]); - } - } - - $message = $dynaform->render(PATH_CORE . 'templates/xmlform.html', $scriptCode); - } else { - $response = $dynaform->render(PATH_CORE . 'templates/xmlform.html', $scriptCode); - $field = $dynaform->fields[$dataRes['ABE_ACTION_FIELD']]; - $message = 'Type: ' . $field->type . '
'; - - switch ($field->type) { - case 'dropdown': - case 'radiogroup': - $message .=$field->label . ' - '; - $message .= $field->options[$value]; - break; - case 'yesno': - $message .= '' . $field->label . ' - '; - $message .= ($value == 1) ? 'Yes' : 'No'; - break; - case 'checkbox': - $message .= '' . $field->label . ' - '; - $message .= ($value == 'On') ? 'Check' : 'Uncheck'; - break; - } - } - } - } - return $message; + return $this->actionsByEmail->viewForm($_REQUEST); } /** - * + * * @url GET /Templates/:proId */ public function getTemplates($proId) diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Cases.php b/workflow/engine/src/ProcessMaker/Services/Api/Cases.php index 090b2f5a0..2f795bcbe 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Cases.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Cases.php @@ -1110,4 +1110,42 @@ class Cases extends Api throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); } } + + + /** + * Mark a task process as a bookmark + * @url POST /bookmark/:tas_uid + * + * @param string $tas_uid {@min 32}{@max 32} + * + */ + public function doPostBookmarkStartCase($tas_uid) + { + try { + $userLoggedUid = $this->getUserId(); + $user = new \ProcessMaker\BusinessModel\User(); + $user->updateBookmark($userLoggedUid, $tas_uid, 'INSERT'); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * Remove a task process from bookmarks + * @url DELETE /bookmark/:tas_uid + * + * @param string $tas_uid {@min 32}{@max 32} + * + */ + public function doDeleteBookmarkStartCase($tas_uid) + { + try { + $userLoggedUid = $this->getUserId(); + $user = new \ProcessMaker\BusinessModel\User(); + $user->updateBookmark($userLoggedUid, $tas_uid, 'DELETE'); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + } diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Cases/Variable.php b/workflow/engine/src/ProcessMaker/Services/Api/Cases/Variable.php new file mode 100644 index 000000000..61620f006 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Services/Api/Cases/Variable.php @@ -0,0 +1,147 @@ +variable = new \ProcessMaker\BusinessModel\Cases\Variable(); + $this->variable->setRunningWorkflow(false); + $this->variable->setArrayVariableNameForException([ + '$applicationUid' => 'app_uid', + '$delIndex' => 'del_index', + '$variableName' => 'var_name', + '$filter' => 'filter', + '$start' => 'start', + '$limit' => 'limit', + '$arrayKey' => 'keys' + ]); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * @url GET /:app_uid/:del_index/variable/:var_name/paged + * @url GET /:app_uid/:del_index/variable/:var_name + * + * @param string $app_uid {@min 32}{@max 32} + * @param int $del_index {@min 1} + * @param string $var_name + */ + public function doGetVariable( + $app_uid, + $del_index, + $var_name, + $filter = null, + $lfilter = null, + $rfilter = null, + $start = null, + $limit = null + ) { + try { + if (preg_match("/^.*\/paged.*$/", $this->restler->url)) { + $arrayFilterData = [ + 'filter' => (!is_null($filter))? + $filter : ((!is_null($lfilter))? $lfilter : ((!is_null($rfilter))? $rfilter : null)), + 'filterOption' => (!is_null($filter))? + '' : ((!is_null($lfilter))? 'LEFT' : ((!is_null($rfilter))? 'RIGHT' : '')) + ]; + + $response = $this->variable->getVariableByNamePaged( + $app_uid, $del_index, $var_name, $arrayFilterData, $start, $limit + ); + } else { + $response = $this->variable->getVariableByName($app_uid, $del_index, $var_name); + } + + return \ProcessMaker\Util\DateTime::convertUtcToIso8601($response); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * @url POST /:app_uid/:del_index/variable/:var_name + * + * @param string $app_uid {@min 32}{@max 32} + * @param int $del_index {@min 1} + * @param string $var_name + * @param array $request_data + * + * @status 201 + */ + public function doPostVariable($app_uid, $del_index, $var_name, array $request_data) + { + try { + $response = $this->variable->create($app_uid, $del_index, $var_name, $request_data); + + return \ProcessMaker\Util\DateTime::convertUtcToIso8601($response); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * @url PUT /:app_uid/:del_index/variable/:var_name + * + * @param string $app_uid {@min 32}{@max 32} + * @param int $del_index {@min 1} + * @param string $var_name + * @param array $request_data + * + * @status 204 + */ + public function doPutVariable($app_uid, $del_index, $var_name, array $request_data) + { + try { + $response = $this->variable->update($app_uid, $del_index, $var_name, $request_data); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * @url DELETE /:app_uid/:del_index/variable/:var_name + * + * @param string $app_uid {@min 32}{@max 32} + * @param int $del_index {@min 1} + * @param string $var_name + */ + public function doDeleteVariable($app_uid, $del_index, $var_name, $keys = null) + { + try { + $arrayKey = null; + + if (!is_null($keys)) { + $keys = trim($keys, ' ,'); + $arrayKey = explode(',', $keys); + + if ($keys == '' || !is_array($arrayKey)) { + throw new \Exception(\G::LoadTranslation('ID_INVALID_VALUE', ['keys'])); + } + } + + $response = $this->variable->delete($app_uid, $del_index, $var_name, $arrayKey); + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } +} + diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Department.php b/workflow/engine/src/ProcessMaker/Services/Api/Department.php index 0ddf30dd3..6c78f01df 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Department.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Department.php @@ -114,20 +114,19 @@ class Department extends Api } /** - * @url PUT /:dep_uid/unassign-user/:usr_uid + * @url DELETE /:dep_uid/unassign-user/:usr_uid * * @param string $dep_uid {@min 1}{@max 32} * @param string $usr_uid {@min 1}{@max 32} * - * @return array + * @status 200 * */ - public function doPutUnassignUser($dep_uid, $usr_uid) + public function doDeleteUnassignUser($dep_uid, $usr_uid) { try { $oDepartment = new \ProcessMaker\BusinessModel\Department(); - $response = $oDepartment->unassignUser($dep_uid, $usr_uid); - return $response; + $oDepartment->unassignUser($dep_uid, $usr_uid); } catch (\Exception $e) { throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); } diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Light.php b/workflow/engine/src/ProcessMaker/Services/Api/Light.php index 91e2eda75..a235b39af 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Light.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Light.php @@ -20,7 +20,7 @@ class Light extends Api private $arrayFieldIso8601 = [ // request lists - 'newestthan', + 'newerThan', 'oldestthan', //return lists 'date', @@ -39,9 +39,25 @@ class Light extends Api { try { $userId = $this->getUserId(); - $lists = new \ProcessMaker\BusinessModel\Lists(); - $response = $lists->getCounters($userId); - $result = $this->parserCountersCases($response); + + /*----------------------------------********---------------------------------*/ + if (true) { + //In enterprise version this block of code should always be executed + //In community version this block of code is deleted and is executed the other + $list = new \ProcessMaker\BusinessModel\Lists(); + $arrayListCounter = $list->getCounters($userId); + } else { + /*----------------------------------********---------------------------------*/ + $case = new \ProcessMaker\BusinessModel\Cases(); + $arrayListCounter = $case->getListCounters( + $userId, + ['to_do', 'draft', 'sent', 'selfservice', 'paused', 'completed', 'cancelled'] + ); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + + $result = $this->parserCountersCases($arrayListCounter); } catch (\Exception $e) { throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); } @@ -58,12 +74,23 @@ class Light extends Api "CASES_PAUSED" => "paused", "CASES_COMPLETED" => "completed", "CASES_SELFSERVICE" => "unassigned", + 'to_do' => 'toDo', + 'draft' => 'draft', + 'cancelled' => 'cancelled', + 'sent' => 'participated', + 'paused' => 'paused', + 'completed' => 'completed', + 'selfservice' => 'unassigned' ); $response = array(); - foreach ($data as $counterList) { + foreach ($data as $key => $counterList) { if(isset($structure[$counterList['item']])){ $name = $structure[$counterList['item']]; $response[$name] = $counterList['count']; + } else { + if (isset($structure[$key])) { + $response[$structure[$key]] = $counterList; + } } } return $response; @@ -105,8 +132,7 @@ class Light extends Api $filter = '', $date_from = '', $date_to = '', - $action = '', - $newestthan = '', + $newerThan = '', $oldestthan ='' ) { try { @@ -116,22 +142,34 @@ class Light extends Api $dataList['start'] = $start; $dataList['limit'] = $limit; $dataList['sort'] = $sort; - $dataList['dir'] = ($newestthan != '') ? 'ASC':$dir; + $dataList['dir'] = $dir; $dataList['category'] = $cat_uid; $dataList['process'] = $pro_uid; $dataList['search'] = $search; $dataList['filter'] = $filter; $dataList['dateFrom'] = $date_from; $dataList['dateTo'] = $date_to; - $dataList['action'] = $action; - $dataList['newestthan'] = $newestthan; - $dataList['oldestthan'] = $oldestthan; + $dataList['newerThan'] = $newerThan; + $dataList['oldestthan'] = $oldestthan; Validator::throwExceptionIfDataNotMetIso8601Format($dataList, $this->arrayFieldIso8601); $dataList = DateTime::convertDataToUtc($dataList, $this->arrayFieldIso8601); - $lists = new \ProcessMaker\BusinessModel\Lists(); - $response = $lists->getList('inbox', $dataList); - if ($newestthan != '') { + + /*----------------------------------********---------------------------------*/ + if (true) { + //In enterprise version this block of code should always be executed + //In community version this block of code is deleted and is executed the other + $list = new \ProcessMaker\BusinessModel\Lists(); + $response = $list->getList('inbox', $dataList); + } else { + /*----------------------------------********---------------------------------*/ + $case = new \ProcessMaker\BusinessModel\Cases(); + $response = $case->getList($dataList); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + + if ($newerThan != '') { $response['data'] = array_reverse($response['data']); } $result = $this->parserDataTodo($response['data']); @@ -189,7 +227,7 @@ class Light extends Api $cat_uid = '', $pro_uid = '', $search = '', - $newestthan = '', + $newerThan = '', $oldestthan ='' ) { try { @@ -200,18 +238,31 @@ class Light extends Api $dataList['start'] = $start; $dataList['limit'] = $limit; $dataList['sort'] = $sort; - $dataList['dir'] = ($newestthan != '') ? 'ASC':$dir; + $dataList['dir'] = $dir; $dataList['category'] = $cat_uid; $dataList['process'] = $pro_uid; $dataList['search'] = $search; - $dataList['newestthan'] = $newestthan; - $dataList['oldestthan'] = $oldestthan; + $dataList['newerThan'] = $newerThan; + $dataList['oldestthan'] = $oldestthan; Validator::throwExceptionIfDataNotMetIso8601Format($dataList, $this->arrayFieldIso8601); $dataList = DateTime::convertDataToUtc($dataList, $this->arrayFieldIso8601); - $oCases = new \ProcessMaker\BusinessModel\Lists(); - $response = $oCases->getList('inbox', $dataList); - if ($newestthan != '') { + + /*----------------------------------********---------------------------------*/ + if (true) { + //In enterprise version this block of code should always be executed + //In community version this block of code is deleted and is executed the other + $list = new \ProcessMaker\BusinessModel\Lists(); + $response = $list->getList('inbox', $dataList); + } else { + /*----------------------------------********---------------------------------*/ + $case = new \ProcessMaker\BusinessModel\Cases(); + $response = $case->getList($dataList); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + + if ($newerThan != '') { $response['data'] = array_reverse($response['data']); } $result = $this->parserDataDraft($response['data']); @@ -234,11 +285,11 @@ class Light extends Api 'user' => array( 'USR_UID' => 'userId' ), - 'prevUser' => array( - 'PREVIOUS_USR_UID' => 'userId', - 'PREVIOUS_USR_FIRSTNAME' => 'firstName', - 'PREVIOUS_USR_LASTNAME' => 'lastName', - 'PREVIOUS_USR_USERNAME' => 'fullName', + 'currentUser' => array( + 'USR_UID' => 'userId', + 'USR_FIRSTNAME' => 'firstName', + 'USR_LASTNAME' => 'lastName', + 'USR_USERNAME' => 'fullName', ), 'process' => array( 'PRO_UID' => 'processId', @@ -274,18 +325,19 @@ class Light extends Api $filter = '', $date_from = '', $date_to = '', - $newestthan = '', + $newerThan = '', $oldestthan ='' ) { try { $dataList['userId'] = $this->getUserId(); + $dataList['action'] = 'sent'; $dataList['paged'] = $paged; $dataList['count'] = $count; $dataList['start'] = $start; $dataList['limit'] = $limit; $dataList['sort'] = $sort; - $dataList['dir'] = ($newestthan != '') ? 'ASC':$dir; + $dataList['dir'] = $dir; $dataList['category'] = $category; $dataList['process'] = $process; @@ -293,14 +345,27 @@ class Light extends Api $dataList['filter'] = $filter; $dataList['dateFrom'] = $date_from; $dataList['dateTo'] = $date_to; - $dataList['newestthan'] = $newestthan; + $dataList['newerThan'] = $newerThan; $dataList['oldestthan'] = $oldestthan; Validator::throwExceptionIfDataNotMetIso8601Format($dataList, $this->arrayFieldIso8601); $dataList = DateTime::convertDataToUtc($dataList, $this->arrayFieldIso8601); - $oCases = new \ProcessMaker\BusinessModel\Lists(); - $response = $oCases->getList('participated_last', $dataList); - if ($newestthan != '') { + + /*----------------------------------********---------------------------------*/ + if (true) { + //In enterprise version this block of code should always be executed + //In community version this block of code is deleted and is executed the other + $list = new \ProcessMaker\BusinessModel\Lists(); + $response = $list->getList('participated_last', $dataList); + } else { + /*----------------------------------********---------------------------------*/ + $case = new \ProcessMaker\BusinessModel\Cases(); + $response = $case->getList($dataList); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + + if ($newerThan != '') { $response['data'] = array_reverse($response['data']); } $result = $this->parserDataParticipated($response['data']); @@ -363,7 +428,9 @@ class Light extends Api $search = '', $filter = '', $date_from = '', - $date_to = '' + $date_to = '', + $newerThan = '', + $oldestthan = '' ) { try { $dataList['userId'] = $this->getUserId(); @@ -380,8 +447,23 @@ class Light extends Api $dataList['filter'] = $filter; $dataList['dateFrom'] = $date_from; $dataList['dateTo'] = $date_to; - $lists = new \ProcessMaker\BusinessModel\Lists(); - $response = $lists->getList('paused', $dataList); + $dataList['newerThan'] = $newerThan; + $dataList['oldestthan'] = $oldestthan; + + /*----------------------------------********---------------------------------*/ + if (true) { + //In enterprise version this block of code should always be executed + //In community version this block of code is deleted and is executed the other + $list = new \ProcessMaker\BusinessModel\Lists(); + $response = $list->getList('paused', $dataList); + } else { + /*----------------------------------********---------------------------------*/ + $case = new \ProcessMaker\BusinessModel\Cases(); + $response = $case->getList($dataList); + /*----------------------------------********---------------------------------*/ + } + /*----------------------------------********---------------------------------*/ + $result = $this->parserDataParticipated($response['data']); return DateTime::convertUtcToIso8601($result, $this->arrayFieldIso8601); } catch (\Exception $e) { @@ -440,7 +522,7 @@ class Light extends Api $cat_uid = '', $pro_uid = '', $search = '', - $newestthan = '', + $newerThan = '', $oldestthan ='' ) { try { @@ -451,11 +533,11 @@ class Light extends Api $dataList['start'] = $start; $dataList['limit'] = $limit; $dataList['sort'] = $sort; - $dataList['dir'] = ($newestthan != '') ? 'ASC':$dir; + $dataList['dir'] = $dir; $dataList['category'] = $cat_uid; $dataList['process'] = $pro_uid; $dataList['search'] = $search; - $dataList['newestthan'] = $newestthan; + $dataList['newerThan'] = $newerThan; $dataList['oldestthan'] = $oldestthan; Validator::throwExceptionIfDataNotMetIso8601Format($dataList, $this->arrayFieldIso8601); $dataList = DateTime::convertDataToUtc($dataList, $this->arrayFieldIso8601); @@ -511,13 +593,27 @@ class Light extends Api if (is_array($d)) { $newData = array(); foreach ($d as $field => $value) { - if (array_key_exists($field, $structure)) { - $newName = $structure[$field]; + if ( + preg_match( + '/\|(' . $field . ')\|/i', + '|' . implode('|', array_keys($structure)) . '|', + $arrayMatch + ) && + !is_array($structure[$arrayMatch[1]]) + ) { + $newName = $structure[$arrayMatch[1]]; $newData[$newName] = is_null($value) ? "":$value; } else { foreach ($structure as $name => $str) { - if (is_array($str) && array_key_exists($field, $str)) { - $newName = $str[$field]; + if (is_array($str) && + preg_match( + '/\|(' . $field . ')\|/i', + '|' . implode('|', array_keys($str)) . '|', + $arrayMatch + ) && + !is_array($str[$arrayMatch[1]]) + ) { + $newName = $str[$arrayMatch[1]]; $newData[$name][$newName] = is_null($value) ? "":$value; } } @@ -526,13 +622,27 @@ class Light extends Api if (count($newData) > 0) $response[] = $newData; } else { - if (array_key_exists($field, $structure)) { - $newName = $structure[$field]; + if ( + preg_match( + '/\|(' . $field . ')\|/i', + '|' . implode('|', array_keys($structure)) . '|', + $arrayMatch + ) && + !is_array($structure[$arrayMatch[1]]) + ) { + $newName = $structure[$arrayMatch[1]]; $response[$newName] = is_null($d) ? "":$d; } else { foreach ($structure as $name => $str) { - if (is_array($str) && array_key_exists($field, $str)) { - $newName = $str[$field]; + if (is_array($str) && + preg_match( + '/\|(' . $field . ')\|/i', + '|' . implode('|', array_keys($str)) .'|', + $arrayMatch + ) && + !is_array($str[$arrayMatch[1]]) + ) { + $newName = $str[$arrayMatch[1]]; $response[$name][$newName] = is_null($d) ? "":$d; } } diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm/Grid.php b/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm/Grid.php new file mode 100644 index 000000000..e24ff4854 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Services/Api/Project/DynaForm/Grid.php @@ -0,0 +1,75 @@ +grid = new \ProcessMaker\BusinessModel\DynaForm\Grid(); + $this->grid->setRunningWorkflow(false); + $this->grid->setArrayVariableNameForException([ + '$projectUid' => 'prj_uid', + '$dynaFormUid' => 'dyn_uid', + '$gridName' => 'grd_name', + '$fieldId' => 'fld_id' + ]); + + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * @url GET /:prj_uid/dynaform/:dyn_uid/grid/:grd_name/field-definitions + * + * @param string $prj_uid {@min 32}{@max 32} + * @param string $dyn_uid {@min 32}{@max 32} + * @param string $grd_name + */ + public function doGetDynaFormGridFieldDefinitions($prj_uid, $dyn_uid, $grd_name) + { + try { + $response = $this->grid->getGridFieldDefinitions($dyn_uid, $grd_name); + + return $response; + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } + + /** + * @url GET /:prj_uid/dynaform/:dyn_uid/grid/:grd_name/field-definition/:fld_id + * + * @param string $prj_uid {@min 32}{@max 32} + * @param string $dyn_uid {@min 32}{@max 32} + * @param string $grd_name + * @param string $fld_id + */ + public function doGetDynaFormGridFieldDefinition($prj_uid, $dyn_uid, $grd_name, $fld_id) + { + try { + $response = $this->grid->getGridFieldDefinition($dyn_uid, $grd_name, $fld_id); + + return $response; + } catch (\Exception $e) { + throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + } + } +} + diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Project/ProcessSupervisors.php b/workflow/engine/src/ProcessMaker/Services/Api/Project/ProcessSupervisors.php index 1d2575ea2..1bfe40447 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Project/ProcessSupervisors.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Project/ProcessSupervisors.php @@ -31,7 +31,7 @@ class ProcessSupervisors extends Api return (preg_match("/^.*\/paged.*$/", $this->restler->url))? $response : $response["data"]; } catch (\Exception $e) { - throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); + throw new RestException(Api::STAT_APP_EXCEPTION, htmlspecialchars($e->getMessage())); } } diff --git a/workflow/engine/src/ProcessMaker/Services/Api/Project/TimerEvent.php b/workflow/engine/src/ProcessMaker/Services/Api/Project/TimerEvent.php index b439b6c90..62d40a8ce 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/Project/TimerEvent.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/Project/TimerEvent.php @@ -118,7 +118,9 @@ class TimerEvent extends Api public function doPutTimerEvent($prj_uid, $tmrevn_uid, array $request_data) { try { - $arrayData = $this->timerEvent->update($tmrevn_uid, $request_data); + \ProcessMaker\BusinessModel\Validator::throwExceptionIfDataNotMetIso8601Format($request_data, $this->arrayFieldIso8601); + + $arrayData = $this->timerEvent->update($tmrevn_uid, \ProcessMaker\Util\DateTime::convertDataToUtc($request_data, $this->arrayFieldIso8601)); } catch (\Exception $e) { throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); } diff --git a/workflow/engine/src/ProcessMaker/Services/Api/System.php b/workflow/engine/src/ProcessMaker/Services/Api/System.php index 9e49e74ae..b29647e26 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/System.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/System.php @@ -65,7 +65,8 @@ class System extends Api try { $enabledFeatures = array(); /*----------------------------------********---------------------------------*/ - $keys = array ('zLhSk5TeEQrNFI2RXFEVktyUGpnczV1WEJNWVp6cjYxbTU3R29mVXVZNWhZQT0='); + $keys = array ('zLhSk5TeEQrNFI2RXFEVktyUGpnczV1WEJNWVp6cjYxbTU3R29mVXVZNWhZQT0=', + 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0='); foreach ($keys as $key) { if (\PMLicensedFeatures ::getSingleton() diff --git a/workflow/engine/src/ProcessMaker/Services/Api/User.php b/workflow/engine/src/ProcessMaker/Services/Api/User.php index 199184939..2bb1ee0e3 100644 --- a/workflow/engine/src/ProcessMaker/Services/Api/User.php +++ b/workflow/engine/src/ProcessMaker/Services/Api/User.php @@ -143,43 +143,5 @@ class User extends Api throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); } } - - /** - * Save Bookmark start case - * @url POST /bookmark/:tas_uid - * - * @param string $tas_uid {@min 32}{@max 32} - * - */ - public function doPostBookmarkStartCase($tas_uid) - { - try { - $userLoggedUid = $this->getUserId(); - $user = new \ProcessMaker\BusinessModel\User(); - $user->updateBookmark($userLoggedUid, $tas_uid, 'INSERT'); - return array('bookmarkedTaskId'=>$tas_uid); - } catch (\Exception $e) { - throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); - } - } - - /** - * Delete Bookmark start case - * @url DELETE /bookmark/:tas_uid - * - * @param string $tas_uid {@min 32}{@max 32} - * - */ - public function doDeleteBookmarkStartCase($tas_uid) - { - try { - $userLoggedUid = $this->getUserId(); - $user = new \ProcessMaker\BusinessModel\User(); - $user->updateBookmark($userLoggedUid, $tas_uid, 'DELETE'); - return array('unbookmarkedTaskId'=>$tas_uid); - } catch (\Exception $e) { - throw new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()); - } - } } diff --git a/workflow/engine/src/ProcessMaker/Services/Google/Authentication.php b/workflow/engine/src/ProcessMaker/Services/Google/Authentication.php index fadfdf02b..b1d9537ad 100644 --- a/workflow/engine/src/ProcessMaker/Services/Google/Authentication.php +++ b/workflow/engine/src/ProcessMaker/Services/Google/Authentication.php @@ -23,7 +23,8 @@ class Authentication // define options $optArray = array( CURLOPT_URL => $url, - CURLOPT_RETURNTRANSFER => true + CURLOPT_RETURNTRANSFER => true, + CURLOPT_SSL_VERIFYPEER => false ); // apply those options curl_setopt_array($ch, $optArray); @@ -33,7 +34,7 @@ class Authentication // Check if any error occurred if(curl_errno($ch)) { - throw (new \Exception(\G::LoadTranslation( 'ID_TO_URL' ))); + throw (new \Exception(curl_error($ch))); } $info = curl_getinfo($ch); curl_close($ch); diff --git a/workflow/engine/src/ProcessMaker/Services/api.ini b/workflow/engine/src/ProcessMaker/Services/api.ini index 6eedd3c3a..9c05af1ba 100644 --- a/workflow/engine/src/ProcessMaker/Services/api.ini +++ b/workflow/engine/src/ProcessMaker/Services/api.ini @@ -21,6 +21,7 @@ debug = 1 trigger2 = "ProcessMaker\Services\Api\Project\Trigger" event = "ProcessMaker\Services\Api\Project\Event" dynaform = "ProcessMaker\Services\Api\Project\DynaForm" + grid = "ProcessMaker\Services\Api\Project\DynaForm\Grid" input-document = "ProcessMaker\Services\Api\Project\InputDocument" output-documents = "ProcessMaker\Services\Api\Project\OutputDocuments" supervisors = "ProcessMaker\Services\Api\Project\ProcessSupervisors" @@ -72,6 +73,7 @@ debug = 1 [alias: case] case = "ProcessMaker\Services\Api\Cases" + variable = "ProcessMaker\Services\Api\Cases\Variable" [alias: cases] case = "ProcessMaker\Services\Api\Cases" diff --git a/workflow/engine/src/ProcessMaker/Util/ElementTranslation.php b/workflow/engine/src/ProcessMaker/Util/ElementTranslation.php new file mode 100644 index 000000000..cfd3679b4 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Util/ElementTranslation.php @@ -0,0 +1,100 @@ + ['table' => 'APPLICATION', 'uid' => 'APP_UID', 'ownedByProcess' => true, 'className' => 'Application'], + 'APP_DOC_COMMENT' => ['table' => 'APPLICATION', 'uid' => 'APP_UID', 'ownedByProcess' => true, 'className' => 'Application'], + 'APP_DOC_FILENAME' => ['table' => 'APPLICATION', 'uid' => 'APP_UID', 'ownedByProcess' => true, 'className' => 'Application'], + 'APP_DOC_TITLE' => ['table' => 'APPLICATION', 'uid' => 'APP_UID', 'ownedByProcess' => true, 'className' => 'Application'], + 'APP_TITLE' => ['table' => 'APPLICATION', 'uid' => 'APP_UID', 'ownedByProcess' => true, 'className' => 'Application'], + 'PRO_TITLE' => ['table' => 'PROCESS', 'uid' => 'PRO_UID', 'ownedByProcess' => false, 'className' => 'Process'], + 'PRO_DESCRIPTION' => ['table'=>'PROCESS', 'uid'=>'PRO_UID', 'ownedByProcess'=>false, 'className'=>'Process'], + 'TAS_DEF_MESSAGE' => ['table' => 'TASK', 'uid' => 'TAS_UID', 'ownedByProcess' => true, 'className' => 'Task'], + 'TAS_TITLE' => ['table' => 'TASK', 'uid' => 'TAS_UID', 'ownedByProcess' => true, 'className' => 'Task'], + 'TAS_DEF_DESCRIPTION' => ['table'=>'TASK', 'uid'=>'TAS_UID', 'ownedByProcess'=>true, 'className'=>'Task'], + 'TAS_DEF_PROC_CODE' => ['table'=>'TASK', 'uid'=>'TAS_UID', 'ownedByProcess'=>true, 'className'=>'Task'], + 'TAS_DEF_SUBJECT_MESSAGE' => ['table'=>'TASK', 'uid'=>'TAS_UID', 'ownedByProcess'=>true, 'className'=>'Task'], + 'TAS_DEF_TITLE' => ['table'=>'TASK', 'uid'=>'TAS_UID', 'ownedByProcess'=>true, 'className'=>'Task'], + 'TAS_DESCRIPTION' => ['table'=>'TASK', 'uid'=>'TAS_UID', 'ownedByProcess'=>true, 'className'=>'Task'], + 'DYN_TITLE' => ['table'=>'DYNAFORM', 'uid'=>'DYN_UID', 'ownedByProcess'=>true, 'className'=>'Dynaform'], + 'DYN_DESCRIPTION' => ['table'=>'DYNAFORM', 'uid'=>'DYN_UID', 'ownedByProcess'=>true, 'className'=>'Dynaform'], + 'GRP_TITLE' => ['table'=>'GROUPWF', 'uid'=>'GRP_UID', 'ownedByProcess'=>false, 'className'=>'Groupwf'], + 'DEPO_TITLE' => ['table'=>'DEPARTMENT', 'uid'=>'DEP_UID', 'ownedByProcess'=>false, 'className'=>'Department'], + 'INP_DOC_DESCRIPTION' => ['table'=>'INPUT_DOCUMENT', 'uid'=>'INP_DOC_UID', 'ownedByProcess'=>true, 'className'=>'InputDocument'], + 'INP_DOC_TITLE' => ['table'=>'INPUT_DOCUMENT', 'uid'=>'INP_DOC_UID', 'ownedByProcess'=>true, 'className'=>'InputDocument'], + 'OUT_DOC_DESCRIPTION' => ['table'=>'OUTPUT_DOCUMENT', 'uid'=>'OUT_DOC_UID', 'ownedByProcess'=>true, 'className'=>'OutputDocument'], + 'OUT_DOC_FILENAME' => ['table'=>'OUTPUT_DOCUMENT', 'uid'=>'OUT_DOC_UID', 'ownedByProcess'=>true, 'className'=>'OutputDocument'], + 'OUT_DOC_TEMPLATE' => ['table'=>'OUTPUT_DOCUMENT', 'uid'=>'OUT_DOC_UID', 'ownedByProcess'=>true, 'className'=>'OutputDocument'], + 'OUT_DOC_TITLE' => ['table'=>'OUTPUT_DOCUMENT', 'uid'=>'OUT_DOC_UID', 'ownedByProcess'=>true, 'className'=>'OutputDocument'], + 'PER_NAME' => ['table'=>'RBAC_PERMISSIONS', 'uid'=>'PER_UID', 'ownedByProcess'=>false, 'className'=>'Permissions'], + 'ROL_NAME' => ['table'=>'RBAC_ROLES', 'uid'=>'ROL_UID', 'ownedByProcess'=>false, 'className'=>'Roles'], + ]; + + protected function getClassNameFrom($category) + { + return $this->map[$category]["className"]; + } + + protected function getTableFrom($category) + { + return $this->map[$category]["table"]; + } + + protected function getUidFieldFrom($category) + { + return $this->map[$category]["uid"]; + } + + protected function getProUidFrom($category) + { + return 'PRO_UID'; + } + + protected function isOwnedByProcess($category) + { + return $this->map[$category]["ownedByProcess"]; + } + + /** + * @param $text + * @param $category + * @param null $proUid + * @param string $lang + * @return array + */ + public function getUidFromTextI18n($text, $category, $proUid = null, $lang = SYS_LANG) + { + if (empty($text) || empty($category)){ + return array(); + } + $uids = array(); + $className = $this->getClassNameFrom($category) . 'Peer'; + $uidField = $this->getUidFieldFrom($category); + $proUidField = $this->getProUidFrom($category); + $ownedByProcess = $this->isOwnedByProcess($category); + require_once("classes/model/$className.php"); + $oCriteria = new \Criteria('workflow'); + if ($ownedByProcess) { + $oCriteria->addSelectColumn(\ContentPeer::CON_ID); + $oCriteria->addJoin(\ContentPeer::CON_ID, constant("$className::$uidField")); + if (!empty($proUid)) { + $oCriteria->add(constant("$className::$proUidField"), $proUid); + } + } else { + $oCriteria->addSelectColumn(\ContentPeer::CON_ID); + } + $oCriteria->add(\ContentPeer::CON_CATEGORY, $category); + $oCriteria->add(\ContentPeer::CON_VALUE, $text); + $oCriteria->add(\ContentPeer::CON_LANG, $lang); + $oDataset = \ContentPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + $oDataset->next(); + while ($row = $oDataset->getRow()) { + $uids[] = $row['CON_ID']; + $oDataset->next(); + } + return $uids; + } +} diff --git a/workflow/engine/templates/actionsByEmail/report.js b/workflow/engine/templates/actionsByEmail/report.js new file mode 100644 index 000000000..1753c9087 --- /dev/null +++ b/workflow/engine/templates/actionsByEmail/report.js @@ -0,0 +1,229 @@ +var actionsByEmailGrid; +var store; +var win ; + +new Ext.KeyMap(document, { + key: Ext.EventObject.F5, + fn: function(keycode, e) { + if (! e.ctrlKey) { + if (Ext.isIE) { + e.browserEvent.keyCode = 8; + } + e.stopEvent(); + document.location = document.location; + } else { + Ext.Msg.alert(_('ID_REFRESH_LABEL'), _('ID_REFRESH_MESSAGE')); + } + } +}); + + +Ext.onReady(function(){ + Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); + Ext.QuickTips.init(); + +store = new Ext.data.GroupingStore( { + proxy : new Ext.data.HttpProxy({ + url: '../actionsByEmail/actionsByEmailAjax', + method: 'POST' + }), + + reader : new Ext.data.JsonReader( { + totalProperty: 'totalCount', + root: 'data', + fields : [ + {name : 'ABE_UID'}, + {name : 'ABE_REQ_UID'}, + {name : 'APP_UID'}, + {name : 'TAS_UID'}, + {name : 'ABE_REQ_DATE'}, + {name : 'ABE_REQ_SUBJECT'}, + {name : 'APP_NUMBER'}, + {name : 'USER'}, + {name : 'ABE_REQ_SENT_TO'}, + {name : 'ABE_REQ_STATUS'}, + {name : 'ABE_REQ_ANSWERED'}, + {name : 'ABE_RES_MESSAGE'} + ] + }) + }); + store.setBaseParam( 'action', 'loadActionByEmail' ); + + actionsByEmailGrid = new Ext.grid.GridPanel( { + region: 'center', + layout: 'fit', + id: 'actionsByEmailGrid', + title : '', + stateful : true, + stateId : 'grid', + enableColumnResize: true, + enableHdMenu: true, + frame:false, + columnLines: true, + + cm: new Ext.grid.ColumnModel({ + defaults: { + sortable: true + }, + columns: [ + {id: "ABE_UID", dataIndex: "ABE_UID", hidden:true, hideable:false}, + {header: _("ID_DATE").toUpperCase(), width: 100, dataIndex: "ABE_REQ_DATE", sortable: true}, + {header: "Case Number".toUpperCase(), width: 70, dataIndex: "APP_NUMBER", sortable: true}, + {header: _("ID_SUBJECT").toUpperCase(), width: 150, dataIndex: "ABE_REQ_SUBJECT", sortable: true}, + {header: _("ID_FROM").toUpperCase(), width: 110, dataIndex: "USER", sortable: true}, + {header: _("ID_TO").toUpperCase(), width: 110, dataIndex: "ABE_REQ_SENT_TO", sortable: true}, + {header: _("ID_STATUS").toUpperCase(), width: 40, dataIndex: "ABE_REQ_STATUS", sortable: true}, + {header: "Answered".toUpperCase(), width: 60, dataIndex: "ABE_REQ_ANSWERED"}, + {header: "View Response".toUpperCase(), width: 80, sortable: false, align: 'center', renderer: function(val){ return '", + { + xtype: "textfield", + id: "txtSearchUsersToReassign", + + emptyText: _("ID_EMPTY_SEARCH"), + width: 150, + allowBlank: true, + + listeners: { + specialkey: function (f, e) + { + if (e.getKey() == e.ENTER) { + pagingUsersToReassign.moveFirst(); + } + } + } + }, + { + text: "X", + ctCls: "pm_search_x_button", + + handler: function () + { + Ext.getCmp("txtSearchUsersToReassign").reset(); + } + }, + { + text: _("ID_SEARCH"), + + handler: function () + { + pagingUsersToReassign.moveFirst(); + } } ], - listeners: { - //rowdblclick: openCase, - render: function(){ - this.loadMask = new Ext.LoadMask(this.body, {msg:_('ID_LOADING')}); - this.ownerCt.doLayout(); - } - } + bbar: pagingUsersToReassign, + + title: "" }); winReassignInCasesList = new Ext.Window({ title: '', width: 450, - height: 280, + height: 350, layout:'fit', autoScroll:true, modal: true, maximizable: false, - items: [grid] + items: [grdpnlUsersToReassign] }); + winReassignInCasesList.show(); + + grdpnlUsersToReassign.store.load(); } } }, diff --git a/workflow/engine/templates/cases/casesListConsolidated.js b/workflow/engine/templates/cases/casesListConsolidated.js index 26a87452a..fec3f8a53 100644 --- a/workflow/engine/templates/cases/casesListConsolidated.js +++ b/workflow/engine/templates/cases/casesListConsolidated.js @@ -421,27 +421,27 @@ Ext.onReady(function () { }); var buttonProcess = new Ext.Action({ - text: "Derivate", + text: _("ID_DERIVATED"), //iconCls: 'ICON_CASES_PAUSED', handler : function (){ - Ext.Msg.confirm('Confirm Routing', 'Route cases per batch?', + Ext.Msg.confirm(_("ID_CONFIRM_ROUTING"), _("ID_ROUTE_BATCH_ROUTING"), function(btn, text){ - if (btn=='yes'){ - htmlMessage = ""; - var selectedRow = Ext.getCmp(gridId).getSelectionModel().getSelections(); - var maxLenght = selectedRow.length; - for (var i in selectedRow) { - rowGrid = selectedRow[i].data - for (fieldGrid in rowGrid){ - if(fieldGrid != 'APP_UID' && fieldGrid != 'APP_NUMBER' && fieldGrid != 'APP_TITLE' && fieldGrid != 'DEL_INDEX' ){ - fieldGridGral = fieldGrid; - fieldGridGralVal = rowGrid[fieldGrid]; - } - } - if (selectedRow[i].data) { - ajaxDerivationRequest(selectedRow[i].data["APP_UID"], selectedRow[i].data["DEL_INDEX"], maxLenght, selectedRow[i].data["APP_NUMBER"],fieldGridGral, fieldGridGralVal); + if (btn == 'yes') { + htmlMessage = ""; + var selectedRow = Ext.getCmp(gridId).getSelectionModel().getSelections(); + var maxLenght = selectedRow.length; + for (var i in selectedRow) { + rowGrid = selectedRow[i].data + for (fieldGrid in rowGrid) { + if (fieldGrid != 'APP_UID' && fieldGrid != 'APP_NUMBER' && fieldGrid != 'APP_TITLE' && fieldGrid != 'DEL_INDEX') { + fieldGridGral = fieldGrid; + fieldGridGralVal = rowGrid[fieldGrid]; } } + if (selectedRow[i].data) { + ajaxDerivationRequest(selectedRow[i].data["APP_UID"], selectedRow[i].data["DEL_INDEX"], maxLenght, selectedRow[i].data["APP_NUMBER"], fieldGridGral, fieldGridGralVal); + } + } } } ); @@ -1321,7 +1321,7 @@ function ajaxDerivationRequest(appUid, delIndex, maxLenght, appNumber, fieldGrid if (index == maxLenght) { Ext.MessageBox.show({ - title: "Derivation Result", + title: _("ID_DERIVATION_RESULT"), msg: htmlMessage, fn: function (btn, text, opt) { diff --git a/workflow/engine/templates/cases/open.js b/workflow/engine/templates/cases/open.js index 1f7a4ee95..459759b0f 100755 --- a/workflow/engine/templates/cases/open.js +++ b/workflow/engine/templates/cases/open.js @@ -157,6 +157,14 @@ Ext.onReady(function(){ tb.add(menu); } } + + var olink = document.location.href; + if(olink.search("gmail") != -1){ + Ext.getCmp('stepsMenu').hide(); + Ext.getCmp('informationMenu').hide(); + Ext.getCmp('actionMenu').hide(); + Ext.getCmp('caseNotes').hide(); + } if (Ext.getCmp('stepsMenu').disabled === true) { Ext.getCmp('stepsMenu').hide(); @@ -926,82 +934,153 @@ Ext.onReady(function(){ Actions.getUsersToReassign = function() { - var store = new Ext.data.Store( { - autoLoad: true, - proxy : new Ext.data.HttpProxy({ - url: 'ajaxListener?action=getUsersToReassign' - }), - reader : new Ext.data.JsonReader( { - root: 'data', - fields : [ - {name : 'USR_UID'}, - {name : 'USR_USERNAME'}, - {name : 'USR_FIRSTNAME'}, - {name : 'USR_LASTNAME'} - ] - }) + var loadMaskUsersToReassign = new Ext.LoadMask(Ext.getBody(), {msg: _("ID_LOADING_GRID")}); + + //Variables + var pageSizeUsersToReassign = 10; + + //Stores + var storeUsersToReassign = new Ext.data.Store({ + proxy: new Ext.data.HttpProxy({ + url: "ajaxListener", + method: "POST" + }), + + reader: new Ext.data.JsonReader({ + root: "resultRoot", + totalProperty: "resultTotal", + fields: [ + {name : "USR_UID"}, + {name : "USR_USERNAME"}, + {name : "USR_FIRSTNAME"}, + {name : "USR_LASTNAME"} + ] + }), + + remoteSort: true, + + listeners: { + beforeload: function (store) + { + winReassignInCasesList.setDisabled(true); + + loadMaskUsersToReassign.show(); + + this.baseParams = { + action: "getUsersToReassign", + search: Ext.getCmp("txtSearchUsersToReassign").getValue(), + pageSize: pageSizeUsersToReassign + }; + }, + load: function (store, record, opt) + { + winReassignInCasesList.setDisabled(false); + + loadMaskUsersToReassign.hide(); + } + } }); - var grid = new Ext.grid.GridPanel( { - id: 'reassignGrid', - height:300, - width:'300', - title : '', - stateful : true, - stateId : 'gridCasesOpen', - enableColumnResize: true, - enableHdMenu: true, - frame:false, - cls : 'grid_with_checkbox', - columnLines: true, + //Components + var pagingUsersToReassign = new Ext.PagingToolbar({ + id: "pagingUsersToReassign", - viewConfig: { - forceFit:true - }, + pageSize: pageSizeUsersToReassign, + store: storeUsersToReassign, + displayInfo: true, + displayMsg: _("ID_DISPLAY_ITEMS"), + emptyMsg: _("ID_NO_RECORDS_FOUND") + }); - cm: new Ext.grid.ColumnModel({ + var cmodelUsersToReassign = new Ext.grid.ColumnModel({ defaults: { width: 200, sortable: true }, columns: [ - {id:'USR_UID', dataIndex: 'USR_UID', hidden:true, hideable:false}, - {header: _('ID_USER_NAME'), dataIndex: 'USR_USERNAME', width: 300}, - {header: _('ID_FIRSTNAME'), dataIndex: 'USR_FIRSTNAME', width: 300}, - {header: _('ID_LASTNAME'), dataIndex: 'USR_LASTNAME', width: 300} + {id: "USR_UID", dataIndex: "USR_UID", hidden: true, hideable: false}, + {id: "USR_FIRSTNAME", dataIndex: "USR_FIRSTNAME", header: _("ID_FIRSTNAME"), width: 300}, + {id: "USR_LASTNAME", dataIndex: "USR_LASTNAME", header: _("ID_LASTNAME"), width: 300} ] - }), - sm: new Ext.grid.RowSelectionModel({singleSelect: true}), - store: store, - - tbar:[ - { - text:_('ID_REASSIGN'), - iconCls: 'ICON_CASES_TO_REASSIGN', - handler: Actions.reassignCase - } - ], - listeners: { - //rowdblclick: openCase, - render: function(){ - this.loadMask = new Ext.LoadMask(this.body, {msg:_('ID_LOADING')}); - this.ownerCt.doLayout(); - } - } }); - var win = new Ext.Window({ + var smodelUsersToReassign = new Ext.grid.RowSelectionModel({ + singleSelect: true + }); + + var grdpnlUsersToReassign = new Ext.grid.GridPanel({ + id: "grdpnlUsersToReassign", + + store: storeUsersToReassign, + colModel: cmodelUsersToReassign, + selModel: smodelUsersToReassign, + + columnLines: true, + viewConfig: {forceFit: true}, + enableColumnResize: true, + enableHdMenu: true, + + tbar: [ + { + text: _("ID_REASSIGN"), + iconCls: "ICON_CASES_TO_REASSIGN", + + handler: Actions.reassignCase + }, + "->", + { + xtype: "textfield", + id: "txtSearchUsersToReassign", + + emptyText: _("ID_EMPTY_SEARCH"), + width: 150, + allowBlank: true, + + listeners: { + specialkey: function (f, e) + { + if (e.getKey() == e.ENTER) { + pagingUsersToReassign.moveFirst(); + } + } + } + }, + { + text: "X", + ctCls: "pm_search_x_button", + + handler: function () + { + Ext.getCmp("txtSearchUsersToReassign").reset(); + } + }, + { + text: _("ID_SEARCH"), + + handler: function () + { + pagingUsersToReassign.moveFirst(); + } + } + ], + bbar: pagingUsersToReassign, + + title: "" + }); + + var winReassignInCasesList = new Ext.Window({ title: '', width: 450, - height: 280, + height: 350, layout:'fit', autoScroll:true, modal: true, resizable: false, maximizable: false, - items: [grid] + items: [grdpnlUsersToReassign] }); - Ext.Ajax.request({ + + Ext.Ajax.request({ url : 'ajaxListener' , params : {action : 'verifySession'}, success: function ( result, request ) { @@ -1026,7 +1105,9 @@ Ext.onReady(function(){ } }); } else { - win.show(); + winReassignInCasesList.show(); + + grdpnlUsersToReassign.store.load(); } }, failure: function ( result, request) { @@ -1039,7 +1120,8 @@ Ext.onReady(function(){ Actions.reassignCase = function() { - var rowSelected = Ext.getCmp('reassignGrid').getSelectionModel().getSelected(); + var rowSelected = Ext.getCmp("grdpnlUsersToReassign").getSelectionModel().getSelected(); + if( rowSelected ) { PMExt.confirm(_('ID_CONFIRM'), _('ID_REASSIGN_CONFIRM'), function(){ Ext.Ajax.request({ diff --git a/workflow/engine/templates/pmTables/edit.js b/workflow/engine/templates/pmTables/edit.js index b7098b0a9..25289121a 100644 --- a/workflow/engine/templates/pmTables/edit.js +++ b/workflow/engine/templates/pmTables/edit.js @@ -212,15 +212,14 @@ Ext.onReady(function(){ listeners:{ change: function(f,e){ this.setValue(this.getValue().replace(/^\s+/,'').replace(/\s+$/,'')); - var valueInputField= /^[0-9a-zA-Z\_|-]+$/.test(this.getValue()) ? true : false; + var valueInputField= /^[0-9a-zA-Z \|-]+$/.test(this.getValue()) ? true : false; if (!valueInputField) { - //Ext.Msg.alert(_('ID_WARNING'), _('ID_FIELD_LABEL')); this.setValue(''); } } }, validator: function(v) { - return valueInputField= /^[0-9a-zA-Z\_|-]+$/.test(v)?true:_('ID_ROLE_NAME_NOT_EMPTY'); + return valueInputField= /^[0-9a-zA-Z \|-]+$/.test(v)?true:_('ID_THE') + ' ' +_('ID_FIELD_LABEL') + ' ' + _('ID_FIELD_NOT_EMPTY_OR_SPECIAL_CHAR'); } } }, { diff --git a/workflow/engine/templates/pmTables/editReport.js b/workflow/engine/templates/pmTables/editReport.js index 0a4e678ab..9ffa277c8 100755 --- a/workflow/engine/templates/pmTables/editReport.js +++ b/workflow/engine/templates/pmTables/editReport.js @@ -427,10 +427,10 @@ Ext.onReady(function(){ } /*----------------------------------********---------------------------------*/ ]; - + function validateFieldSizeAutoincrement(valueType, defaultValue) { if (Ext.getCmp("sizeEdit").getEl()) { - + if (valueType === 'INTEGER' || valueType === 'BIGINT' || valueType === 'SMALLINT' || valueType === 'TINYINT') { Ext.getCmp("sizeEdit").enable(); Ext.getCmp("sizeEdit").setMaxValue(99); @@ -438,13 +438,13 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { if (defaultValue) { Ext.getCmp("sizeEdit").setValue(''); } - + Ext.getCmp("field_incre").enable(); if (defaultValue) { Ext.getCmp("field_incre").setValue(false); } } - + if (valueType === 'CHAR' || valueType === 'VARCHAR' || valueType === 'LONGVARCHAR') { Ext.getCmp("sizeEdit").enable(); Ext.getCmp("sizeEdit").setMaxValue(((valueType === 'CHAR') ? 255 : 999)); @@ -452,15 +452,15 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { if (defaultValue) { Ext.getCmp("sizeEdit").setValue(''); } - + Ext.getCmp("field_incre").disable(); Ext.getCmp("field_incre").setValue(false); } - + if (valueType === 'BOOLEAN' || valueType === 'DATE' || valueType === 'DATETIME' || valueType === 'TIME' || valueType === 'DECIMAL' || valueType === 'DOUBLE' || valueType === 'FLOAT' || valueType === 'REAL') { Ext.getCmp("sizeEdit").disable(); Ext.getCmp("sizeEdit").setValue(''); - + Ext.getCmp("field_incre").disable(); Ext.getCmp("field_incre").setValue(false); } @@ -721,9 +721,15 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { } }); - var types = new Ext.data.SimpleStore({ - fields: ['REP_TAB_TYPE', 'type'], - data : [['NORMAL',_("ID_GLOBAL")],['GRID',_("ID_GRID")]] + var arrayBpmnTypeData = [["NORMAL", _("ID_GLOBAL")]]; + var arrayClassicTypeData = [["NORMAL", _("ID_GLOBAL")], ["GRID", _("ID_GRID")]]; + + var types = new Ext.data.ArrayStore({ + storeId: "types", + autoDestroy: true, + + fields: ["REP_TAB_TYPE", "type"], + data : [['NORMAL',_("ID_GLOBAL")],['GRID',_("ID_GRID")]] }); comboReport = new Ext.form.ComboBox({ @@ -756,6 +762,7 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { } }); + dbConnectionsStore = new Ext.data.Store({ //autoLoad: true, proxy : new Ext.data.HttpProxy({ @@ -876,8 +883,8 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { } } }); - - comboReport.setReadOnly(isBpmn); + + comboReport.setDisabled(isBpmn); processStore = new Ext.data.Store( { autoLoad: true, @@ -889,7 +896,7 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { action: 'getProcessList' }, reader : new Ext.data.JsonReader( { - fields : [{name : 'PRO_UID'}, {name : 'PRO_TITLE'},{name : 'PRO_DESCRIPTION'}] + fields : [{name : 'PRO_UID'}, {name : 'PRO_TITLE'},{name : 'PRO_DESCRIPTION'}, {name: "PRO_PROCESS_TYPE"}] }), listeners: { load: function() { @@ -933,6 +940,7 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { } }); + var rptPosArray = 0; processComboBox = new Ext.form.ComboBox({ id: 'PROCESS', fieldLabel : _("ID_CASESLIST_APP_PRO_TITLE"), @@ -952,6 +960,20 @@ function validateFieldSizeAutoincrement(valueType, defaultValue) { listeners:{ select: function(){ + var dataStore = Ext.getCmp('PROCESS').store.getRange(); + var i = Ext.getCmp('PROCESS').store.find("PRO_UID", Ext.getCmp('PROCESS').getValue()); + + types.loadData( + (dataStore[i].data.PRO_PROCESS_TYPE == "BPMN")? arrayBpmnTypeData : arrayClassicTypeData, false + ); + + var dataStoreAux = types.getRange(rptPosArray); + + comboReport.setValue(dataStoreAux[0].data.REP_TAB_TYPE); + comboReport.setDisabled(dataStore[i].data.PRO_PROCESS_TYPE === "BPMN"); + + comboGridsList.setVisible(false); + comboDbConnections.getStore().reload({params:{PRO_UID : Ext.getCmp('PROCESS').getValue()}}); if (Ext.getCmp('REP_TAB_TYPE').getValue() == 'GRID') { gridsListStore.reload({params:{PRO_UID : Ext.getCmp('PROCESS').getValue()}}); diff --git a/workflow/engine/templates/pmTables/list.js b/workflow/engine/templates/pmTables/list.js index a6f2c8157..90e5e93b1 100755 --- a/workflow/engine/templates/pmTables/list.js +++ b/workflow/engine/templates/pmTables/list.js @@ -247,32 +247,27 @@ Ext.onReady(function(){ chkSelModel = new Ext.grid.CheckboxSelectionModel({ listeners:{ selectionchange: function(sm){ - if (sm.last !== false) { - var count_rows = sm.getCount(); - //var isReport = sm.getSelected().get('PRO_UID') != ''; - - currentSelectedRow = sm.last; - switch(count_rows){ - case 0: - editButton.disable(); - deleteButton.disable(); - exportButton.disable(); - dataButton.disable(); - break; - case 1: - editButton.enable(); - deleteButton.enable(); - exportButton.enable(); - dataButton.enable(); - break; - default: - editButton.disable(); - deleteButton.enable(); - exportButton.enable(); - dataButton.disable(); - break; - } - + var count_rows = sm.getCount(); + currentSelectedRow = sm.last; + switch(count_rows){ + case 0: + editButton.disable(); + deleteButton.disable(); + exportButton.disable(); + dataButton.disable(); + break; + case 1: + editButton.enable(); + deleteButton.enable(); + exportButton.enable(); + dataButton.enable(); + break; + default: + editButton.disable(); + deleteButton.enable(); + exportButton.enable(); + dataButton.disable(); + break; } } } @@ -520,6 +515,9 @@ DeletePMTable = function() { //Load Import PM Table Form ImportPMTable = function(){ + var aOverwrite, + aRelated, + aMessage; var w = new Ext.Window({ id: 'windowPmTableUploaderImport', title: '', @@ -555,12 +553,6 @@ ImportPMTable = function(){ buttonCfg: { iconCls: 'upload-icon' } - }, { - id: 'importPMTableOverwrite', - xtype: 'checkbox', - fieldLabel: '', - boxLabel: _('ID_OVERWRITE_EXIST'), // 'Overwrite if exists?', - name: 'form[OVERWRITE]' }, { xtype: 'hidden', name: 'form[TYPE_TABLE]', @@ -585,7 +577,7 @@ ImportPMTable = function(){ var result = Ext.util.JSON.decode(resp.response.responseText); if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); + PMExt.notify('', result.message); } else { win = new Ext.Window({ @@ -618,219 +610,34 @@ ImportPMTable = function(){ var result = Ext.util.JSON.decode(resp.response.responseText); if (result.errorType == 'warning') { - PMExt.warning(_('ID_WARNING'), result.message.replace(/\n/g,'
')); - } - else { + Ext.MessageBox.show({ + title: _('ID_WARNING_PMTABLES'), + width: 510, + height: 300, + msg: "
" + result.message.replace(/\n/g,'
') + "
", + buttons: Ext.MessageBox.OK, + animEl: 'mb9', + fn: function(){}, + icon: Ext.MessageBox.INFO + }); + } else { if(result.fromAdmin) { /* from admin tab */ - if(result.validationType == 1) { - Ext.MessageBox.confirm('Confirmation', result.message.replace(/\n/g,'
'), function(btn, text){ - if (btn == 'yes'){ - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'overWrite', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), - 'form[OVERWRITE]':true - }, - success: function(resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - if(result.validationType == 2) { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - } - }, - failure: function(obj, resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if(result.validationType == 2) { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - } - }); - } else { - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'clear', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin') - }, - success: function(resp) { - var result = Ext.util.JSON.decode(resp.responseText); - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } - }); - } - Ext.getCmp('infoGrid').getStore().reload(); - }); - return false; - } else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } + aOverwrite = result.arrayOverwrite; + aRelated = result.arrayRelated; + aMessage = result.arrayMessage; + pmtablesErrors(aOverwrite,aRelated,aMessage); } else { /* from designer tab */ - if(result.validationType == 1) { - Ext.MessageBox.confirm('Confirmation', result.message.replace(/\n/g,'
'), function(btn, text){ - if (btn == 'yes'){ - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'2', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), - 'form[OVERWRITE]':true - }, - success: function(resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - if(result.validationType == 2) { - Ext.MessageBox.confirm('Confirmation', result.message.replace(/\n/g,'
'), function(btn, text){ - if (btn == 'yes'){ - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'overWrite', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), - 'form[OVERWRITE]':true - }, - success: function(resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }, - failure: function(obj, resp){ - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }); - Ext.getCmp('infoGrid').getStore().reload(); - } - }); - return false; - } - else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - } - }, - failure: function(obj, resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if(result.validationType == 2) { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - } - }); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'2', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), - 'form[PRO_UID_HELP]':PRO_UID - }, - success: function(resp) { - var result = Ext.util.JSON.decode(resp.responseText); - if(result.validationType == 2) { - /*add code if related process*/ - Ext.MessageBox.confirm('Confirmation', result.message.replace(/\n/g,'
'), function(btn, text){ - if (btn == 'yes'){ - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'overWrite', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), - 'form[PRO_UID_HELP]':PRO_UID - }, - success: function(resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }, - failure: function(obj, resp){ - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }); - Ext.getCmp('infoGrid').getStore().reload(); - } - }); - return false; - } else { - var result = Ext.util.JSON.decode(resp.responseText); - if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - } - //PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - }, - failure: function(obj, resp){ - var result = Ext.util.JSON.decode(resp.responseText); - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }); - } - Ext.getCmp('infoGrid').getStore().reload(); - }); - return false; - } - if(result.validationType == 2) { - Ext.MessageBox.confirm('Confirmation', result.message.replace(/\n/g,'
'), function(btn, text){ - if (btn == 'yes'){ - Ext.Ajax.request({ - url: 'pmTablesProxy/import', - params: { - 'form[FROM_CONFIRM]':'overWrite', - 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), - 'form[OVERWRITE]':true, - 'form[PRO_UID_HELP]':PRO_UID - }, - success: function(resp){ - var result = Ext.util.JSON.decode(resp.responseText); - if (result.success) { - PMExt.notify(_('ID_IMPORT_RESULT'), result.message); - Ext.getCmp('infoGrid').getStore().reload(); - } else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }, - failure: function(obj, resp){ - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } - }); - Ext.getCmp('infoGrid').getStore().reload(); - } - }); - return false; - } else { - PMExt.error(_('ID_ERROR'), result.message.replace(/\n/g,'
')); - } + aOverwrite = result.arrayOverwrite; + aRelated = result.arrayRelated; + aMessage = result.arrayMessage; + pmtablesErrors(aOverwrite,aRelated,aMessage); } } } }); } } - }/*,{ - text: 'Reset', - handler: function(){ - uploader = Ext.getCmp('uploader'); - uploader.getForm().reset(); - } - }*/,{ + },{ id: 'importPMTableButtonCancel', text: TRANSLATIONS.ID_CANCEL, handler: function(){ @@ -964,3 +771,167 @@ function updateTagPermissions(){ var top = (Ext.getBody().getViewSize().height/3); var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left); } + +function pmtablesErrors(aOverwrite,aRelated,aMessage){ + var jsonDataArray = [], + i, + fieldMessage, + fieldRadio2Options, + fieldRadio3Options, + win, + tablesOfNo, + tablesOfYes, + tablesOfNew, + valueSelected, + nameId, + number; + //Show the error message ERROR_PROCESS_NOT_EXIST or ERROR_NO_REPORT_TABLE + for (i = 0; i < aMessage.length; i++){ + fieldMessage = { + xtype : 'fieldset', + title : aMessage[i]['ERROR_MESS'], + id : aMessage[i]['NAME_TABLE'], + autoHeight : true + }; + jsonDataArray.push(fieldMessage); + } + //Check the ERROR_OVERWRITE_RELATED_PROCESS + for (i = 0; i < aRelated.length; i++){ + fieldRadio2Options = { + xtype : 'fieldset', + title : aRelated[i]['ERROR_MESS'], + id : aRelated[i]['NAME_TABLE'], + autoHeight : true, + defaultType: 'radio', // each item will be a radio button + items: [{ + checked : true, + boxLabel : _('ID_RADIO_RELATED_PROCESS'), + name : aRelated[i]['NAME_TABLE'], + inputValue : 'related' + }, { + boxLabel : _('ID_RADIO_NOT_IMPORTED_RPT'), + name : aRelated[i]['NAME_TABLE'], + inputValue : 'no' + }] + }; + jsonDataArray.push(fieldRadio2Options); + } + // check the ERROR_PM_TABLES_OVERWRITE or ERROR_RP_TABLES_OVERWRITE + for (i = 0; i < aOverwrite.length; i++){ + fieldRadio3Options = { + xtype : 'fieldset', + title : aOverwrite[i]['ERROR_MESS'], + id : aOverwrite[i]['NAME_TABLE'], + autoHeight : true, + defaultType : 'radio', // each item will be a radio button + items: [{ + boxLabel : _('ID_RADIO_CREATE_NEW'), + name : aOverwrite[i]['NAME_TABLE'], + inputValue : 'new' + }, { + boxLabel : _('ID_RADIO_OVERWRITE'), + name : aOverwrite[i]['NAME_TABLE'], + inputValue : 'overwrite' + }, { + checked : true, + boxLabel : _('ID_RADIO_NOT_IMPORTED'), + name : aOverwrite[i]['NAME_TABLE'], + inputValue : 'no' + }] + }; + jsonDataArray.push(fieldRadio3Options); + } + + number = Math.floor((Math.random() * 100) + 1); + win = new Ext.Window({ + id : 'winPmtableRptableErrors'+number, + layout : 'fit', + width : 700, + height : 400, + title : _('ID_WARNING_PMTABLES'), + modal : true, + maximizable: true, + constrain : true, + plain : true, + autoScroll : true, + items : jsonDataArray, + buttons : [{ + text : _('ID_CONTINUE'), + handler: function(){ + tablesOfNo = ''; + tablesOfYes = ''; + tablesOfNew = ''; + for (i = 0; i < aMessage.length; i++){ + nameId = aMessage[i]['NAME_TABLE']; + tablesOfNo = tablesOfNo.concat('|',nameId); + } + for (i = 0; i < aRelated.length; i++){ + nameId = aRelated[i]['NAME_TABLE']; + valueSelected = Ext.getCmp(nameId).items.get(0).getGroupValue(); + switch(valueSelected) { + case 'related': + tablesOfYes = tablesOfYes.concat('|',nameId); + break; + case 'no': + tablesOfNo = tablesOfNo.concat('|',nameId); + break; + } + } + for (i = 0; i < aOverwrite.length; i++){ + nameId = aOverwrite[i]['NAME_TABLE']; + valueSelected = Ext.getCmp(nameId).items.get(0).getGroupValue(); + switch(valueSelected) { + case 'new': + tablesOfNew = tablesOfNew.concat('|',nameId); + break; + case 'overwrite': + tablesOfYes = tablesOfYes.concat('|',nameId); + break; + case 'no': + tablesOfNo = tablesOfNo.concat('|',nameId); + break; + } + } + win.close(); + Ext.Ajax.request({ + url: 'pmTablesProxy/import', + params: { + 'form[FROM_CONFIRM]':'yes', + 'form[TYPE_TABLE]':(PRO_UID? 'designer' : 'admin'), + 'form[OVERWRITE]':true, + 'form[TABLES_OF_NO]':tablesOfNo, + 'form[TABLES_OF_YES]':tablesOfYes, + 'form[TABLES_OF_NEW]':tablesOfNew + }, + success: function(resp){ + var result = Ext.util.JSON.decode(resp.responseText); + if (result.success) { + PMExt.notify('', result.message); + Ext.getCmp('infoGrid').getStore().reload(); + } + }, + failure: function(obj, resp){ + var result = Ext.util.JSON.decode(resp.responseText); + Ext.getCmp('infoGrid').getStore().reload(); + } + }); + } + },{ + text: _('ID_CANCEL'), + handler: function(){ + win.close(); + } + }] + }); + win.show(); + + for (i = 0; i < aMessage.length; i++){ + Ext.get(aMessage[i]['NAME_TABLE']).setStyle({border: '0', marginTop:'0'} ); + } + for (i = 0; i < aRelated.length; i++){ + Ext.get(aRelated[i]['NAME_TABLE']).setStyle({border: '0', marginTop:'0'} ); + } + for (i = 0; i < aOverwrite.length; i++){ + Ext.get(aOverwrite[i]['NAME_TABLE']).setStyle({border: '0', marginTop:'0'} ); + } +} \ No newline at end of file diff --git a/workflow/engine/templates/processes/main.js b/workflow/engine/templates/processes/main.js index d537e19e6..d7641d546 100755 --- a/workflow/engine/templates/processes/main.js +++ b/workflow/engine/templates/processes/main.js @@ -7,6 +7,7 @@ var store; var comboCategory; var winDesigner; var newTypeProcess; +var affectedGroups; /** @@ -44,7 +45,7 @@ Ext.apply(Ext.form.VTypes, { }); Ext.onReady(function(){ - Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); + setExtStateManagerSetProvider('gridProcessMain'); Ext.QuickTips.init(); store = new Ext.data.GroupingStore( { @@ -279,6 +280,15 @@ Ext.onReady(function(){ }, columns: [ expander, + + // There is a list of allowed columns to sort: + // workflow/engine/methods/cases/proxyProcessList.php + // This is to prevent ORDER BY injection attacks + + // It is identical to this list. + // If you need to add a new column that is sortable, please + // make sure it is added there or sorting will not work. + {id:'PRO_UID', dataIndex: 'PRO_UID', hidden:true, hideable:false}, {header: "", dataIndex: 'PRO_STATUS', width: 50, hidden:true, hideable:false}, {header: _('ID_PRO_DESCRIPTION'), dataIndex: 'PRO_DESCRIPTION',hidden:true, hideable:false}, @@ -359,6 +369,12 @@ Ext.onReady(function(){ importProcessGlobal.processFileType = "pm"; importProcess(); } + },{ + id: 'deleteCasesId', + text: _('ID_DELETE_CASES'), + iconCls: "button_menu_ext ss_sprite ss_cross", + handler: deleteCases, + hidden: true },{ xtype: 'tbfill' },{ @@ -428,6 +444,10 @@ Ext.onReady(function(){ } }); + if(deleteCasesFlag) { + Ext.getCmp("deleteCasesId").show(); + } + processesGrid.store.load({params: {"function": "languagesList", "start": 0, "limit": 25}}); processesGrid.addListener('rowcontextmenu', onMessageContextMenu,this); processesGrid.on('rowcontextmenu', function (grid, rowIndex, evt) { @@ -823,6 +843,76 @@ deleteProcess = function(){ } } +var deleteCases = function(){ + var rows = processesGrid.getSelectionModel().getSelections(), + totalCases = 0, + ids = Array(), + PRO_UIDS, + i; + if( rows.length > 0 ) { + for(i=0; i limitToShow) { + shortGroupList = arrayGroups.slice(0, limitToShow).join(", "); + shortGroupList = shortGroupList + ", ..., "+ _('ID_SEE_FULL_LIST') +""; + } else { + shortGroupList = affectedGroups; + } var processFileTypeTitle = (processFileType == "pm") ? "" : " " + processFileType; @@ -932,7 +1031,7 @@ importProcessExistGroup = function() title : _('ID_IMPORT_PROCESS') + processFileTypeTitle, header : false, width : 460, - height : 230, + height : 270, modal : true, autoScroll : false, maximizable : false, @@ -970,7 +1069,15 @@ importProcessExistGroup = function() boxLabel : _('ID_PROCESS_GROUP_RENAME'), name : "optionGroupExistInDatabase", inputValue : '1', - tabIndex : 1 + tabIndex : 1, + checked : "checked", + listeners: { + check: function (ctl, val) { + if(val) { + Ext.getCmp("affectedGroups").hide(); + } + } + } } ] }, { @@ -981,7 +1088,27 @@ importProcessExistGroup = function() tabIndex : 2, name : "optionGroupExistInDatabase", inputValue : '2', - checked : "checked" + listeners: { + check: function (ctl, val) { + if(val) { + Ext.getCmp("affectedGroups").show(); + } + } + } + } + ] + }, { + items:[ + { + xtype : 'box', + id: 'affectedGroups', + name: 'affectedGroups', + autoEl : { + tag : 'div', + html : '
'+_('ID_AFFECTED_GROUPS')+': '+shortGroupList+'
' + }, + hidden:true + } ] }, { @@ -1058,6 +1185,42 @@ importProcessExistGroup = function() w.show(); }; +affectedGroupsList = function() +{ + var arrayGroups = affectedGroups.split(", "); + var tableGroups = "" + for(var i = 0; i < arrayGroups.length; i++) { + tableGroups += ""; + } + tableGroups += "
"+arrayGroups[i]+"
"; + + var w = new Ext.Window({ + id : 'affectedGroupsListWindow', + title : _('ID_AFFECTED_GROUPS') + ' ('+arrayGroups.length+')', + header : false, + width : 260, + height : 300, + modal : true, + autoScroll : true, + maximizable : false, + resizable : false, + items : [ + { + xtype : 'box', + id: 'affectedGroupsList', + name: 'affectedGroupsList', + autoEl : { + tag : 'div', + html : '
'+tableGroups+'
' + }, + hidden:false + + } + ] + }); + w.show(); +} + importProcessExistProcess = function() { @@ -1180,6 +1343,7 @@ importProcessExistProcess = function() } } else { + affectedGroups = resp_.affectedGroups; importProcessGlobal.proFileName = resp_.proFileName; importProcessGlobal.groupBeforeAccion = resp_.groupBeforeAccion; importProcessGlobal.sNewProUid = resp_.sNewProUid; @@ -1214,9 +1378,107 @@ importProcessExistProcess = function() w.show(); }; -//importProcess = function(){ -// window.location = 'processes_Import'; -//} +changeOrKeepUids = function() +{ + var processFileType = importProcessGlobal.processFileType; + var proFileName = importProcessGlobal.proFileName; + var w = new Ext.Window({ + id : 'changeOrKeepUidsWindow', + title : _('ID_IMPORT_PROCESS'), + header : false, + width : 460, + height : 230, + autoHeight : true, + modal : true, + autoScroll : false, + maximizable : false, + resizable : false, + items : [ + new Ext.form.FormPanel({ + title : _('ID_LAN_UPLOAD_TITLE'), + header : false, + id : 'formUploader', + fileUpload : false, + width : 440, + frame : true, + autoHeight : true, + bodyStyle : 'padding: 10px 10px 0 10px;', + labelWidth : 50, + defaults : { + anchor : '90%', + allowBlank : false, + msgTarget : 'side' + }, + items : [ + { + xtype : 'box', + autoEl : { + tag : 'div', + html : '
 
' + } + }, + { + items: [ + { + id: "newUids", + xtype: "radio", + name: "IMPORT_OPTION", + inputValue: "new", + boxLabel: _("ID_CREATE_NEW_PROCESS_UID"), + tabIndex: 3 + } + ] + }, + { + items: [ + { + id: "keepUids", + xtype: "radio", + name: "IMPORT_OPTION", + inputValue: "keep", + boxLabel: _("ID_KEEP_PROCESS_UID"), + tabIndex: 1, + checked: "checked" + } + ] + }, { + xtype : 'hidden', + name : 'PRO_FILENAME', + value : proFileName + }, { + name : 'processFileType', + xtype : 'hidden', + value : processFileType + }, { + xtype : 'spacer', + height : 10 + } + ], + buttons:[ + { + text : _('ID_SAVE'), + handler : function() { + var opt1 = Ext.getCmp('newUids').getValue(); + var opt2 = Ext.getCmp('keepUids').getValue(); + if(opt1) { + Ext.getCmp('generateUid').setValue('generate'); + } else { + Ext.getCmp('generateUid').setValue('keep'); + } + Ext.getCmp('buttonUpload').el.dom.click(); + } + }, { + text : _('ID_CANCEL'), + handler : function(){ + w.close(); + } + } + ] + }) + ] + }); + w.show(); +}; importProcess = function() { @@ -1272,9 +1534,15 @@ importProcess = function() buttonCfg : { iconCls : 'upload-icon' } + }, { + id: 'generateUid', + name: 'generateUid', + xtype: 'hidden', + value: '' } ], buttons : [{ + id: 'buttonUpload', text : _('ID_UPLOAD'), handler : function(){ var arrayMatch = []; @@ -1313,6 +1581,13 @@ importProcess = function() if (resp_.catchMessage == "") { if (resp_.ExistProcessInDatabase == "0") { + if(resp_.notExistProcessInDatabase == "1") { + importProcessGlobal.sNewProUid = resp_.sNewProUid; + importProcessGlobal.proFileName = resp_.proFileName; + importProcessGlobal.groupBeforeAccion = resp_.groupBeforeAccion; + changeOrKeepUids(); + return; + } if (resp_.ExistGroupsInDatabase == "0") { var sNewProUid = resp_.sNewProUid; @@ -1326,6 +1601,7 @@ importProcess = function() window.location.href = "processes_Map?PRO_UID=" + sNewProUid; } } else { + affectedGroups = resp_.affectedGroups; importProcessGlobal.sNewProUid = resp_.sNewProUid; importProcessGlobal.proFileName = resp_.proFileName; importProcessGlobal.groupBeforeAccion = resp_.groupBeforeAccion; @@ -1337,6 +1613,9 @@ importProcess = function() } } else { w.close(); + if (Ext.getCmp('changeOrKeepUidsWindow')) { + Ext.getCmp('changeOrKeepUidsWindow').close(); + } Ext.MessageBox.show({ title : "", @@ -1579,6 +1858,8 @@ function openWindowIfIE(pathDesigner) { Ext.getCmp('importProcessExistProcessWindow').close(); if (Ext.getCmp('windowBpmnOptionWindow')) Ext.getCmp('windowBpmnOptionWindow').close(); + if (Ext.getCmp('changeOrKeepUidsWindow')) + Ext.getCmp('changeOrKeepUidsWindow').close(); processesGrid.store.reload(); if (winDesigner && winDesigner.closed === false) { if (winDesigner.window.PMDesigner.project.isDirty()) { diff --git a/workflow/engine/templates/setup/appCacheViewConf.js b/workflow/engine/templates/setup/appCacheViewConf.js index 579a684fa..27677dba3 100755 --- a/workflow/engine/templates/setup/appCacheViewConf.js +++ b/workflow/engine/templates/setup/appCacheViewConf.js @@ -3,7 +3,6 @@ Ext.onReady(function() { Ext.QuickTips.init(); // turn on validation errors beside the field globally Ext.form.Field.prototype.msgTarget = 'side'; - var bd = Ext.getBody(); // Store var store = new Ext.data.Store( { @@ -67,7 +66,7 @@ Ext.onReady(function() { success: function(response) { store.reload(); Ext.MessageBox.hide(); - res = Ext.decode ( response.responseText ); + res = Ext.decode ( response.responseText ); Ext.Msg.alert ( '', res.msg ); }, @@ -109,17 +108,73 @@ Ext.onReady(function() { disabled: false, hidden: false, value: '' - } - - fieldsetRoot = { + }; + + var txtCode = { + allowBlank: false, + disabled: false, + fieldLabel: _('ID_CAPTCHA_INPUT_CODE'),// Security Code + id : 'txtCode', + name: 'code', + xtype : 'textfield' + }; + + var onCaptchaChange = function () { + Ext.get('cacheViewAjax').dom.src = 'appCacheViewAjax?request=captcha&t=' + Math.random(); + }; + + var refreshBtn = new Ext.Button({ + columnWidth: 0.1, + iconCls:'x-tbar-loading', + scale:'small', + handler : function() { + Ext.get('cacheViewAjax').dom.src = 'appCacheViewAjax?request=captcha&t=' + Math.random(); + } + }); + + var boxCaptcha = new Ext.BoxComponent({ + columnWidth: 0.9, + autoEl: { + tag:'img', + id: 'cacheViewAjax', + title : _('ID_CAPTCHA_REFRESH_CODE'), //Click to refresh code + src:'appCacheViewAjax?request=captcha&t=' + Math.random() + } + }); + + boxCaptcha.on('render',function (){ + var curr = Ext.get('cacheViewAjax'); + curr.on('click',onCaptchaChange,this); + },this); + + var captcha = { + xtype:'fieldset', + hideLabels: true, + labelWidth: 0, + width: 350, + layout:'column', + border:false, + items:[ + boxCaptcha, + refreshBtn + ] + }; + + var fieldsetRoot = { xtype : 'fieldset', title : _('ID_CACHE_SUBTITLE_SETUP_DB'), // 'Setup MySql Root Password', collapsible : true, collapsed: true, autoHeight : true, - defaults : { width : 170 }, + defaults : { width : 200 }, defaultType : 'textfield', - items : [txtHost, txtUser, txtPasswd ], + items : [ + txtHost, + txtUser, + txtPasswd, + captcha, + txtCode + ], buttons : [{ text : _('ID_CACHE_BTN_SETUP_PASSWRD'), // 'Setup Password', handler : function() { @@ -139,14 +194,14 @@ Ext.onReady(function() { Ext.Msg.hide(); Ext.Msg.alert ( _('ID_ERROR'), response.responseText ); }, - params: { request: 'recreate-root', lang: 'en', host: Ext.getCmp('txtHost').getValue(), user: Ext.getCmp('txtUser').getValue(), password: Ext.getCmp('txtPasswd').getValue() }, + params: { request: 'recreate-root', lang: 'en', host: Ext.getCmp('txtHost').getValue(), user: Ext.getCmp('txtUser').getValue(), password: Ext.getCmp('txtPasswd').getValue(), codeCaptcha: Ext.getCmp('txtCode').getValue() }, // timeout : 1000 // 30 mins timeout : 1000*60*30 //30 mins }); } }] - } + }; fsf.add(fieldsetRoot); fsf.render(document.getElementById('main-panel')); @@ -155,7 +210,7 @@ Ext.onReady(function() { Ext.Ajax.request({ url: 'appCacheViewAjax', success: function(response) { - myData = Ext.decode ( response.responseText ); + var myData = Ext.decode ( response.responseText ); store.loadData(myData); if ( myData.error ) { Warning( _('ID_ERROR'), myData.errorMsg ); @@ -170,9 +225,10 @@ Ext.onReady(function() { }); //ExtReady var Warning = function( msgTitle, msgError ) { - tplEl = Ext.get ('errorMsg'); + var tplEl = Ext.get ('errorMsg'); - tplText = '
' + msgTitle + ': ' + msgError + '
'; + var tplText = '
' + msgTitle + ': ' + msgError + '
'; tplEl.update ( tplText ); -} +}; diff --git a/workflow/engine/templates/setup/languages.js b/workflow/engine/templates/setup/languages.js index 899cb2560..526fd2e65 100755 --- a/workflow/engine/templates/setup/languages.js +++ b/workflow/engine/templates/setup/languages.js @@ -86,9 +86,9 @@ Ext.onReady(function(){ Ext.MessageBox.show({ title: '', - width: 500, - height: 500, - msg: "
"+resp.result.msg+"
", + width: 510, + height: 300, + msg: "
" + stringReplace("\\x0A", "
", resp.result.msg) + "
", buttons: Ext.MessageBox.OK, animEl: 'mb9', fn: function(){}, diff --git a/workflow/engine/templates/setup/main_Load.php b/workflow/engine/templates/setup/main_Load.php index 74148511b..d98db9871 100755 --- a/workflow/engine/templates/setup/main_Load.php +++ b/workflow/engine/templates/setup/main_Load.php @@ -1,47 +1,43 @@ - - + + \ No newline at end of file diff --git a/workflow/engine/templates/setup/newSite.js b/workflow/engine/templates/setup/newSite.js index badfc12e5..680bef7b4 100755 --- a/workflow/engine/templates/setup/newSite.js +++ b/workflow/engine/templates/setup/newSite.js @@ -3,6 +3,8 @@ * Jan 15th, 2011 */ +Ext.Ajax.timeout = 300000; + Ext.onReady(function(){ var fieldNameWS=new Ext.form.TextField({ @@ -165,7 +167,6 @@ Ext.onReady(function(){ }, waitMsg : _('ID_NEW_SITE_TESTING'), waitTitle : " ", - timeout : 3600, success: function(f,a){ nwTitle =formNewSite.getForm().findField('NW_TITLE').getValue(); aoDbWf =formNewSite.getForm().findField('AO_DB_WF').getValue(); diff --git a/workflow/engine/templates/users/users.js b/workflow/engine/templates/users/users.js index 4be30472e..2727c76bf 100755 --- a/workflow/engine/templates/users/users.js +++ b/workflow/engine/templates/users/users.js @@ -1156,6 +1156,9 @@ function editUser() frmSumary.hide(); frmDetails.show(); + if (window.canEditCalendar === true) { + comboCalendar.setReadOnly(false); + } } function validateUserName() { diff --git a/workflow/engine/test/unit/processmaker/classJrmlTest.php b/workflow/engine/test/unit/processmaker/classJrmlTest.php deleted file mode 100755 index 46daa8692..000000000 --- a/workflow/engine/test/unit/processmaker/classJrmlTest.php +++ /dev/null @@ -1,113 +0,0 @@ -getMethods() as $reflectmethod ) { - $params = ''; - foreach ( $reflectmethod->getParameters() as $key => $row ) { - if ( $params != '' ) $params .= ', '; - $params .= '$' . $row->name; - } - - $testItems++; - $methods[ $reflectmethod->getName() ] = $params; - } - - $t->diag('class $className' ); - $t->isa_ok( $obj , 'Jrml', 'class $className created'); - - $t->is( count($methods) , 8, "class $className have " . 8 . ' methods.' ); - - //checking method '__construct' - $t->can_ok( $obj, '__construct', '__construct() is callable' ); - - //$result = $obj->__construct ( $data); - //$t->isa_ok( $result, 'NULL', 'call to method __construct '); - $t->todo( "call to method __construct using $data "); - - - //checking method 'get_rows' - $t->can_ok( $obj, 'get_rows', 'get_rows() is callable' ); - - //$result = $obj->get_rows ( $a); - //$t->isa_ok( $result, 'NULL', 'call to method get_rows '); - $t->todo( "call to method get_rows using $a "); - - - //checking method 'get_md' - $t->can_ok( $obj, 'get_md', 'get_md() is callable' ); - - //$result = $obj->get_md ( ); - //$t->isa_ok( $result, 'NULL', 'call to method get_md '); - $t->todo( "call to method get_md using "); - - - //checking method 'get_header' - $t->can_ok( $obj, 'get_header', 'get_header() is callable' ); - - //$result = $obj->get_header ( ); - //$t->isa_ok( $result, 'NULL', 'call to method get_header '); - $t->todo( "call to method get_header using "); - - - //checking method 'get_column_header' - $t->can_ok( $obj, 'get_column_header', 'get_column_header() is callable' ); - - //$result = $obj->get_column_header ( ); - //$t->isa_ok( $result, 'NULL', 'call to method get_column_header '); - $t->todo( "call to method get_column_header using "); - - - //checking method 'get_detail' - $t->can_ok( $obj, 'get_detail', 'get_detail() is callable' ); - - //$result = $obj->get_detail ( ); - //$t->isa_ok( $result, 'NULL', 'call to method get_detail '); - $t->todo( "call to method get_detail using "); - - - //checking method 'get_footer' - $t->can_ok( $obj, 'get_footer', 'get_footer() is callable' ); - - //$result = $obj->get_footer ( ); - //$t->isa_ok( $result, 'NULL', 'call to method get_footer '); - $t->todo( "call to method get_footer using "); - - - //checking method 'export' - $t->can_ok( $obj, 'export', 'export() is callable' ); - - //$result = $obj->export ( ); - //$t->isa_ok( $result, 'NULL', 'call to method export '); - $t->todo( "call to method export using "); - - - - $t->todo ( 'review all pendings methods in this class'); diff --git a/workflow/public_html/images/logo-processmaker-google.png b/workflow/public_html/images/logo-processmaker-google.png new file mode 100644 index 000000000..3a9d8024b Binary files /dev/null and b/workflow/public_html/images/logo-processmaker-google.png differ diff --git a/workflow/public_html/pmGmail/sso.php b/workflow/public_html/pmGmail/sso.php index 06d8fe743..27ee3e50f 100644 --- a/workflow/public_html/pmGmail/sso.php +++ b/workflow/public_html/pmGmail/sso.php @@ -1,4 +1,5 @@ - + - - -