From 625792abc4f7960e4ddf145ead5bd477634e6bf9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 02:08:48 +0100
Subject: [PATCH 01/65] Remove test module
---
Resources/modules/mod1/styl.less | 3 ---
1 file changed, 3 deletions(-)
delete mode 100644 Resources/modules/mod1/styl.less
diff --git a/Resources/modules/mod1/styl.less b/Resources/modules/mod1/styl.less
deleted file mode 100644
index aa1634c25..000000000
--- a/Resources/modules/mod1/styl.less
+++ /dev/null
@@ -1,3 +0,0 @@
-body {
- background-color: red;
-}
From de315bd9f89c277832797810d685568d57b26eba Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 02:09:27 +0100
Subject: [PATCH 02/65] Remove unused watchr config
---
Resources/watchr/refresh_assets.rb | 16 ----------------
1 file changed, 16 deletions(-)
delete mode 100644 Resources/watchr/refresh_assets.rb
diff --git a/Resources/watchr/refresh_assets.rb b/Resources/watchr/refresh_assets.rb
deleted file mode 100644
index 5b83cde90..000000000
--- a/Resources/watchr/refresh_assets.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-rootDir = File.expand_path(File.dirname(File.dirname(__FILE__))) + "/../../../../.."
-
-watch( '../views/(.+)\.twigjs' ) {
- require 'fileutils'
- webJsDir = "#{rootDir}/web/js"
- FileUtils.rm_rf("#{webJsDir}/.", :secure => true)
- system("php #{rootDir}/app/console assetic:dump")
-}
-
-watch( '../less/bootstrap/.+' ) {
- system("php #{rootDir}/app/console claroline:themes:compile")
-}
-
-watch( '../less/themes/([^/]+)/.+' ) {
- |md| system("php #{rootDir}/app/console claroline:themes:compile --theme=#{md[1]}")
-}
\ No newline at end of file
From 3a3376929e3c0891adab58810060dd56ded3069c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 02:14:00 +0100
Subject: [PATCH 03/65] Add missing required extensions
---
composer.json | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/composer.json b/composer.json
index 0218bdbfc..30be622c0 100644
--- a/composer.json
+++ b/composer.json
@@ -14,7 +14,11 @@
],
"require": {
"php": ">=5.5",
- "ext-mcrypt": "*",
+ "ext-curl": "*",
+ "ext-fileinfo": "*",
+ "ext-gd": "*",
+ "ext-intl": "*",
+ "ext-pdo_mysql": "*",
"symfony/symfony": "~2.7.0",
"doctrine/dbal": "~2.4",
"symfony/assetic-bundle": "~2.4",
From c49ebe7a41e8ebe8d80f57c4f0a32fa9c6a5fd73 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 02:20:04 +0100
Subject: [PATCH 04/65] Add parameter.yml builder
---
composer.json | 1 +
1 file changed, 1 insertion(+)
diff --git a/composer.json b/composer.json
index 30be622c0..998a97a20 100644
--- a/composer.json
+++ b/composer.json
@@ -19,6 +19,7 @@
"ext-gd": "*",
"ext-intl": "*",
"ext-pdo_mysql": "*",
+ "incenteev/composer-parameter-handler": "~2.1",
"symfony/symfony": "~2.7.0",
"doctrine/dbal": "~2.4",
"symfony/assetic-bundle": "~2.4",
From 7d7889fbc1742bf5930ce597beb22b839d8fe5df Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 12:24:56 +0100
Subject: [PATCH 05/65] Point to tmp parameter handler fork
---
composer.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/composer.json b/composer.json
index 998a97a20..646b594e7 100644
--- a/composer.json
+++ b/composer.json
@@ -19,7 +19,7 @@
"ext-gd": "*",
"ext-intl": "*",
"ext-pdo_mysql": "*",
- "incenteev/composer-parameter-handler": "~2.1",
+ "stefk/incenteev-parameters": "dev-master",
"symfony/symfony": "~2.7.0",
"doctrine/dbal": "~2.4",
"symfony/assetic-bundle": "~2.4",
From fd8b289cf2d13edc0429d554c33d0f134a00eae4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 12:32:29 +0100
Subject: [PATCH 06/65] Sort dependencies
---
composer.json | 68 +++++++++++++++++++++++++--------------------------
1 file changed, 34 insertions(+), 34 deletions(-)
diff --git a/composer.json b/composer.json
index 646b594e7..636cfb43f 100644
--- a/composer.json
+++ b/composer.json
@@ -19,49 +19,49 @@
"ext-gd": "*",
"ext-intl": "*",
"ext-pdo_mysql": "*",
- "stefk/incenteev-parameters": "dev-master",
- "symfony/symfony": "~2.7.0",
+ "besimple/sso-auth-bundle": "*",
+ "claroline/bundle-recorder": "~6.0",
+ "claroline/front-end-bundle": ">=7.0.1,<8",
+ "claroline/installation-bundle": "~6.0",
+ "claroline/kernel-bundle": "~6.0",
+ "claroline/migration-bundle": "~6.0",
+ "cocur/slugify": "~1.0",
+ "composer/composer": "dev-master",
"doctrine/dbal": "~2.4",
- "symfony/assetic-bundle": "~2.4",
- "symfony/swiftmailer-bundle": "~2.3",
- "symfony/monolog-bundle": "~2.5",
- "doctrine/orm": "~2.4",
"doctrine/doctrine-bundle": "~1.3",
- "twig/extensions": "1.2.0",
- "sensio/distribution-bundle": "*",
- "sensio/framework-extra-bundle": "~3.0.0",
- "sensio/generator-bundle": "~2.4",
- "jms/security-extra-bundle": "1.5.1",
- "jms/di-extra-bundle": "1.5.0",
- "jms/twig-js-bundle": "1.0.0",
- "jms/serializer-bundle": "~0.13",
- "stof/doctrine-extensions-bundle": "1.1.0",
- "gedmo/doctrine-extensions": "~2.3",
+ "doctrine/orm": "~2.4",
"friendsofsymfony/jsrouting-bundle": "~1.5",
- "friendsofsymfony/rest-bundle": "~1.4",
"friendsofsymfony/oauth-server-bundle": "~1.4",
- "stfalcon/tinymce-bundle": "0.3.8",
- "white-october/pagerfanta-bundle": "1.0.2",
+ "friendsofsymfony/rest-bundle": "~1.4",
+ "gedmo/doctrine-extensions": "~2.3",
+ "gregwar/captcha-bundle": "1.0.12",
"idci/exporter-bundle": "1.0.0",
+ "jms/di-extra-bundle": "1.5.0",
+ "jms/security-extra-bundle": "1.5.1",
+ "jms/serializer-bundle": "~0.13",
+ "jms/twig-js-bundle": "1.0.0",
+ "johngrogg/ics-parser": "dev-master",
+ "knplabs/knp-menu-bundle": "2.0.0",
"leafo/lessphp": "0.4.0",
- "zenstruck/form-bundle": "1.5.1",
- "zendframework/zend-crypt": "~2.3",
- "besimple/sso-auth-bundle": "*",
- "composer/composer": "dev-master",
- "willdurand/js-translation-bundle": "~2.1",
"mrclay/minify": "~2.2",
"natxet/CssMin": "3.0.2",
- "werkint/jsmin": "1.0.0",
"nelmio/api-doc-bundle": "dev-master",
- "claroline/bundle-recorder": "~6.0",
- "claroline/kernel-bundle": "~6.0",
- "claroline/installation-bundle": "~6.0",
- "claroline/front-end-bundle": ">=7.0.1,<8",
- "claroline/migration-bundle": "~6.0",
- "johngrogg/ics-parser": "dev-master",
- "gregwar/captcha-bundle": "1.0.12",
- "knplabs/knp-menu-bundle": "2.0.0",
- "cocur/slugify": "~1.0"
+ "sensio/distribution-bundle": "*",
+ "sensio/framework-extra-bundle": "~3.0.0",
+ "sensio/generator-bundle": "~2.4",
+ "stefk/incenteev-parameters": "dev-master",
+ "stfalcon/tinymce-bundle": "0.3.8",
+ "stof/doctrine-extensions-bundle": "1.1.0",
+ "symfony/assetic-bundle": "~2.4",
+ "symfony/monolog-bundle": "~2.5",
+ "symfony/swiftmailer-bundle": "~2.3",
+ "symfony/symfony": "~2.7.0",
+ "twig/extensions": "1.2.0",
+ "werkint/jsmin": "1.0.0",
+ "white-october/pagerfanta-bundle": "1.0.2",
+ "willdurand/js-translation-bundle": "~2.1",
+ "zendframework/zend-crypt": "~2.3",
+ "zenstruck/form-bundle": "1.5.1"
},
"autoload": {
"psr-4": { "Claroline\\CoreBundle\\": "" }
From a469ddb8b35e7d4ebcceb3e22616045ea6f8a7af Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 14:35:18 +0100
Subject: [PATCH 07/65] Add script handler to check node/npm dependencies
---
Library/Installation/ScriptHandler.php | 83 ++++++++++++++++++++++++++
composer.json | 1 +
2 files changed, 84 insertions(+)
create mode 100644 Library/Installation/ScriptHandler.php
diff --git a/Library/Installation/ScriptHandler.php b/Library/Installation/ScriptHandler.php
new file mode 100644
index 000000000..af9c3fc3d
--- /dev/null
+++ b/Library/Installation/ScriptHandler.php
@@ -0,0 +1,83 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Installation;
+
+use Composer\IO\ConsoleIO;
+use Composer\Script\Event;
+use Composer\Semver\Comparator;
+use Composer\Semver\VersionParser;
+use Symfony\Component\Process\Process;
+
+class ScriptHandler
+{
+ const MIN_NODE_VERSION = '5.5.0.0';
+ const MIN_NPM_VERSION = '3.7.0.0';
+
+ public static function checkEnvironment(Event $event)
+ {
+ $io = $event->getIO();
+ $parser = new VersionParser();
+ static::checkNode($io, $parser);
+ }
+
+ private static function checkNode(ConsoleIO $io, VersionParser $parser)
+ {
+ $io->write('Checking node and npm dependencies...');
+
+ $nodeVersion = static::getExecutableVersion(
+ $parser,
+ 'node -v',
+ 'Cannot get Node.js version: node executable may be missing on your system'
+ );
+
+ if (!Comparator::greaterThanOrEqualTo($nodeVersion, self::MIN_NODE_VERSION)) {
+ throw new \RuntimeException(sprintf(
+ "Your Node.js version is below the minimal requirement: expected >= %s, found %s.\n" .
+ "If no recent version of Node.js is available as an official package or installer for \n" .
+ "your OS, consider using a version manager like nvm (http://github.com/creationix/nvm).",
+ self::MIN_NODE_VERSION,
+ $version
+ ));
+ }
+
+ $io->write(sprintf('Node.js version: %s (OK)', $nodeVersion));
+
+ $npmVersion = static::getExecutableVersion(
+ $parser,
+ 'npm -v',
+ 'Cannot get npm version: npm executable may be missing on your system'
+ );
+
+ if (!Comparator::greaterThanOrEqualTo($npmVersion, self::MIN_NPM_VERSION)) {
+ throw new \RuntimeException(sprintf(
+ "Your npm version is below the minimal requirement: expected >= %s, found %s.\n" .
+ "You should be able to upgrade it with: npm install -g npm@latest",
+ self::MIN_NPM_VERSION,
+ $npmVersion
+ ));
+ }
+
+ $io->write(sprintf('npm version: %s (OK)', $npmVersion));
+ }
+
+ private static function getExecutableVersion(VersionParser $parser, $versionCmd, $notFoundMsg)
+ {
+ $process = new Process($versionCmd);
+ $process->run();
+
+ if (!$process->isSuccessful()) {
+ throw new \RuntimeException($notFoundMsg);
+ }
+
+ return $parser->normalize($process->getOutput());
+ }
+}
diff --git a/composer.json b/composer.json
index 636cfb43f..7b7185fc8 100644
--- a/composer.json
+++ b/composer.json
@@ -27,6 +27,7 @@
"claroline/migration-bundle": "~6.0",
"cocur/slugify": "~1.0",
"composer/composer": "dev-master",
+ "composer/semver": "dev-master",
"doctrine/dbal": "~2.4",
"doctrine/doctrine-bundle": "~1.3",
"doctrine/orm": "~2.4",
From 1ed61fcf24763d0483c5fa729c89b3e92eaea5e8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 17:03:30 +0100
Subject: [PATCH 08/65] Move deps back from main composer.json
---
composer.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/composer.json b/composer.json
index 7b7185fc8..84ebc0398 100644
--- a/composer.json
+++ b/composer.json
@@ -36,6 +36,7 @@
"friendsofsymfony/rest-bundle": "~1.4",
"gedmo/doctrine-extensions": "~2.3",
"gregwar/captcha-bundle": "1.0.12",
+ "hwi/oauth-bundle": "0.4.*@dev",
"idci/exporter-bundle": "1.0.0",
"jms/di-extra-bundle": "1.5.0",
"jms/security-extra-bundle": "1.5.1",
@@ -47,7 +48,7 @@
"mrclay/minify": "~2.2",
"natxet/CssMin": "3.0.2",
"nelmio/api-doc-bundle": "dev-master",
- "sensio/distribution-bundle": "*",
+ "sensio/distribution-bundle": "~2.3.4",
"sensio/framework-extra-bundle": "~3.0.0",
"sensio/generator-bundle": "~2.4",
"stefk/incenteev-parameters": "dev-master",
From d4e8bf2f1e3d6335ec979581fd25128827888519 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sat, 13 Feb 2016 18:33:15 +0100
Subject: [PATCH 09/65] Add missing 'end()'
---
Library/Installation/Plugin/Configuration.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Library/Installation/Plugin/Configuration.php b/Library/Installation/Plugin/Configuration.php
index 308505dd9..af271c097 100644
--- a/Library/Installation/Plugin/Configuration.php
+++ b/Library/Installation/Plugin/Configuration.php
@@ -331,7 +331,7 @@ private function addAdminToolSection(NodeBuilder $pluginSection)
->prototype('array')
->children()
->scalarNode('name')->isRequired()->end()
- ->scalarNode('class')
+ ->scalarNode('class')->end()
->end()
->end()
->end()
From 78c9bd2ca2c0723ef00689a3a1eb88a8866868ca Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Sun, 14 Feb 2016 19:11:39 +0100
Subject: [PATCH 10/65] Support webpack config per bundle
---
Resources/scripts/lib/collect-packages.js | 68 +++++++++++++++++
Resources/scripts/lib/webpack.js | 73 +++++++++++++++++--
.../scripts/test/collect-packages_test.js | 71 ++++++++++++++++++
.../scripts/test/data/invalid/empty/.gitkeep | 0
.../vendor/composer/installed.json | 1 +
.../valid/node_modules/barLib/bar-content.txt | 0
.../valid/node_modules/devLib/dev-content.txt | 0
.../valid/node_modules/fooLib/foo-content.txt | 0
.../valid/vendor/baz/quz-bundle/assets.json | 7 ++
.../data/valid/vendor/composer/installed.json | 39 ++++++++++
.../valid/vendor/ext/ext-bundle/composer.json | 3 +
.../foo/bar-bundle/Foo/BarBundle/assets.json | 8 ++
.../scripts/test/data/valid/web/.gitkeep | 0
Resources/scripts/test/webpack_test.js | 38 ++++++++++
assets.json | 8 ++
package.json | 6 ++
16 files changed, 315 insertions(+), 7 deletions(-)
create mode 100644 Resources/scripts/lib/collect-packages.js
create mode 100644 Resources/scripts/test/collect-packages_test.js
create mode 100644 Resources/scripts/test/data/invalid/empty/.gitkeep
create mode 100644 Resources/scripts/test/data/invalid/no-packages/vendor/composer/installed.json
create mode 100644 Resources/scripts/test/data/valid/node_modules/barLib/bar-content.txt
create mode 100644 Resources/scripts/test/data/valid/node_modules/devLib/dev-content.txt
create mode 100644 Resources/scripts/test/data/valid/node_modules/fooLib/foo-content.txt
create mode 100644 Resources/scripts/test/data/valid/vendor/baz/quz-bundle/assets.json
create mode 100644 Resources/scripts/test/data/valid/vendor/composer/installed.json
create mode 100644 Resources/scripts/test/data/valid/vendor/ext/ext-bundle/composer.json
create mode 100644 Resources/scripts/test/data/valid/vendor/foo/bar-bundle/Foo/BarBundle/assets.json
create mode 100644 Resources/scripts/test/data/valid/web/.gitkeep
create mode 100644 Resources/scripts/test/webpack_test.js
create mode 100644 assets.json
diff --git a/Resources/scripts/lib/collect-packages.js b/Resources/scripts/lib/collect-packages.js
new file mode 100644
index 000000000..4ff275862
--- /dev/null
+++ b/Resources/scripts/lib/collect-packages.js
@@ -0,0 +1,68 @@
+const assert = require('assert')
+const fs = require('fs')
+
+/**
+ * Collects information about currently installed
+ * claroline packages. Each package will be represented
+ * as an object literal with the following attributes:
+ *
+ * - name: name of the package declared in its composer.json file
+ * - path: path of the package source directory
+ * - assets: package assets config declared its assets.json file, if any
+ */
+function collectPackages(rootDir) {
+ assert.equal(typeof rootDir, 'string', 'Expected string')
+
+ const stats = fs.statSync(rootDir);
+
+ if (!stats.isDirectory()) {
+ throw new Error(`${rootDir} is not a directory`)
+ }
+
+ return getPackageDefinitions(rootDir)
+}
+
+function getPackageDefinitions(rootDir) {
+ const file = `${rootDir}/vendor/composer/installed.json`
+ var data
+
+ try {
+ data = fs.readFileSync(file, 'utf8')
+ } catch (err) {
+ throw new Error('Cannot found package info (composer/installed.json)')
+ }
+
+ const packages = JSON.parse(data)
+
+ if (!(packages instanceof Array) || packages.length < 1) {
+ throw new Error('Cannot find packages in composer/installed.json')
+ }
+
+ const filteredPackages = packages.filter(def =>
+ def.type === 'claroline-core' || def.type === 'claroline-plugin'
+ )
+
+ return filteredPackages.map(extractPackageInfo(rootDir))
+}
+
+function extractPackageInfo(rootDir) {
+ return def => {
+ const targetDir = def['target-dir'] ? `/${def['target-dir']}` : ''
+ const path = `${rootDir}/vendor/${def.name}${targetDir}`
+ const newDef = {
+ name: def.name,
+ path,
+ assets: false
+ }
+ var data
+
+ try {
+ data = fs.readFileSync(`${path}/assets.json`, 'utf8')
+ newDef.assets = JSON.parse(data)
+ } catch (err) {}
+
+ return newDef
+ }
+}
+
+module.exports = collectPackages
diff --git a/Resources/scripts/lib/webpack.js b/Resources/scripts/lib/webpack.js
index 0de470f22..8dbfb4312 100644
--- a/Resources/scripts/lib/webpack.js
+++ b/Resources/scripts/lib/webpack.js
@@ -4,20 +4,28 @@ const webpack = require('webpack')
/**
* Builds a webpack configuration suitable for export.
*
- * @param frontendConfig The configuration from app/config/frontend.json
* @param rootDir The path of the root directory of the application
+ * @param packages An array of bundles configs
* @param isWatchMode Whether webpack is to be run in watch mode
* @returns Object
*/
-function configure(frontendConfig, rootDir, isWatchMode) {
+function configure(rootDir, packages, isWatchMode) {
const isProd = !isWatchMode
- const entries = frontendConfig.webpack.entry
+
+ // first we must parse the webpack configs of each bundle
+ // and prefix/normalize them to avoid name collisions
+ const webpackPackages = packages.filter(def => def.assets && def.assets.webpack)
+ const bundles = webpackPackages.map(def => def.name)
+ const normalizedPackages = normalizeNames(webpackPackages)
+ const normalizedBundles = normalizedPackages.map(def => def.name)
+ const entries = extractEntries(normalizedPackages)
+ const commons = extractCommons(normalizedPackages)
// all entries are compiled in the web/dist directory
const output = {
- path: path.resolve(rootDir, 'web'),
+ path: path.resolve(rootDir, 'web/dist'),
publicPath: 'http://localhost:8080/',
- filename: 'dist/[name].js'
+ filename: '[name].js'
}
// third-party modules are taken from the web/packages directory,
@@ -27,10 +35,10 @@ function configure(frontendConfig, rootDir, isWatchMode) {
// in every environment, plugins are needed for things like bower
// modules support, bundle resolution, common chunks extraction, etc.
const plugins = [
- makeBundleResolverPlugin(frontendConfig.bundles),
+ makeBundleResolverPlugin(normalizedBundles),
makeBowerPlugin(),
//makeBaseCommonsPlugin(),
- ...makeBundleCommonsPlugins(frontendConfig.webpack.commons)
+ ...makeBundleCommonsPlugins(commons)
]
// prod build has additional constraints
@@ -60,10 +68,61 @@ function configure(frontendConfig, rootDir, isWatchMode) {
module: { loaders: loaders },
devServer: {
headers: { "Access-Control-Allow-Origin": "*" }
+ },
+ _debug: {
+ 'Detected webpack configs': bundles,
+ 'Compiled entries': entries,
+ 'Compiled common chunks': commons
}
}
}
+/**
+ * Removes the "bundle" portion of package names and replaces
+ * slashes by hyphens. Example:
+ *
+ * "foo/bar-bundle" -> "foo-bar"
+ */
+function normalizeNames(packages) {
+ return packages.map(def => {
+ var parts = def.name.split(/\/|\-/)
+
+ if (parts[parts.length - 1] === 'bundle') {
+ parts.pop()
+ }
+
+ def.name = parts.join('-')
+
+ return def
+ })
+}
+
+/**
+ * Merges "entry" sections of package configs into one object,
+ * prefixing entry names and paths with package names/paths.
+ */
+function extractEntries(packages) {
+ return packages
+ .filter(def => def.assets.webpack && def.assets.webpack.entry)
+ .reduce((entries, def) => {
+ Object.keys(def.assets.webpack.entry).forEach(entry => {
+ entries[`${def.name}-${entry}`] = `${def.path}/${def.assets.webpack.entry[entry]}`
+ })
+
+ return entries
+ }, {})
+}
+
+/**
+ * TODO: Implement this function
+ *
+ * Merges the "commons" sections of package configs.
+ *
+ */
+function extractCommons(packages) {
+ return []
+}
+
/**
* This plugin allows webpack to discover entry files of modules
* stored in the bower web/packages directory by inspecting their
diff --git a/Resources/scripts/test/collect-packages_test.js b/Resources/scripts/test/collect-packages_test.js
new file mode 100644
index 000000000..efc0593e6
--- /dev/null
+++ b/Resources/scripts/test/collect-packages_test.js
@@ -0,0 +1,71 @@
+const assert = require('assert')
+const collectPackages = require('../lib/collect-packages')
+const dataRoot = `${__dirname}/data`
+
+describe('collectPackages()', () => {
+ it('should err if the root directory doesn\'t exist', () => {
+ assert.throws(
+ () => collectPackages('does/not/exist'),
+ /no such file or directory/
+ )
+ })
+
+ it('should err if the root is not a directory', () => {
+ assert.throws(
+ () => collectPackages(`${dataRoot}/invalid/empty/.gitkeep`),
+ `${dataRoot}/invalid/empty/.gitkeep is not a directory`
+ )
+ })
+
+ it('should err if composer/installed.json doesn\'t exist', () => {
+ assert.throws(
+ () => collectPackages(`${dataRoot}/invalid/empty`),
+ 'Cannot found package info (composer/installed.json)'
+ )
+ })
+
+ it('should err if no packages are found in installed.json', () => {
+ assert.throws(
+ () => collectPackages(`${dataRoot}/invalid/no-packages`),
+ 'Cannot find packages in composer/installed.json'
+ )
+ })
+
+ it('should keep only claroline packages', () => {
+ assert.equal(collectPackages(`${dataRoot}/valid`).length, 3)
+ })
+
+ it('should extract useful attributes and load configs if any', () => {
+ const packages = collectPackages(`${dataRoot}/valid`)
+ assert.deepEqual(packages, [
+ {
+ name: 'foo/bar-bundle',
+ path: `${dataRoot}/valid/vendor/foo/bar-bundle/Foo/BarBundle`,
+ assets: {
+ webpack: {
+ entry: {
+ mod1: 'modules/mod1/main',
+ mod2: 'modules/mod2/index'
+ }
+ }
+ }
+ },
+ {
+ name: 'baz/quz-bundle',
+ path: `${dataRoot}/valid/vendor/baz/quz-bundle`,
+ assets: {
+ webpack: {
+ entry: {
+ fooScript: 'js/foo.js'
+ }
+ }
+ }
+ },
+ {
+ name: 'ext/ext-bundle',
+ path: `${dataRoot}/valid/vendor/ext/ext-bundle`,
+ assets: false
+ },
+ ])
+ })
+})
diff --git a/Resources/scripts/test/data/invalid/empty/.gitkeep b/Resources/scripts/test/data/invalid/empty/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/Resources/scripts/test/data/invalid/no-packages/vendor/composer/installed.json b/Resources/scripts/test/data/invalid/no-packages/vendor/composer/installed.json
new file mode 100644
index 000000000..fe51488c7
--- /dev/null
+++ b/Resources/scripts/test/data/invalid/no-packages/vendor/composer/installed.json
@@ -0,0 +1 @@
+[]
diff --git a/Resources/scripts/test/data/valid/node_modules/barLib/bar-content.txt b/Resources/scripts/test/data/valid/node_modules/barLib/bar-content.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/Resources/scripts/test/data/valid/node_modules/devLib/dev-content.txt b/Resources/scripts/test/data/valid/node_modules/devLib/dev-content.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/Resources/scripts/test/data/valid/node_modules/fooLib/foo-content.txt b/Resources/scripts/test/data/valid/node_modules/fooLib/foo-content.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/Resources/scripts/test/data/valid/vendor/baz/quz-bundle/assets.json b/Resources/scripts/test/data/valid/vendor/baz/quz-bundle/assets.json
new file mode 100644
index 000000000..91c5b47ae
--- /dev/null
+++ b/Resources/scripts/test/data/valid/vendor/baz/quz-bundle/assets.json
@@ -0,0 +1,7 @@
+{
+ "webpack": {
+ "entry": {
+ "fooScript": "js/foo.js"
+ }
+ }
+}
diff --git a/Resources/scripts/test/data/valid/vendor/composer/installed.json b/Resources/scripts/test/data/valid/vendor/composer/installed.json
new file mode 100644
index 000000000..80bcaaf22
--- /dev/null
+++ b/Resources/scripts/test/data/valid/vendor/composer/installed.json
@@ -0,0 +1,39 @@
+[
+ {
+ "name": "behat/transliterator",
+ "version": "v1.1.0",
+ "version_normalized": "1.1.0.0",
+ "type": "library"
+ },
+ {
+ "name": "gedmo/doctrine-extensions",
+ "version": "v2.3.12",
+ "version_normalized": "2.3.12.0",
+ "type": "library"
+ },
+ {
+ "name": "foo/bar-bundle",
+ "version": "v6.0.2",
+ "version_normalized": "6.0.2.0",
+ "target-dir": "Foo/BarBundle",
+ "type": "claroline-core"
+ },
+ {
+ "name": "stof/doctrine-extensions-bundle",
+ "version": "v1.1.0",
+ "version_normalized": "1.1.0.0",
+ "target-dir": "Stof/DoctrineExtensionsBundle"
+ },
+ {
+ "name": "baz/quz-bundle",
+ "version": "v6.2.6",
+ "version_normalized": "6.2.6.0",
+ "type": "claroline-plugin"
+ },
+ {
+ "name": "ext/ext-bundle",
+ "version": "v5.3.3",
+ "version_normalized": "5.3.3.0",
+ "type": "claroline-plugin"
+ }
+]
diff --git a/Resources/scripts/test/data/valid/vendor/ext/ext-bundle/composer.json b/Resources/scripts/test/data/valid/vendor/ext/ext-bundle/composer.json
new file mode 100644
index 000000000..cf0257051
--- /dev/null
+++ b/Resources/scripts/test/data/valid/vendor/ext/ext-bundle/composer.json
@@ -0,0 +1,3 @@
+{
+ "name": "ext/ext-bundle"
+}
diff --git a/Resources/scripts/test/data/valid/vendor/foo/bar-bundle/Foo/BarBundle/assets.json b/Resources/scripts/test/data/valid/vendor/foo/bar-bundle/Foo/BarBundle/assets.json
new file mode 100644
index 000000000..0363b7c2f
--- /dev/null
+++ b/Resources/scripts/test/data/valid/vendor/foo/bar-bundle/Foo/BarBundle/assets.json
@@ -0,0 +1,8 @@
+{
+ "webpack": {
+ "entry": {
+ "mod1": "modules/mod1/main",
+ "mod2": "modules/mod2/index"
+ }
+ }
+}
diff --git a/Resources/scripts/test/data/valid/web/.gitkeep b/Resources/scripts/test/data/valid/web/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/Resources/scripts/test/webpack_test.js b/Resources/scripts/test/webpack_test.js
new file mode 100644
index 000000000..93c1f39b8
--- /dev/null
+++ b/Resources/scripts/test/webpack_test.js
@@ -0,0 +1,38 @@
+const assert = require('assert')
+const buildConfig = require('./../lib/webpack')
+
+describe('buildConfig()', () => {
+ it('should prefix entries by bundle short name and full path', () => {
+ const packages = [
+ {
+ name: 'foo/bar-bundle',
+ path: '/home/bob/src/foo/bar-bundle',
+ assets: {
+ webpack: {
+ entry: {
+ mod1: 'modules/mod1/main'
+ }
+ }
+ }
+ },
+ {
+ name: 'baz/quz-123-bundle',
+ path: '/home/bob/src/baz/quz-123-bundle',
+ assets: {
+ webpack: {
+ entry: {
+ comp1: 'components/comp1/index',
+ comp2: 'components/comp2/main'
+ }
+ }
+ }
+ }
+ ]
+ const config = buildConfig(__dirname, packages)
+ assert.deepEqual(config.entry, {
+ 'foo-bar-mod1': '/home/bob/src/foo/bar-bundle/modules/mod1/main',
+ 'baz-quz-123-comp1': '/home/bob/src/baz/quz-123-bundle/components/comp1/index',
+ 'baz-quz-123-comp2': '/home/bob/src/baz/quz-123-bundle/components/comp2/main'
+ })
+ })
+})
diff --git a/assets.json b/assets.json
new file mode 100644
index 000000000..67b88de7e
--- /dev/null
+++ b/assets.json
@@ -0,0 +1,8 @@
+{
+ "webpack": {
+ "entry": {
+ "mod-1": "modules/foo",
+ "mod-2": "modules/bar"
+ }
+ }
+}
diff --git a/package.json b/package.json
index 4074c1a4d..7ca068f20 100644
--- a/package.json
+++ b/package.json
@@ -3,18 +3,24 @@
"version": "1.0.0",
"description": "core dev dependencies",
"dependencies": {
+ "async": "^1.5.2",
"autoprefixer": "^6.3.1",
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-plugin-transform-runtime": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"bower": "^1.7.7",
+ "colors": "^1.1.2",
"cssnano": "^3.4.0",
"filesystem-bower-resolver": "^1.2.0",
"less": "^2.5.3",
+ "mocha": "^2.4.5",
"postcss-cli": "^2.5.0",
"shelljs": "^0.5.3",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
+ },
+ "scripts": {
+ "test": "mocha Resources/scripts/test"
}
}
From 7d75b802d01d268a6d81e8f0f5f4f1407cb863fc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 15 Feb 2016 13:50:50 +0100
Subject: [PATCH 11/65] Add fail on error plugin for webpack
---
Resources/scripts/lib/webpack.js | 14 +++++++++++++-
package.json | 3 ++-
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/Resources/scripts/lib/webpack.js b/Resources/scripts/lib/webpack.js
index 8dbfb4312..4855dceb8 100644
--- a/Resources/scripts/lib/webpack.js
+++ b/Resources/scripts/lib/webpack.js
@@ -1,5 +1,6 @@
const path = require('path')
const webpack = require('webpack')
+const failPlugin = require('webpack-fail-plugin')
/**
* Builds a webpack configuration suitable for export.
@@ -48,7 +49,8 @@ function configure(rootDir, packages, isWatchMode) {
makeUglifyJsPlugin(),
makeDedupePlugin(),
makeDefinePlugin(),
- makeNoErrorsPlugin()
+ makeNoErrorsPlugin(),
+ makeFailOnErrorPlugin()
)
}
@@ -221,6 +223,16 @@ function makeNoErrorsPlugin() {
})
}
+/**
+ * This plugin makes webpack exit with a non-zero status code
+ * in case of error when not in watch mode.
+ *
+ * @see https://github.com/webpack/webpack/issues/708
+ */
+function makeFailOnErrorPlugin() {
+ return failPlugin
+}
+
/**
* This loader enables es6 transpilation with babel.
*/
diff --git a/package.json b/package.json
index 7ca068f20..fdbc2651c 100644
--- a/package.json
+++ b/package.json
@@ -18,7 +18,8 @@
"postcss-cli": "^2.5.0",
"shelljs": "^0.5.3",
"webpack": "^1.12.13",
- "webpack-dev-server": "^1.14.1"
+ "webpack-dev-server": "^1.14.1",
+ "webpack-fail-plugin": "^1.0.4"
},
"scripts": {
"test": "mocha Resources/scripts/test"
From 4dd49c9a12541a5a69daf91aed76832af56f2db9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 15 Feb 2016 14:51:39 +0100
Subject: [PATCH 12/65] Add raw loader + fix assets config
---
Resources/scripts/lib/webpack.js | 16 ++++++++++++++--
Resources/scripts/test/webpack_test.js | 6 +++---
assets.json | 3 +--
package.json | 1 +
4 files changed, 19 insertions(+), 7 deletions(-)
diff --git a/Resources/scripts/lib/webpack.js b/Resources/scripts/lib/webpack.js
index 4855dceb8..732b8ef57 100644
--- a/Resources/scripts/lib/webpack.js
+++ b/Resources/scripts/lib/webpack.js
@@ -56,6 +56,7 @@ function configure(rootDir, packages, isWatchMode) {
const loaders = [
makeJsLoader(isProd),
+ makeRawLoader()
{
test: /\.html/,
loader: 'raw'
@@ -108,7 +109,7 @@ function extractEntries(packages) {
.filter(def => def.assets.webpack && def.assets.webpack.entry)
.reduce((entries, def) => {
Object.keys(def.assets.webpack.entry).forEach(entry => {
- entries[`${def.name}-${entry}`] = `${def.path}/${def.assets.webpack.entry[entry]}`
+ entries[`${def.name}-${entry}`] = `${def.path}/Resources/${def.assets.webpack.entry[entry]}`
})
return entries
@@ -179,7 +180,7 @@ function makeBaseCommonsPlugin() {
function makeBundleCommonsPlugins(commons) {
return commons.map(config => {
return new webpack.optimize.CommonsChunkPlugin(config)
- });
+ })
}
/**
@@ -249,4 +250,15 @@ function makeJsLoader(isProd) {
}
}
+/**
+ * This loader returns the file content as plain string,
+ * without any transformation.
+ */
+function makeRawLoader() {
+ return {
+ test: /\.html$/,
+ loader: 'raw'
+ }
+}
+
module.exports = configure
diff --git a/Resources/scripts/test/webpack_test.js b/Resources/scripts/test/webpack_test.js
index 93c1f39b8..168218ee8 100644
--- a/Resources/scripts/test/webpack_test.js
+++ b/Resources/scripts/test/webpack_test.js
@@ -30,9 +30,9 @@ describe('buildConfig()', () => {
]
const config = buildConfig(__dirname, packages)
assert.deepEqual(config.entry, {
- 'foo-bar-mod1': '/home/bob/src/foo/bar-bundle/modules/mod1/main',
- 'baz-quz-123-comp1': '/home/bob/src/baz/quz-123-bundle/components/comp1/index',
- 'baz-quz-123-comp2': '/home/bob/src/baz/quz-123-bundle/components/comp2/main'
+ 'foo-bar-mod1': '/home/bob/src/foo/bar-bundle/Resources/modules/mod1/main',
+ 'baz-quz-123-comp1': '/home/bob/src/baz/quz-123-bundle/Resources/components/comp1/index',
+ 'baz-quz-123-comp2': '/home/bob/src/baz/quz-123-bundle/Resources/components/comp2/main'
})
})
})
diff --git a/assets.json b/assets.json
index 67b88de7e..114ab0441 100644
--- a/assets.json
+++ b/assets.json
@@ -1,8 +1,7 @@
{
"webpack": {
"entry": {
- "mod-1": "modules/foo",
- "mod-2": "modules/bar"
+ "user-management": "modules/users/module"
}
}
}
diff --git a/package.json b/package.json
index fdbc2651c..60a751cb3 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"less": "^2.5.3",
"mocha": "^2.4.5",
"postcss-cli": "^2.5.0",
+ "raw-loader": "^0.5.1",
"shelljs": "^0.5.3",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1",
From d2bec9d17f8ed0c3c33ea15a2af98a12248ef8c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 15 Feb 2016 15:41:34 +0100
Subject: [PATCH 13/65] Fix missing comma
---
Resources/scripts/lib/webpack.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Resources/scripts/lib/webpack.js b/Resources/scripts/lib/webpack.js
index 732b8ef57..a99fc8db2 100644
--- a/Resources/scripts/lib/webpack.js
+++ b/Resources/scripts/lib/webpack.js
@@ -56,7 +56,7 @@ function configure(rootDir, packages, isWatchMode) {
const loaders = [
makeJsLoader(isProd),
- makeRawLoader()
+ makeRawLoader(),
{
test: /\.html/,
loader: 'raw'
From 70c1ca8311edab5bdef6ffe1e994016c3a600cd4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 15 Feb 2016 16:20:23 +0100
Subject: [PATCH 14/65] Add db creation attempt in claroline:update
---
Command/PlatformUpdateCommand.php | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/Command/PlatformUpdateCommand.php b/Command/PlatformUpdateCommand.php
index e3d83af9c..8f265df7d 100644
--- a/Command/PlatformUpdateCommand.php
+++ b/Command/PlatformUpdateCommand.php
@@ -12,7 +12,9 @@
namespace Claroline\CoreBundle\Command;
use Claroline\CoreBundle\Library\Maintenance\MaintenanceHandler;
+use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand;
use Psr\Log\LogLevel;
+use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
@@ -44,6 +46,11 @@ protected function configure()
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(sprintf('%s - Updating the platform... ', date('H:i:s')));
+
+ $databaseCreator = new CreateDatabaseDoctrineCommand();
+ $databaseCreator->setContainer($this->getContainer());
+ $databaseCreator->run(new ArrayInput(array()), $output);
+
$verbosityLevelMap = array(
LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL,
From 6814d2471829d143234e392f4c3a72e8f62dc668 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 15 Feb 2016 17:03:39 +0100
Subject: [PATCH 15/65] Add missing module
---
assets.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/assets.json b/assets.json
index 114ab0441..915ccbef6 100644
--- a/assets.json
+++ b/assets.json
@@ -1,7 +1,8 @@
{
"webpack": {
"entry": {
- "user-management": "modules/users/module"
+ "user-management": "modules/groups/module",
+ "organization-management": "modules/organization/module"
}
}
}
From 3eca200f377b8ac7c506b94f6bad4cffd5bde434 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Tue, 16 Feb 2016 09:36:55 +0100
Subject: [PATCH 16/65] Remove composer from explicit deps
---
composer.json | 2 --
1 file changed, 2 deletions(-)
diff --git a/composer.json b/composer.json
index 84ebc0398..742e0b23c 100644
--- a/composer.json
+++ b/composer.json
@@ -26,8 +26,6 @@
"claroline/kernel-bundle": "~6.0",
"claroline/migration-bundle": "~6.0",
"cocur/slugify": "~1.0",
- "composer/composer": "dev-master",
- "composer/semver": "dev-master",
"doctrine/dbal": "~2.4",
"doctrine/doctrine-bundle": "~1.3",
"doctrine/orm": "~2.4",
From 41bffc8b8e657096b853761d0f3641663396201c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Tue, 16 Feb 2016 17:41:05 +0100
Subject: [PATCH 17/65] Change update strategy (use diff of local repos)
---
Command/PlatformUpdateCommand.php | 2 +-
Library/Installation/ExecutorException.php | 19 ++
Library/Installation/Operation.php | 86 ++++++++
Library/Installation/OperationExecutor.php | 193 +++++++++++++++---
Library/Installation/PlatformInstaller.php | 16 +-
Tests/Stub/repo/empty.json | 1 +
Tests/Stub/repo/not-array.json | 1 +
Tests/Stub/repo/not-json.json | 1 +
Tests/Stub/repo/repo-1.json | 17 ++
Tests/Stub/repo/repo-2.json | 17 ++
Tests/Stub/repo/repo-3.json | 22 ++
.../Installation/OperationExecutorTest.php | 188 +++++++++++++++++
package.json | 5 +-
phpunit.xml | 34 +++
14 files changed, 561 insertions(+), 41 deletions(-)
create mode 100644 Library/Installation/ExecutorException.php
create mode 100644 Library/Installation/Operation.php
create mode 100644 Tests/Stub/repo/empty.json
create mode 100644 Tests/Stub/repo/not-array.json
create mode 100644 Tests/Stub/repo/not-json.json
create mode 100644 Tests/Stub/repo/repo-1.json
create mode 100644 Tests/Stub/repo/repo-2.json
create mode 100644 Tests/Stub/repo/repo-3.json
create mode 100644 Tests/Unit/Library/Installation/OperationExecutorTest.php
create mode 100644 phpunit.xml
diff --git a/Command/PlatformUpdateCommand.php b/Command/PlatformUpdateCommand.php
index 8f265df7d..16d957842 100644
--- a/Command/PlatformUpdateCommand.php
+++ b/Command/PlatformUpdateCommand.php
@@ -62,7 +62,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$installer = $this->getContainer()->get('claroline.installation.platform_installer');
$installer->setOutput($output);
$installer->setLogger($consoleLogger);
- $installer->installFromOperationFile();
+ $installer->updateFromComposerInfo();
/** @var \Claroline\CoreBundle\Library\Installation\Refresher $refresher */
$refresher = $this->getContainer()->get('claroline.installation.refresher');
diff --git a/Library/Installation/ExecutorException.php b/Library/Installation/ExecutorException.php
new file mode 100644
index 000000000..3663e857b
--- /dev/null
+++ b/Library/Installation/ExecutorException.php
@@ -0,0 +1,19 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Installation;
+
+class ExecutorException extends \Exception
+{
+ const REPO_NOT_FOUND = 11;
+ const REPO_NOT_JSON = 12;
+ const REPO_NOT_ARRAY = 13;
+}
diff --git a/Library/Installation/Operation.php b/Library/Installation/Operation.php
new file mode 100644
index 000000000..b8b51d897
--- /dev/null
+++ b/Library/Installation/Operation.php
@@ -0,0 +1,86 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Installation;
+
+/**
+ * Holds the details of an install/update operation, such as the type
+ * of the operation, the package name, the target version, etc.
+ */
+class Operation
+{
+ const INSTALL = 'install';
+ const UPDATE = 'update';
+
+ private $type;
+ private $package;
+ private $bundleFqcn;
+ private $fromVersion;
+ private $toVersion;
+
+ public function __construct($type, \stdClass $package, $bundleFqcn)
+ {
+ if (!in_array($type, [self::INSTALL, self::UPDATE])) {
+ throw new \InvalidArgumentException(
+ 'Operation type must be an Operation::* class constant'
+ );
+ }
+
+ $this->type = $type;
+ $this->package = $package;
+ $this->bundleFqcn = $bundleFqcn;
+ }
+
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ public function getPackageName()
+ {
+ return $this->package->name;
+ }
+
+ public function getPackageType()
+ {
+ return $this->package->type;
+ }
+
+ public function getBundleFqcn()
+ {
+ return $this->bundleFqcn;
+ }
+
+ public function setFromVersion($version)
+ {
+ $this->fromVersion = $version;
+ }
+
+ public function getFromVersion()
+ {
+ return $this->fromVersion;
+ }
+
+ public function setToVersion($version)
+ {
+ $this->toVersion = $version;
+ }
+
+ public function getToVersion()
+ {
+ return $this->toVersion;
+ }
+
+ public function getRawPackage()
+ {
+ return $this->package;
+ }
+}
diff --git a/Library/Installation/OperationExecutor.php b/Library/Installation/OperationExecutor.php
index dbe94b1f9..7ba74f1bc 100644
--- a/Library/Installation/OperationExecutor.php
+++ b/Library/Installation/OperationExecutor.php
@@ -11,20 +11,21 @@
namespace Claroline\CoreBundle\Library\Installation;
+use Claroline\BundleRecorder\Detector\Detector;
use Claroline\BundleRecorder\Log\LoggableTrait;
-use Psr\Log\LoggerInterface;
-use Symfony\Component\HttpKernel\KernelInterface;
use Claroline\CoreBundle\Library\Installation\Plugin\Installer;
use Claroline\InstallationBundle\Manager\InstallationManager;
-use Claroline\BundleRecorder\Handler\OperationHandler;
-use Claroline\BundleRecorder\Operation;
use JMS\DiExtraBundle\Annotation as DI;
+use Psr\Log\LoggerInterface;
+use Symfony\Component\Filesystem\Filesystem;
+use Symfony\Component\HttpKernel\KernelInterface;
/**
* @DI\Service("claroline.installation.operation_executor")
*
- * Installs/updates platform bundles as mentioned in the operation
- * file (operations.xml) generated during composer execution.
+ * Installs/updates platform bundles based on the comparison of
+ * previous and current local composer repositories (i.e. the file
+ * "vendor/composer/installed.json" and its backup in "app/config").
*/
class OperationExecutor
{
@@ -33,7 +34,9 @@ class OperationExecutor
private $kernel;
private $baseInstaller;
private $pluginInstaller;
- private $operationFile;
+ private $installedRepoFile;
+ private $previousRepoFile;
+ private $detector;
/**
* @DI\InjectParams({
@@ -51,14 +54,31 @@ public function __construct(
$this->kernel = $kernel;
$this->baseInstaller = $baseInstaller;
$this->pluginInstaller = $pluginInstaller;
+ $this->previousRepoFile = $this->kernel->getRootDir() . '/config/previous-installed.json';
+ $this->installedRepoFile = $this->kernel->getRootDir() . '/../vendor/composer/installed.json';
+ $this->detector = new Detector();
+ }
+
+ /**
+ * Overrides default local repository files (test purposes).
+ *
+ * @param string $previousRepoFile
+ * @param string $installedRepoFile
+ */
+ public function setRepositoryFiles($previousRepoFile, $installedRepoFile)
+ {
+ $this->previousRepoFile = $previousRepoFile;
+ $this->installedRepoFile = $installedRepoFile;
}
/**
- * @param string $operationFile
+ * Overrides the default bundle detector (test purposes).
+ *
+ * @param Detector $detector
*/
- public function setOperationFile($operationFile)
+ public function setBundleDetector(Detector $detector)
{
- $this->operationFile = $operationFile;
+ $this->detector = $detector;
}
/**
@@ -71,44 +91,143 @@ public function setLogger(LoggerInterface $logger)
$this->pluginInstaller->setLogger($logger);
}
- public function execute()
+ /**
+ * Builds the list of operations to be executed based on the comparison
+ * of previous and current installed dependencies.
+ *
+ * @return array
+ */
+ public function buildOperationList()
{
- $this->operationFile = $this->operationFile ?
- $this->operationFile :
- $this->kernel->getRootDir() . '/config/operations.xml';
- $operationsHandler = new OperationHandler($this->operationFile, $this->logger);
- $bundles = $this->getBundlesByFqcn();
- $operations = $operationsHandler->getOperations();
+ $this->log('Building install/update operations list...');
- /** @var \Claroline\BundleRecorder\Operation[] $orderedOperations */
- $orderedOperations = [];
- foreach ($operations as $operation) {
- if ($operation->getBundleType() === Operation::BUNDLE_CORE) {
- array_unshift($orderedOperations, $operation);
- } else {
- array_push($orderedOperations, $operation);
+ $current = $this->openRepository($this->previousRepoFile);
+ $target = $this->openRepository($this->installedRepoFile);
+ $operations = [];
+
+ foreach ($target as $targetName => $targetPackage) {
+ if (!isset($current[$targetName])) {
+ $this->log(" - Installation of {$targetName} required");
+ $operation = $this->buildOperation(Operation::INSTALL, $targetPackage);
+ $operations[$operation->getBundleFqcn()] = $operation;
+ } elseif ($targetPackage->{'version-normalized'}
+ !== $current[$targetName]->{'version-normalized'}) {
+ $this->log(" - Update of {$targetName} required");
+ $operation =$this->buildOperation(Operation::UPDATE, $targetPackage);
+ $operation->setFromVersion($current[$targetName]->{'version-normalized'});
+ $operation->setToVersion($targetPackage->{'version-normalized'});
+ $operations[$operation->getBundleFqcn()] = $operation;
}
}
- foreach ($orderedOperations as $operation) {
- $installer = $operation->getBundleType() === Operation::BUNDLE_CORE ?
+ $this->log("Sorting operations...");
+ $bundles = $this->kernel->getBundles();
+ $sortedOperations = [];
+
+ foreach ($bundles as $bundle) {
+ $bundleClass = $bundle->getNamespace() ?
+ $bundle->getNamespace() . '\\' . $bundle->getName() :
+ $bundle->getName();
+
+ if (isset($operations[$bundleClass])) {
+ $sortedOperations[] = $operations[$bundleClass];
+ }
+ }
+
+ return $sortedOperations;
+ }
+
+ /**
+ * Executes a list of install/update operations. Each successful operation
+ * is followed by an update of the previous local repository, so that the
+ * process can be resumed after an error (e.g. an error) without triggering
+ * again already executed operations. When there's no more operation to
+ * execute, the snapshot of the previous local repository is deleted.
+ *
+ * @param Operation[] $operations
+ * @throws ExecutorException if the the previous repository file is not writable
+ */
+ public function execute(array $operations)
+ {
+ $this->log("Executing install/update operations...");
+
+ $previousRepo = $this->openRepository($this->previousRepoFile, false);
+
+ if (!is_writable($this->previousRepoFile)) {
+ throw new ExecutorException("'{$this->previousRepoFile}' must be writable");
+ }
+
+ $bundles = $this->getBundlesByFqcn();
+
+ foreach ($operations as $operation) {
+ $installer = $operation->getPackageType() === 'claroline-core' ?
$this->baseInstaller :
$this->pluginInstaller;
if ($operation->getType() === Operation::INSTALL) {
$installer->install($bundles[$operation->getBundleFqcn()]);
+ $this->updatePreviousRepo($previousRepo, $operation->getRawPackage(), true);
} elseif ($operation->getType() === Operation::UPDATE) {
$installer->update(
$bundles[$operation->getBundleFqcn()],
$operation->getFromVersion(),
$operation->getToVersion()
);
- } else {
- // remove or disable package
+ $this->updatePreviousRepo($previousRepo, $operation->getRawPackage());
}
}
- rename($this->operationFile, $this->operationFile . '.bup');
+ $this->log("Removing previous local repository snapshot...");
+ $filesystem = new Filesystem();
+ $filesystem->remove($this->previousRepoFile);
+ }
+
+ private function openRepository($repoFile, $filter = true)
+ {
+ if (!file_exists($repoFile)) {
+ throw new ExecutorException(
+ "Repository file '{$repoFile}' doesn't exist",
+ ExecutorException::REPO_NOT_FOUND
+ );
+ }
+
+ $repo = json_decode(file_get_contents($repoFile));
+
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ throw new ExecutorException(
+ "Repository file '{$repoFile}' isn't valid JSON",
+ ExecutorException::REPO_NOT_JSON
+ );
+ }
+
+ if (!is_array($repo)) {
+ throw new ExecutorException(
+ "Repository file '{$repoFile}' doesn't contain an array of packages",
+ ExecutorException::REPO_NOT_ARRAY
+ );
+ }
+
+ $packages = !$filter ? $repo : array_filter($repo, function ($package) {
+ return $package->type === 'claroline-core' || $package->type === 'claroline-plugin';
+ });
+
+ $packagesByName = [];
+
+ foreach ($packages as $package) {
+ $packagesByName[$package->name] = $package;
+ }
+
+ return $packagesByName;
+ }
+
+ private function buildOperation($type, \stdClass $package)
+ {
+ $vendorDir = $this->kernel->getRootDir() . '/../vendor';
+ $targetDir = property_exists($package, 'targetDir') ? $package->targetDir : '';
+ $packageDir = empty($targetDir) ? $package->name : "{$targetDir}/{$package->name}";
+ $fqcn = $this->detector->detectBundle("{$vendorDir}/{$packageDir}");
+
+ return new Operation($type, $package, $fqcn);
}
private function getBundlesByFqcn()
@@ -121,4 +240,20 @@ private function getBundlesByFqcn()
return $byFqcn;
}
+
+ private function updatePreviousRepo(array $repo, \stdClass $package, $add = true)
+ {
+ if ($add) {
+ $repo[] = $package;
+ } else {
+ foreach ($repo as $index => $previousPackage) {
+ if ($previousPackage->name === $package->name) {
+ $repo[$index] = $package;
+ }
+ }
+ }
+
+ $options = JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE;
+ file_put_contents($this->previousRepoFile, json_encode($repo, $options));
+ }
}
diff --git a/Library/Installation/PlatformInstaller.php b/Library/Installation/PlatformInstaller.php
index 9edc0fd74..60d9aa7bd 100644
--- a/Library/Installation/PlatformInstaller.php
+++ b/Library/Installation/PlatformInstaller.php
@@ -18,9 +18,7 @@
use Claroline\InstallationBundle\Manager\InstallationManager;
use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand;
use JMS\DiExtraBundle\Annotation as DI;
-use Claroline\CoreBundle\Entity\Bundle;
use Psr\Log\LoggerInterface;
-use Symfony\Bundle\SecurityBundle\Command\InitAclCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
@@ -92,17 +90,15 @@ public function setOutput(OutputInterface $output)
}
/**
- * This is the method fired when an update is fired.
+ * Installs or updates platform packages based on the comparison
+ * of local repositories versions ("vendor/composer/installed.json"
+ * versus "app/config/previous-installed.json").
*/
- public function installFromOperationFile($operationFile = null)
+ public function updateFromComposerInfo()
{
$this->launchPreInstallActions();
-
- if ($operationFile) {
- $this->operationExecutor->setOperationFile($operationFile);
- }
-
- $this->operationExecutor->execute();
+ $operations = $this->operationExecutor->buildOperationList();
+ $this->operationExecutor->execute($operations);
}
/**
diff --git a/Tests/Stub/repo/empty.json b/Tests/Stub/repo/empty.json
new file mode 100644
index 000000000..fe51488c7
--- /dev/null
+++ b/Tests/Stub/repo/empty.json
@@ -0,0 +1 @@
+[]
diff --git a/Tests/Stub/repo/not-array.json b/Tests/Stub/repo/not-array.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/Tests/Stub/repo/not-array.json
@@ -0,0 +1 @@
+{}
diff --git a/Tests/Stub/repo/not-json.json b/Tests/Stub/repo/not-json.json
new file mode 100644
index 000000000..811526bab
--- /dev/null
+++ b/Tests/Stub/repo/not-json.json
@@ -0,0 +1 @@
+Invalid JSON file
diff --git a/Tests/Stub/repo/repo-1.json b/Tests/Stub/repo/repo-1.json
new file mode 100644
index 000000000..8b536a3cb
--- /dev/null
+++ b/Tests/Stub/repo/repo-1.json
@@ -0,0 +1,17 @@
+[
+ {
+ "name": "foo",
+ "type": "claroline-core",
+ "version-normalized": "1.0.0.0"
+ },
+ {
+ "name": "bar",
+ "type": "claroline-plugin",
+ "version-normalized": "2.0.0.0"
+ },
+ {
+ "name": "baz",
+ "type": "extraneous",
+ "version-normalized": "0.0.1.0"
+ }
+]
diff --git a/Tests/Stub/repo/repo-2.json b/Tests/Stub/repo/repo-2.json
new file mode 100644
index 000000000..c1f69007f
--- /dev/null
+++ b/Tests/Stub/repo/repo-2.json
@@ -0,0 +1,17 @@
+[
+ {
+ "name": "foo",
+ "type": "claroline-core",
+ "version-normalized": "2.0.0.0"
+ },
+ {
+ "name": "bar",
+ "type": "claroline-plugin",
+ "version-normalized": "2.0.0.0"
+ },
+ {
+ "name": "baz",
+ "type": "extraneous",
+ "version-normalized": "0.0.1.0"
+ }
+]
diff --git a/Tests/Stub/repo/repo-3.json b/Tests/Stub/repo/repo-3.json
new file mode 100644
index 000000000..c79783ed3
--- /dev/null
+++ b/Tests/Stub/repo/repo-3.json
@@ -0,0 +1,22 @@
+[
+ {
+ "name": "quz",
+ "type": "claroline-plugin",
+ "version-normalized": "4.2.3.0"
+ },
+ {
+ "name": "foo",
+ "type": "claroline-core",
+ "version-normalized": "1.2.0.0"
+ },
+ {
+ "name": "bar",
+ "type": "claroline-plugin",
+ "version-normalized": "2.0.0.0"
+ },
+ {
+ "name": "baz",
+ "type": "extraneous",
+ "version-normalized": "0.0.1.0"
+ }
+]
diff --git a/Tests/Unit/Library/Installation/OperationExecutorTest.php b/Tests/Unit/Library/Installation/OperationExecutorTest.php
new file mode 100644
index 000000000..29b4a9b3a
--- /dev/null
+++ b/Tests/Unit/Library/Installation/OperationExecutorTest.php
@@ -0,0 +1,188 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Installation;
+
+class OperationExecutorTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @var OperationExecutor
+ */
+ private $executor;
+ private $kernel;
+ private $detector;
+
+ protected function setUp()
+ {
+ $this->kernel = $this->mock('Symfony\Component\HttpKernel\KernelInterface');
+ $installManager = $this->mock('Claroline\InstallationBundle\Manager\InstallationManager');
+ $pluginInstaller = $this->mock('Claroline\CoreBundle\Library\Installation\Plugin\Installer');
+ $this->detector = $this->mock('Claroline\BundleRecorder\Detector\Detector');
+ $this->executor = new OperationExecutor($this->kernel, $installManager, $pluginInstaller);
+ $this->executor->setBundleDetector($this->detector);
+
+ // always build a fake fqcn based on the given path
+ $this->detector->expects($this->any())
+ ->method('detectBundle')
+ ->willReturnCallback(function ($path) {
+ $parts = explode('/', $path);
+ $name = array_pop($parts);
+
+ return ucfirst($name);
+ });
+ }
+
+ /**
+ * @dataProvider missingRepoProvider
+ * @expectedException \Claroline\CoreBundle\Library\Installation\ExecutorException
+ * @expectedExceptionCode 11
+ */
+ public function testBuildOperationListThrowsIfRepoIsMissing($previous, $installed)
+ {
+ $this->executor->setRepositoryFiles($previous, $installed);
+ $this->executor->buildOperationList();
+ }
+
+ /**
+ * @dataProvider notJsonRepoProvider
+ * @expectedException \Claroline\CoreBundle\Library\Installation\ExecutorException
+ * @expectedExceptionCode 12
+ */
+ public function testBuildOperationListExecutorThrowsIfRepoIsNotJson($previous, $installed)
+ {
+ $this->executor->setRepositoryFiles($previous, $installed);
+ $this->executor->buildOperationList();
+ }
+
+ /**
+ * @dataProvider notArrayRepoProvider
+ * @expectedException \Claroline\CoreBundle\Library\Installation\ExecutorException
+ * @expectedExceptionCode 13
+ */
+ public function testOperationListThrowsIfRepoIsNotArray($previous, $installed)
+ {
+ $this->executor->setRepositoryFiles($previous, $installed);
+ $this->executor->buildOperationList();
+ }
+
+ public function testBuildOperationListInstallOnly()
+ {
+ $this->executor->setRepositoryFiles($this->repo('empty'), $this->repo('repo-1'));
+ $this->kernel->expects($this->once())->method('getBundles')->willReturn([
+ $this->mockBundle('Foo'),
+ $this->mockBundle('Bar')
+ ]);
+
+ $operations = $this->executor->buildOperationList();
+ $this->assertEquals(2, count($operations));
+ $this->assertEquals($operations[0]->getPackageName(), 'foo');
+ $this->assertEquals($operations[0]->getBundleFqcn(), 'Foo');
+ $this->assertEquals($operations[0]->getPackageType(), 'claroline-core');
+ $this->assertEquals($operations[0]->getType(), Operation::INSTALL);
+ $this->assertEquals($operations[1]->getPackageName(), 'bar');
+ $this->assertEquals($operations[1]->getBundleFqcn(), 'Bar');
+ $this->assertEquals($operations[1]->getPackageType(), 'claroline-plugin');
+ $this->assertEquals($operations[1]->getType(), Operation::INSTALL);
+ }
+
+ public function testBuildOperationListUpdateOnly()
+ {
+ $this->executor->setRepositoryFiles($this->repo('repo-1'), $this->repo('repo-2'));
+ $this->kernel->expects($this->once())->method('getBundles')->willReturn([
+ $this->mockBundle('Foo')
+ ]);
+
+ $operations = $this->executor->buildOperationList();
+ $this->assertEquals(1, count($operations));
+ $this->assertEquals($operations[0]->getPackageName(), 'foo');
+ $this->assertEquals($operations[0]->getBundleFqcn(), 'Foo');
+ $this->assertEquals($operations[0]->getPackageType(), 'claroline-core');
+ $this->assertEquals($operations[0]->getType(), Operation::UPDATE);
+ $this->assertEquals($operations[0]->getFromVersion(), '1.0.0.0');
+ $this->assertEquals($operations[0]->getToVersion(), '2.0.0.0');
+ }
+
+ public function testBuildOperationsMixedAndSorted()
+ {
+ $this->executor->setRepositoryFiles($this->repo('repo-1'), $this->repo('repo-3'));
+ $this->kernel->expects($this->once())->method('getBundles')->willReturn([
+ $this->mockBundle('Foo'),
+ $this->mockBundle('Quz'),
+ $this->mockBundle('Bar')
+ ]);
+ $operations = $this->executor->buildOperationList();
+ $this->assertEquals(2, count($operations));
+ $this->assertEquals($operations[0]->getPackageName(), 'foo');
+ $this->assertEquals($operations[0]->getBundleFqcn(), 'Foo');
+ $this->assertEquals($operations[0]->getPackageType(), 'claroline-core');
+ $this->assertEquals($operations[0]->getType(), Operation::UPDATE);
+ $this->assertEquals($operations[0]->getFromVersion(), '1.0.0.0');
+ $this->assertEquals($operations[0]->getToVersion(), '1.2.0.0');
+ $this->assertEquals($operations[1]->getPackageName(), 'quz');
+ $this->assertEquals($operations[1]->getBundleFqcn(), 'Quz');
+ $this->assertEquals($operations[1]->getPackageType(), 'claroline-plugin');
+ $this->assertEquals($operations[1]->getType(), Operation::INSTALL);
+ }
+
+ public function missingRepoProvider()
+ {
+ return $this->buildRepoPaths([
+ ['empty', 'non-existent'],
+ ['non-existent', 'empty']
+ ]);
+ }
+
+ public function notJsonRepoProvider()
+ {
+ return $this->buildRepoPaths([
+ ['empty', 'not-json'],
+ ['not-json', 'empty']
+ ]);
+ }
+
+ public function notArrayRepoProvider()
+ {
+ return $this->buildRepoPaths([
+ ['empty', 'not-array'],
+ ['not-array', 'empty']
+ ]);
+ }
+
+ private function mock($class)
+ {
+ return $this->getMockBuilder($class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
+
+ private function buildRepoPaths(array $nameRows)
+ {
+ return array_map(function ($row) {
+ return array_map(function ($name) {
+ return $this->repo($name);
+ }, $row);
+ }, $nameRows);
+ }
+
+ private function repo($name)
+ {
+ return __DIR__ . '/../../../Stub/repo/' . $name . '.json';
+ }
+
+ private function mockBundle($fqcn)
+ {
+ $bundle = $this->mock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
+ $bundle->expects($this->any())->method('getNamespace')->willReturn('');
+ $bundle->expects($this->any())->method('getName')->willReturn($fqcn);
+
+ return $bundle;
+ }
+
+}
diff --git a/package.json b/package.json
index 60a751cb3..ca422861a 100644
--- a/package.json
+++ b/package.json
@@ -24,5 +24,8 @@
},
"scripts": {
"test": "mocha Resources/scripts/test"
- }
+ },
+ "files": [
+ "package.json"
+ ]
}
diff --git a/phpunit.xml b/phpunit.xml
new file mode 100644
index 000000000..22befec65
--- /dev/null
+++ b/phpunit.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+ Tests
+
+
+
+
+
+
+ Command
+ DataFixtures
+ Migrations
+ Resources
+
+
+
+
+
From 27fe30206a5e09e511720714ebffb7a3ba3a2928 Mon Sep 17 00:00:00 2001
From: Nicolas Godfraind
Date: Wed, 17 Feb 2016 11:24:41 +0100
Subject: [PATCH 18/65] User filter list extendable.
---
Controller/API/User/UserController.php | 17 +---
Event/UserAddFilterEvent.php | 48 ++++++++++
Event/UserEditSearchEvent.php | 30 +++++++
Manager/UserManager.php | 87 ++++++++++++++++++-
Persistence/ObjectManager.php | 5 ++
Repository/UserRepository.php | 61 -------------
Resources/config/services.yml | 6 ++
.../modules/users/Partial/user_content.html | 1 -
8 files changed, 176 insertions(+), 79 deletions(-)
create mode 100644 Event/UserAddFilterEvent.php
create mode 100644 Event/UserEditSearchEvent.php
diff --git a/Controller/API/User/UserController.php b/Controller/API/User/UserController.php
index e6876428a..08b408b0e 100644
--- a/Controller/API/User/UserController.php
+++ b/Controller/API/User/UserController.php
@@ -25,7 +25,6 @@
use Claroline\CoreBundle\Manager\GroupManager;
use Claroline\CoreBundle\Manager\RoleManager;
use Claroline\CoreBundle\Manager\MailManager;
-use Claroline\CoreBundle\Manager\FacetManager;
use Claroline\CoreBundle\Manager\AuthenticationManager;
use Claroline\CoreBundle\Manager\ProfilePropertyManager;
use JMS\DiExtraBundle\Annotation as DI;
@@ -55,7 +54,6 @@ class UserController extends FOSRestController
* "groupManager" = @DI\Inject("claroline.manager.group_manager"),
* "om" = @DI\Inject("claroline.persistence.object_manager"),
* "profilePropertyManager" = @DI\Inject("claroline.manager.profile_property_manager"),
- * "facetManager" = @DI\Inject("claroline.manager.facet_manager"),
* "mailManager" = @DI\Inject("claroline.manager.mail_manager"),
* "apiManager" = @DI\Inject("claroline.manager.api_manager")
* })
@@ -70,7 +68,6 @@ public function __construct(
GroupManager $groupManager,
RoleManager $roleManager,
ObjectManager $om,
- FacetManager $facetManager,
ProfilePropertyManager $profilePropertyManager,
MailManager $mailManager,
ApiManager $apiManager
@@ -82,7 +79,6 @@ public function __construct(
$this->localeManager = $localeManager;
$this->request = $request;
$this->userManager = $userManager;
- $this->facetManager = $facetManager;
$this->groupManager = $groupManager;
$this->roleManager = $roleManager;
$this->om = $om;
@@ -142,18 +138,7 @@ public function getSearchUsersAction($page, $limit)
*/
public function getUserSearchableFieldsAction()
{
- $fields = $this->facetManager->getFieldFacets();
-
- $baseFields = User::getSearchableFields();
-
- foreach ($fields as $field) {
- $baseFields[] = $field->getName();
- }
-
- $baseFields[] = 'group_name';
- $baseFields[] = 'organization_name';
-
- return $baseFields;
+ return $this->userManager->getUserSearchableFields();
}
/**
diff --git a/Event/UserAddFilterEvent.php b/Event/UserAddFilterEvent.php
new file mode 100644
index 000000000..c1a7d808d
--- /dev/null
+++ b/Event/UserAddFilterEvent.php
@@ -0,0 +1,48 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Event;
+
+use Claroline\CoreBundle\Entity\User;
+use Symfony\Component\EventDispatcher\Event;
+
+class UserAddFilterEvent extends Event
+{
+ private $filters;
+
+ public function __construct($filters)
+ {
+ $this->filters = $filters;
+ }
+
+ public function addFilter($filter)
+ {
+ $this->filters[] = $filter;
+ }
+
+ public function removeFilter($filter)
+ {
+ if (($key = array_search($filter, $this->filters)) !== false) {
+ unset($filters[$key]);
+ }
+
+ }
+
+ public function getFilters()
+ {
+ return $this->filters;
+ }
+
+ public function setFilters($filters)
+ {
+ $this->filters = $filters;
+ }
+}
diff --git a/Event/UserEditSearchEvent.php b/Event/UserEditSearchEvent.php
new file mode 100644
index 000000000..dfe0ab6f8
--- /dev/null
+++ b/Event/UserEditSearchEvent.php
@@ -0,0 +1,30 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Event;
+
+use Symfony\Component\EventDispatcher\Event;
+use Doctrine\ORM\QueryBuilder;
+
+class UserEditSearchEvent extends Event
+{
+ private $qb;
+
+ public function __construct(QueryBuilder $qb)
+ {
+ $this->qb = $qb;
+ }
+
+ public function getQueryBuilder()
+ {
+ return $this->qb;
+ }
+}
diff --git a/Manager/UserManager.php b/Manager/UserManager.php
index 22029ef31..9dd67067c 100644
--- a/Manager/UserManager.php
+++ b/Manager/UserManager.php
@@ -25,6 +25,7 @@
use Claroline\CoreBundle\Library\Workspace\Configuration;
use Claroline\CoreBundle\Manager\MailManager;
use Claroline\CoreBundle\Manager\TransfertManager;
+use Claroline\CoreBundle\Manager\FacetManager;
use Claroline\CoreBundle\Pager\PagerFactory;
use Claroline\CoreBundle\Persistence\ObjectManager;
use Doctrine\Common\Collections\ArrayCollection;
@@ -1508,8 +1509,92 @@ public function hideEmailValidation(User $user)
$this->objectManager->flush();
}
+ /**
+ * Big user search method ! hell yeah !
+ */
public function searchPartialList($searches, $page, $limit, $count = false)
{
- return $this->userRepo->searchPartialList($searches, $page, $limit, $count);
+ $baseFieldsName = User::getUserSearchableFields();
+ $facetFields = $this->objectManager->getRepository('ClarolineCoreBundle:Facet\FieldFacet')->findAll();
+ $facetFieldsName = array();
+
+ foreach ($facetFields as $facetField) {
+ $facetFieldsName[] = $facetField->getName();
+ }
+
+ $qb = $this->objectManager->createQueryBuilder();
+ $count ? $qb->select('count(u)'): $qb->select('u');
+ $qb->from('Claroline\CoreBundle\Entity\User', 'u')
+ ->where('u.isEnabled = true');
+
+ foreach ($searches as $key => $search) {
+ foreach ($search as $id => $el) {
+ if (in_array($key, $baseFieldsName)) {
+ $qb->andWhere("UPPER (u.{$key}) LIKE :{$key}{$id}");
+ $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
+ } elseif (in_array($key, $facetFieldsName)) {
+ $qb->join('u.fieldsFacetValue', "ffv{$id}");
+ $qb->join("ffv{$id}.fieldFacet", "f{$id}");
+ $qb->andWhere("UPPER (ffv{$id}.stringValue) LIKE :{$key}{$id}");
+ $qb->orWhere("ffv{$id}.floatValue = :{$key}{$id}");
+ $qb->andWhere("f{$id}.name LIKE :facet{$id}");
+ $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
+ $qb->setParameter("facet{$id}", $key);
+ } elseif ($key === 'group_name') {
+ $qb->join('u.groups', "g{$id}");
+ $qb->andWhere("UPPER (g{$id}.name) LIKE :{$key}{$id}");
+ $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
+ } if ($key === 'group_id') {
+ $qb->join('u.groups', "g{$id}");
+ $qb->andWhere("g{$id}.id = :{$key}{$id}");
+ $qb->setParameter($key . $id, $el);
+ } if ($key === 'organization_name') {
+ $qb->join('u.organizations', "o{$id}");
+ $qb->andWhere("UPPER (o{$id}.name) LIKE :{$key}{$id}");
+ $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
+ } if ($key === 'organization_id') {
+ $qb->join('u.organizations', "o{$id}");
+ $qb->andWhere('o{$id}.id = :id');
+ $qb->setParameter($key . $id, $el);
+ }
+ }
+ }
+
+ $event = $this->strictEventDispatcher->dispatch(
+ 'user_edit_search_event',
+ 'UserEditSearch',
+ array($qb)
+ );
+
+ $query = $qb->getQuery();
+
+ if ($page && $limit && !$count) {
+ $query->setMaxResults($limit);
+ $query->setFirstResult($page * $limit);
+ }
+
+ return $count ? $query->getSingleScalarResult(): $query->getResult();
+ }
+
+ public function getUserSearchableFields()
+ {
+ $fields = $this->container->get('claroline.manager.facet_manager')->getFieldFacets();
+
+ $baseFields = User::getSearchableFields();
+
+ foreach ($fields as $field) {
+ $baseFields[] = $field->getName();
+ }
+
+ $baseFields[] = 'group_name';
+ $baseFields[] = 'organization_name';
+
+ $event = $this->strictEventDispatcher->dispatch(
+ 'user_add_filter_event',
+ 'UserAddFilter',
+ array($baseFields)
+ );
+
+ return $event->getFilters();
}
}
diff --git a/Persistence/ObjectManager.php b/Persistence/ObjectManager.php
index 9ec3742d1..e3a97d7e1 100644
--- a/Persistence/ObjectManager.php
+++ b/Persistence/ObjectManager.php
@@ -136,6 +136,11 @@ public function forceFlush()
}
}
+ public function createQueryBuilder()
+ {
+ return $this->wrapped->createQueryBuilder();
+ }
+
/**
* Starts a transaction.
*
diff --git a/Repository/UserRepository.php b/Repository/UserRepository.php
index 45c928eae..7cfc446ec 100644
--- a/Repository/UserRepository.php
+++ b/Repository/UserRepository.php
@@ -1585,65 +1585,4 @@ public function findForApi($data)
return $query->getOneOrNullResult();
}
-
- /**
- * Big method for searching users with filters. It can handle most use cases.
- */
- public function searchPartialList(array $searches = array(), $page = null, $limit = null, $count = false)
- {
- $baseFieldsName = User::getUserSearchableFields();
- $facetFields = $this->_em->getRepository('ClarolineCoreBundle:Facet\FieldFacet')->findAll();
- $facetFieldsName = array();
-
- foreach ($facetFields as $facetField) {
- $facetFieldsName[] = $facetField->getName();
- }
-
- $qb = $this->_em->createQueryBuilder();
- $count ? $qb->select('count(u)'): $qb->select('u');
- $qb->from('Claroline\CoreBundle\Entity\User', 'u')
- ->where('u.isEnabled = true');
-
- foreach ($searches as $key => $search) {
- foreach ($search as $id => $el) {
- if (in_array($key, $baseFieldsName)) {
- $qb->andWhere("UPPER (u.{$key}) LIKE :{$key}{$id}");
- $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
- } elseif (in_array($key, $facetFieldsName)) {
- $qb->join('u.fieldsFacetValue', "ffv{$id}");
- $qb->join("ffv{$id}.fieldFacet", "f{$id}");
- $qb->andWhere("UPPER (ffv{$id}.stringValue) LIKE :{$key}{$id}");
- $qb->orWhere("ffv{$id}.floatValue = :{$key}{$id}");
- $qb->andWhere("f{$id}.name LIKE :facet{$id}");
- $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
- $qb->setParameter("facet{$id}", $key);
- } elseif ($key === 'group_name') {
- $qb->join('u.groups', "g{$id}");
- $qb->andWhere("UPPER (g{$id}.name) LIKE :{$key}{$id}");
- $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
- } if ($key === 'group_id') {
- $qb->join('u.groups', "g{$id}");
- $qb->andWhere("g{$id}.id = :{$key}{$id}");
- $qb->setParameter($key . $id, $el);
- } if ($key === 'organization_name') {
- $qb->join('u.organizations', "o{$id}");
- $qb->andWhere("UPPER (o{$id}.name) LIKE :{$key}{$id}");
- $qb->setParameter($key . $id, '%' . strtoupper($el) . '%');
- } if ($key === 'organization_id') {
- $qb->join('u.organizations', "o{$id}");
- $qb->andWhere('o{$id}.id = :id');
- $qb->setParameter($key . $id, $el);
- }
- }
- }
-
- $query = $qb->getQuery();
-
- if ($page && $limit && !$count) {
- $query->setMaxResults($limit);
- $query->setFirstResult($page * $limit);
- }
-
- return $count ? $query->getSingleScalarResult(): $query->getResult();
- }
}
diff --git a/Resources/config/services.yml b/Resources/config/services.yml
index bb0624f8c..d0a1bedc0 100644
--- a/Resources/config/services.yml
+++ b/Resources/config/services.yml
@@ -21,6 +21,12 @@ services:
arguments:
- Claroline\CoreBundle\Entity\Log\Log
+ claroline.repository.user:
+ class: Claroline\CoreBundle\Repository\UserRepository
+ factory: ["@doctrine.orm.entity_manager", getRepository]
+ arguments:
+ - Claroline\CoreBundle\Entity\User
+
# pseudo-services used for dynamic parameter injection
# (see Claroline\CoreBundle\DependencyInjection\Compiler\DynamicConfigPass
claroline.session.storage_options:
diff --git a/Resources/modules/users/Partial/user_content.html b/Resources/modules/users/Partial/user_content.html
index 010d97473..2f8c21d55 100644
--- a/Resources/modules/users/Partial/user_content.html
+++ b/Resources/modules/users/Partial/user_content.html
@@ -32,7 +32,6 @@
- {{ uc.connectedUser }}
From ee995da23fe766b2f27adc943fabc512c3307ab0 Mon Sep 17 00:00:00 2001
From: Nicolas Godfraind
Date: Wed, 17 Feb 2016 11:37:26 +0100
Subject: [PATCH 19/65] FindAll for organizations.
---
.../API/Organization/OrganizationController.php | 14 +++++++++++++-
Entity/Organization/Organization.php | 6 +++---
Event/UserAddFilterEvent.php | 1 -
3 files changed, 16 insertions(+), 5 deletions(-)
diff --git a/Controller/API/Organization/OrganizationController.php b/Controller/API/Organization/OrganizationController.php
index db093936d..781f13a81 100644
--- a/Controller/API/Organization/OrganizationController.php
+++ b/Controller/API/Organization/OrganizationController.php
@@ -97,7 +97,7 @@ public function deleteOrganizationAction(Organization $organization)
return array('success');
}
- /**
+ /**
* @View(serializerGroups={"api"})
* @ApiDoc(
* description="Returns the organizations list",
@@ -109,6 +109,18 @@ public function getOrganizationsAction()
return $this->organizationManager->getRoots();
}
+ /**
+ * @View(serializerGroups={"organization_list"})
+ * @ApiDoc(
+ * description="Returns the organizations list",
+ * views = {"organization"}
+ * )
+ */
+ public function getOrganizationListAction()
+ {
+ return $this->organizationManager->getAll();
+ }
+
/**
* @View(serializerGroups={"api"})
* @ApiDoc(
diff --git a/Entity/Organization/Organization.php b/Entity/Organization/Organization.php
index 86404cbcc..bab6ee134 100644
--- a/Entity/Organization/Organization.php
+++ b/Entity/Organization/Organization.php
@@ -35,7 +35,7 @@ class Organization
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
- * @Groups({"api"})
+ * @Groups({"api", "organization_list"})
*/
protected $id;
@@ -48,14 +48,14 @@ class Organization
/**
* @ORM\Column()
* @Assert\NotBlank()
- * @Groups({"api"})
+ * @Groups({"api", "organization_list"})
*/
protected $name;
/**
* @ORM\Column(nullable=true)
* @Assert\Email()
- * @Groups({"api"})
+ * @Groups({"api", "organization_list"})
*/
protected $email;
diff --git a/Event/UserAddFilterEvent.php b/Event/UserAddFilterEvent.php
index c1a7d808d..36889efeb 100644
--- a/Event/UserAddFilterEvent.php
+++ b/Event/UserAddFilterEvent.php
@@ -33,7 +33,6 @@ public function removeFilter($filter)
if (($key = array_search($filter, $this->filters)) !== false) {
unset($filters[$key]);
}
-
}
public function getFilters()
From 18752e25ef0c3926e960bf39d84f547bd0c2dcc5 Mon Sep 17 00:00:00 2001
From: Nicolas Godfraind
Date: Wed, 17 Feb 2016 13:29:47 +0100
Subject: [PATCH 20/65] Organizations for group.
---
Controller/API/User/GroupController.php | 4 +-
Entity/Group.php | 26 +++++-
Entity/Organization/Organization.php | 11 +++
Form/User/GroupSettingsType.php | 12 +++
Library/Security/Voter/GroupVoter.php | 39 +++++++++
Library/Security/Voter/UserVoter.php | 39 +++++++++
.../pdo_mysql/Version20160217120917.php | 86 +++++++++++++++++++
.../groups/Controller/GroupController.js | 2 +-
8 files changed, 215 insertions(+), 4 deletions(-)
create mode 100644 Library/Security/Voter/GroupVoter.php
create mode 100644 Library/Security/Voter/UserVoter.php
create mode 100644 Migrations/pdo_mysql/Version20160217120917.php
diff --git a/Controller/API/User/GroupController.php b/Controller/API/User/GroupController.php
index 99b0a830d..4d8fe876c 100644
--- a/Controller/API/User/GroupController.php
+++ b/Controller/API/User/GroupController.php
@@ -104,8 +104,10 @@ public function postGroupAction()
if ($form->isValid()) {
$group = $form->getData();
$newRoles = $form['platformRoles']->getData();
- $this->groupManager->setPlatformRoles($group, $newRoles);
+
+ var_dump(count($form->get('organizations')->getData()));
$this->groupManager->insertGroup($group);
+ $this->groupManager->setPlatformRoles($group, $newRoles);
$httpCode = 200;
}
diff --git a/Entity/Group.php b/Entity/Group.php
index bf24d35e5..d8ec256b9 100644
--- a/Entity/Group.php
+++ b/Entity/Group.php
@@ -19,6 +19,7 @@
use Claroline\CoreBundle\Entity\User;
use Claroline\CoreBundle\Entity\Model\WorkspaceModel;
use JMS\Serializer\Annotation\Groups;
+use Claroline\CoreBundle\Entity\Organization\Organization;
/**
* @ORM\Entity(repositoryClass="Claroline\CoreBundle\Repository\GroupRepository")
@@ -85,11 +86,21 @@ class Group extends AbstractRoleSubject implements OrderableInterface
*/
protected $models;
+ /**
+ * @var Organization[]|ArrayCollection
+ *
+ * @ORM\ManyToMany(
+ * targetEntity="Claroline\CoreBundle\Entity\Organization\Organization"
+ * )
+ */
+ protected $organizations;
+
public function __construct()
{
parent::__construct();
- $this->users = new ArrayCollection();
- $this->models = new ArrayCollection();
+ $this->users = new ArrayCollection();
+ $this->models = new ArrayCollection();
+ $this->organizations = new ArrayCollection();
}
public function getId()
@@ -238,4 +249,15 @@ public function __toString()
{
return $this->name;
}
+
+ public function getOrganizations()
+ {
+ return $this->organizations;
+ }
+
+ public function setOrganizations(ArrayCollection $organizations)
+ {
+ $this->organizations = $organizations;
+ }
+
}
diff --git a/Entity/Organization/Organization.php b/Entity/Organization/Organization.php
index bab6ee134..de4674502 100644
--- a/Entity/Organization/Organization.php
+++ b/Entity/Organization/Organization.php
@@ -118,6 +118,16 @@ class Organization
*/
protected $users;
+ /**
+ * @var User[]|ArrayCollection
+ *
+ * @ORM\ManyToMany(
+ * targetEntity="Claroline\CoreBundle\Entity\Group"
+ * )
+ * @ORM\JoinTable(name="claro_group_organization")
+ */
+ protected $groups;
+
/**
* @var User[]|ArrayCollection
*
@@ -152,6 +162,7 @@ public function __construct()
$this->locations = new ArrayCollection();
$this->departments = new ArrayCollection();
$this->users = new ArrayCollection();
+ $this->groups = new ArrayCollection();
$this->administrators = new ArrayCollection();
$this->timeSlots = new ArrayCollection();
$this->years = new ArrayCollection();
diff --git a/Form/User/GroupSettingsType.php b/Form/User/GroupSettingsType.php
index 8c97e201b..542b9d63f 100644
--- a/Form/User/GroupSettingsType.php
+++ b/Form/User/GroupSettingsType.php
@@ -59,6 +59,18 @@ public function buildForm(FormBuilderInterface $builder, array $options)
}
)
);
+
+ $builder->add(
+ 'organizations',
+ 'entity',
+ array(
+ 'label' => 'organizations',
+ 'class' => 'Claroline\CoreBundle\Entity\Organization\Organization',
+ 'expanded' => true,
+ 'multiple' => true,
+ 'property' => 'name'
+ )
+ );
}
public function getName()
diff --git a/Library/Security/Voter/GroupVoter.php b/Library/Security/Voter/GroupVoter.php
new file mode 100644
index 000000000..9c4b01376
--- /dev/null
+++ b/Library/Security/Voter/GroupVoter.php
@@ -0,0 +1,39 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Security\Voter;
+
+use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
+use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
+use JMS\DiExtraBundle\Annotation as DI;
+
+/**
+ * @DI\Service
+ * @DI\Tag("security.voter")
+ */
+class GroupVoter implements VoterInterface
+{
+ public function vote(TokenInterface $token, $object, array $attributes)
+ {
+ //no implementation yet
+ return true;
+ }
+
+ public function supportsAttribute($attribute)
+ {
+ return true;
+ }
+
+ public function supportsClass($class)
+ {
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/Library/Security/Voter/UserVoter.php b/Library/Security/Voter/UserVoter.php
new file mode 100644
index 000000000..27d80f52c
--- /dev/null
+++ b/Library/Security/Voter/UserVoter.php
@@ -0,0 +1,39 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Security\Voter;
+
+use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
+use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
+use JMS\DiExtraBundle\Annotation as DI;
+
+/**
+ * @DI\Service
+ * @DI\Tag("security.voter")
+ */
+class UserVoter implements VoterInterface
+{
+ public function vote(TokenInterface $token, $object, array $attributes)
+ {
+ //no implementation yet
+ return true;
+ }
+
+ public function supportsAttribute($attribute)
+ {
+ return true;
+ }
+
+ public function supportsClass($class)
+ {
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/Migrations/pdo_mysql/Version20160217120917.php b/Migrations/pdo_mysql/Version20160217120917.php
new file mode 100644
index 000000000..a4c6dcf24
--- /dev/null
+++ b/Migrations/pdo_mysql/Version20160217120917.php
@@ -0,0 +1,86 @@
+addSql("
+ CREATE TABLE group_organization (
+ group_id INT NOT NULL,
+ organization_id INT NOT NULL,
+ INDEX IDX_2DA82945FE54D947 (group_id),
+ INDEX IDX_2DA8294532C8A3DE (organization_id),
+ PRIMARY KEY(group_id, organization_id)
+ ) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
+ ");
+ $this->addSql("
+ CREATE TABLE claro_group_organization (
+ organization_id INT NOT NULL,
+ group_id INT NOT NULL,
+ INDEX IDX_B912197E32C8A3DE (organization_id),
+ INDEX IDX_B912197EFE54D947 (group_id),
+ PRIMARY KEY(organization_id, group_id)
+ ) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB
+ ");
+ $this->addSql("
+ ALTER TABLE group_organization
+ ADD CONSTRAINT FK_2DA82945FE54D947 FOREIGN KEY (group_id)
+ REFERENCES claro_group (id)
+ ON DELETE CASCADE
+ ");
+ $this->addSql("
+ ALTER TABLE group_organization
+ ADD CONSTRAINT FK_2DA8294532C8A3DE FOREIGN KEY (organization_id)
+ REFERENCES claro__organization (id)
+ ON DELETE CASCADE
+ ");
+ $this->addSql("
+ ALTER TABLE claro_group_organization
+ ADD CONSTRAINT FK_B912197E32C8A3DE FOREIGN KEY (organization_id)
+ REFERENCES claro__organization (id)
+ ON DELETE CASCADE
+ ");
+ $this->addSql("
+ ALTER TABLE claro_group_organization
+ ADD CONSTRAINT FK_B912197EFE54D947 FOREIGN KEY (group_id)
+ REFERENCES claro_group (id)
+ ON DELETE CASCADE
+ ");
+ $this->addSql("
+ ALTER TABLE claro_user_administrator
+ DROP PRIMARY KEY
+ ");
+ $this->addSql("
+ ALTER TABLE claro_user_administrator
+ ADD PRIMARY KEY (user_id, organization_id)
+ ");
+ }
+
+ public function down(Schema $schema)
+ {
+ $this->addSql("
+ DROP TABLE group_organization
+ ");
+ $this->addSql("
+ DROP TABLE claro_group_organization
+ ");
+ $this->addSql("
+ ALTER TABLE claro_user_administrator
+ DROP PRIMARY KEY
+ ");
+ $this->addSql("
+ ALTER TABLE claro_user_administrator
+ ADD PRIMARY KEY (organization_id, user_id)
+ ");
+ }
+}
\ No newline at end of file
diff --git a/Resources/modules/groups/Controller/GroupController.js b/Resources/modules/groups/Controller/GroupController.js
index a62998941..51b03deb5 100644
--- a/Resources/modules/groups/Controller/GroupController.js
+++ b/Resources/modules/groups/Controller/GroupController.js
@@ -68,7 +68,7 @@ export default class GroupController {
let qs = '';
for (let i = 0; i < this.selected.length; i++) {
- qs += 'userIds[]=' + this.selected[i].id + '&'
+ qs += 'groupIds[]=' + this.selected[i].id + '&'
}
return qs
From 63f9983dce95eff507f7b860ce00decb044c5c35 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Thu, 18 Feb 2016 11:22:37 +0100
Subject: [PATCH 21/65] Fix variable name
---
Library/Installation/ScriptHandler.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Library/Installation/ScriptHandler.php b/Library/Installation/ScriptHandler.php
index af9c3fc3d..46309b201 100644
--- a/Library/Installation/ScriptHandler.php
+++ b/Library/Installation/ScriptHandler.php
@@ -45,7 +45,7 @@ private static function checkNode(ConsoleIO $io, VersionParser $parser)
"If no recent version of Node.js is available as an official package or installer for \n" .
"your OS, consider using a version manager like nvm (http://github.com/creationix/nvm).",
self::MIN_NODE_VERSION,
- $version
+ $nodeVersion
));
}
From f9044ee3d65067a0d33962fed7b5fc12102095d9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Thu, 18 Feb 2016 16:45:44 +0100
Subject: [PATCH 22/65] Fix raw-loader config + assets desc
---
Resources/modules/fos-js-router/module.js | 4 +++-
Resources/modules/groups/module.js | 4 +++-
Resources/modules/groups/routing.js | 4 ++--
Resources/modules/location/module.js | 8 +++++---
Resources/modules/organization/module.js | 5 +++--
Resources/modules/organization/routing.js | 14 ++++++--------
.../search/Directive/ClarolineSearchDirective.js | 2 +-
Resources/modules/search/module.js | 3 ++-
Resources/modules/services/module.js | 6 ++++--
Resources/modules/users/Partial/main.html | 2 +-
Resources/modules/users/Partial/user_content.html | 2 +-
Resources/modules/users/module.js | 3 ++-
Resources/modules/users/routing.js | 10 ++++------
Resources/scripts/lib/webpack.js | 6 +-----
assets.json | 2 +-
15 files changed, 39 insertions(+), 36 deletions(-)
diff --git a/Resources/modules/fos-js-router/module.js b/Resources/modules/fos-js-router/module.js
index 36b941e3a..60282bb42 100644
--- a/Resources/modules/fos-js-router/module.js
+++ b/Resources/modules/fos-js-router/module.js
@@ -1,7 +1,9 @@
+import 'angular/angular.min'
+
angular.module('ui.fos-js-router', [])
.filter('path', function () {
return function (route, parameters = {}) {
console.log(route, parameters)
return Routing.generate(route, parameters)
};
- })
\ No newline at end of file
+ })
diff --git a/Resources/modules/groups/module.js b/Resources/modules/groups/module.js
index f06296507..e64789993 100644
--- a/Resources/modules/groups/module.js
+++ b/Resources/modules/groups/module.js
@@ -1,3 +1,5 @@
+import 'angular/angular.min'
+
import GroupController from './Controller/GroupController'
import EditGroupModalController from './Controller/EditGroupModalController'
import CreateGroupModalController from './Controller/CreateGroupModalController'
@@ -12,4 +14,4 @@ angular.module('GroupsManager', ['ClarolineSearch', 'data-table', 'ui.router', '
.controller('EditGroupModalController', EditGroupModalController)
.controller('UserListController', ['$http', 'ClarolineSearchService', '$stateParams', 'GroupAPIService', 'ClarolineAPIService', UserListController])
.service('GroupAPIService', GroupAPIService)
- .config(Routing);
\ No newline at end of file
+ .config(Routing);
diff --git a/Resources/modules/groups/routing.js b/Resources/modules/groups/routing.js
index 00553b322..9e7b42271 100644
--- a/Resources/modules/groups/routing.js
+++ b/Resources/modules/groups/routing.js
@@ -1,4 +1,4 @@
-export default function($stateProvider, $urlRouterProvider) {
+export default function($stateProvider, $urlRouterProvider) {
const translate = function(key) {
return window.Translator.trans(key, {}, 'platform');
}
@@ -39,4 +39,4 @@ export default function($stateProvider, $urlRouterProvider) {
}
)
;
-}
\ No newline at end of file
+}
diff --git a/Resources/modules/location/module.js b/Resources/modules/location/module.js
index 80fe37680..1bffaff5c 100644
--- a/Resources/modules/location/module.js
+++ b/Resources/modules/location/module.js
@@ -1,9 +1,11 @@
+import 'angular/angular.min'
+
import bootstrap from 'angular-bootstrap'
-import LocationAPIService from './Service/LocationAPIService'
-import LocationController from './Controller/LocationController'
+import LocationAPIService from './Service/LocationAPIService'
+import LocationController from './Controller/LocationController'
import EditLocationModalController from './Controller/EditLocationModalController'
-import CreateLocationModalController from './Controller/CreateLocationModalController'
+import CreateLocationModalController from './Controller/CreateLocationModalController'
import ClarolineAPI from '../services/module'
var LocationManager = angular.module('LocationManager', [
diff --git a/Resources/modules/organization/module.js b/Resources/modules/organization/module.js
index 98f6fcae9..e3347ee03 100644
--- a/Resources/modules/organization/module.js
+++ b/Resources/modules/organization/module.js
@@ -1,4 +1,5 @@
import 'angular/angular.min'
+
import dataTable from 'angular-data-table/release/dataTable.helpers.min'
import bootstrap from 'angular-bootstrap'
import translation from 'angular-ui-translation/angular-translation'
@@ -16,7 +17,7 @@ import OrganizationAPIService from './Service/OrganizationAPIService'
var OrganizationManager = angular.module('OrganizationManager', [
'ui.router',
'ui.tree',
- 'ui.bootstrap.tpls',
+ 'ui.bootstrap.tpls',
'LocationManager',
'ui.translation',
'ClarolineAPI',
@@ -25,4 +26,4 @@ var OrganizationManager = angular.module('OrganizationManager', [
.controller('EditOrganizationModalController', EditOrganizationModalController)
.controller('OrganizationController', ['$http', 'OrganizationAPIService', '$uibModal', 'ClarolineAPIService', OrganizationController])
.service('OrganizationAPIService', OrganizationAPIService)
- .config(Routing)
\ No newline at end of file
+ .config(Routing)
diff --git a/Resources/modules/organization/routing.js b/Resources/modules/organization/routing.js
index dfd5d80a4..b00daa5be 100644
--- a/Resources/modules/organization/routing.js
+++ b/Resources/modules/organization/routing.js
@@ -13,7 +13,7 @@ export default function($stateProvider, $urlRouterProvider) {
.state(
'organizations.list',
{
- url: "",
+ url: '',
ncyBreadcrumb: {
label: translate('organizations')
},
@@ -26,26 +26,24 @@ export default function($stateProvider, $urlRouterProvider) {
}
}
)
-
+
.state(
'organizations.locations',
{
- url: "/locations",
+ url: '/locations',
ncyBreadcrumb: {
label: translate('locations'),
parent: 'organizations.list'
},
views: {
'locations': {
- template: require('../location/Partial/locations_main.html'),
+ template: require('./../location/Partial/locations_main.html'),
controller: 'LocationController',
controllerAs: 'lc'
}
}
}
)
- ;
-
- $urlRouterProvider.otherwise("/organizations");
-}
\ No newline at end of file
+ $urlRouterProvider.otherwise('/organizations')
+}
diff --git a/Resources/modules/search/Directive/ClarolineSearchDirective.js b/Resources/modules/search/Directive/ClarolineSearchDirective.js
index 84cedc538..691757746 100644
--- a/Resources/modules/search/Directive/ClarolineSearchDirective.js
+++ b/Resources/modules/search/Directive/ClarolineSearchDirective.js
@@ -11,7 +11,7 @@ export default class ClarolineSearchDirective {
this.bindToController = {
onSearch: '&',
fields: '='
- };
+ };
}
}
diff --git a/Resources/modules/search/module.js b/Resources/modules/search/module.js
index 59232af11..739375128 100644
--- a/Resources/modules/search/module.js
+++ b/Resources/modules/search/module.js
@@ -1,3 +1,4 @@
+import 'angular/angular.min'
import 'angular-ui-select'
import Interceptors from '../interceptorsDefault'
@@ -10,4 +11,4 @@ angular.module('ClarolineSearch', ['ui.select'])
.config(Interceptors)
.directive('clarolinesearch', () => new ClarolineSearchDirective)
.service('SearchOptionsService', () => new SearchOptionsService)
- .provider('ClarolineSearchService', () => new ClarolineSearchService)
\ No newline at end of file
+ .provider('ClarolineSearchService', () => new ClarolineSearchService)
diff --git a/Resources/modules/services/module.js b/Resources/modules/services/module.js
index 8c0f536bb..9cd6b0347 100644
--- a/Resources/modules/services/module.js
+++ b/Resources/modules/services/module.js
@@ -1,11 +1,13 @@
+import 'angular/angular.min'
import 'angular-sanitize'
+
import ConfirmModalController from './Controller/ConfirmModalController'
import ClarolineAPIService from './Service/ClarolineAPIService'
import Interceptors from '../interceptorsDefault'
-angular.module('ClarolineAPI', ['ui.bootstrap', 'ui.bootstrap.tpls', 'ngSanitize'])
+angular.module('ClarolineAPI', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.config(Interceptors)
.controller('ConfirmModalController', ['callback', 'urlObject', 'title', 'content', '$http', '$uibModalInstance', ConfirmModalController])
.service('ClarolineAPIService', ClarolineAPIService)
-//ClarolineAPIService.$inject('$http', '$httpParamSerializer', '$uibModal')
\ No newline at end of file
+//ClarolineAPIService.$inject('$http', '$httpParamSerializer', '$uibModal')
diff --git a/Resources/modules/users/Partial/main.html b/Resources/modules/users/Partial/main.html
index 0f5208d71..251893dc4 100644
--- a/Resources/modules/users/Partial/main.html
+++ b/Resources/modules/users/Partial/main.html
@@ -1,4 +1,4 @@
-
\ No newline at end of file
+
diff --git a/Resources/modules/users/Partial/user_content.html b/Resources/modules/users/Partial/user_content.html
index 2f8c21d55..d44bf9152 100644
--- a/Resources/modules/users/Partial/user_content.html
+++ b/Resources/modules/users/Partial/user_content.html
@@ -29,7 +29,7 @@
diff --git a/Resources/modules/users/module.js b/Resources/modules/users/module.js
index 2c6f2d63d..2f0c8b470 100644
--- a/Resources/modules/users/module.js
+++ b/Resources/modules/users/module.js
@@ -1,4 +1,5 @@
import 'angular/angular.min'
+
import dataTable from 'angular-data-table/release/dataTable.helpers.min'
import bootstrap from 'angular-bootstrap'
import translation from 'angular-ui-translation/angular-translation'
@@ -23,4 +24,4 @@ angular.module('UsersManager', [
'GroupsManager',
'ncy-angular-breadcrumb'
]) .controller('UserController', ['$http', 'ClarolineSearchService', 'ClarolineAPIService', UserController])
- .config(Routing)
\ No newline at end of file
+ .config(Routing)
diff --git a/Resources/modules/users/routing.js b/Resources/modules/users/routing.js
index e67405429..46c74e5fa 100644
--- a/Resources/modules/users/routing.js
+++ b/Resources/modules/users/routing.js
@@ -7,8 +7,7 @@ export default function($stateProvider, $urlRouterProvider) {
.state ('users', {
abstract: true,
url: '/users',
- template: require('./Partial/main.html'),
-
+ template: require('./Partial/main.html')
})
.state(
'users.list',
@@ -37,12 +36,11 @@ export default function($stateProvider, $urlRouterProvider) {
},
views: {
'groups': {
- template: require('../groups/Partial/main.html')
+ template: require('./../groups/Partial/main.html')
}
}
}
)
- ;
- $urlRouterProvider.otherwise("/users");
-}
\ No newline at end of file
+ $urlRouterProvider.otherwise('/users');
+}
diff --git a/Resources/scripts/lib/webpack.js b/Resources/scripts/lib/webpack.js
index 768496bd0..5d038d032 100644
--- a/Resources/scripts/lib/webpack.js
+++ b/Resources/scripts/lib/webpack.js
@@ -56,11 +56,7 @@ function configure(rootDir, packages, isWatchMode) {
const loaders = [
makeJsLoader(isProd),
- makeRawLoader(),
- {
- test: /\.html/,
- loader: 'raw'
- }
+ makeRawLoader()
]
return {
diff --git a/assets.json b/assets.json
index 915ccbef6..b90141268 100644
--- a/assets.json
+++ b/assets.json
@@ -1,7 +1,7 @@
{
"webpack": {
"entry": {
- "user-management": "modules/groups/module",
+ "user-management": "modules/users/module",
"organization-management": "modules/organization/module"
}
}
From cd9d861bea8ed69ec6f9dcdf3e79ee2aad5eadcb Mon Sep 17 00:00:00 2001
From: ngodfraind
Date: Thu, 18 Feb 2016 16:48:00 +0100
Subject: [PATCH 23/65] Removing updater.
---
Library/Installation/AdditionalInstaller.php | 3 --
.../Updater/ResourceIconsUpdater.php | 5 +-
.../Installation/Updater/RootDirUpdater.php | 49 -------------------
3 files changed, 3 insertions(+), 54 deletions(-)
delete mode 100644 Library/Installation/Updater/RootDirUpdater.php
diff --git a/Library/Installation/AdditionalInstaller.php b/Library/Installation/AdditionalInstaller.php
index 6826b2fc2..d92d8763f 100644
--- a/Library/Installation/AdditionalInstaller.php
+++ b/Library/Installation/AdditionalInstaller.php
@@ -29,9 +29,6 @@ public function preUpdate($currentVersion, $targetVersion)
{
$maintenanceUpdater = new Updater\WebUpdater($this->container->getParameter('kernel.root_dir'));
$maintenanceUpdater->preUpdate();
- $rootDirUpdater = new Updater\RootDirUpdater($this->container->getParameter('kernel.root_dir'));
- $rootDirUpdater->setLogger($this->logger);
- $rootDirUpdater->preUpdate();
$this->setLocale();
diff --git a/Library/Installation/Updater/ResourceIconsUpdater.php b/Library/Installation/Updater/ResourceIconsUpdater.php
index 39b3c4576..460fc8632 100644
--- a/Library/Installation/Updater/ResourceIconsUpdater.php
+++ b/Library/Installation/Updater/ResourceIconsUpdater.php
@@ -41,8 +41,9 @@ private function updateIcons()
foreach ($resourceImages as $resourceImage) {
$mimeType = $resourceImage[1];
- $results = $this->repo->findBy(array('mimeType' => $mimeType, 'isShortcut' => false));
- $rimg = count($results > 0) ? $results[0]: null;
+ $rimg = $this->repo->findOneBy(array('mimeType' => $mimeType, 'isShortcut' => false));
+ //var_dump(count($results));
+ //$rimg = count($results > 0) ? $results[0]: null;
if ($rimg === null) {
$this->log('Adding mime type for ' . $mimeType . '.');
diff --git a/Library/Installation/Updater/RootDirUpdater.php b/Library/Installation/Updater/RootDirUpdater.php
deleted file mode 100644
index 28575b593..000000000
--- a/Library/Installation/Updater/RootDirUpdater.php
+++ /dev/null
@@ -1,49 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Library\Installation\Updater;
-
-use Claroline\InstallationBundle\Updater\Updater;
-use Claroline\CoreBundle\Library\Utilities\FileSystem;
-
-class RootDirUpdater extends Updater
-{
- private $fs = null;
- private $rootSrc;
- private $rootProd;
-
- public function __construct($rootDir)
- {
- $ds = DIRECTORY_SEPARATOR;
- $this->rootSrc = "{$rootDir}{$ds}..{$ds}vendor{$ds}claroline{$ds}core-bundle{$ds}Resources/rootDir";
- $this->rootProd = "{$rootDir}{$ds}..{$ds}";
- $this->fs = new FileSystem();
- }
-
- public function preUpdate()
- {
- $this->log('Updating root files...');
- $this->copyDirContent($this->rootSrc, $this->rootProd);
- }
-
- private function copyDirContent($path, $target)
- {
- $iterator = new \DirectoryIterator($path);
-
- foreach ($iterator as $el) {
- if (!$el->isDot()) {
- $parts = explode($el->getPathName(), '/');
- $newPath = $target . $el->getFileName();
- if (file_exists($newPath)) unlink($newPath);
- $this->fs->copy($el->getRealPath(), $newPath);
- }
- }
- }
-}
From be9a1166a6ee4c5a91e1e67a1e6948024d06b035 Mon Sep 17 00:00:00 2001
From: Nicolas Godfraind
Date: Fri, 19 Feb 2016 13:35:03 +0100
Subject: [PATCH 24/65] Removing useless code from UserManager, UserRepository
and removing AdministrationControllerTest.
---
Library/Security/Voter/GroupVoter.php | 2 +-
Library/Security/Voter/UserVoter.php | 2 +-
Manager/UserManager.php | 109 +-
Repository/UserRepository.php | 143 --
.../Repository/UserRepositoryTest.php | 14 -
.../AdministrationControllerTest.php | 1172 -----------------
Tests/Unit/Manager/UserManagerTest.php | 56 +-
7 files changed, 11 insertions(+), 1487 deletions(-)
delete mode 100644 Tests/Unit/Controller/AdministrationControllerTest.php
diff --git a/Library/Security/Voter/GroupVoter.php b/Library/Security/Voter/GroupVoter.php
index 9c4b01376..0b5e7f5a3 100644
--- a/Library/Security/Voter/GroupVoter.php
+++ b/Library/Security/Voter/GroupVoter.php
@@ -24,7 +24,7 @@ class GroupVoter implements VoterInterface
public function vote(TokenInterface $token, $object, array $attributes)
{
//no implementation yet
- return true;
+ return false;
}
public function supportsAttribute($attribute)
diff --git a/Library/Security/Voter/UserVoter.php b/Library/Security/Voter/UserVoter.php
index 27d80f52c..d87137a9e 100644
--- a/Library/Security/Voter/UserVoter.php
+++ b/Library/Security/Voter/UserVoter.php
@@ -24,7 +24,7 @@ class UserVoter implements VoterInterface
public function vote(TokenInterface $token, $object, array $attributes)
{
//no implementation yet
- return true;
+ return false;
}
public function supportsAttribute($attribute)
diff --git a/Manager/UserManager.php b/Manager/UserManager.php
index 9dd67067c..4affc56fe 100644
--- a/Manager/UserManager.php
+++ b/Manager/UserManager.php
@@ -60,6 +60,7 @@ class UserManager
private $uploadsDirectory;
private $transfertManager;
private $container;
+ private $authorization;
/**
* Constructor.
@@ -469,11 +470,12 @@ public function setPlatformRoles(User $user, $roles)
}
/**
- * Serialize a user.
+ * Serialize a user. Use JMS serializer from entities instead
*
* @param array $users
*
* @return array
+ * @deprecated
*/
public function convertUsersToArray(array $users)
{
@@ -555,34 +557,6 @@ public function getAll()
return $this->userRepo->findAll();
}
- /**
- * @param integer $page
- * @param integer $max
- * @param string $orderedBy
- * @param string $order
- *
- * @return \Pagerfanta\Pagerfanta;
- */
- public function getAllUsersExcept($page, $max = 20, $orderedBy = 'id', $order = null, array $users )
- {
- $query = $this->userRepo->findAllExcept($users);
- return $this->pagerFactory->createPagerFromArray($query, $page, $max);
- }
-
- /**
- * @param string $search
- * @param integer $page
- * @param integer $max
- *
- * @return \Pagerfanta\Pagerfanta;
- */
- public function getAllUsersBySearch($page, $search, $max = 20)
- {
- $users = $this->userRepo->findAllUserBySearch($search);
-
- return $this->pagerFactory->createPagerFromArray($users, $page, $max);
- }
-
/**
* @param string $search
* @param integer $page
@@ -619,26 +593,6 @@ public function getUsersByGroup(
return $this->pagerFactory->createPager($query, $page, $max);
}
- /**
- * @param \Claroline\CoreBundle\Entity\Group $group
- *
- * @return User[]
- */
- public function getUsersByGroupWithoutPager(Group $group)
- {
- return $this->userRepo->findByGroup($group);
- }
-
- /**
- * @param Workspace $workspace
- *
- * @return User[]
- */
- public function getByWorkspaceWithUsersFromGroup(Workspace $workspace)
- {
- return $this->userRepo->findByWorkspaceWithUsersFromGroup($workspace);
- }
-
/**
*
* @param string $search
@@ -689,27 +643,6 @@ public function getUsersByWorkspaces(array $workspaces, $page = 1, $max = 20, $w
}
- /**
- * @param \Claroline\CoreBundle\Entity\Workspace\Workspace[] $workspaces
- * @param integer $page
- * @param string $search
- * @param integer $max
- *
- * @return \Pagerfanta\Pagerfanta
- */
- public function getUsersByWorkspacesAndSearch(
- array $workspaces,
- $page,
- $search,
- $max = 20
- )
- {
- $users = $this->userRepo
- ->findUsersByWorkspacesAndSearch($workspaces, $search);
-
- return $this->pagerFactory->createPagerFromArray($users, $page, $max);
- }
-
/**
* @param \Claroline\CoreBundle\Entity\Workspace\Workspace $workspace
* @param string $search
@@ -725,37 +658,6 @@ public function getAllUsersByWorkspaceAndName(Workspace $workspace, $search, $pa
return $this->pagerFactory->createPager($query, $page, $max);
}
- /**
- * @param \Claroline\CoreBundle\Entity\Group $group
- * @param integer $page
- * @param integer $max
- * @param string $orderedBy
- *
- * @return \Pagerfanta\Pagerfanta
- */
- public function getGroupOutsiders(Group $group, $page, $max = 20, $orderedBy = 'id')
- {
- $query = $this->userRepo->findGroupOutsiders($group, false, $orderedBy);
-
- return $this->pagerFactory->createPager($query, $page, $max);
- }
-
- /**
- * @param \Claroline\CoreBundle\Entity\Group $group
- * @param integer $page
- * @param string $search
- * @param integer $max
- * @param string $orderedBy
- *
- * @return \Pagerfanta\Pagerfanta
- */
- public function getGroupOutsidersByName(Group $group, $page, $search, $max = 20, $orderedBy = 'id')
- {
- $query = $this->userRepo->findGroupOutsidersByName($group, $search, false, $orderedBy);
-
- return $this->pagerFactory->createPager($query, $page, $max);
- }
-
/**
* @return integer
*/
@@ -1597,4 +1499,9 @@ public function getUserSearchableFields()
return $event->getFilters();
}
+
+ public function isGranted($action, User $user)
+ {
+ return $this->container->get('security.authorization_checker')->isGranted($action, $user);
+ }
}
diff --git a/Repository/UserRepository.php b/Repository/UserRepository.php
index 7cfc446ec..6a6274b2c 100644
--- a/Repository/UserRepository.php
+++ b/Repository/UserRepository.php
@@ -113,36 +113,6 @@ public function findAll($executeQuery = true, $orderedBy = 'id', $order = null)
return parent::findAll();
}
- /**
- * Returns all the users by search.
- *
- * @param string $search
- *
- * @return User[]
- */
- public function findAllUserBySearch($search)
- {
- $upperSearch = strtoupper(trim($search));
-
- if ($search !== '') {
- $dql = '
- SELECT u
- FROM Claroline\CoreBundle\Entity\User u
- WHERE UPPER(u.firstName) LIKE :search
- OR UPPER(u.lastName) LIKE :search
- OR UPPER(u.username) LIKE :search
- AND u.isEnabled = true
- ';
-
- $query = $this->_em->createQuery($dql);
- $query->setParameter('search', "%{$upperSearch}%");
-
- return $query->getResult();
- }
-
- return parent::findAll();
- }
-
/**
* Search users whose first name, last name or username match a given search string.
*
@@ -402,93 +372,6 @@ public function findAllByWorkspaceAndName(Workspace $workspace, $search, $execut
return $executeQuery ? $query->getResult() : $query;
}
- /**
- * Returns the users who are not members of a group.
- *
- * @param Group $group
- * @param boolean $executeQuery
- * @param string $orderedBy
- *
- * @return User[]|Query
- *
- * @todo Find out why the join on profile preferences is necessary
- */
- public function findGroupOutsiders(Group $group, $executeQuery = true, $orderedBy = 'id')
- {
- $dql = "
- SELECT DISTINCT u FROM Claroline\CoreBundle\Entity\User u
- WHERE u NOT IN (
- SELECT us FROM Claroline\CoreBundle\Entity\User us
- JOIN us.groups gs
- WHERE gs.id = :groupId
- )
- AND u.isEnabled = true
- ORDER BY u.{$orderedBy}
- ";
- $query = $this->_em->createQuery($dql);
- $query->setParameter('groupId', $group->getId());
-
- return $executeQuery ? $query->getResult() : $query;
- }
-
- /**
- * Returns the users who are not members of a group and whose first name, last
- * name or username match a given search string.
- *
- * @param \Claroline\CoreBundle\Entity\Group $group
- * @param string $search
- * @param boolean $executeQuery
- * @param string $orderedBy
- *
- * @return User[]|Query
- *
- * @todo Find out why the join on profile preferences is necessary
- */
- public function findGroupOutsidersByName(Group $group, $search, $executeQuery = true, $orderedBy = 'id')
- {
- $dql = "
- SELECT DISTINCT u FROM Claroline\CoreBundle\Entity\User u
- WHERE (
- UPPER(u.lastName) LIKE :search
- OR UPPER(u.firstName) LIKE :search
- OR UPPER(u.lastName) LIKE :search
- )
- AND u NOT IN (
- SELECT us FROM Claroline\CoreBundle\Entity\User us
- JOIN us.groups gr
- WHERE gr.id = :groupId
- )
- AND u.isEnabled = true
- ORDER BY u.{$orderedBy}
- ";
- $search = strtoupper($search);
- $query = $this->_em->createQuery($dql);
- $query->setParameter('groupId', $group->getId());
- $query->setParameter('search', "%{$search}%");
-
- return $executeQuery ? $query->getResult() : $query;
- }
-
- /**
- * Returns all the users except a given one.
- *
- * @param array $excludedUser
- *
- * @return User[]
- */
- public function findAllExcept(array $excludedUser)
- {
- $dql = '
- SELECT u FROM Claroline\CoreBundle\Entity\User u
- WHERE u NOT IN (:userIds)
- AND u.isEnabled = true
- ';
- $query = $this->_em->createQuery($dql);
- $query->setParameter('userIds', $excludedUser);
-
- return $query->getResult();
- }
-
/**
* Returns users by their usernames.
*
@@ -784,32 +667,6 @@ public function findUserByUsernameOrEmail($username, $email)
return $query->getResult();
}
- /**
- * @param Workspace $workspace
- *
- * @return array
- */
- public function findByWorkspaceWithUsersFromGroup(Workspace $workspace)
- {
- $dql = '
- SELECT u
- FROM Claroline\CoreBundle\Entity\User u
- JOIN u.roles ur
- LEFT JOIN u.groups g
- LEFT JOIN g.roles gr
- LEFT JOIN gr.workspace grws
- LEFT JOIN ur.workspace uws
- WHERE uws.id = :wsId
- OR grws.id = :wsId
- ';
-
- $query = $this->_em->createQuery($dql);
- $query->setParameter('wsId', $workspace->getId());
- $res = $query->getResult();
-
- return $res;
- }
-
/**
* @param string $search
*
diff --git a/Tests/Database/Repository/UserRepositoryTest.php b/Tests/Database/Repository/UserRepositoryTest.php
index c10b82310..992b6a47a 100644
--- a/Tests/Database/Repository/UserRepositoryTest.php
+++ b/Tests/Database/Repository/UserRepositoryTest.php
@@ -97,20 +97,6 @@ public function testFindByNameAndGroup()
$this->assertEquals(2, count($users));
}
- public function testFindGroupOutsiders()
- {
- $users = self::$repo->findGroupOutsiders(self::get('group_1'));
- $this->assertEquals(3, count($users));
- }
-
- public function testFindGroupOutsidersByName()
- {
- $users = self::$repo->findGroupOutsidersByName(self::get('group_1'), 'o');
- $this->assertEquals(2, count($users));
- $users = self::$repo->findGroupOutsidersByName(self::get('group_1'), 'iLL');
- $this->assertEquals(1, count($users));
- }
-
public function testFindAllExcept()
{
$users = self::$repo->findAllExcept(self::get('john'));
diff --git a/Tests/Unit/Controller/AdministrationControllerTest.php b/Tests/Unit/Controller/AdministrationControllerTest.php
deleted file mode 100644
index 2ee2d899e..000000000
--- a/Tests/Unit/Controller/AdministrationControllerTest.php
+++ /dev/null
@@ -1,1172 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Controller;
-
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Symfony\Component\HttpFoundation\Response;
-use Claroline\CoreBundle\Entity\Group;
-use Claroline\CoreBundle\Entity\Role;
-use Claroline\CoreBundle\Entity\User;
-use Claroline\CoreBundle\Form\Factory\FormFactory;
-use Claroline\CoreBundle\Library\Testing\MockeryTestCase;
-use Doctrine\Common\Collections\ArrayCollection;
-use org\bovigo\vfs\vfsStream;
-use Mockery as m;
-
-class AdministrationControllerTest extends MockeryTestCase
-{
- private $userManager;
- private $roleManager;
- private $groupManager;
- private $workspaceManager;
- private $workspaceTagManager;
- private $security;
- private $eventDispatcher;
- private $configHandler;
- private $formFactory;
- private $analyticsManager;
- private $translator;
- private $request;
- private $mailManager;
- private $localeManager;
- private $router;
-
- protected function setUp()
- {
- parent::setUp();
- $this->userManager = $this->mock('Claroline\CoreBundle\Manager\UserManager');
- $this->roleManager = $this->mock('Claroline\CoreBundle\Manager\RoleManager');
- $this->groupManager = $this->mock('Claroline\CoreBundle\Manager\GroupManager');
- $this->workspaceManager = $this->mock('Claroline\CoreBundle\Manager\WorkspaceManager');
- $this->workspaceTagManager = $this->mock('Claroline\CoreBundle\Manager\WorkspaceTagManager');
- $this->security = $this->mock('Symfony\Component\Security\Core\SecurityContextInterface');
- $this->eventDispatcher = $this->mock('Claroline\CoreBundle\Event\StrictDispatcher');
- $this->configHandler = $this->mock('Claroline\CoreBundle\Library\Configuration\PlatformConfigurationHandler');
- $this->formFactory = $this->mock('Claroline\CoreBundle\Form\Factory\FormFactory');
- $this->analyticsManager = $this->mock('Claroline\CoreBundle\Manager\AnalyticsManager');
- $this->translator = $this->mock('Symfony\Component\Translation\Translator');
- $this->request = $this->mock('Symfony\Component\HttpFoundation\Request');
- $this->mailManager = $this->mock('Claroline\CoreBundle\Manager\MailManager');
- $this->localeManager = $this->mock('Claroline\CoreBundle\Manager\LocaleManager');
- $this->router = $this->mock('Symfony\Component\Routing\RouterInterface');
- }
-
- public function testIndexAction()
- {
- $this->assertEquals(array(), $this->getController()->indexAction());
- }
-
- public function testUserCreationFormAction()
- {
- $user = new User();
- $roleA = new Role();
- $roleB = new Role();
- $roles = array($roleA, $roleB);
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->roleManager->shouldReceive('getPlatformRoles')
- ->with($user)
- ->once()
- ->andReturn($roles);
- $this->localeManager->shouldReceive('getAvailableLocales')
- ->once()
- ->andReturn(array('en'));
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_USER_FULL, array($roles, array('en')))
- ->once()
- ->andReturn($form);
- $this->mailManager
- ->shouldReceive('isMailerAvailable')
- ->once()
- ->andReturn(true);
- $form->shouldReceive('createView')
- ->once()
- ->andReturn('view');
-
- $this->assertEquals(
- array('form_complete_user' => 'view'),
- $this->getController()->userCreationFormAction($user)
- );
- }
-
- public function testCreateUserAction()
- {
- $controller = $this->getController(array('redirect', 'generateUrl'));
- $currentUser = new User();
- $user = $this->mock('Claroline\CoreBundle\Entity\User');
- $roleA = new Role();
- $roleB = new Role();
- $roleC = new Role();
- $roleD = new Role();
- $roles = array($roleA, $roleB);
- $newRoles = new ArrayCollection(array($roleC, $roleD));
- $form = $this->mock('Symfony\Component\Form\Form');
- $formInterface = $this->mock('Symfony\Component\Form\FormInterface');
-
- $this->roleManager->shouldReceive('getPlatformRoles')
- ->with($currentUser)
- ->once()
- ->andReturn($roles);
- $this->localeManager->shouldReceive('getAvailableLocales')
- ->once()
- ->andReturn(array('en'));
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_USER_FULL, array($roles, array('en')))
- ->once()
- ->andReturn($form);
- $form->shouldReceive('handleRequest')
- ->with($this->request)
- ->once();
- $form->shouldReceive('isValid')
- ->once()
- ->andReturn(true);
- $form->shouldReceive('getData')
- ->once()
- ->andReturn($user);
- $form->shouldReceive('get')
- ->with('platformRoles')
- ->once()
- ->andReturn($formInterface);
- $formInterface->shouldReceive('getData')
- ->once()
- ->andReturn($newRoles);
- $this->userManager->shouldReceive('insertUserWithRoles')
- ->with($user, $newRoles)
- ->once();
- $this->mailManager
- ->shouldReceive('isMailerAvailable')
- ->once()
- ->andReturn(true);
- $this->translator
- ->shouldReceive('trans')
- ->with('username', array(), 'platform')
- ->once()
- ->andReturn('admin form username');
- $user->shouldReceive('getUsername')
- ->once()
- ->andReturn('username');
- $this->translator
- ->shouldReceive('trans')
- ->with('password', array(), 'platform')
- ->once()
- ->andReturn('admin form plainPassword first');
- $user->shouldReceive('getPlainPassword')
- ->once()
- ->andReturn('password');
- $user->shouldReceive('getMail')
- ->once()
- ->andReturn('mail');
- $this->mailManager
- ->shouldReceive('sendCreationMessage')
- ->with(
- 'noreply@claroline.net',
- 'mail',
- 'admin form username: usernameadmin form plainPassword first: password'
- )
- ->once()
- ->andReturn(true);
- $controller->shouldReceive('generateUrl')
- ->with('claro_admin_user_list')
- ->once()
- ->andReturn('url');
- $controller->shouldReceive('redirect')
- ->with('url')
- ->once()
- ->andReturn('redirection');
-
- $this->assertEquals(
- 'redirection',
- $controller->createUserAction($currentUser)
- );
- }
-
- public function testDeleteUsersAction()
- {
- $userA = new User();
- $userB = new User();
- $users = array($userA, $userB);
-
- $this->userManager->shouldReceive('deleteUser')
- ->with($userA)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogUserDelete', array($userA))
- ->once();
- $this->userManager->shouldReceive('deleteUser')
- ->with($userB)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogUserDelete', array($userB))
- ->once();
-
- $this->getController()->deleteUsersAction($users);
- }
-
- public function testUserListActionWithoutSearch()
- {
- $this->userManager->shouldReceive('getAllUsers')
- ->with(1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => '', 'max' => 50, 'order' => 'id'),
- $this->getController()->userListAction(1, '', 50, 'id')
- );
- }
-
- public function testUserListActionWithSearch()
- {
- $this->userManager->shouldReceive('getUsersByName')
- ->with('search', 1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => 'search', 'max' => 50, 'order' => 'id'),
- $this->getController()->userListAction(1, 'search', 50, 'id')
- );
- }
-
- public function testGroupListActionWithoutSearch()
- {
- $this->groupManager->shouldReceive('getGroups')
- ->with(1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => '', 'max' => 50, 'order' => 'id'),
- $this->getController()->groupListAction(1, '', 50, 'id')
- );
- }
-
- public function testGroupListActionWithSearch()
- {
- $this->groupManager->shouldReceive('getGroupsByName')
- ->with('search', 1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => 'search', 'max' => 50, 'order' => 'id'),
- $this->getController()->groupListAction(1, 'search', 50, 'id')
- );
- }
-
- public function testUsersOfGroupListActionWithoutSearch()
- {
- $group = new Group();
-
- $this->userManager->shouldReceive('getUsersByGroup')
- ->with($group, 1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => '', 'group' => $group, 'max' => 50, 'order' => 'id'),
- $this->getController()->usersOfGroupListAction($group, 1, '', 50, 'id')
- );
- }
-
- public function testUsersOfGroupListActionWithSearch()
- {
- $group = new Group();
-
- $this->userManager->shouldReceive('getUsersByNameAndGroup')
- ->with('search', $group, 1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => 'search', 'group' => $group, 'max' => 50, 'order' => 'id'),
- $this->getController()->usersOfGroupListAction($group, 1, 'search', 50, 'id')
- );
- }
-
- public function testOutsideOfGroupUserListActionWithoutSearch()
- {
- $group = new Group();
-
- $this->userManager->shouldReceive('getGroupOutsiders')
- ->with($group, 1, 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => '', 'group' => $group, 'max' => 50, 'order' => 'id'),
- $this->getController()->outsideOfGroupUserListAction($group, 1, '', 50, 'id')
- );
- }
-
- public function testOutsideOfGroupUserListActionWithSearch()
- {
- $group = new Group();
-
- $this->userManager->shouldReceive('getGroupOutsidersByName')
- ->with($group, 1, 'search', 50, 'id')
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array('pager' => 'pager', 'search' => 'search', 'group' => $group, 'max' => 50, 'order' => 'id'),
- $this->getController()->outsideOfGroupUserListAction($group, 1, 'search', 50, 'id')
- );
- }
-
- public function testGroupCreationFormAction()
- {
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_GROUP)
- ->once()
- ->andReturn($form);
- $form->shouldReceive('createView')
- ->once()
- ->andReturn('view');
-
- $this->assertEquals(
- array('form_group' => 'view'),
- $this->getController()->groupCreationFormAction()
- );
- }
-
- public function testCreateGroupAction()
- {
- $controller = $this->getController(array('redirect', 'generateUrl'));
- $form = $this->mock('Symfony\Component\Form\Form');
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $role = new Role();
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_GROUP, array())
- ->once()
- ->andReturn($form);
- $form->shouldReceive('handleRequest')
- ->with($this->request)
- ->once();
- $form->shouldReceive('isValid')
- ->once()
- ->andReturn(true);
- $form->shouldReceive('getData')
- ->once()
- ->andReturn($group);
- $this->roleManager->shouldReceive('getRoleByName')
- ->with('ROLE_USER')
- ->once()
- ->andReturn($role);
- $group->shouldReceive('setPlatformRole')
- ->with($role)
- ->once();
- $this->groupManager->shouldReceive('insertGroup')
- ->with($group)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupCreate', array($group))
- ->once();
- $controller->shouldReceive('generateUrl')
- ->with('claro_admin_group_list')
- ->once()
- ->andReturn('url');
- $controller->shouldReceive('redirect')
- ->with('url')
- ->once()
- ->andReturn('redirection');
-
- $this->assertEquals('redirection', $controller->createGroupAction());
- }
-
- public function testAddUsersToGroupAction()
- {
- $userA = new User();
- $userB = new User();
- $users = array($userA, $userB);
- $group = new Group();
-
- $this->groupManager->shouldReceive('addUsersToGroup')
- ->with($group, $users)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupAddUser', array($group, $userA))
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupAddUser', array($group, $userB))
- ->once();
-
- $this->getController()->addUsersToGroupAction($group, $users);
- }
-
- public function testDeleteUsersFromGroupAction()
- {
- $userA = new User();
- $userB = new User();
- $users = array($userA, $userB);
- $group = new Group();
-
- $this->groupManager->shouldReceive('removeUsersFromGroup')
- ->with($group, $users)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupRemoveUser', array($group, $userA))
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupRemoveUser', array($group, $userB))
- ->once();
-
- $this->getController()->deleteUsersFromGroupAction($group, $users);
- }
-
- public function testDeleteGroupsAction()
- {
- $groupA = new Group();
- $groupB = new Group();
- $groups = array($groupA, $groupB);
-
- $this->groupManager->shouldReceive('deleteGroup')
- ->with($groupA)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupDelete', array($groupA))
- ->once();
- $this->groupManager->shouldReceive('deleteGroup')
- ->with($groupB)
- ->once();
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('log', 'Log\LogGroupDelete', array($groupB))
- ->once();
-
- $this->getController()->deleteGroupsAction($groups);
- }
-
- public function testGroupSettingsFormAction()
- {
- $group = new Group();
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_GROUP_SETTINGS, array(), $group)
- ->once()
- ->andReturn($form);
- $form->shouldReceive('createView')
- ->once()
- ->andReturn('form');
-
- $this->assertEquals(
- array('group' => $group, 'form_settings' => 'form'),
- $this->getController()->groupSettingsFormAction($group)
- );
- }
-
- public function testUpdateGroupSettingsAction()
- {
- $controller = $this->getController(array('redirect', 'generateUrl'));
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $newGroup = $this->mock('Claroline\CoreBundle\Entity\Group');
- $role = $this->mock('Claroline\CoreBundle\Entity\Role');
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $group->shouldReceive('getPlatformRole')
- ->once()
- ->andReturn($role);
- $role->shouldReceive('getTranslationKey')
- ->once()
- ->andReturn('old_key');
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_GROUP_SETTINGS, array(), $group)
- ->once()
- ->andReturn($form);
- $form->shouldReceive('handleRequest')
- ->with($this->request)
- ->once();
- $form->shouldReceive('isValid')
- ->once()
- ->andReturn(true);
- $form->shouldReceive('getData')
- ->once()
- ->andReturn($newGroup);
- $this->groupManager->shouldReceive('updateGroup')
- ->with($newGroup, 'old_key')
- ->once();
- $controller->shouldReceive('generateUrl')
- ->with('claro_admin_group_list')
- ->once()
- ->andReturn('url');
- $controller->shouldReceive('redirect')
- ->with('url')
- ->once()
- ->andReturn('redirection');
-
- $this->assertEquals(
- 'redirection',
- $controller->updateGroupSettingsAction($group)
- );
- }
-
- public function testPlatformSettingsFormAction()
- {
- $this->markTestSkipped('Unable to test because it uses getThemes which is a private function');
- }
-
- public function testUpdatePlatformSettingsAction()
- {
- $this->markTestSkipped('Unable to test because it uses getThemes which is a private function');
- }
-
- public function testPluginParametersAction()
- {
- $event = $this->mock('Claroline\CoreBundle\Event\PluginOptionsEvent');
-
- $this->eventDispatcher->shouldReceive('dispatch')
- ->with('plugin_options_domain', 'PluginOptions', array())
- ->once()
- ->andReturn($event);
- $event->shouldReceive('getResponse')
- ->once()
- ->andReturn('response');
-
- $this->assertEquals('response', $this->getController()->pluginParametersAction('domain'));
- }
-
- public function testUsersManagementAction()
- {
- $this->assertEquals(array(), $this->getController()->usersManagementAction());
- }
-
- public function testImportUsersFormAction()
- {
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_USER_IMPORT)
- ->once()
- ->andReturn($form);
- $form->shouldReceive('createView')
- ->once()
- ->andReturn('view');
-
- $this->assertEquals(array('form' => 'view'), $this->getController()->importUsersFormAction());
- }
-
- public function testImportUsers()
- {
- vfsStream::setup('root', null, array('users.txt' => "gg,gg,gg,gg,gg,gg,gg"));
-
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_USER_IMPORT)
- ->once()
- ->andReturn($form);
-
- $form->shouldReceive('handleRequest')
- ->with($this->request)
- ->once();
-
- $form->shouldReceive('isValid')
- ->with()
- ->once()
- ->andReturn(true);
-
- m::getConfiguration()->allowMockingNonExistentMethods(true);
- $form->shouldReceive('get->getData')->andReturn(vfsStream::url('root/users.txt'));
- m::getConfiguration()->allowMockingNonExistentMethods(false);
- $this->userManager->shouldReceive('importUsers')->once()
- ->with(array(array('gg', 'gg', 'gg', 'gg', 'gg', 'gg', 'gg')));
-
- $this->router->shouldReceive('generate')->once()->with('claro_admin_user_list')->andReturn('yolo');
-
- $this->assertTrue($this->getController()->importUsers() instanceof RedirectResponse);
- }
-
- public function testImportUsersIntoGroupFormAction()
- {
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_USER_IMPORT)
- ->once()
- ->andReturn($form);
- $form->shouldReceive('createView')
- ->once()
- ->andReturn('view');
-
- $this->assertEquals(
- array('form' => 'view', 'group' => $group),
- $this->getController()->importUsersIntoGroupFormAction($group)
- );
- }
-
- public function testImportUsersIntoGroupAction()
- {
- vfsStream::setup('root', null, array('users.txt' => "gg,gg,gg,gg,gg,gg,gg"));
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $group->shouldReceive('getId')->andReturn(42);
-
- $form = $this->mock('Symfony\Component\Form\Form');
-
- $this->formFactory->shouldReceive('create')
- ->with(FormFactory::TYPE_USER_IMPORT)
- ->once()
- ->andReturn($form);
-
- $form->shouldReceive('handleRequest')
- ->with($this->request)
- ->once();
-
- $form->shouldReceive('isValid')
- ->with()
- ->once()
- ->andReturn(true);
-
- m::getConfiguration()->allowMockingNonExistentMethods(true);
- $form->shouldReceive('get->getData')->andReturn(vfsStream::url('root/users.txt'));
- m::getConfiguration()->allowMockingNonExistentMethods(false);
- $users = array(array('gg', 'gg', 'gg', 'gg', 'gg', 'gg', 'gg'));
- $this->userManager->shouldReceive('importUsers')->once()->with($users);
- $this->groupManager->shouldReceive('importUsers')->once()->with($group, $users);
- $this->router->shouldReceive('generate')->once()
- ->with('claro_admin_user_of_group_list', array('groupId' => 42))
- ->andReturn('azertyuiop');
-
- $this->assertTrue($this->getController()->importUsersIntoGroupAction($group) instanceof RedirectResponse);
- }
-
- public function testRegistrationManagementActionWithoutSearch()
- {
- $datas = array(
- 'workspaces' => 'workspaces',
- 'tags' => 'tags',
- 'tagWorkspaces' => 'tagWorkspaces',
- 'hierarchy' => 'hierarchy',
- 'rootTags' => 'rootTags',
- 'displayable' => 'displayable'
- );
-
- $this->workspaceTagManager
- ->shouldReceive('getDatasForWorkspaceList')
- ->with(false)
- ->once()
- ->andReturn($datas);
-
- $this->assertEquals(
- array(
- 'workspaces' => 'workspaces',
- 'tags' => 'tags',
- 'tagWorkspaces' => 'tagWorkspaces',
- 'hierarchy' => 'hierarchy',
- 'rootTags' => 'rootTags',
- 'displayable' => 'displayable',
- 'search' => ''
- ),
- $this->getController()->registrationManagementAction('')
- );
- }
-
- public function testRegistrationManagementActionWithSearch()
- {
- $this->workspaceManager
- ->shouldReceive('getDisplayableWorkspacesBySearchPager')
- ->with('search', 1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'workspaces' => 'pager',
- 'search' => 'search'
- ),
- $this->getController()->registrationManagementAction('search')
- );
- }
-
- public function testRegistrationManagementUserListAction()
- {
- $workspaces = array('workspace_1', 'workspace_2');
-
- $this->userManager
- ->shouldReceive('getAllUsers')
- ->with(1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'workspaces' => $workspaces,
- 'users' => 'pager',
- 'search' => ''
- ),
- $this->getController()->registrationManagementUserListAction($workspaces)
- );
- }
-
- public function testRegistrationManagementGroupListAction()
- {
- $workspaces = array('workspace_1', 'workspace_2');
-
- $this->groupManager
- ->shouldReceive('getGroups')
- ->with(1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'workspaces' => $workspaces,
- 'groups' => 'pager',
- 'search' => ''
- ),
- $this->getController()->registrationManagementGroupListAction($workspaces)
- );
- }
-
- public function testUserListPagerActionWithSearch()
- {
- $this->userManager
- ->shouldReceive('getUsersByName')
- ->with('search', 1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'users' => 'pager',
- 'search' => 'search'
- ),
- $this->getController()->userListPagerAction(1, 'search')
- );
- }
-
- public function testUserListPagerActionWithoutSearch()
- {
- $this->userManager
- ->shouldReceive('getAllUsers')
- ->with(1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'users' => 'pager',
- 'search' => ''
- ),
- $this->getController()->userListPagerAction(1, '')
- );
- }
-
- public function testGroupListPagerActionWithSearch()
- {
- $this->groupManager
- ->shouldReceive('getGroupsByName')
- ->with('search', 1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'groups' => 'pager',
- 'search' => 'search'
- ),
- $this->getController()->groupListPagerAction(1, 'search')
- );
- }
-
- public function testGroupListPagerActionWithoutSearch()
- {
- $this->groupManager
- ->shouldReceive('getGroups')
- ->with(1)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals(
- array(
- 'groups' => 'pager',
- 'search' => ''
- ),
- $this->getController()->groupListPagerAction(1, '')
- );
- }
-
- public function testSubscribeMultipleUsersToMultipleWorkspacesAction()
- {
- $workspaceA = $this->mock('Claroline\CoreBundle\Entity\Workspace\Workspace');
- $workspaceB = $this->mock('Claroline\CoreBundle\Entity\Workspace\Workspace');
- $workspaces = array($workspaceA, $workspaceB);
- $userA = $this->mock('Claroline\CoreBundle\Entity\User');
- $userB = $this->mock('Claroline\CoreBundle\Entity\User');
- $users = array($userA, $userB);
- $roleA = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleB = $this->mock('Claroline\CoreBundle\Entity\Role');
- $msgA = 'firstA lastA has been suscribed with role "roleTrad"';
- $msgB = 'firstB lastB has been suscribed with role "roleTrad"';
- $msg = $msgA . '-;-' . $msgB . '-;-';
-
- $this->roleManager
- ->shouldReceive('getRoleByTranslationKeyAndWorkspace')
- ->with('role', $workspaceA)
- ->once()
- ->andReturn($roleA);
- $this->roleManager
- ->shouldReceive('associateRoleToMultipleSubjects')
- ->with($users, $roleA)
- ->once();
- $this->roleManager
- ->shouldReceive('getRoleByTranslationKeyAndWorkspace')
- ->with('role', $workspaceB)
- ->once()
- ->andReturn($roleB);
- $this->roleManager
- ->shouldReceive('associateRoleToMultipleSubjects')
- ->with($users, $roleB)
- ->once();
- $userA->shouldReceive('getFirstName')
- ->once()
- ->andReturn('firstA');
- $userA->shouldReceive('getLastName')
- ->once()
- ->andReturn('lastA');
- $userB->shouldReceive('getFirstName')
- ->once()
- ->andReturn('firstB');
- $userB->shouldReceive('getLastName')
- ->once()
- ->andReturn('lastB');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'has_been_suscribed_with_role',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('has been suscribed with role');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'role',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('roleTrad');
-
- $response = $this->getController()
- ->subscribeMultipleUsersToMultipleWorkspacesAction(
- 'role',
- $workspaces,
- $users
- );
- $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
- $this->assertEquals($msg, $response->getContent());
- }
-
- public function testSubscribeMultipleGroupsToMultipleWorkspacesAction()
- {
- $workspaceA = $this->mock('Claroline\CoreBundle\Entity\Workspace\Workspace');
- $workspaceB = $this->mock('Claroline\CoreBundle\Entity\Workspace\Workspace');
- $workspaces = array($workspaceA, $workspaceB);
- $groupA = $this->mock('Claroline\CoreBundle\Entity\Group');
- $groupB = $this->mock('Claroline\CoreBundle\Entity\Group');
- $groups = array($groupA, $groupB);
- $roleA = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleB = $this->mock('Claroline\CoreBundle\Entity\Role');
- $msgA = '"groupA" has been suscribed with role "roleTrad"';
- $msgB = '"groupB" has been suscribed with role "roleTrad"';
- $msg = $msgA . '-;-' . $msgB . '-;-';
-
- $this->roleManager
- ->shouldReceive('getRoleByTranslationKeyAndWorkspace')
- ->with('role', $workspaceA)
- ->once()
- ->andReturn($roleA);
- $this->roleManager
- ->shouldReceive('associateRoleToMultipleSubjects')
- ->with($groups, $roleA)
- ->once();
- $this->roleManager
- ->shouldReceive('getRoleByTranslationKeyAndWorkspace')
- ->with('role', $workspaceB)
- ->once()
- ->andReturn($roleB);
- $this->roleManager
- ->shouldReceive('associateRoleToMultipleSubjects')
- ->with($groups, $roleB)
- ->once();
- $groupA->shouldReceive('getName')
- ->once()
- ->andReturn('groupA');
- $groupB->shouldReceive('getName')
- ->once()
- ->andReturn('groupB');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'has_been_suscribed_with_role_group',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('has been suscribed with role');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'role',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('roleTrad');
-
- $response = new Response($msg, 200);
- $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
- $this->assertEquals(
- $response->getContent(),
- $this->getController()
- ->subscribeMultipleGroupsToMultipleWorkspacesAction(
- 'role',
- $workspaces,
- $groups
- )->getContent()
- );
- }
-
- public function testSubscribeMultipleUsersToOneWorkspaceAction()
- {
- $roleA = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleB = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roles = array($roleA, $roleB);
- $userA = $this->mock('Claroline\CoreBundle\Entity\User');
- $userB = $this->mock('Claroline\CoreBundle\Entity\User');
- $users = array($userA, $userB);
- $msgAA = 'firstA lastA has been suscribed with role "roleATrad"';
- $msgAB = 'firstA lastA has been suscribed with role "roleBTrad"';
- $msgBA = 'firstB lastB has been suscribed with role "roleATrad"';
- $msgBB = 'firstB lastB has been suscribed with role "roleBTrad"';
- $msg = $msgAA . '-;-' . $msgAB . '-;-' . $msgBA . '-;-' . $msgBB . '-;-';
-
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($userA, $roleA)
- ->once();
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($userA, $roleB)
- ->once();
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($userB, $roleA)
- ->once();
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($userB, $roleB)
- ->once();
-
- $userA->shouldReceive('getFirstName')
- ->times(2)
- ->andReturn('firstA');
- $userA->shouldReceive('getLastName')
- ->times(2)
- ->andReturn('lastA');
- $userB->shouldReceive('getFirstName')
- ->times(2)
- ->andReturn('firstB');
- $userB->shouldReceive('getLastName')
- ->times(2)
- ->andReturn('lastB');
- $roleA->shouldReceive('getTranslationKey')
- ->times(2)
- ->andReturn('roleA');
- $roleB->shouldReceive('getTranslationKey')
- ->times(2)
- ->andReturn('roleB');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'has_been_suscribed_with_role',
- array(),
- 'platform'
- )
- ->times(4)
- ->andReturn('has been suscribed with role');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'roleA',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('roleATrad');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'roleB',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('roleBTrad');
-
- $response = new Response($msg, 200);
- $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
- $this->assertEquals(
- $response->getContent(),
- $this->getController()->subscribeMultipleUsersToOneWorkspaceAction(
- $roles,
- $users
- )->getContent()
- );
- }
-
- public function testSubscribeMultipleGroupsToOneWorkspaceAction()
- {
- $roleA = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleB = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roles = array($roleA, $roleB);
- $groupA = $this->mock('Claroline\CoreBundle\Entity\Group');
- $groupB = $this->mock('Claroline\CoreBundle\Entity\Group');
- $groups = array($groupA, $groupB);
- $msgAA = '"groupA" has been suscribed with role "roleATrad"';
- $msgAB = '"groupA" has been suscribed with role "roleBTrad"';
- $msgBA = '"groupB" has been suscribed with role "roleATrad"';
- $msgBB = '"groupB" has been suscribed with role "roleBTrad"';
- $msg = $msgAA . '-;-' . $msgAB . '-;-' . $msgBA . '-;-' . $msgBB . '-;-';
-
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($groupA, $roleA)
- ->once();
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($groupA, $roleB)
- ->once();
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($groupB, $roleA)
- ->once();
- $this->roleManager
- ->shouldReceive('associateRole')
- ->with($groupB, $roleB)
- ->once();
-
- $groupA->shouldReceive('getName')
- ->times(2)
- ->andReturn('groupA');
- $groupB->shouldReceive('getName')
- ->times(2)
- ->andReturn('groupB');
- $roleA->shouldReceive('getTranslationKey')
- ->times(2)
- ->andReturn('roleA');
- $roleB->shouldReceive('getTranslationKey')
- ->times(2)
- ->andReturn('roleB');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'has_been_suscribed_with_role_group',
- array(),
- 'platform'
- )
- ->times(4)
- ->andReturn('has been suscribed with role');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'roleA',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('roleATrad');
- $this->translator
- ->shouldReceive('trans')
- ->with(
- 'roleB',
- array(),
- 'platform'
- )
- ->times(2)
- ->andReturn('roleBTrad');
-
- $response = new Response($msg, 200);
- $this->assertEquals(
- $response->getContent(),
- $this->getController()->subscribeMultipleGroupsToOneWorkspaceAction(
- $roles,
- $groups
- )->getContent()
- );
- $this->assertInstanceOf(
- 'Symfony\Component\HttpFoundation\Response',
- $this->getController()->subscribeMultipleGroupsToOneWorkspaceAction(
- $roles,
- $groups
- )
- );
- }
-
- private function getController(array $mockedMethods = array())
- {
- if (count($mockedMethods) === 0) {
- return new AdministrationController(
- $this->userManager,
- $this->roleManager,
- $this->groupManager,
- $this->workspaceManager,
- $this->workspaceTagManager,
- $this->security,
- $this->eventDispatcher,
- $this->configHandler,
- $this->formFactory,
- $this->analyticsManager,
- $this->translator,
- $this->request,
- $this->mailManager,
- $this->localeManager,
- $this->router
- );
- }
-
- $stringMocked = '[';
- $stringMocked .= array_pop($mockedMethods);
-
- foreach ($mockedMethods as $mockedMethod) {
- $stringMocked .= ",{$mockedMethod}";
- }
-
- $stringMocked .= ']';
-
- return $this->mock(
- 'Claroline\CoreBundle\Controller\AdministrationController' . $stringMocked,
- array(
- $this->userManager,
- $this->roleManager,
- $this->groupManager,
- $this->workspaceManager,
- $this->workspaceTagManager,
- $this->security,
- $this->eventDispatcher,
- $this->configHandler,
- $this->formFactory,
- $this->analyticsManager,
- $this->translator,
- $this->request,
- $this->mailManager,
- $this->localeManager,
- $this->router
- )
- );
- }
-}
diff --git a/Tests/Unit/Manager/UserManagerTest.php b/Tests/Unit/Manager/UserManagerTest.php
index b8536d541..d13edd594 100644
--- a/Tests/Unit/Manager/UserManagerTest.php
+++ b/Tests/Unit/Manager/UserManagerTest.php
@@ -327,24 +327,6 @@ public function testGetUsersByName()
$this->assertEquals('pager', $this->getManager()->getUsersByName('search', 1));
}
- public function testGetUsersByGroup()
- {
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $em = $this->mock('Doctrine\ORM\EntityManager');
- $query = new \Doctrine\ORM\Query($em);
-
- $this->userRepo->shouldReceive('findByGroup')
- ->with($group, false, 'id')
- ->once()
- ->andReturn($query);
- $this->pagerFactory->shouldReceive('createPager')
- ->with($query, 1, 20)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals('pager', $this->getManager()->getUsersByGroup($group, 1));
- }
-
public function testGetUsersByNameAndGroup()
{
$group = $this->mock('Claroline\CoreBundle\Entity\Group');
@@ -362,43 +344,7 @@ public function testGetUsersByNameAndGroup()
$this->assertEquals('pager', $this->getManager()->getUsersByNameAndGroup('search', $group, 1));
}
-
- public function testGetGroupOutsiders()
- {
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $em = $this->mock('Doctrine\ORM\EntityManager');
- $query = new \Doctrine\ORM\Query($em);
-
- $this->userRepo->shouldReceive('findGroupOutsiders')
- ->with($group, false, 'id')
- ->once()
- ->andReturn($query);
- $this->pagerFactory->shouldReceive('createPager')
- ->with($query, 1, 20)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals('pager', $this->getManager()->getGroupOutsiders($group, 1));
- }
-
- public function testGetGroupOutsidersByName()
- {
- $group = $this->mock('Claroline\CoreBundle\Entity\Group');
- $em = $this->mock('Doctrine\ORM\EntityManager');
- $query = new \Doctrine\ORM\Query($em);
-
- $this->userRepo->shouldReceive('findGroupOutsidersByName')
- ->with($group, 'search', false, 'id')
- ->once()
- ->andReturn($query);
- $this->pagerFactory->shouldReceive('createPager')
- ->with($query, 1, 20)
- ->once()
- ->andReturn('pager');
-
- $this->assertEquals('pager', $this->getManager()->getGroupOutsidersByName($group, 1, 'search'));
- }
-
+
public function testGetNbUsers()
{
$this->userRepo->shouldReceive('count')
From 68db9899cda99014e4df948533c04530844faca9 Mon Sep 17 00:00:00 2001
From: Nicolas Godfraind
Date: Fri, 19 Feb 2016 13:46:31 +0100
Subject: [PATCH 25/65] Removing more useless code.
---
Controller/UserController.php | 2 +-
Manager/GroupManager.php | 93 +++----------------------
Manager/UserManager.php | 2 -
Tests/Unit/Manager/GroupManagerTest.php | 39 -----------
4 files changed, 9 insertions(+), 127 deletions(-)
diff --git a/Controller/UserController.php b/Controller/UserController.php
index 11ec910f7..06628ee83 100644
--- a/Controller/UserController.php
+++ b/Controller/UserController.php
@@ -377,7 +377,7 @@ public function filtersListForUserPickerAction(
case 'group':
if ($isAdmin) {
- $groups = $this->groupManager->getAllGroupsWithoutPager('name');
+ $groups = $this->groupManager->getAll();
} else {
$groups = $authenticatedUser->getGroups();
}
diff --git a/Manager/GroupManager.php b/Manager/GroupManager.php
index aedd4909d..624024c22 100644
--- a/Manager/GroupManager.php
+++ b/Manager/GroupManager.php
@@ -206,42 +206,6 @@ public function importUsers(Group $group, array $users)
$this->addUsersToGroup($group, $toImport);
}
- /**
- * Serialize a group array.
- *
- * @param Group[] $groups
- *
- * @return array
- */
- public function convertGroupsToArray(array $groups)
- {
- $content = array();
- $i = 0;
-
- foreach ($groups as $group) {
- $content[$i]['id'] = $group->getId();
- $content[$i]['name'] = $group->getName();
-
- $rolesString = '';
- $roles = $group->getEntityRoles();
- $rolesCount = count($roles);
- $j = 0;
-
- foreach ($roles as $role) {
- $rolesString .= "{$this->translator->trans($role->getTranslationKey(), array(), 'platform')}";
-
- if ($j < $rolesCount - 1) {
- $rolesString .= ' ,';
- }
- $j++;
- }
- $content[$i]['roles'] = $rolesString;
- $i++;
- }
-
- return $content;
- }
-
/**
* @param \Claroline\CoreBundle\Entity\Workspace\Workspace $workspace
* @param integer $page
@@ -330,6 +294,8 @@ public function getGroupsByWorkspaceAndName(Workspace $workspace, $search, $page
* @param string $orderedBy
* @param string $order
*
+ * @deprecated use api instead.
+ *
* @return \PagerFanta\PagerFanta
*/
public function getGroups($page, $max = 50, $orderedBy = 'id', $order = null)
@@ -345,6 +311,8 @@ public function getGroups($page, $max = 50, $orderedBy = 'id', $order = null)
* @param integer $max
* @param string $orderedBy
*
+ * @deprecated use api instead.
+ *
* @return \PagerFanta\PagerFanta
*/
public function getGroupsByName($search, $page, $max = 50, $orderedBy = 'id')
@@ -423,47 +391,6 @@ public function getOutsidersByWorkspaceRolesAndName(
return $this->pagerFactory->createPager($query, $page, $max);
}
- /**
- * @param integer $page
- * @param int $max
- *
- * @return \PagerFanta\PagerFanta
- */
- public function getAllGroups($page, $max = 50)
- {
- $query = $this->groupRepo->findAll(false);
-
- return $this->pagerFactory->createPager($query, $page, $max);
- }
-
- /**
- * @param integer $page
- * @param string $search
- * @param int $max
- *
- * @return \PagerFanta\PagerFanta
- */
- public function getAllGroupsBySearch($page, $search, $max = 50)
- {
- $query = $this->groupRepo->findAllGroupsBySearch($search);
-
- return $this->pagerFactory->createPagerFromArray($query, $page, $max);
- }
-
- /**
- * @param string[] $names
- *
- * @return Group[]
- */
- public function getGroupsByNames(array $names)
- {
- if (count($names) > 0) {
- return $this->groupRepo->findGroupsByNames($names);
- }
-
- return array();
- }
-
/**
* Returns users who don't have access to the model $model
*
@@ -527,17 +454,13 @@ public function getGroupByName($name, $executeQuery = true)
return $this->groupRepo->findGroupByName($name, $executeQuery);
}
- public function getAllGroupsWithoutPager(
- $orderedBy = 'id',
- $order = 'ASC',
- $executeQuery = true
- )
+ public function searchPartialList($searches, $page, $limit, $count = false)
{
- return $this->groupRepo->findAllGroups($orderedBy, $order, $executeQuery);
+ return $this->groupRepo->searchPartialList($searches, $page, $limit, $count);
}
- public function searchPartialList($searches, $page, $limit, $count = false)
+ public function getAll()
{
- return $this->groupRepo->searchPartialList($searches, $page, $limit, $count);
+ return $this->groupRepo->findAll();
}
}
diff --git a/Manager/UserManager.php b/Manager/UserManager.php
index 4affc56fe..ff0d95b4a 100644
--- a/Manager/UserManager.php
+++ b/Manager/UserManager.php
@@ -550,8 +550,6 @@ public function getAllUsers($page, $max = 20, $orderedBy = 'id', $order = null)
return $this->pagerFactory->createPager($query, $page, $max);
}
- /**
- */
public function getAll()
{
return $this->userRepo->findAll();
diff --git a/Tests/Unit/Manager/GroupManagerTest.php b/Tests/Unit/Manager/GroupManagerTest.php
index a4806864d..52a8edc40 100644
--- a/Tests/Unit/Manager/GroupManagerTest.php
+++ b/Tests/Unit/Manager/GroupManagerTest.php
@@ -156,45 +156,6 @@ public function testImportUsers()
$manager->importUsers($group, $users);
}
- public function testConvertGroupsToArray()
- {
- $groupA = $this->mock('Claroline\CoreBundle\Entity\Group');
- $groupB = $this->mock('Claroline\CoreBundle\Entity\Group');
- $roleAA = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleAB = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleBA = $this->mock('Claroline\CoreBundle\Entity\Role');
- $roleBB = $this->mock('Claroline\CoreBundle\Entity\Role');
-
- $groupA->shouldReceive('getId')->once()->andReturn(1);
- $groupA->shouldReceive('getName')->once()->andReturn('group_1');
- $groupA->shouldReceive('getEntityRoles')->once()->andReturn(array($roleAA, $roleAB));
- $roleAA->shouldReceive('getTranslationKey')->once()->andReturn('ROLE_AA');
- $this->translator->shouldReceive('trans')
- ->with('ROLE_AA', array(), 'platform')
- ->once()
- ->andReturn('ROLE_AA_TRAD');
- $roleAB->shouldReceive('getTranslationKey')->once()->andReturn('ROLE_AB');
- $this->translator->shouldReceive('trans')
- ->with('ROLE_AB', array(), 'platform')
- ->once()
- ->andReturn('ROLE_AB_TRAD');
- $groupB->shouldReceive('getId')->once()->andReturn(2);
- $groupB->shouldReceive('getName')->once()->andReturn('group_2');
- $groupB->shouldReceive('getEntityRoles')->once()->andReturn(array($roleBA, $roleBB));
- $roleBA->shouldReceive('getTranslationKey')->once()->andReturn('ROLE_BA');
- $this->translator->shouldReceive('trans')
- ->with('ROLE_BA', array(), 'platform')
- ->once()
- ->andReturn('ROLE_BA_TRAD');
- $roleBB->shouldReceive('getTranslationKey')->once()->andReturn('ROLE_BB');
- $this->translator->shouldReceive('trans')
- ->with('ROLE_BB', array(), 'platform')
- ->once()
- ->andReturn('ROLE_BB_TRAD');
-
- $this->getManager()->convertGroupsToArray(array($groupA, $groupB));
- }
-
public function testGetWorkspaceOutsiders()
{
$workspace = $this->mock('Claroline\CoreBundle\Entity\Workspace\Workspace');
From 21980d93a04bdcef02a19503d9671743b0122200 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Fri, 19 Feb 2016 11:26:17 +0100
Subject: [PATCH 26/65] Use composer higher level api (fix version-normalized
access)
---
Library/Installation/ExecutorException.php | 19 ---
Library/Installation/Operation.php | 20 +--
Library/Installation/OperationExecutor.php | 135 ++++++++--------
Library/Installation/Plugin/Installer.php | 20 +--
Library/PluginBundleInterface.php | 28 ++++
Resources/views/layout.html.twig | 2 +-
Tests/Stub/repo/not-array.json | 1 -
Tests/Stub/repo/repo-1.json | 3 +
Tests/Stub/repo/repo-2.json | 3 +
Tests/Stub/repo/repo-3.json | 4 +
.../Installation/OperationExecutorTest.php | 146 +++++++++++++-----
11 files changed, 231 insertions(+), 150 deletions(-)
delete mode 100644 Library/Installation/ExecutorException.php
create mode 100644 Library/PluginBundleInterface.php
delete mode 100644 Tests/Stub/repo/not-array.json
diff --git a/Library/Installation/ExecutorException.php b/Library/Installation/ExecutorException.php
deleted file mode 100644
index 3663e857b..000000000
--- a/Library/Installation/ExecutorException.php
+++ /dev/null
@@ -1,19 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Library\Installation;
-
-class ExecutorException extends \Exception
-{
- const REPO_NOT_FOUND = 11;
- const REPO_NOT_JSON = 12;
- const REPO_NOT_ARRAY = 13;
-}
diff --git a/Library/Installation/Operation.php b/Library/Installation/Operation.php
index b8b51d897..78d18651d 100644
--- a/Library/Installation/Operation.php
+++ b/Library/Installation/Operation.php
@@ -11,9 +11,11 @@
namespace Claroline\CoreBundle\Library\Installation;
+use Composer\Package\PackageInterface;
+
/**
* Holds the details of an install/update operation, such as the type
- * of the operation, the package name, the target version, etc.
+ * of the operation, the original package, the target version, etc.
*/
class Operation
{
@@ -26,7 +28,7 @@ class Operation
private $fromVersion;
private $toVersion;
- public function __construct($type, \stdClass $package, $bundleFqcn)
+ public function __construct($type, PackageInterface $package, $bundleFqcn)
{
if (!in_array($type, [self::INSTALL, self::UPDATE])) {
throw new \InvalidArgumentException(
@@ -44,14 +46,9 @@ public function getType()
return $this->type;
}
- public function getPackageName()
+ public function getPackage()
{
- return $this->package->name;
- }
-
- public function getPackageType()
- {
- return $this->package->type;
+ return $this->package;
}
public function getBundleFqcn()
@@ -78,9 +75,4 @@ public function getToVersion()
{
return $this->toVersion;
}
-
- public function getRawPackage()
- {
- return $this->package;
- }
}
diff --git a/Library/Installation/OperationExecutor.php b/Library/Installation/OperationExecutor.php
index 7ba74f1bc..7d3279911 100644
--- a/Library/Installation/OperationExecutor.php
+++ b/Library/Installation/OperationExecutor.php
@@ -15,6 +15,9 @@
use Claroline\BundleRecorder\Log\LoggableTrait;
use Claroline\CoreBundle\Library\Installation\Plugin\Installer;
use Claroline\InstallationBundle\Manager\InstallationManager;
+use Composer\Json\JsonFile;
+use Composer\Package\PackageInterface;
+use Composer\Repository\InstalledFilesystemRepository;
use JMS\DiExtraBundle\Annotation as DI;
use Psr\Log\LoggerInterface;
use Symfony\Component\Filesystem\Filesystem;
@@ -105,22 +108,30 @@ public function buildOperationList()
$target = $this->openRepository($this->installedRepoFile);
$operations = [];
- foreach ($target as $targetName => $targetPackage) {
- if (!isset($current[$targetName])) {
- $this->log(" - Installation of {$targetName} required");
+ /** @var PackageInterface $targetPackage */
+ foreach ($target->getCanonicalPackages() as $targetPackage) {
+ if (!($currentPackage = $current->findPackage($targetPackage->getName(), '*'))) {
+ $this->log(" - Installation of {$targetPackage->getName()} required");
$operation = $this->buildOperation(Operation::INSTALL, $targetPackage);
$operations[$operation->getBundleFqcn()] = $operation;
- } elseif ($targetPackage->{'version-normalized'}
- !== $current[$targetName]->{'version-normalized'}) {
- $this->log(" - Update of {$targetName} required");
- $operation =$this->buildOperation(Operation::UPDATE, $targetPackage);
- $operation->setFromVersion($current[$targetName]->{'version-normalized'});
- $operation->setToVersion($targetPackage->{'version-normalized'});
+ } elseif ($targetPackage->getVersion() !== $currentPackage->getVersion()
+ || $targetPackage->isDev()) {
+ $this->log(" - Update of {$targetPackage->getName()} required");
+ $operation = $this->buildOperation(Operation::UPDATE, $targetPackage);
+ $operation->setFromVersion($currentPackage->getVersion());
+ $operation->setToVersion($targetPackage->getVersion());
$operations[$operation->getBundleFqcn()] = $operation;
}
}
- $this->log("Sorting operations...");
+ // TODO: we *should* do something in case a platform package is
+ // removed (e.g. if the package is a plugin, at least unregister it)
+ // but AFAIK we don't have anything now to support removal of a bundle
+ // whose sources are already gone. Maybe the platform installer could
+ // look after each update if there are records in the plugin table
+ // that don't match any known bundle?
+
+ $this->log('Sorting operations...');
$bundles = $this->kernel->getBundles();
$sortedOperations = [];
@@ -140,91 +151,94 @@ public function buildOperationList()
/**
* Executes a list of install/update operations. Each successful operation
* is followed by an update of the previous local repository, so that the
- * process can be resumed after an error (e.g. an error) without triggering
- * again already executed operations. When there's no more operation to
- * execute, the snapshot of the previous local repository is deleted.
+ * process can be resumed after an interruption (e.g. due to an error)
+ * without triggering again already executed operations. When there's no
+ * more operation to execute, the snapshot of the previous local repository
+ * is deleted.
*
* @param Operation[] $operations
- * @throws ExecutorException if the the previous repository file is not writable
+ * @throws \RuntimeException if the the previous repository file is not writable
*/
public function execute(array $operations)
{
- $this->log("Executing install/update operations...");
+ $this->log('Executing install/update operations...');
$previousRepo = $this->openRepository($this->previousRepoFile, false);
if (!is_writable($this->previousRepoFile)) {
- throw new ExecutorException("'{$this->previousRepoFile}' must be writable");
+ throw new \RuntimeException(
+ "'{$this->previousRepoFile}' must be writable",
+ 456 // this code is there for unit testing only
+ );
}
$bundles = $this->getBundlesByFqcn();
foreach ($operations as $operation) {
- $installer = $operation->getPackageType() === 'claroline-core' ?
+ $installer = $operation->getPackage()->getType() === 'claroline-core' ?
$this->baseInstaller :
$this->pluginInstaller;
if ($operation->getType() === Operation::INSTALL) {
$installer->install($bundles[$operation->getBundleFqcn()]);
- $this->updatePreviousRepo($previousRepo, $operation->getRawPackage(), true);
+ $previousRepo->addPackage($operation->getPackage());
} elseif ($operation->getType() === Operation::UPDATE) {
$installer->update(
$bundles[$operation->getBundleFqcn()],
$operation->getFromVersion(),
$operation->getToVersion()
);
- $this->updatePreviousRepo($previousRepo, $operation->getRawPackage());
+ // there's no cleaner way to update the version of a package...
+ $version = new \ReflectionProperty('Composer\Package\Package', 'version');
+ $version->setAccessible(true);
+ $version->setValue($operation->getPackage(), $operation->getToVersion());
}
+
+ $previousRepo->write();
}
- $this->log("Removing previous local repository snapshot...");
+ $this->log('Removing previous local repository snapshot...');
$filesystem = new Filesystem();
$filesystem->remove($this->previousRepoFile);
}
+ /**
+ * @param string $repoFile
+ * @param bool $filter
+ * @return InstalledFilesystemRepository
+ */
private function openRepository($repoFile, $filter = true)
{
- if (!file_exists($repoFile)) {
- throw new ExecutorException(
- "Repository file '{$repoFile}' doesn't exist",
- ExecutorException::REPO_NOT_FOUND
- );
- }
-
- $repo = json_decode(file_get_contents($repoFile));
-
- if (json_last_error() !== JSON_ERROR_NONE) {
- throw new ExecutorException(
- "Repository file '{$repoFile}' isn't valid JSON",
- ExecutorException::REPO_NOT_JSON
- );
- }
+ $json = new JsonFile($repoFile);
- if (!is_array($repo)) {
- throw new ExecutorException(
- "Repository file '{$repoFile}' doesn't contain an array of packages",
- ExecutorException::REPO_NOT_ARRAY
+ if (!$json->exists()) {
+ throw new \RuntimeException(
+ "Repository file '{$repoFile}' doesn't exist",
+ 123 // this code is there for unit testing only
);
}
- $packages = !$filter ? $repo : array_filter($repo, function ($package) {
- return $package->type === 'claroline-core' || $package->type === 'claroline-plugin';
- });
+ $repo = new InstalledFilesystemRepository($json);
- $packagesByName = [];
-
- foreach ($packages as $package) {
- $packagesByName[$package->name] = $package;
+ if ($filter) {
+ foreach ($repo->getCanonicalPackages() as $package) {
+ if ($package->getType() !== 'claroline-core'
+ && $package->getType() !== 'claroline-plugin') {
+ $repo->removePackage($package);
+ }
+ }
}
- return $packagesByName;
+ return $repo;
}
- private function buildOperation($type, \stdClass $package)
+ private function buildOperation($type, PackageInterface $package)
{
$vendorDir = $this->kernel->getRootDir() . '/../vendor';
- $targetDir = property_exists($package, 'targetDir') ? $package->targetDir : '';
- $packageDir = empty($targetDir) ? $package->name : "{$targetDir}/{$package->name}";
+ $targetDir = $package->getTargetDir() ?: '';
+ $packageDir = empty($targetDir) ?
+ $package->getPrettyName() :
+ "{$targetDir}/{$package->getName()}";
$fqcn = $this->detector->detectBundle("{$vendorDir}/{$packageDir}");
return new Operation($type, $package, $fqcn);
@@ -235,25 +249,12 @@ private function getBundlesByFqcn()
$byFqcn = array();
foreach ($this->kernel->getBundles() as $bundle) {
- $byFqcn[get_class($bundle)] = $bundle;
+ $fqcn = $bundle->getNamespace() ?
+ $bundle->getNamespace() . '\\' . $bundle->getName() :
+ $bundle->getName();
+ $byFqcn[$fqcn] = $bundle;
}
return $byFqcn;
}
-
- private function updatePreviousRepo(array $repo, \stdClass $package, $add = true)
- {
- if ($add) {
- $repo[] = $package;
- } else {
- foreach ($repo as $index => $previousPackage) {
- if ($previousPackage->name === $package->name) {
- $repo[$index] = $package;
- }
- }
- }
-
- $options = JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE;
- file_put_contents($this->previousRepoFile, json_encode($repo, $options));
- }
}
diff --git a/Library/Installation/Plugin/Installer.php b/Library/Installation/Plugin/Installer.php
index b6c436cbe..083463ba2 100644
--- a/Library/Installation/Plugin/Installer.php
+++ b/Library/Installation/Plugin/Installer.php
@@ -12,7 +12,7 @@
namespace Claroline\CoreBundle\Library\Installation\Plugin;
use Claroline\BundleRecorder\Log\LoggableTrait;
-use Claroline\CoreBundle\Library\PluginBundle;
+use Claroline\CoreBundle\Library\PluginBundleInterface;
use Claroline\CoreBundle\Persistence\ObjectManager;
use Claroline\InstallationBundle\Manager\InstallationManager;
use JMS\DiExtraBundle\Annotation as DI;
@@ -73,13 +73,13 @@ public function setLogger(LoggerInterface $logger)
/**
* Installs a plugin.
*
- * PluginBundle $plugin
+ * PluginBundleInterface $plugin
*
- * @param PluginBundle $plugin
+ * @param PluginBundleInterface $plugin
*
* @throws \Exception if the plugin doesn't pass the validation
*/
- public function install(PluginBundle $plugin)
+ public function install(PluginBundleInterface $plugin)
{
$this->checkInstallationStatus($plugin, false);
$this->validatePlugin($plugin);
@@ -91,9 +91,9 @@ public function install(PluginBundle $plugin)
/**
* Uninstalls a plugin.
*
- * @param PluginBundle $plugin
+ * @param PluginBundleInterface $plugin
*/
- public function uninstall(PluginBundle $plugin)
+ public function uninstall(PluginBundleInterface $plugin)
{
$this->checkInstallationStatus($plugin, true);
$this->log('Removing plugin configuration...');
@@ -104,11 +104,11 @@ public function uninstall(PluginBundle $plugin)
/**
* Upgrades/downgrades a plugin to a specific version.
*
- * @param PluginBundle $plugin
+ * @param PluginBundleInterface $plugin
* @param string $currentVersion
* @param string $targetVersion
*/
- public function update(PluginBundle $plugin, $currentVersion, $targetVersion)
+ public function update(PluginBundleInterface $plugin, $currentVersion, $targetVersion)
{
$this->checkInstallationStatus($plugin, true);
$this->validator->activeUpdateMode();
@@ -119,7 +119,7 @@ public function update(PluginBundle $plugin, $currentVersion, $targetVersion)
$this->recorder->update($plugin, $this->validator->getPluginConfiguration());
}
- private function checkInstallationStatus(PluginBundle $plugin, $shouldBeInstalled = true)
+ private function checkInstallationStatus(PluginBundleInterface $plugin, $shouldBeInstalled = true)
{
$this->log(sprintf('Checking installation status for plugin %s ', $plugin->getName()));
@@ -132,7 +132,7 @@ private function checkInstallationStatus(PluginBundle $plugin, $shouldBeInstalle
}
}
- private function validatePlugin(PluginBundle $plugin)
+ private function validatePlugin(PluginBundleInterface $plugin)
{
$this->log('Validating plugin...');
$errors = $this->validator->validate($plugin);
diff --git a/Library/PluginBundleInterface.php b/Library/PluginBundleInterface.php
new file mode 100644
index 000000000..64fc6eb7e
--- /dev/null
+++ b/Library/PluginBundleInterface.php
@@ -0,0 +1,28 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library;
+
+use Claroline\InstallationBundle\Bundle\InstallableInterface;
+use Claroline\KernelBundle\Bundle\AutoConfigurableInterface;
+use Symfony\Component\HttpKernel\Bundle\BundleInterface;
+
+/**
+ * Interface of all the plugin bundles on the claroline platform.
+ */
+interface PluginBundleInterface extends BundleInterface, AutoConfigurableInterface, InstallableInterface
+{
+ function getVendorName();
+ function getBundleName();
+ function getConfigFile();
+ function getImgFolder();
+ function getAssetsFolder();
+}
diff --git a/Resources/views/layout.html.twig b/Resources/views/layout.html.twig
index 39f912287..5d7a4d083 100644
--- a/Resources/views/layout.html.twig
+++ b/Resources/views/layout.html.twig
@@ -135,4 +135,4 @@
{% block javascripts %}
{% include 'ClarolineCoreBundle:Layout:javascripts.html.twig' %}
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/Tests/Stub/repo/not-array.json b/Tests/Stub/repo/not-array.json
deleted file mode 100644
index 0967ef424..000000000
--- a/Tests/Stub/repo/not-array.json
+++ /dev/null
@@ -1 +0,0 @@
-{}
diff --git a/Tests/Stub/repo/repo-1.json b/Tests/Stub/repo/repo-1.json
index 8b536a3cb..8f9851c59 100644
--- a/Tests/Stub/repo/repo-1.json
+++ b/Tests/Stub/repo/repo-1.json
@@ -2,16 +2,19 @@
{
"name": "foo",
"type": "claroline-core",
+ "version": "1.0.0",
"version-normalized": "1.0.0.0"
},
{
"name": "bar",
"type": "claroline-plugin",
+ "version": "2.0.0",
"version-normalized": "2.0.0.0"
},
{
"name": "baz",
"type": "extraneous",
+ "version": "0.0.1",
"version-normalized": "0.0.1.0"
}
]
diff --git a/Tests/Stub/repo/repo-2.json b/Tests/Stub/repo/repo-2.json
index c1f69007f..1352a19d9 100644
--- a/Tests/Stub/repo/repo-2.json
+++ b/Tests/Stub/repo/repo-2.json
@@ -2,16 +2,19 @@
{
"name": "foo",
"type": "claroline-core",
+ "version": "2.0.0",
"version-normalized": "2.0.0.0"
},
{
"name": "bar",
"type": "claroline-plugin",
+ "version": "2.0.0",
"version-normalized": "2.0.0.0"
},
{
"name": "baz",
"type": "extraneous",
+ "version": "0.0.1",
"version-normalized": "0.0.1.0"
}
]
diff --git a/Tests/Stub/repo/repo-3.json b/Tests/Stub/repo/repo-3.json
index c79783ed3..f76fd254f 100644
--- a/Tests/Stub/repo/repo-3.json
+++ b/Tests/Stub/repo/repo-3.json
@@ -2,21 +2,25 @@
{
"name": "quz",
"type": "claroline-plugin",
+ "version": "4.2.3",
"version-normalized": "4.2.3.0"
},
{
"name": "foo",
"type": "claroline-core",
+ "version": "1.2.0",
"version-normalized": "1.2.0.0"
},
{
"name": "bar",
"type": "claroline-plugin",
+ "version": "2.0.0",
"version-normalized": "2.0.0.0"
},
{
"name": "baz",
"type": "extraneous",
+ "version": "0.0.1",
"version-normalized": "0.0.1.0"
}
]
diff --git a/Tests/Unit/Library/Installation/OperationExecutorTest.php b/Tests/Unit/Library/Installation/OperationExecutorTest.php
index 29b4a9b3a..8a6cd5cd7 100644
--- a/Tests/Unit/Library/Installation/OperationExecutorTest.php
+++ b/Tests/Unit/Library/Installation/OperationExecutorTest.php
@@ -1,4 +1,5 @@
kernel = $this->mock('Symfony\Component\HttpKernel\KernelInterface');
- $installManager = $this->mock('Claroline\InstallationBundle\Manager\InstallationManager');
- $pluginInstaller = $this->mock('Claroline\CoreBundle\Library\Installation\Plugin\Installer');
+ $this->baseInstaller = $this->mock('Claroline\InstallationBundle\Manager\InstallationManager');
+ $this->pluginInstaller = $this->mock('Claroline\CoreBundle\Library\Installation\Plugin\Installer');
$this->detector = $this->mock('Claroline\BundleRecorder\Detector\Detector');
- $this->executor = new OperationExecutor($this->kernel, $installManager, $pluginInstaller);
+ $this->executor = new OperationExecutor($this->kernel, $this->baseInstaller, $this->pluginInstaller);
$this->executor->setBundleDetector($this->detector);
// always build a fake fqcn based on the given path
@@ -41,8 +49,8 @@ protected function setUp()
/**
* @dataProvider missingRepoProvider
- * @expectedException \Claroline\CoreBundle\Library\Installation\ExecutorException
- * @expectedExceptionCode 11
+ * @expectedException \RuntimeException
+ * @expectedExceptionCode 123
*/
public function testBuildOperationListThrowsIfRepoIsMissing($previous, $installed)
{
@@ -52,8 +60,7 @@ public function testBuildOperationListThrowsIfRepoIsMissing($previous, $installe
/**
* @dataProvider notJsonRepoProvider
- * @expectedException \Claroline\CoreBundle\Library\Installation\ExecutorException
- * @expectedExceptionCode 12
+ * @expectedException \Composer\Repository\InvalidRepositoryException
*/
public function testBuildOperationListExecutorThrowsIfRepoIsNotJson($previous, $installed)
{
@@ -61,17 +68,6 @@ public function testBuildOperationListExecutorThrowsIfRepoIsNotJson($previous, $
$this->executor->buildOperationList();
}
- /**
- * @dataProvider notArrayRepoProvider
- * @expectedException \Claroline\CoreBundle\Library\Installation\ExecutorException
- * @expectedExceptionCode 13
- */
- public function testOperationListThrowsIfRepoIsNotArray($previous, $installed)
- {
- $this->executor->setRepositoryFiles($previous, $installed);
- $this->executor->buildOperationList();
- }
-
public function testBuildOperationListInstallOnly()
{
$this->executor->setRepositoryFiles($this->repo('empty'), $this->repo('repo-1'));
@@ -82,13 +78,13 @@ public function testBuildOperationListInstallOnly()
$operations = $this->executor->buildOperationList();
$this->assertEquals(2, count($operations));
- $this->assertEquals($operations[0]->getPackageName(), 'foo');
+ $this->assertEquals($operations[0]->getPackage()->getName(), 'foo');
$this->assertEquals($operations[0]->getBundleFqcn(), 'Foo');
- $this->assertEquals($operations[0]->getPackageType(), 'claroline-core');
+ $this->assertEquals($operations[0]->getPackage()->getType(), 'claroline-core');
$this->assertEquals($operations[0]->getType(), Operation::INSTALL);
- $this->assertEquals($operations[1]->getPackageName(), 'bar');
+ $this->assertEquals($operations[1]->getPackage()->getName(), 'bar');
$this->assertEquals($operations[1]->getBundleFqcn(), 'Bar');
- $this->assertEquals($operations[1]->getPackageType(), 'claroline-plugin');
+ $this->assertEquals($operations[1]->getPackage()->getType(), 'claroline-plugin');
$this->assertEquals($operations[1]->getType(), Operation::INSTALL);
}
@@ -101,9 +97,9 @@ public function testBuildOperationListUpdateOnly()
$operations = $this->executor->buildOperationList();
$this->assertEquals(1, count($operations));
- $this->assertEquals($operations[0]->getPackageName(), 'foo');
+ $this->assertEquals($operations[0]->getPackage()->getName(), 'foo');
$this->assertEquals($operations[0]->getBundleFqcn(), 'Foo');
- $this->assertEquals($operations[0]->getPackageType(), 'claroline-core');
+ $this->assertEquals($operations[0]->getPackage()->getType(), 'claroline-core');
$this->assertEquals($operations[0]->getType(), Operation::UPDATE);
$this->assertEquals($operations[0]->getFromVersion(), '1.0.0.0');
$this->assertEquals($operations[0]->getToVersion(), '2.0.0.0');
@@ -119,18 +115,90 @@ public function testBuildOperationsMixedAndSorted()
]);
$operations = $this->executor->buildOperationList();
$this->assertEquals(2, count($operations));
- $this->assertEquals($operations[0]->getPackageName(), 'foo');
+ $this->assertEquals($operations[0]->getPackage()->getName(), 'foo');
$this->assertEquals($operations[0]->getBundleFqcn(), 'Foo');
- $this->assertEquals($operations[0]->getPackageType(), 'claroline-core');
+ $this->assertEquals($operations[0]->getPackage()->getType(), 'claroline-core');
$this->assertEquals($operations[0]->getType(), Operation::UPDATE);
$this->assertEquals($operations[0]->getFromVersion(), '1.0.0.0');
$this->assertEquals($operations[0]->getToVersion(), '1.2.0.0');
- $this->assertEquals($operations[1]->getPackageName(), 'quz');
+ $this->assertEquals($operations[1]->getPackage()->getName(), 'quz');
$this->assertEquals($operations[1]->getBundleFqcn(), 'Quz');
- $this->assertEquals($operations[1]->getPackageType(), 'claroline-plugin');
+ $this->assertEquals($operations[1]->getPackage()->getType(), 'claroline-plugin');
$this->assertEquals($operations[1]->getType(), Operation::INSTALL);
}
+ /**
+ * @expectedException \RuntimeException
+ * @expectedExceptionCode 123
+ */
+ public function testExecuteThrowsIfPreviousRepoDoesNotExist()
+ {
+ $this->executor->setRepositoryFiles('/does/not/exist', '/either');
+ $this->executor->execute([]);
+ }
+
+ /**
+ * @expectedException \RuntimeException
+ * @expectedExceptionCode 456
+ */
+ public function testExecuteThrowsIfPreviousRepoIsNotWritable()
+ {
+ vfsStream::setup('root');
+ $previous = vfsStream::url('root/previous-installed.json');
+ file_put_contents($previous, '[]');
+ chmod($previous, 0444);
+ $this->executor->setRepositoryFiles($previous, '/does/not/exist');
+ $this->executor->execute([]);
+ }
+
+ public function testExecuteRemovesPreviousRepoWhenNoOperationRemain()
+ {
+ vfsStream::setup('root');
+ $previous = vfsStream::url('root/previous-installed.json');
+ file_put_contents($previous, '[]');
+ $this->executor->setRepositoryFiles($previous, '/does/not/exist');
+
+ $this->kernel->expects($this->once())->method('getBundles')->willReturn([]);
+
+ $this->executor->execute([]);
+
+ $this->assertFalse(file_exists($previous));
+ }
+
+ public function testExecuteCallsInstallersAndUpdatePreviousRepo()
+ {
+ vfsStream::setup('root');
+ $previous = vfsStream::url('root/previous-installed.json');
+ file_put_contents($previous, file_get_contents($this->repo('repo-1')));
+ $this->executor->setRepositoryFiles($previous, '/does/not/exist');
+
+ $this->kernel->expects($this->once())->method('getBundles')->willReturn([
+ $this->mockBundle('Foo'),
+ $this->mockBundle('Quz', true),
+ $this->mockBundle('Bar', true)
+ ]);
+
+ $this->baseInstaller->expects($this->once())
+ ->method('install')
+ ->will($this->throwException(new \Exception('from test')));
+
+ $installOp1 = new Operation(Operation::INSTALL, $this->package('quz', '3.4.1.2', 'claroline-plugin'), 'Quz');
+ $updateOp = new Operation(Operation::UPDATE, $this->package('bar', '2.0.0.0', 'claroline-plugin'), 'Bar');
+ $updateOp->setFromVersion('2.0.0.0');
+ $updateOp->setToVersion('3.0.0.0');
+ $installOp2 = new Operation(Operation::INSTALL, $this->package('foo', '5.2.3.1', 'claroline-core'), 'Foo');
+
+ try {
+ $this->executor->execute([$installOp1, $updateOp, $installOp2]);
+ $this->fail('An exception should have been thrown');
+ } catch (\Exception $ex) {
+ $this->assertTrue(file_exists($previous));
+ $repo = new InstalledFilesystemRepository(new JsonFile($previous));
+ $this->assertNotNull($repo->findPackage('quz', '3.4.1.2'));
+ $this->assertNotNull($repo->findPackage('bar', '2.0.0.0'));
+ }
+ }
+
public function missingRepoProvider()
{
return $this->buildRepoPaths([
@@ -147,14 +215,6 @@ public function notJsonRepoProvider()
]);
}
- public function notArrayRepoProvider()
- {
- return $this->buildRepoPaths([
- ['empty', 'not-array'],
- ['not-array', 'empty']
- ]);
- }
-
private function mock($class)
{
return $this->getMockBuilder($class)
@@ -176,13 +236,23 @@ private function repo($name)
return __DIR__ . '/../../../Stub/repo/' . $name . '.json';
}
- private function mockBundle($fqcn)
+ private function mockBundle($fqcn, $plugin = false)
{
- $bundle = $this->mock('Symfony\Component\HttpKernel\Bundle\BundleInterface');
+ $class = $plugin ?
+ 'Claroline\CoreBundle\Library\PluginBundleInterface' :
+ 'Claroline\InstallationBundle\Bundle\InstallableInterface';
+ $bundle = $this->mock($class);
$bundle->expects($this->any())->method('getNamespace')->willReturn('');
$bundle->expects($this->any())->method('getName')->willReturn($fqcn);
return $bundle;
}
+ private function package($name, $version, $type)
+ {
+ $package = new Package($name, $version, 'not-important');
+ $package->setType($type);
+
+ return $package;
+ }
}
From b532e405efd0e2d248953bd95e78ad97cbec0083 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Fri, 19 Feb 2016 18:09:03 +0100
Subject: [PATCH 27/65] Remove every package instance when filtering repo + add
missing interface
---
Library/Installation/OperationExecutor.php | 33 +++++++++++++---------
Library/PluginBundle.php | 2 +-
2 files changed, 20 insertions(+), 15 deletions(-)
diff --git a/Library/Installation/OperationExecutor.php b/Library/Installation/OperationExecutor.php
index 7d3279911..5c3227110 100644
--- a/Library/Installation/OperationExecutor.php
+++ b/Library/Installation/OperationExecutor.php
@@ -104,22 +104,27 @@ public function buildOperationList()
{
$this->log('Building install/update operations list...');
- $current = $this->openRepository($this->previousRepoFile);
- $target = $this->openRepository($this->installedRepoFile);
+ $previous = $this->openRepository($this->previousRepoFile);
+ $current = $this->openRepository($this->installedRepoFile);
$operations = [];
- /** @var PackageInterface $targetPackage */
- foreach ($target->getCanonicalPackages() as $targetPackage) {
- if (!($currentPackage = $current->findPackage($targetPackage->getName(), '*'))) {
- $this->log(" - Installation of {$targetPackage->getName()} required");
- $operation = $this->buildOperation(Operation::INSTALL, $targetPackage);
+ /** @var PackageInterface $currentPackage */
+ foreach ($current->getCanonicalPackages() as $currentPackage) {
+ if (!($previousPackage = $previous->findPackage($currentPackage->getName(), '*'))) {
+ $this->log("Installation of {$currentPackage->getName()} required");
+ $operation = $this->buildOperation(Operation::INSTALL, $currentPackage);
$operations[$operation->getBundleFqcn()] = $operation;
- } elseif ($targetPackage->getVersion() !== $currentPackage->getVersion()
- || $targetPackage->isDev()) {
- $this->log(" - Update of {$targetPackage->getName()} required");
- $operation = $this->buildOperation(Operation::UPDATE, $targetPackage);
- $operation->setFromVersion($currentPackage->getVersion());
- $operation->setToVersion($targetPackage->getVersion());
+ } elseif ($currentPackage->getVersion() !== $previousPackage->getVersion()
+ || $currentPackage->isDev()) {
+ $this->log(sprintf(
+ 'Update of %s from %s to %s required',
+ $previousPackage->getName(),
+ $previousPackage->getVersion(),
+ $currentPackage->getVersion()
+ ));
+ $operation = $this->buildOperation(Operation::UPDATE, $currentPackage);
+ $operation->setFromVersion($previousPackage->getVersion());
+ $operation->setToVersion($currentPackage->getVersion());
$operations[$operation->getBundleFqcn()] = $operation;
}
}
@@ -221,7 +226,7 @@ private function openRepository($repoFile, $filter = true)
$repo = new InstalledFilesystemRepository($json);
if ($filter) {
- foreach ($repo->getCanonicalPackages() as $package) {
+ foreach ($repo->getPackages() as $package) {
if ($package->getType() !== 'claroline-core'
&& $package->getType() !== 'claroline-plugin') {
$repo->removePackage($package);
diff --git a/Library/PluginBundle.php b/Library/PluginBundle.php
index 65da8bd71..5c1de0c24 100644
--- a/Library/PluginBundle.php
+++ b/Library/PluginBundle.php
@@ -18,7 +18,7 @@
/**
* Base class of all the plugin bundles on the claroline platform.
*/
-abstract class PluginBundle extends InstallableBundle implements AutoConfigurableInterface
+abstract class PluginBundle extends InstallableBundle implements PluginBundleInterface
{
final public function getVendorName()
{
From 0a4a76ec06e8326fd15812344a0ef4d4044d257f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Fri, 19 Feb 2016 20:11:15 +0100
Subject: [PATCH 28/65] Fix package copy + psr-0 paths
---
Library/Installation/OperationExecutor.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/Library/Installation/OperationExecutor.php b/Library/Installation/OperationExecutor.php
index 5c3227110..27d0fca63 100644
--- a/Library/Installation/OperationExecutor.php
+++ b/Library/Installation/OperationExecutor.php
@@ -186,7 +186,7 @@ public function execute(array $operations)
if ($operation->getType() === Operation::INSTALL) {
$installer->install($bundles[$operation->getBundleFqcn()]);
- $previousRepo->addPackage($operation->getPackage());
+ $previousRepo->addPackage(clone $operation->getPackage());
} elseif ($operation->getType() === Operation::UPDATE) {
$installer->update(
$bundles[$operation->getBundleFqcn()],
@@ -243,7 +243,7 @@ private function buildOperation($type, PackageInterface $package)
$targetDir = $package->getTargetDir() ?: '';
$packageDir = empty($targetDir) ?
$package->getPrettyName() :
- "{$targetDir}/{$package->getName()}";
+ "{$package->getName()}/{$targetDir}";
$fqcn = $this->detector->detectBundle("{$vendorDir}/{$packageDir}");
return new Operation($type, $package, $fqcn);
From b1f55d233081de778511d5f113a49bc8668b9012 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 22 Feb 2016 11:19:10 +0100
Subject: [PATCH 29/65] Remove package management tool
---
Controller/API/Admin/PackageController.php | 97 ----
.../Administration/PackageController.php | 266 ----------
.../Required/Data/LoadAdminToolsData.php | 1 -
Entity/Bundle.php | 203 --------
Library/Installation/AdditionalInstaller.php | 4 +-
.../Installation/Updater/Updater060704.php | 45 --
.../Installation/Updater/Updater060800.php | 69 +++
Listener/AdministrationToolListener.php | 13 -
Manager/BundleManager.php | 371 --------------
Manager/DependencyManager.php | 473 ------------------
Resources/config/parameters.yml | 1 -
Resources/config/routing.yml | 13 -
.../public/js/administration/packages.js | 100 ----
Resources/translations/platform.de.yml | 12 -
Resources/translations/platform.en.yml | 14 +-
Resources/translations/platform.es.yml | 12 -
Resources/translations/platform.fr.yml | 16 +-
Resources/translations/platform.nl.yml | 12 -
Resources/translations/tools.de.yml | 1 -
Resources/translations/tools.en.yml | 1 -
Resources/translations/tools.es.yml | 1 -
Resources/translations/tools.fr.yml | 3 +-
Resources/translations/tools.nl.yml | 1 -
.../Administration/Package/list.html.twig | 177 -------
.../Administration/Package/logs.html.twig | 11 -
.../Package/refresher.html.twig | 11 -
Resources/views/Layout/javascripts.html.twig | 2 -
Resources/views/macros.html.twig | 146 ------
Twig/PackageExtension.php | 173 -------
29 files changed, 75 insertions(+), 2174 deletions(-)
delete mode 100644 Controller/API/Admin/PackageController.php
delete mode 100644 Controller/Administration/PackageController.php
delete mode 100644 Entity/Bundle.php
delete mode 100644 Library/Installation/Updater/Updater060704.php
create mode 100644 Library/Installation/Updater/Updater060800.php
delete mode 100644 Manager/BundleManager.php
delete mode 100644 Manager/DependencyManager.php
delete mode 100644 Resources/public/js/administration/packages.js
delete mode 100644 Resources/views/Administration/Package/list.html.twig
delete mode 100644 Resources/views/Administration/Package/logs.html.twig
delete mode 100644 Resources/views/Administration/Package/refresher.html.twig
delete mode 100644 Twig/PackageExtension.php
diff --git a/Controller/API/Admin/PackageController.php b/Controller/API/Admin/PackageController.php
deleted file mode 100644
index 4874cab8b..000000000
--- a/Controller/API/Admin/PackageController.php
+++ /dev/null
@@ -1,97 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Controller\API\Admin;
-
-use JMS\DiExtraBundle\Annotation as DI;
-use Symfony\Component\HttpFoundation\Request;
-use FOS\RestBundle\Controller\FOSRestController;
-use FOS\RestBundle\Controller\Annotations\View;
-use Claroline\CoreBundle\Library\Configuration\PlatformConfigurationHandler;
-use Nelmio\ApiDocBundle\Annotation\ApiDoc;
-use Claroline\CoreBundle\Persitence\ObjectManager;
-use Claroline\CoreBundle\Manager\BundleManager;
-use FOS\RestBundle\Controller\Annotations\NamePrefix;
-
-/**
- * @NamePrefix("api_")
- */
-class PackageController extends FOSRestController
-{
- private $bundleManager;
- private $om;
- private $fileDir;
- private $ch;
-
- /**
- * @DI\InjectParams({
- * "bundleManager" = @DI\Inject("claroline.manager.bundle_manager"),
- * "ch" = @DI\Inject("claroline.config.platform_config_handler"),
- * "om" = @DI\Inject("claroline.persistence.object_manager"),
- * "fileDir" = @DI\Inject("%claroline.param.files_directory%")
- * })
- */
- public function __construct(
- BundleManager $bundleManager,
- PlatformConfigurationHandler $ch,
- $om,
- $fileDir
- )
- {
- $this->bundleManager = $bundleManager;
- $this->ch = $ch;
- $this->fileDir = $fileDir;
- $this->om = $om;
- $this->$fileDir = $fileDir;
- }
-
- /**
- * @View(serializerGroups={"api"})
- * @ApiDoc(
- * description="Returns the package list",
- * views = {"package"}
- * )
- */
- public function getPackagesAction()
- {
- return $this->bundleManager->getInstalled();
- }
-
- /**
- * @ApiDoc(
- * description="Returns the platform infos",
- * views = {"package"}
- * )
- */
- public function getInfosAction()
- {
- return array(
- 'name' => $this->ch->getParameter('name'),
- 'support_email' => $this->ch->getParameter('support_email'),
- 'storage_used' => $this->getUsedStorage(),
- 'resources_created' => $this->om->count('Claroline\CoreBundle\Entity\Resource\ResourceNode'),
- 'workspace_created' => $this->om->count('Claroline\CoreBundle\Entity\Workspace\Workspace'),
- 'users_enabled' => $this->om->getRepository('ClarolineCoreBundle:User')->countAllEnabledUsers(),
- 'users_all' => $this->om->count('Claroline\CoreBundle\Entity\User')
- );
- }
-
- private function getUsedStorage()
- {
- $size = 0;
-
- foreach(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->fileDir)) as $file){
- $size += $file->getSize();
- }
-
- return $this->get('claroline.utilities.misc')->formatFileSize($size);
- }
-}
diff --git a/Controller/Administration/PackageController.php b/Controller/Administration/PackageController.php
deleted file mode 100644
index 7b1e3350a..000000000
--- a/Controller/Administration/PackageController.php
+++ /dev/null
@@ -1,266 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Controller\Administration;
-
-use Symfony\Bundle\FrameworkBundle\Controller\Controller;
-use Claroline\CoreBundle\Event\StrictDispatcher;
-use Claroline\CoreBundle\Manager\ToolManager;
-use Claroline\CoreBundle\Manager\DependencyManager;
-use Claroline\CoreBundle\Manager\BundleManager;
-use Claroline\CoreBundle\Manager\IPWhiteListManager;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use JMS\DiExtraBundle\Annotation as DI;
-use Sensio\Bundle\FrameworkExtraBundle\Configuration as EXT;
-use JMS\SecurityExtraBundle\Annotation as SEC;
-use Symfony\Component\Security\Core\Exception\AccessDeniedException;
-use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpFoundation\RedirectResponse;
-use Symfony\Component\HttpFoundation\JsonResponse;
-use Claroline\CoreBundle\Library\Configuration\PlatformConfigurationHandler;
-use Claroline\CoreBundle\Library\Utilities\FileSystem;
-
-/**
- * @DI\Tag("security.secure_service")
- * @SEC\PreAuthorize("canOpenAdminTool('platform_packages')")
- */
-class PackageController extends Controller
-{
- private $toolManager;
- private $eventDispatcher;
- private $adminToolPlugin;
- private $ipwlm;
- private $bundleManager;
- private $platformConfigHandler;
-
- /**
- * @DI\InjectParams({
- * "eventDispatcher" = @DI\Inject("claroline.event.event_dispatcher"),
- * "toolManager" = @DI\Inject("claroline.manager.tool_manager"),
- * "dm" = @DI\Inject("claroline.manager.dependency_manager"),
- * "ipwlm" = @DI\Inject("claroline.manager.ip_white_list_manager"),
- * "bundleManager" = @DI\Inject("claroline.manager.bundle_manager"),
- * "configHandler" = @DI\Inject("claroline.config.platform_config_handler")
- * })
- */
- public function __construct(
- StrictDispatcher $eventDispatcher,
- ToolManager $toolManager,
- DependencyManager $dm,
- IPWhiteListManager $ipwlm,
- BundleManager $bundleManager,
- PlatformConfigurationHandler $configHandler
-
- )
- {
- $this->eventDispatcher = $eventDispatcher;
- $this->toolManager = $toolManager;
- $this->adminToolPlugin = $toolManager->getAdminToolByName('platform_packages');
- $this->dm = $dm;
- $this->ipwlm = $ipwlm;
- $this->bundleManager = $bundleManager;
- $this->configHandler = $configHandler;
- }
-
- /**
- * @EXT\Route(
- * "/",
- * name="claro_admin_plugins",
- * options = {"expose"=true}
- * )
- *
- * @EXT\Template()
- *
- * Display the plugin list
- *
- * @return Response
- */
- public function listAction()
- {
- $fs = new FileSystem();
- $rootPath = $this->container->getParameter('claroline.param.root_directory') . '/';
- $danger = array(
- 'simple' => array(
- realpath($rootPath . 'vendor/composer/autoload_namespaces.php') => is_writable(realpath($rootPath . 'vendor/composer/autoload_namespaces.php')),
- realpath($rootPath . 'app/config/bundles.ini') => is_writable(realpath($rootPath . 'app/config/bundles.ini')),
- realpath($rootPath . 'vendor') => is_writable(realpath($rootPath . 'vendor')),
- realpath($rootPath . 'app/logs') => is_writable(realpath($rootPath . 'app/logs')),
- realpath($rootPath . 'web/bundles') => is_writable(realpath($rootPath . 'web/bundles'))
- ),
- 'recursive' => array(
- realpath($rootPath . 'web/js') => $fs->isWritable(realpath($rootPath . 'web/js'), true),
- realpath($rootPath . 'app/cache') => $fs->isWritable(realpath($rootPath . 'app/cache'), true),
- realpath($rootPath . 'web/themes') => $fs->isWritable(realpath($rootPath . 'web/themes'), true),
- realpath($rootPath . 'web/css') => $fs->isWritable(realpath($rootPath . 'web/css'), true),
- realpath($rootPath . 'web/vendor') => $fs->isWritable(realpath($rootPath . 'web/vendor'), true)
- )
- );
-
- $refresh = array(
- 'simple' => array(
- realpath($rootPath . 'web/bundles') => is_writable(realpath($rootPath . 'web/bundles')),
- ),
- 'recursive' => array(
- realpath($rootPath . 'web/js') => $fs->isWritable(realpath($rootPath . 'web/js'), true),
- realpath($rootPath . 'web/themes') => $fs->isWritable(realpath($rootPath . 'web/themes'), true),
- realpath($rootPath . 'web/css') => $fs->isWritable(realpath($rootPath . 'web/css'), true),
- realpath($rootPath . 'web/vendor') => $fs->isWritable(realpath($rootPath . 'web/vendor'), true)
- )
- );
-
- $coreBundle = $this->bundleManager->getBundle('CoreBundle');
- $coreVersion = $coreBundle->getVersion();
- $api = $this->configHandler->getParameter('repository_api');
- $url = $api . "/version/$coreVersion/tags/last";
-
- if ($this->configHandler->getParameter('use_repository_test')) {
- $url .= '/test';
- }
- //ask the server wich are the last available packages now.
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $data = curl_exec($ch);
- curl_close($ch);
- $fetched = json_decode($data);
- $installed = $this->bundleManager->getInstalled();
- $plugins = $this->bundleManager->getConfigurablePlugins();
-
- foreach ($installed as $install) {
- foreach ($plugins as $plugin) {
- if ($plugin->getBundleName() === $install->getName()) {
- $install->setIsConfigurable(true);
- }
- }
- }
-
- $uninstalled = $this->bundleManager->getUninstalledFromServer($fetched);
-
- return array(
- 'fetched' => $fetched,
- 'installed' => $installed,
- 'uninstalled' => $uninstalled,
- 'danger' => $danger,
- 'refresh' => $refresh,
- 'useTestRepo' => $this->configHandler->getParameter('use_repository_test')
- );
- }
-
- /**
- * @EXT\Route(
- * "/bundle/{bundle}/install/log/{date}",
- * name="claro_admin_plugin_install",
- * options = {"expose"=true}
- * )
- *
- * Install a plugin.
- *
- * @return Response
- */
- public function installFromRemoteAction($bundle, $date)
- {
- $this->bundleManager->installRemoteBundle($bundle, $date);
-
- return new Response('Done.');
- }
-
- /**
- * @EXT\Route(
- * "/install/log/{date}",
- * name="claro_admin_plugins_log",
- * options = {"expose"=true}
- * )
- *
- * Install a plugin.
- *
- * @return Response
- */
- public function displayUpdateLog($date)
- {
- $content = @file_get_contents($this->bundleManager->getLogFile() . '-' . $date . '.log');
- if (!$content) $content = '';
-
- return new Response($content);
- }
-
- /**
- * @EXT\Route(
- * "/plugin/parameters/{pluginShortName}",
- * name="claro_admin_plugin_parameters"
- * )
- */
- public function pluginParametersAction($pluginShortName)
- {
- $eventName = strtolower("plugin_options_{$pluginShortName}");
- $event = $this->eventDispatcher->dispatch($eventName, 'PluginOptions', array());
-
- return $event->getResponse();
- }
-
- /**
- * @EXT\Route(
- * "/package/repository/test",
- * name="claro_admin_use_test_repository"
- * )
- */
- public function useTestPackageAction()
- {
- $this->configHandler->setParameter('use_repository_test', true);
-
- return new RedirectResponse($this->generateUrl('claro_admin_plugins'));
- }
-
- /**
- * @EXT\Route(
- * "/package/repository/stable",
- * name="claro_admin_use_stable_repository"
- * )
- */
- public function useStablePackageAction()
- {
- $this->configHandler->setParameter('use_repository_test', false);
-
- return new RedirectResponse($this->generateUrl('claro_admin_plugins'));
- }
-
- /**
- * @EXT\Route(
- * "/refresh/{date}",
- * name="claro_admin_refresh",
- * options = {"expose"=true}
- * )
- */
- public function refreshPlatformAction($date)
- {
- $this->bundleManager->refresh($date);
-
- return new Response('done');
- }
-
- /**
- * @EXT\Route(
- * "/refresh/log/{date}",
- * name="claro_admin_plugins_refresh_log",
- * options = {"expose"=true}
- * )
- *
- * Install a plugin.
- *
- * @return Response
- */
- public function displayRefreshLog($date)
- {
- $content = @file_get_contents($this->bundleManager->getRefreshLog() . '-' . $date . '.log');
- if (!$content) $content = '';
-
- return new Response($content);
- }
-}
diff --git a/DataFixtures/Required/Data/LoadAdminToolsData.php b/DataFixtures/Required/Data/LoadAdminToolsData.php
index 00a32658d..942065c0c 100644
--- a/DataFixtures/Required/Data/LoadAdminToolsData.php
+++ b/DataFixtures/Required/Data/LoadAdminToolsData.php
@@ -31,7 +31,6 @@ public function load(ObjectManager $manager)
array('user_management', 'user'),
array('workspace_management', 'book'),
array('registration_to_workspace', 'book'),
- array('platform_packages', 'wrench'),
array('desktop_and_home', 'home'),
array('desktop_tools', 'pencil'),
array('platform_logs', 'bars'),
diff --git a/Entity/Bundle.php b/Entity/Bundle.php
deleted file mode 100644
index 9338b980d..000000000
--- a/Entity/Bundle.php
+++ /dev/null
@@ -1,203 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Entity;
-
-use Doctrine\ORM\Mapping as ORM;
-use JMS\Serializer\Annotation\Groups;
-
-/**
- * @ORM\Entity()
- * @ORM\Table(name="claro_bundle")
- */
-class Bundle
-{
- /**
- * @var integer
- *
- * @ORM\Id
- * @ORM\Column(type="integer")
- * @ORM\GeneratedValue(strategy="AUTO")
- * @Groups({"api"})
- */
- private $id;
-
- /**
- * @var string
- * @ORM\Column(length=100)
- * @Groups({"api"})
- */
- private $name;
-
- /**
- * @var string
- * @ORM\Column(length=50)
- * @Groups({"api"})
- */
- private $version;
-
- /**
- * @var string
- * @ORM\Column(length=50)
- */
- private $type;
-
- /**
- * @ORM\Column(type="json_array")
- */
- private $authors;
-
- /**
- * @ORM\Column(type="text", nullable = true)
- */
- private $description;
-
- /**
- * @ORM\Column(type="text")
- */
- private $targetDir;
-
- /**
- * @ORM\Column(type="text")
- */
- private $basePath;
-
- /**
- * @ORM\Column(type="json_array")
- */
- private $license;
-
- /**
- * @ORM\Column(type="boolean", nullable = false)
- */
- protected $isInstalled = false;
-
- /**
- * Unmapped field if "stuff" need to be added to the description
- */
- private $extra;
-
- /**
- * Unmapped field. Is the plugin configurable ? Fetched from claro_plugin table
- * @todo remove claro_plugin table. It's useless now. claro_bundle can replace it and contains more datas
- */
- private $isConfigurable = false;
-
- public function getId()
- {
- return $this->id;
- }
-
- public function setName($name)
- {
- $this->name = $name;
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function setVersion($version)
- {
- $this->version = $version;
- }
-
- public function getVersion()
- {
- return $this->version;
- }
-
- public function setType($type)
- {
- $this->type = $type;
- }
-
- public function setLicense($license)
- {
- $this->license = $license;
- }
-
- public function getLicense()
- {
- return $this->license;
- }
-
- public function setAuthors(array $authors)
- {
- $this->authors = $authors;
- }
-
- public function getAuthors()
- {
- return $this->authors;
- }
-
- public function setDescription($description)
- {
- $this->description = $description;
- }
-
- public function getDescription()
- {
- return $this->description;
- }
-
- public function setTargetDir($targetDir)
- {
- $this->targetDir = $targetDir;
- }
-
- public function getTargetDir()
- {
- return $this->targetDir;
- }
-
- public function setBasePath($basePath)
- {
- $this->basePath = $basePath;
- }
-
- public function getBasePath()
- {
- return $this->basePath;
- }
-
- public function setIsInstalled($boolean)
- {
- $this->isInstalled = $boolean;
- }
-
- public function isInstalled()
- {
- return $this->isInstalled;
- }
-
- public function setExtra($extra)
- {
- $this->extra = $extra;
- }
-
- public function getExtra()
- {
- return $this->extra;
- }
-
- public function isConfigurable()
- {
- return $this->isConfigurable;
- }
-
- public function setIsConfigurable($boolean)
- {
- $this->isConfigurable = true;
- }
-}
diff --git a/Library/Installation/AdditionalInstaller.php b/Library/Installation/AdditionalInstaller.php
index d92d8763f..3af02ed6a 100644
--- a/Library/Installation/AdditionalInstaller.php
+++ b/Library/Installation/AdditionalInstaller.php
@@ -242,8 +242,8 @@ public function postUpdate($currentVersion, $targetVersion)
$updater = new Updater\Updater060700($this->container);
$updater->setLogger($this->logger);
$updater->postUpdate();
- case version_compare($currentVersion, '6.7.4'):
- $updater = new Updater\Updater060704($this->container);
+ case version_compare($currentVersion, '6.8.0', '<'):
+ $updater = new Updater\Updater060800($this->container);
$updater->setLogger($this->logger);
$updater->postUpdate();
}
diff --git a/Library/Installation/Updater/Updater060704.php b/Library/Installation/Updater/Updater060704.php
deleted file mode 100644
index 5a5cd4504..000000000
--- a/Library/Installation/Updater/Updater060704.php
+++ /dev/null
@@ -1,45 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Library\Installation\Updater;
-
-use Claroline\InstallationBundle\Updater\Updater;
-use Symfony\Component\DependencyInjection\ContainerInterface;
-use Claroline\CoreBundle\Entity\Tool\AdminTool;
-
-class Updater060704 extends Updater
-{
- private $container;
-
- public function __construct(ContainerInterface $container)
- {
- $this->container = $container;
- $this->om = $container->get('claroline.persistence.object_manager');
- }
-
- public function postUpdate()
- {
- if (!$this->om->getRepository('ClarolineCoreBundle:Tool\AdminTool')->findOneByName('organization_management')) {
- $this->createTool();
- }
-
- $this->container->get('claroline.manager.administration_manager')->addDefaultUserAdminActions();
- }
-
- private function createTool()
- {
- $this->log('Creating institution admin tool...');
- $entity = new AdminTool();
- $entity ->setName('organization_management');
- $entity ->setClass('institution');
- $this->om->persist($entity);
- $this->om->flush();
- }
-}
diff --git a/Library/Installation/Updater/Updater060800.php b/Library/Installation/Updater/Updater060800.php
new file mode 100644
index 000000000..5be1796f6
--- /dev/null
+++ b/Library/Installation/Updater/Updater060800.php
@@ -0,0 +1,69 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Library\Installation\Updater;
+
+use Claroline\CoreBundle\Entity\Tool\AdminTool;
+use Claroline\InstallationBundle\Updater\Updater;
+use Doctrine\DBAL\Schema\AbstractSchemaManager;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+class Updater060800 extends Updater
+{
+ private $container;
+ private $om;
+ private $adminToolRepo;
+
+ public function __construct(ContainerInterface $container)
+ {
+ $this->container = $container;
+ $this->om = $container->get('claroline.persistence.object_manager');
+ $this->adminToolRepo = $this->om->getRepository('ClarolineCoreBundle:Tool\AdminTool');
+ }
+
+ public function postUpdate()
+ {
+ $this->createOrganizationTool();
+ $this->removePackageTool();
+ $this->removeBundleTable();
+ $this->container->get('claroline.manager.administration_manager')->addDefaultUserAdminActions();
+ }
+
+ private function createOrganizationTool()
+ {
+ if (!$this->adminToolRepo->findOneByName('organization_management')) {
+ $this->log('Creating institution admin tool...');
+ $entity = new AdminTool();
+ $entity->setName('organization_management');
+ $entity->setClass('institution');
+ $this->om->persist($entity);
+ $this->om->flush();
+ }
+ }
+
+ private function removePackageTool()
+ {
+ if ($tool = $this->adminToolRepo->findOneByName('platform_packages')) {
+ $this->log('Removing package management admin tool...');
+ $this->om->remove($tool);
+ $this->om->flush();
+ }
+ }
+
+ private function removeBundleTable()
+ {
+ $schema = $this->container->get('doctrine.dbal.default_connection')->getSchemaManager();
+
+ if ($schema->tablesExist('claro_bundle')) {
+ $this->log('Removing bundle table...');
+ $schema->dropTable('claro_bundle');
+ }
+ }
+}
diff --git a/Listener/AdministrationToolListener.php b/Listener/AdministrationToolListener.php
index e0e02c902..be52c2980 100644
--- a/Listener/AdministrationToolListener.php
+++ b/Listener/AdministrationToolListener.php
@@ -84,19 +84,6 @@ public function onOpenRegistrationToWorkspace(OpenAdministrationToolEvent $event
$this->redirect($params, $event);
}
- /**
- * @DI\Observe("administration_tool_platform_packages")
- *
- * @param OpenAdministrationToolEvent $event
- */
- public function onOpenPlatformPackages(OpenAdministrationToolEvent $event)
- {
- $params = array();
- $params['_controller'] = 'ClarolineCoreBundle:Administration\Package:list';
- $this->redirect($params, $event);
- }
-
-
/**
* @DI\Observe("administration_tool_desktop_and_home")
*
diff --git a/Manager/BundleManager.php b/Manager/BundleManager.php
deleted file mode 100644
index 8be673c06..000000000
--- a/Manager/BundleManager.php
+++ /dev/null
@@ -1,371 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Manager;
-
-use JMS\DiExtraBundle\Annotation\Inject;
-use JMS\DiExtraBundle\Annotation\InjectParams;
-use JMS\DiExtraBundle\Annotation\Service;
-use Claroline\BundleRecorder\Operation;
-use Claroline\BundleRecorder\Handler\OperationHandler;
-use Claroline\BundleRecorder\Detector\Detector;
-use Claroline\BundleRecorder\Handler\BundleHandler;
-use Claroline\BundleRecorder\Recorder;
-use Claroline\CoreBundle\Manager\IniFileManager;
-use Claroline\CoreBundle\Persistence\ObjectManager;
-use Claroline\CoreBundle\Library\Configuration\PlatformConfigurationHandler;
-use Claroline\CoreBundle\Library\Utilities\FileSystem;
-use Psr\Log\LogLevel;
-use Symfony\Component\Console\Logger\ConsoleLogger;
-use Symfony\Component\Console\Output\StreamOutput;
-use Symfony\Component\Console\Output\OutputInterface;
-
-/**
- * @Service("claroline.manager.bundle_manager")
- */
-class BundleManager
-{
- private $om;
- private $bundleRepository;
- private $pluginRepository;
- private $kernelRootDir;
- private $configHandler;
- private $vendorDir;
- private $iniFileManager;
- private $installer;
- private $refresher;
-
- /**
- * @InjectParams({
- * "om" = @Inject("claroline.persistence.object_manager"),
- * "kernelRootDir" = @Inject("%kernel.root_dir%"),
- * "configHandler" = @Inject("claroline.config.platform_config_handler"),
- * "vendorDir" = @Inject("%claroline.param.vendor_directory%"),
- * "iniFileManager" = @Inject("claroline.manager.ini_file_manager"),
- * "installer" = @Inject("claroline.installation.platform_installer"),
- * "refresher" = @Inject("claroline.installation.refresher")
- * })
- */
- public function __construct(
- ObjectManager $om,
- $kernelRootDir,
- PlatformConfigurationHandler $configHandler,
- $vendorDir,
- IniFileManager $iniFileManager,
- $installer,
- $refresher
- )
- {
- $this->om = $om;
- $this->bundleRepository = $om->getRepository('ClarolineCoreBundle:Bundle');
- $this->pluginRepository = $om->getRepository('ClarolineCoreBundle:Plugin');
- $this->kernelRootDir = $kernelRootDir;
- $this->configHandler = $configHandler;
- $this->vendorDir = $vendorDir;
- $this->iniFileManager = $iniFileManager;
- $this->installer = $installer;
- $this->refresher = $refresher;
- }
-
- public function getBundle($bundle)
- {
- return $this->bundleRepository->findOneByName($bundle);
- }
-
- public function getInstalled()
- {
- return $this->bundleRepository->findAll();
- }
-
- /**
- * Get a list of uninstalled bundle.
- *
- * @param $bundles the list of available bundle fetched from the server
- */
- public function getUninstalledFromServer($bundles)
- {
- $installed = $this->getInstalled();
- $uninstalled = array();
-
- foreach ($bundles as $fetchedBundle) {
- $found = false;
- foreach ($installed as $bundle) {
- if ($bundle->getName() === $fetchedBundle->name) {
- $found = true;
- }
- }
-
- if (!$found) $uninstalled[] = $fetchedBundle;
- }
-
- return $uninstalled;
- }
-
- public function getCoreBundleVersion()
- {
- $core = $this->getBundle('CoreBundle');
-
- return $core->getVersion();
- }
-
- public function installRemoteBundle($bundle, $date = null)
- {
- //step 1, get the archive from the remote server
- $zipFile = $this->fetchLastInstallableFromRemote($bundle);
-
- $this->installBundle($bundle, $zipFile, $date);
- }
-
- public function fetchLastInstallableFromRemote($bundle)
- {
- $api = $this->configHandler->getParameter('repository_api');
- $url = $api . "/bundle/$bundle/coreVersion/{$this->getCoreBundleVersion()}/download";
-
- if ($this->configHandler->getParameter('use_repository_test')) {
- $url .= '/test';
- }
-
- $ch = curl_init();
- $zipFile = sys_get_temp_dir() . '/' . uniqid() . '.zip';
- curl_setopt($ch, CURLOPT_URL, $url);
- $file = fopen($zipFile, "w+");;
- curl_setopt($ch, CURLOPT_FILE, $file);
- curl_exec($ch);
- curl_close($ch);
- fclose($file);
-
- return $zipFile;
- }
-
- public function getBundleLastInstallableVersion($bundle, $coreVersion)
- {
- $api = $this->configHandler->getParameter('repository_api');
- $url = $api . "/bundle/$bundle/coreVersion/{$this->getCoreBundleVersion()}/installable";
-
- if ($this->configHandler->getParameter('use_repository_test')) {
- $url .= '/test';
- }
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $data = curl_exec($ch);
- curl_close($ch);
- $o = json_decode($data);
-
- return $o->tag;
- }
-
- public function installBundle($bundle, $zipFile, $date = null)
- {
- $logFile = $this->getLogFile();
- if ($date) $logFile = $logFile . '-' . $date;
- $logFile .= '.log';
- @unlink($logFile);
- $fileLogger = new \Monolog\Logger('package.update');
- $fileLogger->pushHandler(new \Monolog\Handler\StreamHandler($logFile));
- $fileLogger->addInfo('Downloading archive...');
- $version = $this->getBundleLastInstallableVersion($bundle, $this->getCoreBundleVersion());
- $fs = new FileSystem();
-
- //extract and unzip in the correct directory
- $extractPath = sys_get_temp_dir() . '/' . uniqid();
- $zip = new \ZipArchive();
- $zip->open($zipFile);
- $fileLogger->addInfo("Extraction...");
- $zip->extractTo($extractPath);
-
- //rename the $extractPath root (it currently has -version at the end)
- $iterator = new \DirectoryIterator($extractPath);
-
- foreach ($iterator as $el) {
- //there should be only one directory so...
- if ($el->isDir() && !$el->isDot()) {
- $parts = explode('-', $el->getBaseName());
- $fs->rename($el->getPathName(), $extractPath . '/' . $parts[0]);
- }
- }
-
- //move the source where they should be
- $composer = $extractPath . "/$bundle/composer.json";
- $json = file_get_contents($composer);
- $data = json_decode($json);
- $targetDir = 'target-dir';
- $parts = explode('/', $data->$targetDir);
- $newPath = $this->vendorDir . '/' . $data->name . '/' . $data->$targetDir;
- $vendor = $parts[0];
- $baseParts = explode('Bundle', $parts[1]);
- $baseName = $baseParts[0];
- $fileLogger->addInfo("Removing old sources...");
- $fs->rmdir($newPath, true);
- $fileLogger->addInfo("Copying sources from temporary directory...");
- $fs->copyDir($extractPath . "/$bundle", $newPath);
- //then we update the autoloader
- $parts = explode('/', $data->name);
- $vname = $parts[0];
- $bname = $parts[1];
- $bundleType = $data->type;
- $updatedTarget = str_replace('/', '\\', $data->$targetDir);
- $fqcn = $updatedTarget . '\\' . str_replace('\\', '', $updatedTarget);
- $fileLogger->addInfo("Updating vendor/composer/autoload_namespace.php...");
- $this->updateAutoload($vendor, $baseName, $vname, $bname);
- $fileLogger->addInfo("Updating app/config/bundle.ini...");
- $this->updateIniFile($vendor, $baseName);
- $fileLogger->addInfo("Generating app/config/operations.xml...");
- $this->generateUniqueOperationFile($bundle, $version, $bundleType, $fqcn, $logFile);
- //We need a different process to execute the update as the new sources were
- //not loaded by php yet.
- //It's much easier than trying to load/refresh everything.
- //TODO: use Sf2 proces library to avoid mistakes
- //sanitize this
- $executor = $this->kernelRootDir . '/../vendor/claroline/core-bundle/Library/Installation/scripts/operation_executor.php';
- $phpErrors = $this->kernelRootDir . "/logs/php_errors_{$date}.log";
- exec("php $executor $date > $phpErrors");
- }
-
- public function getLogFile()
- {
- return $this->kernelRootDir . "/logs/update";
- }
-
- public function getRefreshLog()
- {
- return $this->kernelRootDir . "/logs/refresh";
- }
-
- public function executeOperationFile($date = null)
- {
- $logFile = $this->getLogFile();
- if ($date) $logFile = $logFile . '-' . $date;
- $logFile .= '.log';
- $output = new StreamOutput(fopen($logFile, 'a', false));
-
- $verbosityLevelMap = array(
- LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
- LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL,
- LogLevel::DEBUG => OutputInterface::VERBOSITY_NORMAL
- );
- $consoleLogger = new ConsoleLogger($output, $verbosityLevelMap);
-
- $this->installer->setLogger($consoleLogger);
- $this->refresher->setOutput($output);
- $this->installer->installFromOperationFile();
- $this->refresher->installAssets();
- $this->refresher->dumpAssets('prod');
- $logLine = "Done !\n";
- file_put_contents($logFile, $logLine, FILE_APPEND);
- }
-
- public function updateIniFile($vendor, $bundle)
- {
- $iniFile = $this->kernelRootDir . '/config/bundles.ini';
-
- //update ini file
- $this->iniFileManager
- ->updateKey(
- $vendor . '\\' . $bundle . 'Bundle\\' . $vendor . $bundle . 'Bundle',
- true,
- $iniFile
- );
- }
-
- public function updateAutoload($ivendor, $ibundle, $vname, $bname)
- {
- //update namespace file
- $namespaces = $this->kernelRootDir . '/../vendor/composer/autoload_namespaces.php';
- $content = file_get_contents($namespaces);
- $lineToAdd = "\n '{$ivendor}\\\\{$ibundle}Bundle' => array(\$vendorDir . '/{$vname}/{$bname}'),";
-
- if (!strpos($content, $lineToAdd)) {
- //add the correct line after corebundle...
- $content = str_replace(
- "/core-bundle'),",
- "/core-bundle'), {$lineToAdd}",
- $content
- );
-
- file_put_contents($namespaces, $content);
- }
- }
-
- /**
- * Here we generate a new operation.xml file.
- */
- public function generateUniqueOperationFile($bundle, $version, $bundleType, $fqcn, $logFile)
- {
- $entity = $this->getBundle($bundle);
- $isInstalled = false;
-
- if ($entity) {
- $oldVersion = $entity->getVersion();
- $isInstalled = true;
- }
-
- $operationFilePath = $this->kernelRootDir . "/config/operations.xml";
- //remove the old operation file if it exists (maybe it would be better to do a backup).
- @unlink($operationFilePath);
-
- $fileLogger = new \Monolog\Logger('package.update');
- $fileLogger->pushHandler(new \Monolog\Handler\StreamHandler($logFile));
- $operationHandler = new OperationHandler($operationFilePath, $fileLogger);
-
- //generating the operations.xml file
- $operation = new Operation(
- $isInstalled ? Operation::UPDATE: Operation::INSTALL,
- $fqcn,
- $bundleType === 'claroline-plugin' ? Operation::BUNDLE_PLUGIN: Operation::BUNDLE_CORE
- );
-
- if (isset($entity)) {
- $operation->setFromVersion($oldVersion);
- }
-
- $operation->setToVersion($version);
- $operation->setDependencies(array());
- $operationHandler->addOperation($operation, false);
- }
-
- public function checkInstallRequirements()
- {
- $rootDir = $this->kernelRootDir . '/..';
-
- $writableElements = array(
- 'vendor' => 'directory',
- 'web' => 'directory',
- 'app/cache' => 'directory',
- 'app/config/bundles.ini' => 'file',
- 'vendor/composer/autoload_namespaces.php' => 'file'
- );
-
- $data = array();
-
- foreach ($writableElements as $el => $type) {
- $data[$el] = is_writable($rootDir . "/$el");
- }
-
- return $data;
- }
-
- public function getConfigurablePlugins()
- {
- return $this->pluginRepository->findBy(array('hasOptions' => true));
- }
-
- public function refresh($date)
- {
- $logFile = $this->getRefreshLog() . '-' . $date;
- $logFile .= '.log';
- $output = new StreamOutput(fopen($logFile, 'a', false));
- $this->refresher->setOutput($output);
- $this->refresher->installAssets();
- $this->refresher->dumpAssets('prod');
- }
-}
diff --git a/Manager/DependencyManager.php b/Manager/DependencyManager.php
deleted file mode 100644
index 3d3d7f598..000000000
--- a/Manager/DependencyManager.php
+++ /dev/null
@@ -1,473 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Manager;
-
-use Claroline\CoreBundle\Library\Composer\FileIO;
-use Claroline\CoreBundle\Library\Maintenance\MaintenanceHandler;
-use Claroline\CoreBundle\Command\PlatformUpdateCommand;
-use Claroline\CoreBundle\Persistence\ObjectManager;
-use Composer\Package\CompletePackage;
-use JMS\DiExtraBundle\Annotation as DI;
-use Composer\Package\CompletePackageInterface;
-use Composer\IO\NullIO;
-use Composer\Config;
-use Composer\Installer;
-use Composer\Factory;
-use Composer\Repository\InstalledFilesystemRepository;
-use Composer\Repository\CompositeRepository;
-use Composer\Json\JsonFile;
-use Symfony\Component\Console\Output\StreamOutput;
-use Symfony\Component\Console\Output\NullOutput;
-use Symfony\Component\Console\Input\ArgvInput;
-
-/**
- * @DI\Service("claroline.manager.dependency_manager")
- */
-class DependencyManager {
-
- private $vendorDir;
- private $repo;
- private $installedJson;
- private $logFile;
- private $lastTagsFile;
- private $iniFileManager;
- private $composerLogFile;
- private $cacheDir;
- private $env;
- private $updater;
- private $om;
- private $projectComposerJson;
- private $rootDir;
-
- const CLAROLINE_CORE_TYPE = 'claroline-core';
- const CLAROLINE_PLUGIN_TYPE = 'claroline-plugin';
-
- /**
- * @DI\InjectParams({
- * "vendorDir" = @DI\Inject("%claroline.param.vendor_directory%"),
- * "lastTagsFile" = @DI\Inject("%claroline.packages_last_tags_file%"),
- * "composerLogFile" = @DI\Inject("%claroline.composer_log_file%"),
- * "iniFileManager" = @DI\Inject("claroline.manager.ini_file_manager"),
- * "cacheDir" = @DI\Inject("%claroline.cache_dir%"),
- * "env" = @DI\Inject("%kernel.environment%"),
- * "updater" = @DI\Inject("claroline.command.update_command"),
- * "rootDir" = @DI\Inject("%kernel.root_dir%"),
- * "om" = @DI\Inject("claroline.persistence.object_manager")
- * })
- */
- public function __construct(
- $vendorDir,
- $lastTagsFile,
- IniFileManager $iniFileManager,
- $composerLogFile,
- $cacheDir,
- $env,
- PlatformUpdateCommand $updater,
- $rootDir,
- ObjectManager $om
- )
- {
- $this->vendorDir = $vendorDir;
- $ds = DIRECTORY_SEPARATOR;
- $this->installedJson = "{$vendorDir}{$ds}composer{$ds}installed.json";
- $this->logFile = "{$lastTagsFile}{$ds}..{$ds}composer.log";
- $this->projectComposerJson = "{$vendorDir}{$ds}..{$ds}composer.json";
- $installedFile = new JsonFile($this->installedJson);
- $this->repo = new InstalledFilesystemRepository($installedFile);
- $this->lastTagsFile = $lastTagsFile;
- $this->iniFileManager = $iniFileManager;
- $this->composerLogFile = $composerLogFile;
- $this->cacheDir = $cacheDir;
- $this->env = $env;
- $this->updater = $updater;
- $this->rootDir = $rootDir;
- $this->om = $om;
- }
-
- /**
- * Returns every packages installed by composer.
- *
- * @return CompletePackageInterface[]
- */
- public function getAllInstalled()
- {
- return $this->repo->getPackages();
- }
-
- /**
- * Returns installed packages by composer by type.
- *
- * @param $type
- *
- * @return CompletePackageInterface[]
- */
- public function getInstalledByType($type)
- {
- $packages = [];
-
- foreach ($this->getAllInstalled() as $package) {
- if ($package->getType() === $type) {
- $packages[] = $package;
- }
- }
-
- return $packages;
- }
-
- /**
- * Returns installed packages by composer by name.
- *
- * @param $name
- *
- * @return CompletePackageInterface
- */
- public function getInstalledByName($name)
- {
- foreach ($this->getAllInstalled() as $package) {
- if ($package->getName() === $name || $package->getPrettyName() === $name) {
- return $package;
- }
- }
-
- return null;
- }
-
- /**
- * Finds package by dist reference.
- *
- * @param string $distReference
- *
- * @return CompletePackageInterface|null
- */
- public function getByDistReference($distReference)
- {
- foreach ($this->getAllInstalled() as $package) {
-
- if ($package->getDistReference() === $distReference) {
- return $package;
- }
- }
-
- return null;
- }
-
- /**
- * Return each installed claroline plugins or core packages.
- *
- * @return array
- */
- public function getAllClaroPackages()
- {
- return array_merge(
- $this->getInstalledByType(self::CLAROLINE_CORE_TYPE),
- $this->getInstalledByType(self::CLAROLINE_PLUGIN_TYPE)
- );
- }
-
- /**
- * Returns the list of installed plugin packages, with extra information
- * relative to their options. Local packages (i.e. not manager by composer)
- * are also included in the list.
- *
- * @return CompletePackageInterface[]
- */
- public function getPluginList()
- {
- $repoPackages = $this->getInstalledByType(self::CLAROLINE_PLUGIN_TYPE);
- $registeredPlugins = $this->om->getRepository('ClarolineCoreBundle:Plugin')->findAll();
- $packages = [];
-
- foreach ($registeredPlugins as $plugin) {
- $targetPackage = null;
- $isInRepo = true;
-
- // looks for the corresponding package
- foreach ($repoPackages as $package) {
- $packageParts = explode('/', $package->getName());
- $bundleParts = explode('-', $packageParts[1]);
- $vendorName = $packageParts[0];
- $bundleName = '';
-
- foreach ($bundleParts as $part) {
- $bundleName .= $part;
- }
-
- if (strtoupper($plugin->getVendorName()) === strtoupper($vendorName)
- && strtoupper($plugin->getBundleName()) === strtoupper($bundleName)) {
- $targetPackage = $package;
- break;
- }
- }
-
- // builds a "fake" package if the plugin is not managed by composer
- if (!$targetPackage) {
- $isInRepo = false;
- $vendorName = strtolower($plugin->getVendorName());
- $bundleParts = preg_split('/(?=[A-Z])/', $plugin->getBundleName());
- array_shift($bundleParts);
- $bundleName = strtolower(implode('-', $bundleParts));
- $targetPackage = new CompletePackage(
- "{$vendorName}/{$bundleName}",
- '9999999-dev',
- 'unknown / local'
- );
- }
-
- // adds plugin options info in the "extra" attribute
- $extra = $targetPackage->getExtra();
- $extra['is_in_repo'] = $isInRepo;
- $extra['has_options'] = $plugin->hasOptions();
- $extra['plugin_short_name'] = $plugin->getShortName();
- $targetPackage->setExtra($extra);
- $packages[] = $targetPackage;
- }
-
- return $packages;
- }
-
- /**
- * Returns a package tag list.
- *
- * @param CompletePackageInterface $package
- *
- * @return array
- */
- public function getPackageTags(CompletePackageInterface $package)
- {
- $ds = DIRECTORY_SEPARATOR;
- putenv("COMPOSER_HOME={$this->vendorDir}{$ds}composer");
- $repos = Factory::createDefaultRepositories(new NullIO());
- $compositeRepo = new CompositeRepository($repos);
- $pkgs = $compositeRepo->findPackages($package->getPrettyName());
- $tags = array();
-
- foreach ($pkgs as $pkg) {
- $tags[] = $pkg->getPrettyVersion();
- }
-
- return $tags;
- }
-
- /**
- * Returns the last tag of a package.
- *
- * @param CompletePackageInterface $package
- *
- * @return string
- */
- public function getLastTag(CompletePackageInterface $package)
- {
- $tags = $this->getPackageTags($package);
- $lastTag = 0;
- $toReturn = 0;
-
- foreach ($tags as $tag) {
-
- //remove the "v" from the version tags. It's hard to compare otherwise.
- $tag = str_replace('v', '', $tag);
-
- if (version_compare($lastTag, $tag, '<')) {
- $lastTag = $tag;
- }
- }
-
- return $lastTag;
- }
-
- /**
- * Update the cache file containing the list of last available tags.
- *
- * @return array
- */
- public function updateAllPackages()
- {
- $packages = $this->getAllClaroPackages();
-
- foreach ($packages as $package) {
- $this->updatePackage($package);
- }
-
- return $tagList;
- }
-
- /**
- * Update a single package in the cache file.
- *
- * @param CompletePackageInterface $package
- */
- public function updatePackage(CompletePackageInterface $package)
- {
- $tag = $this->getLastTag($package);
- $this->iniFileManager->updateKey($package->getPrettyName(), $tag, $this->lastTagsFile);
-
- return $tag;
- }
-
- /**
- * Returns if the tag cache exists.
- *
- * @return bool
- */
- public function cacheExists()
- {
- return file_exists($this->lastTagsFile);
- }
-
- /**
- * Returns the tag cache.
- */
- private function removeCache()
- {
- if ($this->cacheExists()) {
- unlink($this->lastTagsFile);
- }
- }
-
- /**
- * Returns a list of upgradeable packages.
- *
- * @return array
- */
- public function getUpgradeablePackages()
- {
- //if the cache does not exists, wait for a refresh
- if (!$this->cacheExists()) {
- return array();
- }
-
- $tags = parse_ini_file($this->lastTagsFile);
- $packages = $this->getAllClaroPackages();
- $toUpgrade = [];
-
- foreach ($packages as $package) {
- foreach ($tags as $prettyName => $tag) {
- if ($package->getPrettyName() === $prettyName) {
- $toUpgrade[] = array('tag' => $tag, 'package' => $package);
- }
- }
- }
-
- return $toUpgrade;
- }
-
- /**
- * Upgrade claroline packages.
- */
- public function upgrade()
- {
- $this->removeUpdateLog();
- MaintenanceHandler::enableMaintenance();
-
- ini_set('max_execution_time', 1800);
- ini_set('memory_limit', '-1');
- //get the list of upgradable packages from the cache
- $pkgList = $this->getUpgradableFromCache();
- $this->updateRequirements('>=', $pkgList);
- $ds = DIRECTORY_SEPARATOR;
- $factory = new Factory();
- $io = new FileIO($this->composerLogFile);
- putenv("COMPOSER_HOME={$this->vendorDir}{$ds}composer");
- $composer = $factory->createComposer($io, "{$this->vendorDir}{$ds}..{$ds}composer.json", false);
- //this is the default github token. An other way to do it must be found sooner or later.
- $config = $composer->getConfig();
- $config->merge(array('github-oauth' => array('github.com' => '5d86c61eec8089d2dd22aebb79c37bebe4b6f86e')));
- $install = Installer::create($io, $composer);
- $continue = true;
-
- try {
- $install->setDryRun($this->env === 'dev')
- ->setVerbose($this->env === 'dev')
- ->setPreferSource($this->env === 'dev')
- ->setPreferDist($this->env !== 'dev')
- ->setDevMode($this->env === 'dev')
- ->setRunScripts(true)
- ->setOptimizeAutoloader(true)
- ->setUpdate(true);
-
- $install->run();
- } catch (\Exception $e) {
- file_put_contents($this->composerLogFile, "[Claroline updater Exception]: {$e->getMessage()}\n", FILE_APPEND);
- $continue = false;
- }
-
- if ($continue) {
- try {
- $this->updater->run(new ArgvInput(array()), new StreamOutput(fopen($this->composerLogFile, 'a')));
- } catch (\Exception $e) {
- file_put_contents($this->composerLogFile, "[Claroline updater Exception]: {$e->getMessage()}\n", FILE_APPEND);
- $continue = false;
- }
-
- if ($continue) {
- //remove the old cache file
- $this->iniFileManager->remove($this->lastTagsFile);
- file_put_contents($this->composerLogFile, "\nDone.", FILE_APPEND);
- }
- }
- }
-
- public function removeUpdateLog()
- {
- @unlink($this->composerLogFile);
- }
-
- /**
- * Update the main composer.json
- *
- * @param string $operator a comparison operator ('>=', '=', '>')
- * @param array $toUpdate an array of prettyName of packages
- */
- public function updateRequirements($operator, array $toUpdate)
- {
- $data = json_decode(file_get_contents($this->projectComposerJson));
- $new = clone $data;
-
- foreach ($data->require as $prettyName => $version) {
- foreach ($this->getAllInstalled() as $package) {
- foreach ($toUpdate as $ppn) {
- if ($package->getPrettyName() === $prettyName && $prettyName == $ppn) {
- $versions = explode(',', $package->getPrettyVersion());
- if ($package->getPrettyVersion() !== 'dev-master') {
- $new->require->$prettyName = $operator . $versions[0];
- }
- }
- }
- }
- };
-
- $ds = DIRECTORY_SEPARATOR;
- file_put_contents($this->rootDir . "{$ds}config{$ds}composer.json.old", json_encode($data, JSON_PRETTY_PRINT));
- file_put_contents($this->projectComposerJson, json_encode($new, JSON_PRETTY_PRINT));
- }
-
- /**
- * Get the a list of upgradable packages from the cache.
- *
- * @return array
- */
- public function getUpgradableFromCache()
- {
- $datas = $this->iniFileManager->getValues($this->lastTagsFile);
- $installed = $this->getAllClaroPackages();
- $toUpdate = [];
-
- foreach ($datas as $prettyName => $version) {
- foreach ($installed as $pkg) {
- if ($pkg->getPrettyName() === $prettyName && version_compare($pkg->getPrettyVersion(), $version, '<')) {
- $toUpdate[] = $pkg->getPrettyName();
- }
- }
- }
-
- return $toUpdate;
- }
-}
diff --git a/Resources/config/parameters.yml b/Resources/config/parameters.yml
index c0c5ae0df..8470e85c0 100644
--- a/Resources/config/parameters.yml
+++ b/Resources/config/parameters.yml
@@ -32,7 +32,6 @@ parameters:
claroline.param.web_dir: "%kernel.root_dir%/../web"
claroline.param.platform_generated_archive_path: %kernel.root_dir%/config/tmp_files
#todo: add .param. in the pathaname
- claroline.packages_last_tags_file: "%claroline.cache_dir%/last_tags.cache.ini"
claroline.composer_log_file: "%kernel.root_dir%/logs/composer.log"
claroline.ip_white_list_file: "%kernel.root_dir%/config/ip_white_list.yml"
claroline.cache_dir: "%kernel.root_dir%/cache"
diff --git a/Resources/config/routing.yml b/Resources/config/routing.yml
index 0b762b5d6..841aaf9e4 100644
--- a/Resources/config/routing.yml
+++ b/Resources/config/routing.yml
@@ -244,11 +244,6 @@ claro_admin_workspace_registration:
resource: "@ClarolineCoreBundle/Controller/Administration/WorkspaceRegistrationController.php"
type: annotation
-claro_admin_package:
- resource: "@ClarolineCoreBundle/Controller/Administration/PackageController.php"
- prefix: admin/package
- type: annotation
-
claro_admin_facet:
resource: "@ClarolineCoreBundle/Controller/Administration/FacetController.php"
prefix: admin/facet
@@ -327,14 +322,6 @@ claro_parameters_api:
options:
expose: true
-claro_packages_api:
- resource: "@ClarolineCoreBundle/Controller/API/Admin/PackageController.php"
- type: rest
- prefix: api
- defaults: {_format: json}
- options:
- expose: true
-
claro_year_api:
resource: "@ClarolineCoreBundle/Controller/API/Calendar/YearController.php"
type: rest
diff --git a/Resources/public/js/administration/packages.js b/Resources/public/js/administration/packages.js
deleted file mode 100644
index 1dafe2adc..000000000
--- a/Resources/public/js/administration/packages.js
+++ /dev/null
@@ -1,100 +0,0 @@
-$('.install-pkg').on('click', function(event) {
- event.preventDefault();
- var date = new Date().getTime();
- var bundle = $(event.target).attr('data-package-name');
- var version = $(event.target).attr('data-package-version');
- var url = Routing.generate('claro_admin_plugin_install', {
- 'bundle': $(event.target).attr('data-package-name'),
- 'date': date
- });
-
- var html = Twig.render(PackageLog, {'bundle': bundle, 'version': version});
-
- var waitingHandler = function() {
- $('#log-content').show();
- //var logFile = Routing.generate('claro_admin_plugins_log', {'date': date});
- var logFile = $('#log-content').attr('href') + '?logFile=' + 'update-' + date + '.log';
- var logDisplayer = new window.Claroline.LogDisplayer.Displayer('#log-content');
- logDisplayer.setLogFile(logFile);
- logDisplayer.start();
- };
-
- var errorHandler = function(logDisplayer) {
- location.reload();
- };
-
- var successHandler = function(logDisplayer) {
- location.reload();
- }
-
- var modal = window.Claroline.Modal.confirmRequest(
- url,
- successHandler,
- undefined,
- html,
- Translator.trans('package_install', {}, 'platform'),
- waitingHandler,
- undefined,
- errorHandler,
- undefined,
- true,
- true
- );
-
- $('.btn-modal-confirm').on('click', function(e) {
- modal.on('hide.bs.modal', function(e) {
- e.preventDefault();
- });
- $('.modal-footer').hide();
- $('#package-confirm-msg').hide();
- });
-});
-
-$('.refresh-platform').on('click', function(event) {
- var date = new Date().getTime();
- var url = Routing.generate('claro_admin_refresh', {
- 'date': date
- });
- var html = Twig.render(RefresherLog, {});
-
- var errorHandler = function(logDisplayer) {
- location.reload();
- };
-
- var successHandler = function(logDisplayer) {
- location.reload();
- }
-
- var waitingHandler = function() {
- $('#log-content').show();
- //var logFile = Routing.generate('claro_admin_plugins_log', {'date': date});
- var logFile = $('#log-content').attr('href') + '?logFile=' + 'refresh-' + date + '.log';
- var logDisplayer = new window.Claroline.LogDisplayer.Displayer('#log-content');
- logDisplayer.setLogFile(logFile);
- logDisplayer.start();
- };
-
- var modal = window.Claroline.Modal.confirmRequest(
- url,
- successHandler,
- undefined,
- html,
- Translator.trans('platform_refresh', {}, 'platform'),
- waitingHandler,
- undefined,
- errorHandler,
- undefined,
- true,
- true
- );
-
- //it's dirty but I'm lazy.
- $('.btn-modal-confirm').on('click', function(e) {
- modal.on('hide.bs.modal', function(e) {
- e.preventDefault();
- });
- $('.modal-footer').hide();
- $('#package-confirm-msg').hide();
- $('#refresher-confirm-msg').hide();
- });
-});
diff --git a/Resources/translations/platform.de.yml b/Resources/translations/platform.de.yml
index 87fe66901..0b3f37ec2 100644
--- a/Resources/translations/platform.de.yml
+++ b/Resources/translations/platform.de.yml
@@ -176,7 +176,6 @@ cookie_lifetime: 'Durée de vie du cookie'
copiable: Copiable
copies: Copies
copy: Copier
-core_packages: 'Paquets du noyau'
count_resources: 'Nombre de ressource'
create: Créer
create_account: create_account
@@ -613,7 +612,6 @@ no_home_tab: 'Il n''y a aucun onglet'
no_learning_outcomes: 'Aucun référentiel de compétences'
no_message: 'Aucun message'
no_model: 'Aucun modèle'
-no_package_description: 'Aucune description du paquet.'
no_resources_in_workspace: 'Cet espace ne contient actuellement aucune ressource.'
no_role_selected_message: 'Aucun role sélectionné.'
no_search_results: 'Votre recherche n''a retourné aucun résultat.'
@@ -651,15 +649,6 @@ others: Autres
over_max_length: 'Cette valeur est trop longue'
owner: Propriétaire
owner_s: Propriétaire(s)
-package_install: 'Installation d''un paquet'
-package_install_auto_reload: 'Cette page est rechargée automatiquement à la fin de l''installation d''un paquet.'
-package_install_confirm: 'Êtes-vous sûr de vouloir installer %bundle% %version% ?'
-package_update_danger: 'Cette fonctionnalité n''est pas encore totalement stable et peut rendre inutilisable votre plateforme. Il est important de bien faire un backup de vos données avant de l''utiliser.'
-package_update_impossible: 'Mise à jour des paquets impossible sur cette page. Veuillez contacter l''administrateur.'
-package_upgrade_all_warning: 'Attention, ceci mettra à jour tous les paquets de la plateforme. Cette opération ne peut être annulée. Il est conseillé d''effectuer une sauvegarde des fichiers ainsi que de la base de données avant d''effectuer cette opération.'
-packages: Paquets
-packages_permissions_error: 'Veuillez corriger les erreurs suivantes pour commencer les mises à jour.'
-packages_upgrade_info_message: 'Attention, ceci est la page de gestion de mises à jour.'
parameters: Paramètres
parameters_save_error: 'Une erreur est survenue pendant la sauvegarde des paramètres.'
parameters_save_success: 'Paramètres sauvegardés avec succès.'
@@ -700,7 +689,6 @@ platform_role: 'Rôle plateforme'
platform_widgets: 'Widgets de la plateforme'
please_validate_your_account: 'Un email vient de vous être envoyé pour activer votre compte.'
please_wait: 'Veuillez patienter...'
-plugin_packages: 'Paquets des plugins'
port: Port
portfolio_url: 'Url d''accès à l''outil de portfolio'
position: Position
diff --git a/Resources/translations/platform.en.yml b/Resources/translations/platform.en.yml
index a270a62d7..60039450a 100644
--- a/Resources/translations/platform.en.yml
+++ b/Resources/translations/platform.en.yml
@@ -179,7 +179,6 @@ cookie_lifetime: 'Cookie lifetime'
copiable: Copiable
copies: Copies
copy: Copy
-core_packages: 'Core packages'
count_resources: 'Amount of resources'
create: Create
create_account: 'Create account'
@@ -623,7 +622,6 @@ no_home_tab: 'There is no Home tab'
no_learning_outcomes: 'No learning outcomes'
no_message: 'No message'
no_model: 'No model'
-no_package_description: 'No package description.'
no_resources_in_workspace: 'There are currently no resources in this workspace.'
no_role_selected_message: 'No role selected.'
no_search_results: 'Your search hasn''t returned any result.'
@@ -662,15 +660,6 @@ others: Others
over_max_length: 'This value is too long'
owner: Owner
owner_s: Owner(s)
-package_install: 'Package install'
-package_install_auto_reload: 'This page will be reload automatically once an operation is done'
-package_install_confirm: 'Do you really want to install %bundle% %version% ?'
-package_update_danger: 'This functionnality is not stable yet and can crash your platform. Please backup your data before going further.'
-package_update_impossible: 'Package update impossible on this page. please contact the administrator.'
-package_upgrade_all_warning: 'Warning, this will update all packages on the platform. This operation can not be canceled. It is recommended to make a backup of the files and the database before performing this operation.'
-packages: Packages
-packages_permissions_error: 'Please fix these errors before starting any update.'
-packages_upgrade_info_message: 'Warning, this page allows you to update the platform.'
parameters: Parameters
parameters_save_error: 'An error occured while saving parameters.'
parameters_save_success: 'Parameters saved with success.'
@@ -711,7 +700,6 @@ platform_role: 'Platform role'
platform_widgets: 'Platform widgets'
please_validate_your_account: 'An email was sent for you to activate your account'
please_wait: 'Please wait...'
-plugin_packages: 'Plugin packages'
port: Port
portfolio_url: 'Portfolio tool''s access url'
position: Position
@@ -1238,4 +1226,4 @@ add: Add
administrators: Administrators
edit_organization: Edit organization
coordinates: Coordinates
-address: Address
\ No newline at end of file
+address: Address
diff --git a/Resources/translations/platform.es.yml b/Resources/translations/platform.es.yml
index 18b2c14cb..a9d3bdd22 100644
--- a/Resources/translations/platform.es.yml
+++ b/Resources/translations/platform.es.yml
@@ -178,7 +178,6 @@ cookie_lifetime: 'Duración de la cookie'
copiable: Copiable
copies: copies
copy: Copiar
-core_packages: 'Core packages'
count_resources: count_resources
create: Crear
create_account: 'Crear la cuenta'
@@ -619,7 +618,6 @@ no_home_tab: 'No hay pestañas'
no_learning_outcomes: no_learning_outcomes
no_message: 'No hay mensajes'
no_model: no_model
-no_package_description: no_package_description
no_resources_in_workspace: no_resources_in_workspace
no_role_selected_message: no_role_selected_message
no_search_results: 'Su búsqueda no ha producido ningún resultado.'
@@ -658,15 +656,6 @@ others: others
over_max_length: 'Este valor es muy largo'
owner: Propietario
owner_s: Propietario(s)
-package_install: package_install
-package_install_auto_reload: package_install_auto_reload
-package_install_confirm: package_install_confirm
-package_update_danger: package_update_danger
-package_update_impossible: package_update_impossible
-package_upgrade_all_warning: 'Advertencia, esto actualizará todos los paquetes de la plataforma. Esta operación no puede ser cancelada. Se recomienda hacer una copia de seguridad de los archivos y de la base de datos antes de realizar esta operación.'
-packages: Packages
-packages_permissions_error: packages_permissions_error
-packages_upgrade_info_message: 'Advertencia, esta es la página de administración de las actualizaciones.'
parameters: Parámetros
parameters_save_error: parameters_save_error
parameters_save_success: parameters_save_success
@@ -707,7 +696,6 @@ platform_role: 'Roles de la plataforma'
platform_widgets: 'Widgets de la plataforma'
please_validate_your_account: please_validate_your_account
please_wait: 'Por favor espere...'
-plugin_packages: 'Plugin packages'
port: Puerto
portfolio_url: portfolio_url
position: posición
diff --git a/Resources/translations/platform.fr.yml b/Resources/translations/platform.fr.yml
index f29e15cb9..0321dacfb 100644
--- a/Resources/translations/platform.fr.yml
+++ b/Resources/translations/platform.fr.yml
@@ -179,7 +179,6 @@ cookie_lifetime: 'Durée de vie du cookie'
copiable: Copiable
copies: Copies
copy: Copier
-core_packages: 'Paquets du noyau'
count_resources: 'Nombre de ressources'
create: Créer
create_account: 'Créer le compte'
@@ -624,7 +623,6 @@ no_home_tab: 'Il n''y a aucun onglet'
no_learning_outcomes: 'Aucun référentiel de compétences'
no_message: 'Aucun message'
no_model: 'Aucun modèle'
-no_package_description: 'Aucune description du paquet.'
no_resources_in_workspace: 'Cet espace ne contient actuellement aucune ressource.'
no_role_selected_message: 'Aucun rôle sélectionné.'
no_search_results: 'Votre recherche n''a retourné aucun résultat.'
@@ -663,15 +661,6 @@ others: Autres
over_max_length: 'Cette valeur est trop longue.'
owner: Propriétaire
owner_s: Propriétaire(s)
-package_install: 'Installation d''un paquet'
-package_install_auto_reload: 'Cette page est rechargée automatiquement à la fin de l''installation d''un paquet.'
-package_install_confirm: 'Êtes-vous sûr de vouloir installer %bundle% %version% ?'
-package_update_danger: 'Cette fonctionnalité n''est pas encore totalement stable et peut rendre votre plateforme inutilisable . Il est important de bien d''effectuer une sauvegarde de vos données avant de l''utiliser.'
-package_update_impossible: 'Mise à jour des paquets impossible sur cette page. Veuillez contacter l''administrateur de la plateforme.'
-package_upgrade_all_warning: 'Attention, ceci mettra à jour tous les paquets de la plateforme. Cette opération ne peut être annulée. Il est conseillé d''effectuer une sauvegarde des fichiers ainsi que de la base de données avant de poursuivre cette opération.'
-packages: Paquets
-packages_permissions_error: 'Veuillez corriger les erreurs suivantes pour commencer les mises à jour.'
-packages_upgrade_info_message: 'Attention, ceci est la page de gestion de mises à jour.'
parameters: Paramètres
parameters_save_error: 'Une erreur est survenue pendant la sauvegarde des paramètres.'
parameters_save_success: 'Paramètres sauvegardés avec succès.'
@@ -712,7 +701,6 @@ platform_role: 'Rôle plateforme'
platform_widgets: 'Widgets de la plateforme'
please_validate_your_account: 'Un courriel vient de vous être envoyé pour activer votre compte.'
please_wait: 'Veuillez patienter...'
-plugin_packages: 'Paquets des plugins'
port: Port
portfolio_url: 'Url d''accès à l''outil de portfolio'
position: Position
@@ -1239,7 +1227,7 @@ edit_organization: Modifier une organisation
coordinates: Coordonnées
address: Adresse
add_users_to_group: Ajouter des utilisateurs à un groupe
-add_users_to_group_confirm: Êtes-vous sûr de vouloir ajouter le(s) utlisateur(s) [ %user_list% ] dans le groupe %group% ?
+add_users_to_group_confirm: Êtes-vous sûr de vouloir ajouter le(s) utlisateur(s) [ %user_list% ] dans le groupe %group% ?
user_added: Utilisateur %user% ajouté.
user_removed: Utilisateur %user% supprimé.
remove_users_from_group: Supprimer des utilisateurs d'un groupe
@@ -1259,4 +1247,4 @@ organizations: Organisation
group_name: Nom du groupe
profile_edition: Modification du profil
claro_admin_personal_workspace_resource_rights: Gestion des ressources de l'espace personnel
-organization_name: Nom de l'organisation
\ No newline at end of file
+organization_name: Nom de l'organisation
diff --git a/Resources/translations/platform.nl.yml b/Resources/translations/platform.nl.yml
index 41fb36a3e..7afd82ee9 100644
--- a/Resources/translations/platform.nl.yml
+++ b/Resources/translations/platform.nl.yml
@@ -176,7 +176,6 @@ cookie_lifetime: cookie_lifetime
copiable: copiable
copies: copies
copy: copy
-core_packages: core_packages
count_resources: count_resources
create: create
create_and_update: create_and_update
@@ -603,7 +602,6 @@ no_home_tab: no_home_tab
no_learning_outcomes: no_learning_outcomes
no_message: no_message
no_model: no_model
-no_package_description: no_package_description
no_resources_in_workspace: no_resources_in_workspace
no_role_selected_message: no_role_selected_message
no_search_results: no_search_results
@@ -640,15 +638,6 @@ others: others
over_max_length: over_max_length
owner: owner
owner_s: owner_s
-package_install: package_install
-package_install_auto_reload: package_install_auto_reload
-package_install_confirm: package_install_confirm
-package_update_danger: package_update_danger
-package_update_impossible: package_update_impossible
-package_upgrade_all_warning: package_upgrade_all_warning
-packages: packages
-packages_permissions_error: packages_permissions_error
-packages_upgrade_info_message: packages_upgrade_info_message
parameters: parameters
parameters_save_error: parameters_save_error
parameters_save_success: parameters_save_success
@@ -688,7 +677,6 @@ platform_role: platform_role
platform_widgets: platform_widgets
please_validate_your_account: please_validate_your_account
please_wait: please_wait
-plugin_packages: plugin_packages
port: port
portfolio_url: portfolio_url
position: position
diff --git a/Resources/translations/tools.de.yml b/Resources/translations/tools.de.yml
index aefaf61f0..cb7e1938a 100644
--- a/Resources/translations/tools.de.yml
+++ b/Resources/translations/tools.de.yml
@@ -11,7 +11,6 @@ my_contacts: 'Mes contacts'
parameters: Paramètres
platform_analytics: 'Statistiques de la plateforme'
platform_logs: 'Suivi de la plateforme'
-platform_packages: 'Paquets de la plateforme'
platform_parameters: 'Paramètres de la plateforme'
platform_plugins: 'Plugins de la plateforme'
registration_to_workspace: 'Inscription à des espaces d''activités'
diff --git a/Resources/translations/tools.en.yml b/Resources/translations/tools.en.yml
index f3f3ee180..9de682970 100644
--- a/Resources/translations/tools.en.yml
+++ b/Resources/translations/tools.en.yml
@@ -11,7 +11,6 @@ my_contacts: 'My contacts'
parameters: Settings
platform_analytics: 'Platform analytics'
platform_logs: 'Platform logs'
-platform_packages: 'Platform packages'
platform_parameters: 'Platform parameters'
platform_plugins: 'Platform plugins'
registration_to_workspace: 'Registration to workspaces'
diff --git a/Resources/translations/tools.es.yml b/Resources/translations/tools.es.yml
index 7a1eab4d2..bff86bcc7 100644
--- a/Resources/translations/tools.es.yml
+++ b/Resources/translations/tools.es.yml
@@ -11,7 +11,6 @@ my_contacts: 'Mis contactos'
parameters: Parámetros
platform_analytics: 'Análisis de la plataforma'
platform_logs: 'Registros de la plataforma'
-platform_packages: platform_packages
platform_parameters: 'Parámetros de la plataforma'
platform_plugins: 'Plugins de la plataforma'
registration_to_workspace: 'Inscripción a un espacio de trabajo'
diff --git a/Resources/translations/tools.fr.yml b/Resources/translations/tools.fr.yml
index 1a2bd1f30..68dc61e37 100644
--- a/Resources/translations/tools.fr.yml
+++ b/Resources/translations/tools.fr.yml
@@ -11,7 +11,6 @@ my_contacts: 'Mes contacts'
parameters: Paramètres
platform_analytics: 'Statistiques de la plateforme'
platform_logs: 'Suivi de la plateforme'
-platform_packages: 'Paquets de la plateforme'
platform_parameters: 'Paramètres de la plateforme'
platform_plugins: 'Plugins de la plateforme'
registration_to_workspace: 'Inscription à des espaces d''activités'
@@ -21,4 +20,4 @@ user_management: 'Gestion des utilisateurs'
users: Utilisateurs
widgets_management: 'Gestion des widgets'
workspace_management: 'Gestion des espaces d''activités'
-organization_management: 'Gestion des organisations'
\ No newline at end of file
+organization_management: 'Gestion des organisations'
diff --git a/Resources/translations/tools.nl.yml b/Resources/translations/tools.nl.yml
index 354972476..ae0ed6902 100644
--- a/Resources/translations/tools.nl.yml
+++ b/Resources/translations/tools.nl.yml
@@ -11,7 +11,6 @@ my_contacts: my_contacts
parameters: parameters
platform_analytics: platform_analytics
platform_logs: platform_logs
-platform_packages: platform_packages
platform_parameters: platform_parameters
platform_plugins: platform_plugins
registration_to_workspace: registration_to_workspace
diff --git a/Resources/views/Administration/Package/list.html.twig b/Resources/views/Administration/Package/list.html.twig
deleted file mode 100644
index 1e4e6f517..000000000
--- a/Resources/views/Administration/Package/list.html.twig
+++ /dev/null
@@ -1,177 +0,0 @@
-{% extends "ClarolineCoreBundle:Administration:layout.html.twig" %}
-
-{% block title %}{{ parent() ~ ' - ' ~ 'packages' | trans({}, 'platform') | striptags | raw }}{% endblock %}
-
-{% block breadcrumb %}
- {{
- macros.breadcrumbs([
- {
- 'icon': 'icon-cog',
- 'name': 'administration'|trans({}, 'platform'),
- 'href': path('claro_admin_index')
- },
- {
- 'name': 'packages'|trans({}, 'platform'),
- 'href': ''
- }
- ])
- }}
-{% endblock %}
-
-{% block section_content %}
-{% set allowUpdate = true %}
-{% for file, isWritable in danger.simple %}
- {% if not isWritable %}
- {% set allowUpdate = false %}
- {% endif %}
-{% endfor %}
-{% for file, isWritable in danger.recursive %}
- {% if not isWritable %}
- {% set allowUpdate = false %}
- {% endif %}
-{% endfor %}
-
-
-
- {{ 'package_update_danger'|trans({}, 'platform') }}
-
-
-
- {% if not allowUpdate %}
-
{{ 'packages_permissions_error'|trans({}, 'platform') }}
-
- {% for file, isWritable in danger.simple %}
- {% if not isWritable %}
- {{ file }} {{ 'is_not_writable'|trans({}, 'platform') }}.
- {% endif %}
- {% endfor %}
- {% for file, isWritable in danger.recursive %}
- {% if not isWritable %}
- {{ file }} {{ 'is_not_writable_recursive'|trans({}, 'platform') }}.
- {% endif %}
- {% endfor %}
-
- {% else %}
-
{{ 'tips'|trans({}, 'platform') }}
-
- {{ 'backup_reminder'|trans({}, 'platform') }}
- {{ 'logs_error_location'|trans({}, 'platform') }}
- {{ 'package_install_auto_reload'|trans({}, 'platform') }}
- {{ 'activate_maintenance_mode'|trans({}, 'platform') }}
- {{ 'install_update_cant_be_undone'|trans({}, 'platform') }}
- {{ 'put_back_permissions_after_update'|trans({}, 'platform') }}
-
- {% if useTestRepo %}
-
- {{ 'test_repository_activated'|trans({}, 'platform') }}
-
- {% endif %}
- {% endif %}
-
-
- {% set refreshAllowed = true %}
- {% for file, isWritable in refresh.simple %}
- {% if not isWritable %}
- {% set refreshAllowed = false %}
- {% endif %}
- {% endfor %}
- {% for file, isWritable in refresh.recursive %}
- {% if not isWritable %}
- {% set refreshAllowed = false %}
- {% endif %}
- {% endfor %}
-
-
-
-
-
-
-
-
- {% for file, isWritable in refresh.simple %}
- {% if not isWritable %}
- {{ file }} {{ 'is_not_writable'|trans({}, 'platform') }}.
- {% endif %}
- {% endfor %}
- {% for file, isWritable in refresh.recursive %}
- {% if not isWritable %}
- {{ file }} {{ 'is_not_writable_recursive'|trans({}, 'platform') }}.
- {% endif %}
- {% endfor %}
-
-
-
{{ 'refresh_explanation'|trans({}, 'platform')|raw }}
-
-
-
-
-
-
-
-
-
-
-
- {% for installedPkg in installed %}
- {{ macros.renderPackageElement(installedPkg, fetched, false, allowUpdate) }}
- {% endfor %}
-
-
-
-
-
-
-
-
-
- {% for package in uninstalled %}
- {{ macros.renderPackageElement(package, fetched, true, allowUpdate)}}
- {% endfor %}
-
-
-
-
-
- {% if useTestRepo %}
-
{{ 'use_stable_repo'|trans({}, 'platform') }}
- {% else %}
-
{{ 'use_test_repo'|trans({}, 'platform') }}
- {% endif %}
-
-
-{% endblock %}
-{% block javascripts %}
- {{ parent() }}
-
-
-{% endblock %}
diff --git a/Resources/views/Administration/Package/logs.html.twig b/Resources/views/Administration/Package/logs.html.twig
deleted file mode 100644
index dca3319fc..000000000
--- a/Resources/views/Administration/Package/logs.html.twig
+++ /dev/null
@@ -1,11 +0,0 @@
-{% twig_js name="PackageLog" %}
-
- {{ 'package_install_confirm'|trans({'bundle': bundle, 'version': version}, 'platform') }}
-
-
diff --git a/Resources/views/Administration/Package/refresher.html.twig b/Resources/views/Administration/Package/refresher.html.twig
deleted file mode 100644
index 897301429..000000000
--- a/Resources/views/Administration/Package/refresher.html.twig
+++ /dev/null
@@ -1,11 +0,0 @@
-{% twig_js name="RefresherLog" %}
-
- {{ 'platform_refresh_confirm'|trans({}, 'platform') }}
-
-
diff --git a/Resources/views/Layout/javascripts.html.twig b/Resources/views/Layout/javascripts.html.twig
index 2f2012d89..bd576f530 100644
--- a/Resources/views/Layout/javascripts.html.twig
+++ b/Resources/views/Layout/javascripts.html.twig
@@ -54,8 +54,6 @@
"@ClarolineCoreBundle/Resources/views/Administration/Facet/fieldElementInnerHtml.html.twigjs"
"@ClarolineCoreBundle/Resources/views/Administration/Facet/panelElement.html.twigjs"
"@ClarolineCoreBundle/Resources/views/Administration/Roles/renderRoleRow.html.twig"
- "@ClarolineCoreBundle/Resources/views/Administration/Package/logs.html.twig"
- "@ClarolineCoreBundle/Resources/views/Administration/Package/refresher.html.twig"
"@ClarolineCoreBundle/Resources/views/Tool/workspace/parameters/model/modelRow.html.twig"
"@ClarolineCoreBundle/Resources/views/Tool/workspace/parameters/model/userRow.html.twig"
"@ClarolineCoreBundle/Resources/views/Tool/workspace/parameters/model/groupRow.html.twig"
diff --git a/Resources/views/macros.html.twig b/Resources/views/macros.html.twig
index c58d3fa68..3104c26f4 100644
--- a/Resources/views/macros.html.twig
+++ b/Resources/views/macros.html.twig
@@ -141,149 +141,3 @@
{% endif %}
{% endmacro %}
-
-{#
- I know this is dirty because I use the same structrure for installed package
- and soon to be installed but I'm very lazy.
- Feel free to split this method if you want.
-#}
-{% macro renderPackageElement(package, upgradablePackages, fetchNew, baseRequirementSatisfied) %}
- {% set displayUpgradePerms = false %}
-
-
-
-
-
- {% set version = package.version | replace({'v': ''}) %}
- {{ package.name }}
-
- {% if fetchNew == false and package.isConfigurable() %}
-
-
-
- {% endif %}
- {{ version }}
-
-
- {% if fetchNew == false %}
- {% set found = false %}
- {% set foundPkg = null %}
- {% for upgradablePackage in upgradablePackages %}
- {% if upgradablePackage.name == package.name %}
- {% set found = true %}
- {% set foundPkg = upgradablePackage %}
- {% endif %}
- {% endfor %}
- {% if found == true %}
- {% if version_compare(version, foundPkg.version, '<') and baseRequirementSatisfied %}
- {% if is_installation_requirement_satisfied(package.basePath) %}
-
- {{ 'update'|trans({'%version%': foundPkg.version}, 'platform') }}
-
- {% else %}
- {% set displayUpgradePerms = true %}
-
- {{ 'requirement_failed_for_update'|trans({}, 'platform') }}
-
- {% endif %}
- {% else %}
- {% if version_compare(version, foundPkg.version, '=') %}
-
- {{ 'up_to_date'|trans({}, 'platform') }}
-
- {% else %}
-
- {{ 'update_impossible'|trans({}, 'platform') }}
-
- {% endif %}
- {% endif %}
- {% else %}
-
- {{ 'not_managed_by_claroline_repository'|trans({}, 'platform') }}
-
- {% endif %}
- {% else %}
- {% if baseRequirementSatisfied and is_installation_requirement_satisfied(package.basePath, package.requirements) %}
-
- {{ 'install'|trans({}, 'platform') }}
-
- {% else %}
-
- {{ 'requirement_failed_for_install'|trans({}, 'platform') }}
-
- {% endif %}
- {% endif %}
-
-
-
-
- {% if
- not package.description
- and not package.authors | length > 0
- and not package.license
- %}
- {{ 'no_package_description'|trans({}, 'platform') }}
- {% else %}
- {% if package.description %}
-
- {{ package.description }}
-
- {% endif %}
- {% if package.authors | length > 0 %}
-
-
- {% for author in package.authors %}
-
- {% if author.name is defined %}
- {{ author.name }}
- {% endif %}
-
- {% if author.email is defined %}
-
- {{ author.email }}
-
- {% endif %}
- {% if author.homepage is defined %}
-
-
- {{ author.homepage }}
-
-
- {% endif %}
-
-
- {% endfor %}
-
-
- {% endif %}
- {% if package.license %}
-
- {#{{ package.license }}#}
-
- {% endif %}
- {% endif %}
-
- {% if fetchNew and not is_installation_requirement_satisfied(package.basePath, package.requirements) %}
- {{ render_package_missing_permissions(package.basePath)|raw }}
- {{ render_package_missing_require(package.requirements)|raw }}
- {% else %}
- {% if displayUpgradePerms == true %}
- {{ render_package_missing_permissions(package.basePath)|raw }}
- {% endif %}
- {% endif %}
-
-
-
-{% endmacro %}
diff --git a/Twig/PackageExtension.php b/Twig/PackageExtension.php
deleted file mode 100644
index 1e6754801..000000000
--- a/Twig/PackageExtension.php
+++ /dev/null
@@ -1,173 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Twig;
-
-use JMS\DiExtraBundle\Annotation\Inject;
-use JMS\DiExtraBundle\Annotation\InjectParams;
-use JMS\DiExtraBundle\Annotation\Service;
-use JMS\DiExtraBundle\Annotation\Tag;
-use Symfony\Component\Translation\TranslatorInterface;
-use Symfony\Component\HttpKernel\KernelInterface;
-use Claroline\CoreBundle\Library\Utilities\FileSystem;
-
-/**
- * @Service
- * @Tag("twig.extension")
- */
-class PackageExtension extends \Twig_Extension
-{
- private $vendorPath;
- private $translator;
-
- /**
- * @InjectParams({
- * "vendorPath" = @Inject("%claroline.param.vendor_directory%"),
- * "translator" = @Inject("translator")
- * })
- */
- public function __construct($vendorPath, $translator)
- {
- $this->vendorPath = $vendorPath;
- $this->translator = $translator;
- }
-
- public function getFunctions()
- {
- return array(
- 'is_installation_requirement_satisfied' => new \Twig_Function_Method($this, 'isPackageInstallable'),
- 'render_package_missing_permissions' => new \Twig_Function_Method($this, 'renderMissingPermissions'),
- 'render_package_missing_require' => new \Twig_Function_Method($this, 'renderMissingRequire')
- );
- }
-
- public function getName()
- {
- return 'package_extension';
- }
-
- public function isPackageInstallable($basePath, $requirements = null)
- {
- $fs = new FileSystem();
- $fullPath = realpath($this->vendorPath . '/' . $basePath);
- $basePath = realpath($this->vendorPath . '/' . substr($basePath, 0, strrpos($basePath, '/')));
- $requirementsMet = true;
- $isWritable = true;
-
- if ($fullPath && $basePath) {
- $isWritable = $fs->isWritable($fullPath, true) & is_writable($basePath);
- } else {
- if ($fullPath) $isWritable = is_writable($fullPath);
- if ($basePath) $isWritable = is_writable($basePath);
- }
-
- $missingsExtensions = $this->findMissingRequireExtensions($requirements);
- if (count($missingsExtensions) >= 1) $requirementsMet = false;
-
- $missingsBundles = $this->findMissingRequireBundle($requirements);
- if (count($missingsBundles) >= 1) $requirementsMet = false;
-
- return $isWritable & $requirementsMet;
- }
-
- public function renderMissingPermissions($basePath)
- {
- $fs = new FileSystem();
- $fullPath = realpath($this->vendorPath . '/' . $basePath);
- $basePath = realpath($this->vendorPath . '/' . substr($basePath, 0, strrpos($basePath, '/')));
- $fullPathElement = $basePathElement = '';
- $notWritable = $this->translator->trans('is_not_writable', array(), 'platform');
- $notWritableRecursive = $this->translator->trans('is_not_writable_recursive', array(), 'platform');
-
- if ($fullPath && !$fs->isWritable($fullPath, true)) {
- $fullPathElement = "" . $fullPath . ' ' . $notWritableRecursive . " ";
- }
-
- if (!is_writable($basePath) && $basePath) {
- $basePathElement = "" . $basePath . ' ' . $notWritable . " ";
- }
-
- $rendering = sprintf(
- '',
- $fullPathElement,
- $basePathElement
- );
-
- return $rendering;
- }
-
- public function renderMissingRequire($require = null)
- {
- $liExt = '';
- $liBundle = '';
- $missingExtensions = $this->findMissingRequireExtensions($require);
-
- foreach ($missingExtensions as $ext) {
- $arr = explode('ext-', $ext);
- $missingExtensionMsg = $this->translator->trans('ext_php_missing', array('%ext%' => $arr[1]), 'platform');
- $liExt .= sprintf("%s ", $missingExtensionMsg);
- }
-
- $missingBundles = $this->findMissingRequireBundle($require);
-
- foreach ($missingBundles as $bundle) {
- $missingExtensionMsg = $this->translator->trans('claroline_bundle_missing', array('%bundle%' => $bundle), 'platform');
- $liExt .= sprintf("%s ", $missingExtensionMsg);
- }
-
- $rendering = sprintf(
- '',
- $liExt,
- $liBundle
- );
-
- return $rendering;
- }
-
- //do not support version yet...
- private function findMissingRequireExtensions($object)
- {
- $missings = array();
- if ($object === null) return $missings;
- $requires = get_object_vars($object);
-
- //check php extension...
- foreach ($requires as $require => $version) {
- if (strpos($require, 'ext-') === 0) {
- $arr = explode('ext-', $require);
- if (!extension_loaded($arr[1])) {
- $missings[] = $require;
- }
- }
- }
-
- return $missings;
- }
-
- private function findMissingRequireBundle($object)
- {
- $missings = array();
- if ($object === null) return $missings;
- $requires = get_object_vars($object);
-
- //check composer requirements...
- foreach ($requires as $require => $version) {
- if (strpos($require, 'ext-') !== 0 && strpos($require, 'php') !== 0) {
- //then we must check if the require is somewhere...
- if (!is_dir($this->vendorPath . '/' . $require)) {
- $missings[] = $require;
- }
- }
- }
-
- return $missings;
- }
-}
From d83b02ff8f1429716419339c9f4b3050fdb6ed6f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 22 Feb 2016 11:40:30 +0100
Subject: [PATCH 30/65] Disable web upgrade + remove operation file references
---
Command/DumpIniFileCommand.php | 51 ----
Command/PlatformUpdateCommand.php | 10 +-
.../scripts/operation_executor.php | 20 --
Resources/web/upgrade/authorize.php | 23 --
Resources/web/upgrade/libs.js | 98 -------
Resources/web/upgrade/libs.php | 102 -------
Resources/web/upgrade/maintenance.php | 13 -
Resources/web/upgrade/post_update.php | 157 -----------
Resources/web/upgrade/pre_update.php | 76 -----
Resources/web/upgrade/refresh.php | 16 --
Resources/web/upgrade/update_tool.php | 265 ------------------
11 files changed, 5 insertions(+), 826 deletions(-)
delete mode 100644 Command/DumpIniFileCommand.php
delete mode 100755 Library/Installation/scripts/operation_executor.php
delete mode 100644 Resources/web/upgrade/authorize.php
delete mode 100644 Resources/web/upgrade/libs.js
delete mode 100644 Resources/web/upgrade/libs.php
delete mode 100644 Resources/web/upgrade/maintenance.php
delete mode 100644 Resources/web/upgrade/post_update.php
delete mode 100644 Resources/web/upgrade/pre_update.php
delete mode 100644 Resources/web/upgrade/refresh.php
delete mode 100644 Resources/web/upgrade/update_tool.php
diff --git a/Command/DumpIniFileCommand.php b/Command/DumpIniFileCommand.php
deleted file mode 100644
index 0d57615f5..000000000
--- a/Command/DumpIniFileCommand.php
+++ /dev/null
@@ -1,51 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Claroline\CoreBundle\Command;
-
-use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
-use Symfony\Component\Console\Input\InputArgument;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Output\OutputInterface;
-use Symfony\Component\Console\Input\InputOption;
-use Claroline\CoreBundle\Entity\User;
-use Claroline\CoreBundle\Library\Security\PlatformRoles;
-use Claroline\BundleRecorder\Handler\OperationHandler;
-use Claroline\BundleRecorder\Detector\Detector;
-use Claroline\BundleRecorder\Handler\BundleHandler;
-use Claroline\BundleRecorder\Recorder;
-
-/**
- * Creates an user, optionaly with a specific role (default to simple user).
- */
-class DumpIniFileCommand extends ContainerAwareCommand
-{
- protected function configure()
- {
- $this->setName('claroline:ini_file:dump')
- ->setDescription('Dump the ini file.');
- $this->setDefinition(array());
- }
-
- protected function execute(InputInterface $input, OutputInterface $output)
- {
- $vendorDir = $this->getContainer()->getParameter('claroline.param.vendor_directory');
- $configDir = $this->getContainer()->getParameter('kernel.root_dir') . '/config';
- $recorder = new Recorder(
- new Detector($vendorDir),
- new BundleHandler($configDir . '/bundles.ini'),
- new OperationHandler($configDir . '/operations.xml'),
- $vendorDir
- );
-
- $recorder->buildBundleFile();
- }
-}
diff --git a/Command/PlatformUpdateCommand.php b/Command/PlatformUpdateCommand.php
index 16d957842..1b62d9666 100644
--- a/Command/PlatformUpdateCommand.php
+++ b/Command/PlatformUpdateCommand.php
@@ -25,9 +25,10 @@
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
- * Updates, installs or uninstalls the core and plugin bundles, following
- * the operation order logged in *app/config/operations.xml* during
- * composer execution.
+ * Updates, installs or uninstalls core and plugin bundles, based
+ * on the comparison of packages previously and currently installed
+ * by composer (vendor/composer/installed.json and
+ * app/config/previous-installed.json).
*
* @Service("claroline.command.update_command")
*/
@@ -38,8 +39,7 @@ protected function configure()
parent::configure();
$this->setName('claroline:update')
->setDescription(
- 'Updates, installs or uninstalls the platform packages '
- . 'brought by composer (requires an operation file).'
+ 'Updates, installs or uninstalls the platform packages brought by composer.'
);
}
diff --git a/Library/Installation/scripts/operation_executor.php b/Library/Installation/scripts/operation_executor.php
deleted file mode 100755
index b19cc16a7..000000000
--- a/Library/Installation/scripts/operation_executor.php
+++ /dev/null
@@ -1,20 +0,0 @@
-loadClassCache();
-$kernel->boot();
-$container = $kernel->getContainer();
-$bundleManager = $container->get('claroline.manager.bundle_manager');
-$bundleManager->executeOperationFile($argv[1]);
diff --git a/Resources/web/upgrade/authorize.php b/Resources/web/upgrade/authorize.php
deleted file mode 100644
index 8faa7d827..000000000
--- a/Resources/web/upgrade/authorize.php
+++ /dev/null
@@ -1,23 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-$maintenanceMode = file_exists(__DIR__ . '/../../app/config/.update');
-$authorized = false;
-
-if (file_exists($file = __DIR__ . '/../../app/config/ips')) {
- $authorizedIps = file($file, FILE_IGNORE_NEW_LINES);
- $authorized = in_array($_SERVER['REMOTE_ADDR'], $authorizedIps);
-}
-
-if (!$authorized) {
- $url = $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '/../../app.php';
- header("Location: http://{$url}");
-}
\ No newline at end of file
diff --git a/Resources/web/upgrade/libs.js b/Resources/web/upgrade/libs.js
deleted file mode 100644
index ddca07ec3..000000000
--- a/Resources/web/upgrade/libs.js
+++ /dev/null
@@ -1,98 +0,0 @@
-//translator class
-var Translator = function () {
- this.translations = {
- 'fr': {
- 'backup_title': 'Creation d\'un backup',
- 'backup_content': 'Avant de continuer, nous vous conseillons d\'effectuer une sauvegarde de votre plateforme (fichiers et base de données).',
- 'activate_maintenance_title': 'Activation du mode maintenance',
- 'activate_maintenance_content': 'Cliquez sur exécuter pour activer le mode maintenance. Ceci créera un fichier .update dans votre répertoire app/config. Vous pouvez quitter ce mode en supprimant ce fichier manuellement ou dans l\'administration.',
- 'pre_update_title': 'Initialisation de la base de données',
- 'pre_update_content': 'Cliquez sur exécuter pour lancer le script d\'initialisation de la base de données.',
- 'replace_vendor_title': 'Remplacement des vendors',
- 'replace_vendor_content': 'Veuillez remplacer le dossier vendor de votre application.',
- 'post_update_title': 'Exécution de la mise à jour',
- 'post_update': 'Cliquez sur exécuter pour lancer le script de mise à jour. Le paramètre MEMORY_LIMIT du php.ini doit être supérieur à 512M.',
- 'disable_maintenance_title': 'Désactivation du mode maintenance',
- 'disable_maintenance_content': 'Cliquez sur exécuter pour désactiver le mode mainteance.',
- 'maintenance_enabled': 'Mode maintenance activé',
- 'database_updated': 'Version des paquets mise à jour',
- 'upgrade_executed': 'Mise à jour exécutée',
- 'maintenance_disabled': 'Mode maintenance désactivé'
- },
- 'en': {
- 'backup_title': 'Backup creation',
- 'backup_content': 'A backup (files and database) should be done before going further.',
- 'activate_maintenance_title': 'Maintenance activation',
- 'activate_maintenance_content': 'Press execute to active the maintenance mode. This will create a .update file in your app/config directory. You can disable this mode by manually removing the file or in the administration.',
- 'pre_update_title': 'Database initialization',
- 'pre_update_content': 'Press execute to initialize the database.',
- 'replace_vendor_title': 'Vendors replacement',
- 'replace_vendor_content': 'Please replace the vendor directory of your application.',
- 'post_update_title': 'Upgrade execution',
- 'post_update_content': 'Press execute to start the upgrade script. The php MEMORY_LIMIT parameter MUST be above 512M.',
- 'disable_maintenance_title': 'Disabling maintenance',
- 'disable_maintenance_content': 'Press execute to disable the maintenance mode.',
- 'maintenance_enabled': 'Maintenance mode enabled',
- 'database_updated': 'Packages versions updated',
- 'upgrade_executed': 'Upgrade executed',
- 'maintenance_disabled': 'Maintenance mode disabled'
- }
- };
- this.locale = 'en';
-};
-
-Translator.prototype.translate = function(translationKey) {
- return this.translations[this.locale][translationKey] || translationKey;
-};
-
-Translator.prototype.setLocale = function(locale) {
- this.locale = locale;
-};
-
-/********************************************************************/
-
-//logDisplayer class
-var LogDisplayer = function(logWindow) {
- this.logWindow = $(logWindow);
- this.logFile = undefined;
- this.url = undefined;
- //base64 spinning wheel
- this.inlineLoadingImg = ' ';
-};
-
-LogDisplayer.prototype.pollStatus = function () {
- $.ajax(this.url).done((function (data) {
- data += this.inlineLoadingImg;
- this.logWindow.html(data);
- this.tail();
- }).bind(this));
-};
-
-LogDisplayer.prototype.setLogFile = function(logFile) {
- this.logFile = logFile;
- //maybe this shouldn't be done here but w/e
- this.url = this.logWindow.attr('data-url') + '?logFile=' + logFile;
-}
-
-LogDisplayer.prototype.start = function() {
- this.pollStatus();
- this.refresh = setInterval((function () {
- this.pollStatus();
- }).bind(this), 2000);
-};
-
-LogDisplayer.prototype.stop = function () {
- clearInterval(this.refresh);
-}
-
-LogDisplayer.prototype.end = function() {
- this.stop();
- $.ajax(this.url).done((function (data) {
- this.logWindow.html(data);
- this.tail();
- }).bind(this));
-}
-
-LogDisplayer.prototype.tail = function() {
- this.logWindow.animate({ scrollTop: this.logWindow[0].scrollHeight });
-}
diff --git a/Resources/web/upgrade/libs.php b/Resources/web/upgrade/libs.php
deleted file mode 100644
index 128244ab3..000000000
--- a/Resources/web/upgrade/libs.php
+++ /dev/null
@@ -1,102 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-class Translator
-{
- private static $initialized = false;
- private static $translations = array();
-
- public static function translate($key, $language = null) {
- if (!self::$initialized) self::init();
- if (!$language) $language = isset($_GET['_locale']) ? $_GET['_locale']: 'en';
- echo isset(self::$translations[$language][$key]) ? self::$translations[$language][$key]: $key;
- }
-
- public static function init()
- {
- $en = array(
- 'upgrade_tool' => 'Upgrade tool',
- 'upgrade_steps' => 'Upgrade steps',
- 'create_backup' => 'Backup creation',
- 'activate_maintenance_mode' => 'Maintenance activation',
- 'bundle_table_initialization' => 'Database initialization',
- 'vendor_replacement' => 'Vendor replacement',
- 'executing_migrations' => 'Upgrade execution',
- 'remove_maintenance_mode' => 'Disabling maintenance',
- 'start' => 'Start',
- 'return' => 'Return',
- 'close' => 'Close',
- 'debug_mode' => 'Debug mode',
- 'debug_mode_explanation' => 'The debug mode allows you to execute the update operations in an arbitrary order.'
- );
-
- $fr = array(
- 'upgrade_tool' => 'Outil de mise à jour',
- 'upgrade_steps' => 'Étapes de la mise à jour',
- 'create_backup' => 'Creation d\'un backup',
- 'activate_maintenance_mode' => 'Activation du mode maintenance',
- 'bundle_table_initialization' => 'Initialisation de la base de donnée',
- 'vendor_replacement' => 'Remplacement du dossier vendor',
- 'executing_migrations' => 'Exécution de la mise à jour',
- 'remove_maintenance_mode' => 'Désactivation du mode maintenance',
- 'start' => 'Commencer',
- 'return' => 'Retour',
- 'close' => 'Fermer',
- 'debug_mode' => 'Mode de debug',
- 'debug_mode_explanation' => 'Le mode de debug vous permet d\'exécuter les opérations de mise à jour dans un ordre arbitraire.'
- );
-
- $es = array(
- 'return' => 'Regresar',
- 'close' => 'Cerrar'
- );
-
- self::$translations = array(
- 'fr' => $fr,
- 'en' => $en,
- 'es' => $es
- );
-
- self::$initialized = true;
- }
-}
-
-class FileManager
-{
- /**
- * http://stackoverflow.com/questions/1653771/how-do-i-remove-a-directory-that-is-not-empty
- * @param $dir
- * @return bool
- */
- public static function deleteDirectory($dir)
- {
- if (!file_exists($dir)) {
- return true;
- }
-
- if (!is_dir($dir)) {
- return unlink($dir);
- }
-
- foreach (scandir($dir) as $item) {
- if ($item == '.' || $item == '..') {
- continue;
- }
-
- if (self::deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
- return false;
- }
-
- }
-
- return rmdir($dir);
- }
-}
diff --git a/Resources/web/upgrade/maintenance.php b/Resources/web/upgrade/maintenance.php
deleted file mode 100644
index b484ed2eb..000000000
--- a/Resources/web/upgrade/maintenance.php
+++ /dev/null
@@ -1,13 +0,0 @@
-buildBundleFile();
-
-$kernel = new AppKernel('prod', false);
-$kernel->loadClassCache();
-//I need to do that in order to access some services required for the installation...
-$kernel->boot();
-
-$bundles = array();
-
-//retrieve the current bundles
-foreach ($recorder->getOperations() as $operation) {
- $package = $operation->getPackage();
- if ($package->getType() === 'claroline-plugin' ||
- $package->getType() === 'claroline-core') {
- $bundles[] = array(
- 'type' => $package->getType(),
- 'name' => $package->getPrettyName(),
- 'new_version' => $package->getVersion(),
- 'is_installed' => false,
- 'fqcn' => $detector->detectBundle($package->getPrettyName()),
- 'dependencies' => array($recorder->getDependencies($package))
- );
- }
-}
-
-//retrieve the already installed bundles
-$sql = "SELECT * from `claro_bundle`";
-$res = $conn->query($sql);
-
-$operations = [];
-
-foreach ($res->fetchAll() as $installedBundle) {
- foreach ($bundles as &$bundle) {
- if ($bundle['name'] === $installedBundle['name']) {
- $bundle['is_installed'] = true;
- $bundle['old_version'] = $installedBundle['version'];
- }
- }
- //removing last ref
- unset($bundle);
-}
-
-//generating the operations.xml file
-foreach ($bundles as $bundle) {
- $operation = new Operation(
- $bundle['is_installed'] ? Operation::UPDATE: Operation::INSTALL,
- $bundle['fqcn'],
- $bundle['type'] === 'claroline-plugin' ? Operation::BUNDLE_PLUGIN: Operation::BUNDLE_CORE
- );
-
- if (isset($bundle['old_version'])) {
- $operation->setFromVersion($bundle['old_version']);
- }
-
- $operation->setToVersion($bundle['new_version']);
- $operation->setDependencies($bundle['dependencies']);
- $operationHandler->addOperation($operation, false);
-}
-
-//Build the bundle file
-$recorder->buildBundleFile();
-
-//reboot the kernel for the new bundle file
-$kernel->shutdown();
-$kernel->boot();
-
-//install from the operation file
-$container = $kernel->getContainer();
- /** @var \Claroline\CoreBundle\Library\Installation\PlatformInstaller $installer */
-$installer = $container->get('claroline.installation.platform_installer');
-
-//assets & assetic dump
-$installer->installFromOperationFile();
- /** @var \Claroline\CoreBundle\Library\Installation\Refresher $refresher */
-$refresher = $container->get('claroline.installation.refresher');
-$output = new StreamOutput(fopen($logFile, 'a', false));
-$verbosityLevelMap = array(
- LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
- LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL,
- LogLevel::DEBUG => OutputInterface::VERBOSITY_NORMAL
-);
-$consoleLogger = new ConsoleLogger($output, $verbosityLevelMap);
-$installer->setLogger($consoleLogger);
-
-$refresher->setOutput($output);
-$refresher->installAssets();
-$refresher->dumpAssets($container->getParameter('kernel.environment'));
-$installer->setBundleVersion();
-
-$logLine = "Done\n";
-file_put_contents($logFile, $logLine, FILE_APPEND);
-
-exit(0);
diff --git a/Resources/web/upgrade/pre_update.php b/Resources/web/upgrade/pre_update.php
deleted file mode 100644
index 7fe31ef2e..000000000
--- a/Resources/web/upgrade/pre_update.php
+++ /dev/null
@@ -1,76 +0,0 @@
-query($query);
-
-//create the table if it doesn't
-$sql = "CREATE TABLE claro_bundle (
- id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- name VARCHAR(100),
- version VARCHAR(50)
-)";
-
-$logLine = $conn->query($sql) ?
- "Creating table claro_bundle...\n":
- "Table claro_bundle already exists.\n";
-touch($logFile);
-file_put_contents($logFile, $logLine, FILE_APPEND);
-
-//update the table
-$ds = DIRECTORY_SEPARATOR;
-$jsonFile = "{$vendorDir}/composer/installed.json";
-$data = json_decode(file_get_contents($jsonFile));
-
-foreach ($data as $row) {
- if ($row->type === 'claroline-plugin' || $row->type === 'claroline-core') {
- $name = $row->name;
- $version = $row->version;
- //let's find if there is something in the database !
- $sql = "SELECT * from `claro_bundle` where `name` LIKE \"{$name}\"";
- $res = $conn->query($sql);
-
- if (count($res->fetchAll()) > 0) {
- $sql = "UPDATE `claro_bundle` set version='{$version}'
- where `name` LIKE \"{$name}\"";
- $conn->query($sql);
- $logLine = "Updating {$name} to the current version ({$version})\n";
- } else {
- //insert
- $sql = "INSERT into claro_bundle (name, version)
- VALUES('{$name}', '{$version}')";
- $conn->query($sql);
- $logLine = "Inserting {$name} to the current version ({$version})\n";
- }
-
- file_put_contents($logFile, $logLine, FILE_APPEND);
- }
-}
-
-$logLine = "Done !\n";
-file_put_contents($logFile, $logLine, FILE_APPEND);
diff --git a/Resources/web/upgrade/refresh.php b/Resources/web/upgrade/refresh.php
deleted file mode 100644
index becdc7ac8..000000000
--- a/Resources/web/upgrade/refresh.php
+++ /dev/null
@@ -1,16 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-include __DIR__ . '/authorize.php';
-
-$logFile = $_GET['logFile'];
-$file = '../../app/logs/' . $logFile;
-echo @file_get_contents($file);
diff --git a/Resources/web/upgrade/update_tool.php b/Resources/web/upgrade/update_tool.php
deleted file mode 100644
index 229fcae84..000000000
--- a/Resources/web/upgrade/update_tool.php
+++ /dev/null
@@ -1,265 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-include __DIR__ . '/authorize.php';
-include __DIR__ . '/libs.php';
-
-$vendorDir = __DIR__ . "/../../vendor";
-
-?>
-
-
-
-
-
- Claroline upgrader
-
-
-
-
-
-
-
-
-
- '>
-
-
-
-
-
-
-
-
-
-
-
(beta)
-
-
-
-
-
-
-
-
-
- 1 -
- 2 -
- 3 -
- 4 -
- 5 -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
From da8ff0b3b023e4376f9e4df14107d7d7c039270b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 22 Feb 2016 12:11:38 +0100
Subject: [PATCH 31/65] Partially restore bundle manager
---
Controller/LayoutController.php | 4 +-
Manager/BundleManager.php | 78 +++++++++++++++++++++++++
Resources/views/Layout/footer.html.twig | 3 +-
3 files changed, 81 insertions(+), 4 deletions(-)
create mode 100644 Manager/BundleManager.php
diff --git a/Controller/LayoutController.php b/Controller/LayoutController.php
index c7304f110..cf2dc377f 100644
--- a/Controller/LayoutController.php
+++ b/Controller/LayoutController.php
@@ -104,8 +104,8 @@ public function headerAction()
*/
public function footerAction()
{
- //for some reason this doesn't work unless we use the cache:warm command. Since it's annoying
- //and that I can't find why, we retrieve the version the old fashioned way;
+ // TODO: replace core bundle version by distribution version when available
+ // TODO: find the lightest way to get that information
$bundleManager = $this->get('claroline.manager.bundle_manager');
$version = $bundleManager->getCoreBundleVersion();
diff --git a/Manager/BundleManager.php b/Manager/BundleManager.php
new file mode 100644
index 000000000..384e8ecff
--- /dev/null
+++ b/Manager/BundleManager.php
@@ -0,0 +1,78 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Claroline\CoreBundle\Manager;
+
+use Composer\Json\JsonFile;
+use Composer\Repository\InstalledFilesystemRepository;
+use JMS\DiExtraBundle\Annotation as DI;
+
+/**
+ * @DI\Service("claroline.manager.bundle_manager")
+ */
+class BundleManager
+{
+ private $iniFileManager;
+ private $kernelRootDir;
+
+ /**
+ * @DI\InjectParams({
+ * "iniFileManager" = @DI\Inject("claroline.manager.ini_file_manager"),
+ * "kernelRootDir" = @DI\Inject("%kernel.root_dir%")
+ * })
+ */
+ public function __construct(IniFileManager $iniFileManager, $kernelRootDir)
+ {
+ $this->iniFileManager = $iniFileManager;
+ $this->kernelRootDir = $kernelRootDir;
+ }
+
+ public function getCoreBundleVersion()
+ {
+ $installedFile = $this->kernelRootDir . '/../vendor/composer/installed.json';
+ $repo = new InstalledFilesystemRepository(new JsonFile($installedFile));
+ $corePackage = $repo->findPackage('claroline/core-bundle', '*');
+
+ return $corePackage->getPrettyVersion();
+ }
+
+ public function updateIniFile($vendor, $bundle)
+ {
+ $iniFile = $this->kernelRootDir . '/config/bundles.ini';
+
+ //update ini file
+ $this->iniFileManager
+ ->updateKey(
+ $vendor . '\\' . $bundle . 'Bundle\\' . $vendor . $bundle . 'Bundle',
+ true,
+ $iniFile
+ );
+ }
+
+ public function updateAutoload($ivendor, $ibundle, $vname, $bname)
+ {
+ //update namespace file
+ $namespaces = $this->kernelRootDir . '/../vendor/composer/autoload_namespaces.php';
+ $content = file_get_contents($namespaces);
+ $lineToAdd = "\n '{$ivendor}\\\\{$ibundle}Bundle' => array(\$vendorDir . '/{$vname}/{$bname}'),";
+
+ if (!strpos($content, $lineToAdd)) {
+ //add the correct line after corebundle...
+ $content = str_replace(
+ "/core-bundle'),",
+ "/core-bundle'), {$lineToAdd}",
+ $content
+ );
+
+ file_put_contents($namespaces, $content);
+ }
+ }
+}
diff --git a/Resources/views/Layout/footer.html.twig b/Resources/views/Layout/footer.html.twig
index 94a7c800b..98bd55906 100644
--- a/Resources/views/Layout/footer.html.twig
+++ b/Resources/views/Layout/footer.html.twig
@@ -25,9 +25,8 @@
{% if not footerMessage is empty %}{{ footerMessage|raw }}{% endif %}
- {{ 'powered_by' | trans({}, 'platform') }} Claroline (v{{ coreVersion }})
+ {{ 'powered_by' | trans({}, 'platform') }} Claroline ({{ coreVersion }})
-
From 928c0e44c6c7457e14371759a53d8c74bfc2a3c3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Klein?=
Date: Mon, 22 Feb 2016 13:36:41 +0100
Subject: [PATCH 32/65] Point to bower packages dir instead of front bundle
---
Resources/public/js/tinymce/tinymce.js | 10 +++---
.../Analytics/analytics.html.twig | 16 +++++-----
.../Analytics/analytics_connections.html.twig | 14 ++++----
.../HomeTab/adminHomeTabsConfig.html.twig | 10 +++---
.../Parameters/generalForm.html.twig | 4 +--
Resources/views/Exception/layout.html.twig | 4 +--
Resources/views/Form/date_range.html.twig | 8 ++---
Resources/views/Form/select2.html.twig | 6 ++--
.../views/Form/simple_auto_complete.html.twig | 2 +-
.../views/Form/two_level_select.html.twig | 2 +-
Resources/views/Home/home.html.twig | 2 +-
Resources/views/Install/layout.html.twig | 2 +-
Resources/views/Layout/javascripts.html.twig | 32 +++++++++----------
.../Layout/javascripts_headers.html.twig | 2 +-
Resources/views/Layout/stylesheets.html.twig | 12 +++----
.../views/Log/count_by_day_chart.html.twig | 14 ++++----
.../Log/resource_by_type_chart.html.twig | 8 ++---
Resources/views/Log/view_user_list.html.twig | 16 +++++-----
.../desktop/home/desktopHomeLayout.html.twig | 10 +++---
.../parameters/userOptionsEditForm.html.twig | 4 +--
.../resource_manager/resources.html.twig | 2 +-
.../workspace/analytics/resources.html.twig | 14 ++++----
.../home/workspaceHomeLayout.html.twig | 10 +++---
.../workspaceDisplayEditForm.html.twig | 4 +--
.../resource_manager/resources.html.twig | 2 +-
Resources/views/Widget/embed/widget.html.twig | 4 +--
Resources/views/layout.html.twig | 2 +-
27 files changed, 108 insertions(+), 108 deletions(-)
diff --git a/Resources/public/js/tinymce/tinymce.js b/Resources/public/js/tinymce/tinymce.js
index 7f90d4852..f4bcbf891 100644
--- a/Resources/public/js/tinymce/tinymce.js
+++ b/Resources/public/js/tinymce/tinymce.js
@@ -19,12 +19,12 @@
var routing = window.Routing;
//Load external plugins
- tinymce.PluginManager.load('mention', home.asset + 'bundles/frontend/claroline-tinymce-mention/plugin.min.js');
- tinymce.PluginManager.load('accordion', home.asset + 'bundles/frontend/claroline-tinymce-accordion/plugin.min.js');
- tinymce.PluginManager.load('codemirror', home.asset + 'bundles/frontend/tinymce-codemirror/plugins/codemirror/plugin.min.js');
- tinymce.DOM.loadCSS(home.asset + 'bundles/frontend/claroline-tinymce-mention/css/autocomplete.css');
+ tinymce.PluginManager.load('mention', home.asset + 'packages/claroline-tinymce-mention/plugin.min.js');
+ tinymce.PluginManager.load('accordion', home.asset + 'packages/claroline-tinymce-accordion/plugin.min.js');
+ tinymce.PluginManager.load('codemirror', home.asset + 'packages/tinymce-codemirror/plugins/codemirror/plugin.min.js');
+ tinymce.DOM.loadCSS(home.asset + 'packages/claroline-tinymce-mention/css/autocomplete.css');
- var codemirrorPath = home.asset + 'bundles/frontend/tinymce-codemirror/plugins/codemirror/codemirror-4.8';
+ var codemirrorPath = home.asset + 'packages/tinymce-codemirror/plugins/codemirror/codemirror-4.8';
/**
* Claroline TinyMCE parameters and methods.
diff --git a/Resources/views/Administration/Analytics/analytics.html.twig b/Resources/views/Administration/Analytics/analytics.html.twig
index 02d8f5984..8fb50a91a 100644
--- a/Resources/views/Administration/Analytics/analytics.html.twig
+++ b/Resources/views/Administration/Analytics/analytics.html.twig
@@ -145,16 +145,16 @@
{% block javascripts %}
{{ parent() }}
-
+
{% javascripts debug=false filter='jsmin' output='js/corebundle/jqplot.analytics.min.js'
'bundles/clarolinecore/js/jqplot/jqplot.colors.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.highlighter.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.pieRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.barRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.highlighter.js'
+ 'packages/jqPlot/src/plugins/jqplot.pieRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.barRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
%}
{% endjavascripts %}
diff --git a/Resources/views/Administration/Analytics/analytics_connections.html.twig b/Resources/views/Administration/Analytics/analytics_connections.html.twig
index bf85aab6a..c60bab683 100644
--- a/Resources/views/Administration/Analytics/analytics_connections.html.twig
+++ b/Resources/views/Administration/Analytics/analytics_connections.html.twig
@@ -78,15 +78,15 @@
{% block javascripts %}
{{ parent() }}
-
+
{% javascripts debug=false filter='jsmin' output='js/corebundle/jqplot.analytics-connections.min.js'
'bundles/clarolinecore/js/jqplot/jqplot.colors.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.highlighter.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.cursor.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.highlighter.js'
+ 'packages/jqPlot/src/plugins/jqplot.cursor.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
%}
{% endjavascripts %}
diff --git a/Resources/views/Administration/HomeTab/adminHomeTabsConfig.html.twig b/Resources/views/Administration/HomeTab/adminHomeTabsConfig.html.twig
index 95091598c..aed968589 100644
--- a/Resources/views/Administration/HomeTab/adminHomeTabsConfig.html.twig
+++ b/Resources/views/Administration/HomeTab/adminHomeTabsConfig.html.twig
@@ -198,15 +198,15 @@
{% block javascripts %}
{{ parent() }}
-
-
-
@@ -220,11 +220,11 @@
{{ parent() }}
{% endblock %}
@@ -104,7 +104,7 @@
})(jQuery);
+
{% endblock %}
{% block favicon %}
diff --git a/Resources/views/Form/date_range.html.twig b/Resources/views/Form/date_range.html.twig
index ef30183d1..b0ba4af80 100644
--- a/Resources/views/Form/date_range.html.twig
+++ b/Resources/views/Form/date_range.html.twig
@@ -7,10 +7,10 @@
{% block daterange_assets %}
-
-
-
-
+
+
+
+
{% endblock %}
+
+
+
{{ block('choice_widget') }}
diff --git a/Resources/views/Form/simple_auto_complete.html.twig b/Resources/views/Form/simple_auto_complete.html.twig
index 73ed24d4a..de987cf88 100644
--- a/Resources/views/Form/simple_auto_complete.html.twig
+++ b/Resources/views/Form/simple_auto_complete.html.twig
@@ -5,7 +5,7 @@
{% block simpleautocomplete_assets %}
{% if with_vendors %}
-
+
{% endif %}
{% endblock %}
diff --git a/Resources/views/Form/two_level_select.html.twig b/Resources/views/Form/two_level_select.html.twig
index fe35cab6a..989188ffa 100644
--- a/Resources/views/Form/two_level_select.html.twig
+++ b/Resources/views/Form/two_level_select.html.twig
@@ -44,6 +44,6 @@
return preselectedValuePath;
}
-
+
{% endspaceless %}
{% endblock %}
diff --git a/Resources/views/Home/home.html.twig b/Resources/views/Home/home.html.twig
index c68d5e435..87de45a31 100644
--- a/Resources/views/Home/home.html.twig
+++ b/Resources/views/Home/home.html.twig
@@ -78,7 +78,7 @@
{% block javascripts %}
{{ parent() }}
-
+
{% if is_granted('ROLE_HOME_MANAGER') %}
diff --git a/Resources/views/Install/layout.html.twig b/Resources/views/Install/layout.html.twig
index 5a51a4441..005b8aa46 100644
--- a/Resources/views/Install/layout.html.twig
+++ b/Resources/views/Install/layout.html.twig
@@ -3,7 +3,7 @@
{% set themePath = 'themes/' ~ config.getParameter('theme') %}
{% block stylesheets %}
-
+
{% endblock %}
{% block favicon %}
diff --git a/Resources/views/Layout/javascripts.html.twig b/Resources/views/Layout/javascripts.html.twig
index bd576f530..a106a2e1d 100644
--- a/Resources/views/Layout/javascripts.html.twig
+++ b/Resources/views/Layout/javascripts.html.twig
@@ -64,10 +64,10 @@
{# TODO: remove this when custom js builds are available #}
{% javascripts debug=false filter='jsmin' output='vendor/jquery/ui/jqueryui.js'
- 'bundles/frontend/jquery-ui/ui/core.js'
- 'bundles/frontend/jquery-ui/ui/widget.js'
- 'bundles/frontend/jquery-ui/ui/mouse.js'
- 'bundles/frontend/jquery-ui/ui/sortable.js'
+ 'packages/jquery-ui/ui/core.js'
+ 'packages/jquery-ui/ui/widget.js'
+ 'packages/jquery-ui/ui/mouse.js'
+ 'packages/jquery-ui/ui/sortable.js'
%}
{% endjavascripts %}
@@ -83,13 +83,13 @@
-
+
{% if 'en' != app.request.locale %}
-
+
{% endif %}
-
-
+
+
{% javascripts debug=false filter='jsmin' output='vendor/claroline/js/libraries.js'
'bundles/clarolinecore/js/common.js'
@@ -126,19 +126,19 @@
{# Angular JS #}
{% javascripts debug=false filter='jsmin' output='vendor/angular.js'
- 'bundles/frontend/angular/angular.min.js'
- 'bundles/frontend/angular-route/angular-route.min.js'
+ 'packages/angular/angular.min.js'
+ 'packages/angular-route/angular-route.min.js'
%}
{% endjavascripts %}
{# Angular UI #}
{% javascripts debug=false filter='jsmin' output='vendor/angular-ui.js'
- 'bundles/frontend/angular-ui-tree/dist/angular-ui-tree.js'
- 'bundles/frontend/angular-ui-select/dist/select.min.js'
- 'bundles/frontend/angular-data-table/release/dataTable.helpers.min.js'
- 'bundles/frontend/angular-breadcrumb/dist/angular-breadcrumb.min.js'
- 'bundles/frontend/angular-ui-router/release/angular-ui-router.min.js'
- 'bundles/frontend/angular-sanitize/angular-sanitize.min.js'
+ 'packages/angular-ui-tree/dist/angular-ui-tree.js'
+ 'packages/angular-ui-select/dist/select.min.js'
+ 'packages/angular-data-table/release/dataTable.helpers.min.js'
+ 'packages/angular-breadcrumb/dist/angular-breadcrumb.min.js'
+ 'packages/angular-ui-router/release/angular-ui-router.min.js'
+ 'packages/angular-sanitize/angular-sanitize.min.js'
%}
{% endjavascripts %}
diff --git a/Resources/views/Layout/javascripts_headers.html.twig b/Resources/views/Layout/javascripts_headers.html.twig
index 46750a93c..2fabe5e3a 100644
--- a/Resources/views/Layout/javascripts_headers.html.twig
+++ b/Resources/views/Layout/javascripts_headers.html.twig
@@ -1 +1 @@
-
+
diff --git a/Resources/views/Layout/stylesheets.html.twig b/Resources/views/Layout/stylesheets.html.twig
index 8bbd0c058..fa2ec27d9 100644
--- a/Resources/views/Layout/stylesheets.html.twig
+++ b/Resources/views/Layout/stylesheets.html.twig
@@ -13,15 +13,15 @@
{# Angular UI #}
{% stylesheets debug=false output='vendor/angular-ui.css'
- 'bundles/frontend/angular-ui-tree/dist/angular-ui-tree.min.css'
- 'bundles/frontend/angular-data-table/release/dataTable.css'
- 'bundles/frontend/angular-data-table/release/material.css'
+ 'packages/angular-ui-tree/dist/angular-ui-tree.min.css'
+ 'packages/angular-data-table/release/dataTable.css'
+ 'packages/angular-data-table/release/material.css'
'bundles/clarolinecore/css/common/angular-ui-tree.css'
- 'bundles/frontend/angular-ui-select/dist/select.min.css'
+ 'packages/angular-ui-select/dist/select.min.css'
'bundles/clarolinecore/css/common/select.css'
%}
{% endstylesheets %}
-
-
+
+
diff --git a/Resources/views/Log/count_by_day_chart.html.twig b/Resources/views/Log/count_by_day_chart.html.twig
index dd0718c8e..cda287916 100644
--- a/Resources/views/Log/count_by_day_chart.html.twig
+++ b/Resources/views/Log/count_by_day_chart.html.twig
@@ -14,15 +14,15 @@
{% if not app.request.isXmlHttpRequest() %}
-
+
{% javascripts debug=false filter='jsmin' output='js/corebundle/jqplot.count-by-day.min.js'
'bundles/clarolinecore/js/jqplot/jqplot.colors.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.highlighter.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.cursor.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.highlighter.js'
+ 'packages/jqPlot/src/plugins/jqplot.cursor.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
%}
{% endjavascripts %}
diff --git a/Resources/views/Log/resource_by_type_chart.html.twig b/Resources/views/Log/resource_by_type_chart.html.twig
index d79bb0594..8f6bc1285 100644
--- a/Resources/views/Log/resource_by_type_chart.html.twig
+++ b/Resources/views/Log/resource_by_type_chart.html.twig
@@ -10,12 +10,12 @@
{% if filesImported is not defined or filesImported is empty %}
-
+
-
-
+
+
{% else %}
-
+
{% endif %}
diff --git a/Resources/views/Log/view_user_list.html.twig b/Resources/views/Log/view_user_list.html.twig
index f832066b1..fd28e3e67 100644
--- a/Resources/views/Log/view_user_list.html.twig
+++ b/Resources/views/Log/view_user_list.html.twig
@@ -28,16 +28,16 @@
-
+
{% javascripts debug=false filter='jsmin' output='js/corebundle/jqplot.view-user-list.min.js'
'bundles/clarolinecore/js/jqplot/jqplot.colors.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.highlighter.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.barRenderer.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.cursor.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
-'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
+'packages/jqPlot/src/plugins/jqplot.highlighter.js'
+'packages/jqPlot/src/plugins/jqplot.barRenderer.js'
+'packages/jqPlot/src/plugins/jqplot.cursor.js'
+'packages/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
+'packages/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
+'packages/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
+'packages/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
%}
{% endjavascripts %}
diff --git a/Resources/views/Tool/desktop/home/desktopHomeLayout.html.twig b/Resources/views/Tool/desktop/home/desktopHomeLayout.html.twig
index cf5d67756..88fae3a24 100644
--- a/Resources/views/Tool/desktop/home/desktopHomeLayout.html.twig
+++ b/Resources/views/Tool/desktop/home/desktopHomeLayout.html.twig
@@ -102,15 +102,15 @@
{% block javascripts %}
{{ parent() }}
-
-
-
@@ -143,11 +143,11 @@
{{ parent() }}
@@ -62,6 +62,6 @@
{{ parent() }}
{% endblock %}
diff --git a/Resources/views/Tool/desktop/resource_manager/resources.html.twig b/Resources/views/Tool/desktop/resource_manager/resources.html.twig
index 687d9608b..be6f85ed6 100644
--- a/Resources/views/Tool/desktop/resource_manager/resources.html.twig
+++ b/Resources/views/Tool/desktop/resource_manager/resources.html.twig
@@ -71,6 +71,6 @@
-
+
{% endblock %}
diff --git a/Resources/views/Tool/workspace/analytics/resources.html.twig b/Resources/views/Tool/workspace/analytics/resources.html.twig
index 7d701c744..d8cbacb30 100644
--- a/Resources/views/Tool/workspace/analytics/resources.html.twig
+++ b/Resources/views/Tool/workspace/analytics/resources.html.twig
@@ -23,15 +23,15 @@
{% if 0 < resourceCount|length %}
-
+
{% javascripts debug=false filter='jsmin' output='js/corebundle/jqplot.resources.min.js'
'bundles/clarolinecore/js/jqplot/jqplot.colors.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.highlighter.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.cursor.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
- 'bundles/frontend/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.highlighter.js'
+ 'packages/jqPlot/src/plugins/jqplot.cursor.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasTextRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.dateAxisRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisTickRenderer.js'
+ 'packages/jqPlot/src/plugins/jqplot.canvasAxisLabelRenderer.js'
%}
{% endjavascripts %}
diff --git a/Resources/views/Tool/workspace/home/workspaceHomeLayout.html.twig b/Resources/views/Tool/workspace/home/workspaceHomeLayout.html.twig
index 96afa0439..03546605c 100644
--- a/Resources/views/Tool/workspace/home/workspaceHomeLayout.html.twig
+++ b/Resources/views/Tool/workspace/home/workspaceHomeLayout.html.twig
@@ -93,11 +93,11 @@
{% block javascripts %}
{{ parent() }}
-
-
@@ -109,7 +109,7 @@
{% if canEdit %}
-
@@ -129,7 +129,7 @@
{{ parent() }}
{% endif %}
{% endblock %}
diff --git a/Resources/views/Tool/workspace/parameters/workspaceDisplayEditForm.html.twig b/Resources/views/Tool/workspace/parameters/workspaceDisplayEditForm.html.twig
index 176c1d46b..dfc20e3b0 100644
--- a/Resources/views/Tool/workspace/parameters/workspaceDisplayEditForm.html.twig
+++ b/Resources/views/Tool/workspace/parameters/workspaceDisplayEditForm.html.twig
@@ -53,7 +53,7 @@
{% block javascripts %}
{{ parent() }}
-
@@ -67,6 +67,6 @@
{{ parent() }}
{% endblock %}
diff --git a/Resources/views/Tool/workspace/resource_manager/resources.html.twig b/Resources/views/Tool/workspace/resource_manager/resources.html.twig
index 74329efdb..9bb5bcf08 100644
--- a/Resources/views/Tool/workspace/resource_manager/resources.html.twig
+++ b/Resources/views/Tool/workspace/resource_manager/resources.html.twig
@@ -76,6 +76,6 @@
-
+
{% endblock %}
diff --git a/Resources/views/Widget/embed/widget.html.twig b/Resources/views/Widget/embed/widget.html.twig
index 54dd7b55f..90cbcd78b 100644
--- a/Resources/views/Widget/embed/widget.html.twig
+++ b/Resources/views/Widget/embed/widget.html.twig
@@ -5,7 +5,7 @@
{% endif %}
-
+