Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
core/Command/L10n/CreateJs.php 1 patch
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -36,134 +36,134 @@
 block discarded – undo
36 36
 
37 37
 class CreateJs extends Command implements CompletionAwareInterface {
38 38
 
39
-	protected function configure() {
40
-		$this
41
-			->setName('l10n:createjs')
42
-			->setDescription('Create javascript translation files for a given app')
43
-			->addArgument(
44
-				'app',
45
-				InputOption::VALUE_REQUIRED,
46
-				'name of the app'
47
-			)
48
-			->addArgument(
49
-				'lang',
50
-				InputOption::VALUE_OPTIONAL,
51
-				'name of the language'
52
-			);
53
-	}
54
-
55
-	protected function execute(InputInterface $input, OutputInterface $output) {
56
-		$app = $input->getArgument('app');
57
-		$lang = $input->getArgument('lang');
58
-
59
-		$path = \OC_App::getAppPath($app);
60
-		if ($path === false) {
61
-			$output->writeln("The app <$app> is unknown.");
62
-			return;
63
-		}
64
-		$languages = $lang;
65
-		if (empty($lang)) {
66
-			$languages= $this->getAllLanguages($path);
67
-		}
68
-
69
-		foreach($languages as $lang) {
70
-			$this->writeFiles($app, $path, $lang, $output);
71
-		}
72
-	}
73
-
74
-	private function getAllLanguages($path) {
75
-		$result = [];
76
-		foreach (new DirectoryIterator("$path/l10n") as $fileInfo) {
77
-			if($fileInfo->isDot()) {
78
-				continue;
79
-			}
80
-			if($fileInfo->isDir()) {
81
-				continue;
82
-			}
83
-			if($fileInfo->getExtension() !== 'php') {
84
-				continue;
85
-			}
86
-			$result[]= substr($fileInfo->getBasename(), 0, -4);
87
-		}
88
-
89
-		return $result;
90
-	}
91
-
92
-	private function writeFiles($app, $path, $lang, OutputInterface $output) {
93
-		list($translations, $plurals) = $this->loadTranslations($path, $lang);
94
-		$this->writeJsFile($app, $path, $lang, $output, $translations, $plurals);
95
-		$this->writeJsonFile($path, $lang, $output, $translations, $plurals);
96
-	}
97
-
98
-	private function writeJsFile($app, $path, $lang, OutputInterface $output, $translations, $plurals) {
99
-		$jsFile = "$path/l10n/$lang.js";
100
-		if (file_exists($jsFile)) {
101
-			$output->writeln("File already exists: $jsFile");
102
-			return;
103
-		}
104
-		$content = "OC.L10N.register(\n    \"$app\",\n    {\n    ";
105
-		$jsTrans = [];
106
-		foreach ($translations as $id => $val) {
107
-			if (is_array($val)) {
108
-				$val = '[ ' . implode(',', $val) . ']';
109
-			}
110
-			$jsTrans[] = "\"$id\" : \"$val\"";
111
-		}
112
-		$content .= implode(",\n    ", $jsTrans);
113
-		$content .= "\n},\n\"$plurals\");\n";
114
-
115
-		file_put_contents($jsFile, $content);
116
-		$output->writeln("Javascript translation file generated: $jsFile");
117
-	}
118
-
119
-	private function writeJsonFile($path, $lang, OutputInterface $output, $translations, $plurals) {
120
-		$jsFile = "$path/l10n/$lang.json";
121
-		if (file_exists($jsFile)) {
122
-			$output->writeln("File already exists: $jsFile");
123
-			return;
124
-		}
125
-		$content = ['translations' => $translations, 'pluralForm' => $plurals];
126
-		file_put_contents($jsFile, json_encode($content));
127
-		$output->writeln("Json translation file generated: $jsFile");
128
-	}
129
-
130
-	private function loadTranslations($path, $lang) {
131
-		$phpFile = "$path/l10n/$lang.php";
132
-		$TRANSLATIONS = [];
133
-		$PLURAL_FORMS = '';
134
-		if (!file_exists($phpFile)) {
135
-			throw new UnexpectedValueException("PHP translation file <$phpFile> does not exist.");
136
-		}
137
-		require $phpFile;
138
-
139
-		return [$TRANSLATIONS, $PLURAL_FORMS];
140
-	}
141
-
142
-	/**
143
-	 * Return possible values for the named option
144
-	 *
145
-	 * @param string $optionName
146
-	 * @param CompletionContext $context
147
-	 * @return string[]
148
-	 */
149
-	public function completeOptionValues($optionName, CompletionContext $context) {
150
-		return [];
151
-	}
152
-
153
-	/**
154
-	 * Return possible values for the named argument
155
-	 *
156
-	 * @param string $argumentName
157
-	 * @param CompletionContext $context
158
-	 * @return string[]
159
-	 */
160
-	public function completeArgumentValues($argumentName, CompletionContext $context) {
161
-		if ($argumentName === 'app') {
162
-			return \OC_App::getAllApps();
163
-		} else if ($argumentName === 'lang') {
164
-			$appName = $context->getWordAtIndex($context->getWordIndex() - 1);
165
-			return $this->getAllLanguages(\OC_App::getAppPath($appName));
166
-		}
167
-		return [];
168
-	}
39
+    protected function configure() {
40
+        $this
41
+            ->setName('l10n:createjs')
42
+            ->setDescription('Create javascript translation files for a given app')
43
+            ->addArgument(
44
+                'app',
45
+                InputOption::VALUE_REQUIRED,
46
+                'name of the app'
47
+            )
48
+            ->addArgument(
49
+                'lang',
50
+                InputOption::VALUE_OPTIONAL,
51
+                'name of the language'
52
+            );
53
+    }
54
+
55
+    protected function execute(InputInterface $input, OutputInterface $output) {
56
+        $app = $input->getArgument('app');
57
+        $lang = $input->getArgument('lang');
58
+
59
+        $path = \OC_App::getAppPath($app);
60
+        if ($path === false) {
61
+            $output->writeln("The app <$app> is unknown.");
62
+            return;
63
+        }
64
+        $languages = $lang;
65
+        if (empty($lang)) {
66
+            $languages= $this->getAllLanguages($path);
67
+        }
68
+
69
+        foreach($languages as $lang) {
70
+            $this->writeFiles($app, $path, $lang, $output);
71
+        }
72
+    }
73
+
74
+    private function getAllLanguages($path) {
75
+        $result = [];
76
+        foreach (new DirectoryIterator("$path/l10n") as $fileInfo) {
77
+            if($fileInfo->isDot()) {
78
+                continue;
79
+            }
80
+            if($fileInfo->isDir()) {
81
+                continue;
82
+            }
83
+            if($fileInfo->getExtension() !== 'php') {
84
+                continue;
85
+            }
86
+            $result[]= substr($fileInfo->getBasename(), 0, -4);
87
+        }
88
+
89
+        return $result;
90
+    }
91
+
92
+    private function writeFiles($app, $path, $lang, OutputInterface $output) {
93
+        list($translations, $plurals) = $this->loadTranslations($path, $lang);
94
+        $this->writeJsFile($app, $path, $lang, $output, $translations, $plurals);
95
+        $this->writeJsonFile($path, $lang, $output, $translations, $plurals);
96
+    }
97
+
98
+    private function writeJsFile($app, $path, $lang, OutputInterface $output, $translations, $plurals) {
99
+        $jsFile = "$path/l10n/$lang.js";
100
+        if (file_exists($jsFile)) {
101
+            $output->writeln("File already exists: $jsFile");
102
+            return;
103
+        }
104
+        $content = "OC.L10N.register(\n    \"$app\",\n    {\n    ";
105
+        $jsTrans = [];
106
+        foreach ($translations as $id => $val) {
107
+            if (is_array($val)) {
108
+                $val = '[ ' . implode(',', $val) . ']';
109
+            }
110
+            $jsTrans[] = "\"$id\" : \"$val\"";
111
+        }
112
+        $content .= implode(",\n    ", $jsTrans);
113
+        $content .= "\n},\n\"$plurals\");\n";
114
+
115
+        file_put_contents($jsFile, $content);
116
+        $output->writeln("Javascript translation file generated: $jsFile");
117
+    }
118
+
119
+    private function writeJsonFile($path, $lang, OutputInterface $output, $translations, $plurals) {
120
+        $jsFile = "$path/l10n/$lang.json";
121
+        if (file_exists($jsFile)) {
122
+            $output->writeln("File already exists: $jsFile");
123
+            return;
124
+        }
125
+        $content = ['translations' => $translations, 'pluralForm' => $plurals];
126
+        file_put_contents($jsFile, json_encode($content));
127
+        $output->writeln("Json translation file generated: $jsFile");
128
+    }
129
+
130
+    private function loadTranslations($path, $lang) {
131
+        $phpFile = "$path/l10n/$lang.php";
132
+        $TRANSLATIONS = [];
133
+        $PLURAL_FORMS = '';
134
+        if (!file_exists($phpFile)) {
135
+            throw new UnexpectedValueException("PHP translation file <$phpFile> does not exist.");
136
+        }
137
+        require $phpFile;
138
+
139
+        return [$TRANSLATIONS, $PLURAL_FORMS];
140
+    }
141
+
142
+    /**
143
+     * Return possible values for the named option
144
+     *
145
+     * @param string $optionName
146
+     * @param CompletionContext $context
147
+     * @return string[]
148
+     */
149
+    public function completeOptionValues($optionName, CompletionContext $context) {
150
+        return [];
151
+    }
152
+
153
+    /**
154
+     * Return possible values for the named argument
155
+     *
156
+     * @param string $argumentName
157
+     * @param CompletionContext $context
158
+     * @return string[]
159
+     */
160
+    public function completeArgumentValues($argumentName, CompletionContext $context) {
161
+        if ($argumentName === 'app') {
162
+            return \OC_App::getAllApps();
163
+        } else if ($argumentName === 'lang') {
164
+            $appName = $context->getWordAtIndex($context->getWordIndex() - 1);
165
+            return $this->getAllLanguages(\OC_App::getAppPath($appName));
166
+        }
167
+        return [];
168
+    }
169 169
 }
Please login to merge, or discard this patch.
core/Command/App/Update.php 1 patch
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -36,93 +36,93 @@
 block discarded – undo
36 36
 
37 37
 class Update extends Command {
38 38
 
39
-	/** @var IAppManager */
40
-	protected $manager;
41
-	/** @var Installer */
42
-	private $installer;
43
-	/** @var ILogger */
44
-	private $logger;
39
+    /** @var IAppManager */
40
+    protected $manager;
41
+    /** @var Installer */
42
+    private $installer;
43
+    /** @var ILogger */
44
+    private $logger;
45 45
 
46
-	/**
47
-	 * @param IAppManager $manager
48
-	 * @param Installer $installer
49
-	 */
50
-	public function __construct(IAppManager $manager, Installer $installer, ILogger $logger) {
51
-		parent::__construct();
52
-		$this->manager = $manager;
53
-		$this->installer = $installer;
54
-		$this->logger = $logger;
55
-	}
46
+    /**
47
+     * @param IAppManager $manager
48
+     * @param Installer $installer
49
+     */
50
+    public function __construct(IAppManager $manager, Installer $installer, ILogger $logger) {
51
+        parent::__construct();
52
+        $this->manager = $manager;
53
+        $this->installer = $installer;
54
+        $this->logger = $logger;
55
+    }
56 56
 
57
-	protected function configure() {
58
-		$this
59
-			->setName('app:update')
60
-			->setDescription('update an app or all apps')
61
-			->addArgument(
62
-				'app-id',
63
-				InputArgument::OPTIONAL,
64
-				'update the specified app'
65
-			)
66
-			->addOption(
67
-				'all',
68
-				null,
69
-				InputOption::VALUE_NONE,
70
-				'update all updatable apps'
71
-			)
72
-			->addOption(
73
-				'showonly',
74
-				null,
75
-				InputOption::VALUE_NONE,
76
-				'show update(s) without updating'
77
-			)
57
+    protected function configure() {
58
+        $this
59
+            ->setName('app:update')
60
+            ->setDescription('update an app or all apps')
61
+            ->addArgument(
62
+                'app-id',
63
+                InputArgument::OPTIONAL,
64
+                'update the specified app'
65
+            )
66
+            ->addOption(
67
+                'all',
68
+                null,
69
+                InputOption::VALUE_NONE,
70
+                'update all updatable apps'
71
+            )
72
+            ->addOption(
73
+                'showonly',
74
+                null,
75
+                InputOption::VALUE_NONE,
76
+                'show update(s) without updating'
77
+            )
78 78
 
79
-		;
80
-	}
79
+        ;
80
+    }
81 81
 
82
-	protected function execute(InputInterface $input, OutputInterface $output) {
83
-		$singleAppId = $input->getArgument('app-id');
82
+    protected function execute(InputInterface $input, OutputInterface $output) {
83
+        $singleAppId = $input->getArgument('app-id');
84 84
 
85
-		if ($singleAppId) {
86
-			$apps = [$singleAppId];
87
-			try {
88
-				$this->manager->getAppPath($singleAppId);
89
-			} catch (\OCP\App\AppPathNotFoundException $e) {
90
-				$output->writeln($singleAppId . ' not installed');
91
-				return 1;
92
-			}
85
+        if ($singleAppId) {
86
+            $apps = [$singleAppId];
87
+            try {
88
+                $this->manager->getAppPath($singleAppId);
89
+            } catch (\OCP\App\AppPathNotFoundException $e) {
90
+                $output->writeln($singleAppId . ' not installed');
91
+                return 1;
92
+            }
93 93
 
94
-		} else if ($input->getOption('all') || $input->getOption('showonly')) {
95
-			$apps = \OC_App::getAllApps();
96
-		} else {
97
-			$output->writeln("<error>Please specify an app to update or \"--all\" to update all updatable apps\"</error>");
98
-			return 1;
99
-		}
94
+        } else if ($input->getOption('all') || $input->getOption('showonly')) {
95
+            $apps = \OC_App::getAllApps();
96
+        } else {
97
+            $output->writeln("<error>Please specify an app to update or \"--all\" to update all updatable apps\"</error>");
98
+            return 1;
99
+        }
100 100
 
101
-		$return = 0;
102
-		foreach ($apps as $appId) {
103
-			$newVersion = $this->installer->isUpdateAvailable($appId);
104
-			if ($newVersion) {
105
-				$output->writeln($appId . ' new version available: ' . $newVersion);
101
+        $return = 0;
102
+        foreach ($apps as $appId) {
103
+            $newVersion = $this->installer->isUpdateAvailable($appId);
104
+            if ($newVersion) {
105
+                $output->writeln($appId . ' new version available: ' . $newVersion);
106 106
 
107
-				if (!$input->getOption('showonly')) {
108
-					try {
109
-						$result = $this->installer->updateAppstoreApp($appId);
110
-					} catch(\Exception $e) {
111
-						$this->logger->logException($e, ['message' => 'Failure during update of app "' . $appId . '"','app' => 'app:update']);
112
-						$output->writeln('Error: ' . $e->getMessage());
113
-						$return = 1;
114
-					}
107
+                if (!$input->getOption('showonly')) {
108
+                    try {
109
+                        $result = $this->installer->updateAppstoreApp($appId);
110
+                    } catch(\Exception $e) {
111
+                        $this->logger->logException($e, ['message' => 'Failure during update of app "' . $appId . '"','app' => 'app:update']);
112
+                        $output->writeln('Error: ' . $e->getMessage());
113
+                        $return = 1;
114
+                    }
115 115
 
116
-					if ($result === false) {
117
-						$output->writeln($appId . ' couldn\'t be updated');
118
-						$return = 1;
119
-					} else if($result === true) {
120
-						$output->writeln($appId . ' updated');
121
-					}
122
-				}
123
-			}
124
-		}
116
+                    if ($result === false) {
117
+                        $output->writeln($appId . ' couldn\'t be updated');
118
+                        $return = 1;
119
+                    } else if($result === true) {
120
+                        $output->writeln($appId . ' updated');
121
+                    }
122
+                }
123
+            }
124
+        }
125 125
 
126
-		return $return;
127
-	}
126
+        return $return;
127
+    }
128 128
 }
Please login to merge, or discard this patch.
core/Command/Encryption/ListModules.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -30,69 +30,69 @@
 block discarded – undo
30 30
 use Symfony\Component\Console\Output\OutputInterface;
31 31
 
32 32
 class ListModules extends Base {
33
-	/** @var IManager */
34
-	protected $encryptionManager;
33
+    /** @var IManager */
34
+    protected $encryptionManager;
35 35
 
36
-	/** @var IConfig */
37
-	protected $config;
36
+    /** @var IConfig */
37
+    protected $config;
38 38
 
39
-	/**
40
-	 * @param IManager $encryptionManager
41
-	 * @param IConfig $config
42
-	 */
43
-	public function __construct(
44
-		IManager $encryptionManager,
45
-		IConfig $config
46
-	) {
47
-		parent::__construct();
48
-		$this->encryptionManager = $encryptionManager;
49
-		$this->config = $config;
50
-	}
39
+    /**
40
+     * @param IManager $encryptionManager
41
+     * @param IConfig $config
42
+     */
43
+    public function __construct(
44
+        IManager $encryptionManager,
45
+        IConfig $config
46
+    ) {
47
+        parent::__construct();
48
+        $this->encryptionManager = $encryptionManager;
49
+        $this->config = $config;
50
+    }
51 51
 
52
-	protected function configure() {
53
-		parent::configure();
52
+    protected function configure() {
53
+        parent::configure();
54 54
 
55
-		$this
56
-			->setName('encryption:list-modules')
57
-			->setDescription('List all available encryption modules')
58
-		;
59
-	}
55
+        $this
56
+            ->setName('encryption:list-modules')
57
+            ->setDescription('List all available encryption modules')
58
+        ;
59
+    }
60 60
 
61
-	protected function execute(InputInterface $input, OutputInterface $output) {
62
-		$isMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
63
-		if ($isMaintenanceModeEnabled) {
64
-			$output->writeln("Maintenance mode must be disabled when listing modules");
65
-			$output->writeln("in order to list the relevant encryption modules correctly.");
66
-			return;
67
-		}
61
+    protected function execute(InputInterface $input, OutputInterface $output) {
62
+        $isMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
63
+        if ($isMaintenanceModeEnabled) {
64
+            $output->writeln("Maintenance mode must be disabled when listing modules");
65
+            $output->writeln("in order to list the relevant encryption modules correctly.");
66
+            return;
67
+        }
68 68
 
69
-		$encryptionModules = $this->encryptionManager->getEncryptionModules();
70
-		$defaultEncryptionModuleId = $this->encryptionManager->getDefaultEncryptionModuleId();
69
+        $encryptionModules = $this->encryptionManager->getEncryptionModules();
70
+        $defaultEncryptionModuleId = $this->encryptionManager->getDefaultEncryptionModuleId();
71 71
 
72
-		$encModules = [];
73
-		foreach ($encryptionModules as $module) {
74
-			$encModules[$module['id']]['displayName'] = $module['displayName'];
75
-			$encModules[$module['id']]['default'] = $module['id'] === $defaultEncryptionModuleId;
76
-		}
77
-		$this->writeModuleList($input, $output, $encModules);
78
-	}
72
+        $encModules = [];
73
+        foreach ($encryptionModules as $module) {
74
+            $encModules[$module['id']]['displayName'] = $module['displayName'];
75
+            $encModules[$module['id']]['default'] = $module['id'] === $defaultEncryptionModuleId;
76
+        }
77
+        $this->writeModuleList($input, $output, $encModules);
78
+    }
79 79
 
80
-	/**
81
-	 * @param InputInterface $input
82
-	 * @param OutputInterface $output
83
-	 * @param array $items
84
-	 */
85
-	protected function writeModuleList(InputInterface $input, OutputInterface $output, $items) {
86
-		if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
87
-			array_walk($items, function(&$item) {
88
-				if (!$item['default']) {
89
-					$item = $item['displayName'];
90
-				} else {
91
-					$item = $item['displayName'] . ' [default*]';
92
-				}
93
-			});
94
-		}
80
+    /**
81
+     * @param InputInterface $input
82
+     * @param OutputInterface $output
83
+     * @param array $items
84
+     */
85
+    protected function writeModuleList(InputInterface $input, OutputInterface $output, $items) {
86
+        if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
87
+            array_walk($items, function(&$item) {
88
+                if (!$item['default']) {
89
+                    $item = $item['displayName'];
90
+                } else {
91
+                    $item = $item['displayName'] . ' [default*]';
92
+                }
93
+            });
94
+        }
95 95
 
96
-		$this->writeArrayInOutputFormat($input, $output, $items);
97
-	}
96
+        $this->writeArrayInOutputFormat($input, $output, $items);
97
+    }
98 98
 }
Please login to merge, or discard this patch.
core/templates/update.admin.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@
 block discarded – undo
4 4
 		<h2 class="title"><?php p($l->t('App update required')); ?></h2>
5 5
 		<?php } else { ?>
6 6
 		<h2 class="title"><?php p($l->t('%1$s will be updated to version %2$s',
7
-			[$_['productName'], $_['version']])); ?></h2>
7
+            [$_['productName'], $_['version']])); ?></h2>
8 8
 		<?php } ?>
9 9
 		<?php if (!empty($_['appsToUpgrade'])) { ?>
10 10
 		<div class="infogroup">
Please login to merge, or discard this patch.
core/Controller/SetupController.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -37,117 +37,117 @@
 block discarded – undo
37 37
 use function urlencode;
38 38
 
39 39
 class SetupController {
40
-	/** @var Setup */
41
-	protected $setupHelper;
42
-	/** @var string */
43
-	private $autoConfigFile;
44
-
45
-	/**
46
-	 * @param Setup $setupHelper
47
-	 */
48
-	function __construct(Setup $setupHelper) {
49
-		$this->autoConfigFile = \OC::$configDir.'autoconfig.php';
50
-		$this->setupHelper = $setupHelper;
51
-	}
52
-
53
-	/**
54
-	 * @param $post
55
-	 */
56
-	public function run($post) {
57
-		// Check for autosetup:
58
-		$post = $this->loadAutoConfig($post);
59
-		$opts = $this->setupHelper->getSystemInfo();
60
-
61
-		// convert 'abcpassword' to 'abcpass'
62
-		if (isset($post['adminpassword'])) {
63
-			$post['adminpass'] = $post['adminpassword'];
64
-		}
65
-		if (isset($post['dbpassword'])) {
66
-			$post['dbpass'] = $post['dbpassword'];
67
-		}
68
-
69
-		if (!is_file(\OC::$configDir.'/CAN_INSTALL')) {
70
-			$this->displaySetupForbidden();
71
-			return;
72
-		}
73
-
74
-		if(isset($post['install']) AND $post['install']=='true') {
75
-			// We have to launch the installation process :
76
-			$e = $this->setupHelper->install($post);
77
-			$errors = ['errors' => $e];
78
-
79
-			if(count($e) > 0) {
80
-				$options = array_merge($opts, $post, $errors);
81
-				$this->display($options);
82
-			} else {
83
-				$this->finishSetup(isset($post['install-recommended-apps']));
84
-			}
85
-		} else {
86
-			$options = array_merge($opts, $post);
87
-			$this->display($options);
88
-		}
89
-	}
90
-
91
-	private function displaySetupForbidden() {
92
-		\OC_Template::printGuestPage('', 'installation_forbidden');
93
-	}
94
-
95
-	public function display($post) {
96
-		$defaults = [
97
-			'adminlogin' => '',
98
-			'adminpass' => '',
99
-			'dbuser' => '',
100
-			'dbpass' => '',
101
-			'dbname' => '',
102
-			'dbtablespace' => '',
103
-			'dbhost' => 'localhost',
104
-			'dbtype' => '',
105
-		];
106
-		$parameters = array_merge($defaults, $post);
107
-
108
-		\OC_Util::addScript('setup');
109
-		\OC_Template::printGuestPage('', 'installation', $parameters);
110
-	}
111
-
112
-	private function finishSetup(bool $installRecommended) {
113
-		if( file_exists( $this->autoConfigFile )) {
114
-			unlink($this->autoConfigFile);
115
-		}
116
-		\OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
117
-
118
-		if (\OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL')) {
119
-			if (!unlink(\OC::$configDir.'/CAN_INSTALL')) {
120
-				\OC_Template::printGuestPage('', 'installation_incomplete');
121
-			}
122
-		}
123
-
124
-		if ($installRecommended) {
125
-			$urlGenerator = \OC::$server->getURLGenerator();
126
-			$location = $urlGenerator->getAbsoluteURL('index.php/core/apps/recommended');
127
-			header('Location: ' . $location);
128
-			exit();
129
-		}
130
-		\OC_Util::redirectToDefaultPage();
131
-	}
132
-
133
-	public function loadAutoConfig($post) {
134
-		if( file_exists($this->autoConfigFile)) {
135
-			\OCP\Util::writeLog('core', 'Autoconfig file found, setting up Nextcloud…', ILogger::INFO);
136
-			$AUTOCONFIG = [];
137
-			include $this->autoConfigFile;
138
-			$post = array_merge ($post, $AUTOCONFIG);
139
-		}
140
-
141
-		$dbIsSet = isset($post['dbtype']);
142
-		$directoryIsSet = isset($post['directory']);
143
-		$adminAccountIsSet = isset($post['adminlogin']);
144
-
145
-		if ($dbIsSet AND $directoryIsSet AND $adminAccountIsSet) {
146
-			$post['install'] = 'true';
147
-		}
148
-		$post['dbIsSet'] = $dbIsSet;
149
-		$post['directoryIsSet'] = $directoryIsSet;
150
-
151
-		return $post;
152
-	}
40
+    /** @var Setup */
41
+    protected $setupHelper;
42
+    /** @var string */
43
+    private $autoConfigFile;
44
+
45
+    /**
46
+     * @param Setup $setupHelper
47
+     */
48
+    function __construct(Setup $setupHelper) {
49
+        $this->autoConfigFile = \OC::$configDir.'autoconfig.php';
50
+        $this->setupHelper = $setupHelper;
51
+    }
52
+
53
+    /**
54
+     * @param $post
55
+     */
56
+    public function run($post) {
57
+        // Check for autosetup:
58
+        $post = $this->loadAutoConfig($post);
59
+        $opts = $this->setupHelper->getSystemInfo();
60
+
61
+        // convert 'abcpassword' to 'abcpass'
62
+        if (isset($post['adminpassword'])) {
63
+            $post['adminpass'] = $post['adminpassword'];
64
+        }
65
+        if (isset($post['dbpassword'])) {
66
+            $post['dbpass'] = $post['dbpassword'];
67
+        }
68
+
69
+        if (!is_file(\OC::$configDir.'/CAN_INSTALL')) {
70
+            $this->displaySetupForbidden();
71
+            return;
72
+        }
73
+
74
+        if(isset($post['install']) AND $post['install']=='true') {
75
+            // We have to launch the installation process :
76
+            $e = $this->setupHelper->install($post);
77
+            $errors = ['errors' => $e];
78
+
79
+            if(count($e) > 0) {
80
+                $options = array_merge($opts, $post, $errors);
81
+                $this->display($options);
82
+            } else {
83
+                $this->finishSetup(isset($post['install-recommended-apps']));
84
+            }
85
+        } else {
86
+            $options = array_merge($opts, $post);
87
+            $this->display($options);
88
+        }
89
+    }
90
+
91
+    private function displaySetupForbidden() {
92
+        \OC_Template::printGuestPage('', 'installation_forbidden');
93
+    }
94
+
95
+    public function display($post) {
96
+        $defaults = [
97
+            'adminlogin' => '',
98
+            'adminpass' => '',
99
+            'dbuser' => '',
100
+            'dbpass' => '',
101
+            'dbname' => '',
102
+            'dbtablespace' => '',
103
+            'dbhost' => 'localhost',
104
+            'dbtype' => '',
105
+        ];
106
+        $parameters = array_merge($defaults, $post);
107
+
108
+        \OC_Util::addScript('setup');
109
+        \OC_Template::printGuestPage('', 'installation', $parameters);
110
+    }
111
+
112
+    private function finishSetup(bool $installRecommended) {
113
+        if( file_exists( $this->autoConfigFile )) {
114
+            unlink($this->autoConfigFile);
115
+        }
116
+        \OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
117
+
118
+        if (\OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL')) {
119
+            if (!unlink(\OC::$configDir.'/CAN_INSTALL')) {
120
+                \OC_Template::printGuestPage('', 'installation_incomplete');
121
+            }
122
+        }
123
+
124
+        if ($installRecommended) {
125
+            $urlGenerator = \OC::$server->getURLGenerator();
126
+            $location = $urlGenerator->getAbsoluteURL('index.php/core/apps/recommended');
127
+            header('Location: ' . $location);
128
+            exit();
129
+        }
130
+        \OC_Util::redirectToDefaultPage();
131
+    }
132
+
133
+    public function loadAutoConfig($post) {
134
+        if( file_exists($this->autoConfigFile)) {
135
+            \OCP\Util::writeLog('core', 'Autoconfig file found, setting up Nextcloud…', ILogger::INFO);
136
+            $AUTOCONFIG = [];
137
+            include $this->autoConfigFile;
138
+            $post = array_merge ($post, $AUTOCONFIG);
139
+        }
140
+
141
+        $dbIsSet = isset($post['dbtype']);
142
+        $directoryIsSet = isset($post['directory']);
143
+        $adminAccountIsSet = isset($post['adminlogin']);
144
+
145
+        if ($dbIsSet AND $directoryIsSet AND $adminAccountIsSet) {
146
+            $post['install'] = 'true';
147
+        }
148
+        $post['dbIsSet'] = $dbIsSet;
149
+        $post['directoryIsSet'] = $directoryIsSet;
150
+
151
+        return $post;
152
+    }
153 153
 }
Please login to merge, or discard this patch.
core/Controller/UserController.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -30,46 +30,46 @@
 block discarded – undo
30 30
 use OCP\IUserManager;
31 31
 
32 32
 class UserController extends Controller {
33
-	/**
34
-	 * @var IUserManager
35
-	 */
36
-	protected $userManager;
33
+    /**
34
+     * @var IUserManager
35
+     */
36
+    protected $userManager;
37 37
 
38
-	public function __construct($appName,
39
-								IRequest $request,
40
-								IUserManager $userManager
41
-	) {
42
-		parent::__construct($appName, $request);
43
-		$this->userManager = $userManager;
44
-	}
38
+    public function __construct($appName,
39
+                                IRequest $request,
40
+                                IUserManager $userManager
41
+    ) {
42
+        parent::__construct($appName, $request);
43
+        $this->userManager = $userManager;
44
+    }
45 45
 
46
-	/**
47
-	 * Lookup user display names
48
-	 *
49
-	 * @NoAdminRequired
50
-	 *
51
-	 * @param array $users
52
-	 *
53
-	 * @return JSONResponse
54
-	 */
55
-	public function getDisplayNames($users) {
56
-		$result = [];
46
+    /**
47
+     * Lookup user display names
48
+     *
49
+     * @NoAdminRequired
50
+     *
51
+     * @param array $users
52
+     *
53
+     * @return JSONResponse
54
+     */
55
+    public function getDisplayNames($users) {
56
+        $result = [];
57 57
 
58
-		foreach ($users as $user) {
59
-			$userObject = $this->userManager->get($user);
60
-			if (is_object($userObject)) {
61
-				$result[$user] = $userObject->getDisplayName();
62
-			} else {
63
-				$result[$user] = $user;
64
-			}
65
-		}
58
+        foreach ($users as $user) {
59
+            $userObject = $this->userManager->get($user);
60
+            if (is_object($userObject)) {
61
+                $result[$user] = $userObject->getDisplayName();
62
+            } else {
63
+                $result[$user] = $user;
64
+            }
65
+        }
66 66
 
67
-		$json = [
68
-			'users' => $result,
69
-			'status' => 'success'
70
-		];
67
+        $json = [
68
+            'users' => $result,
69
+            'status' => 'success'
70
+        ];
71 71
 
72
-		return new JSONResponse($json);
72
+        return new JSONResponse($json);
73 73
 
74
-	}
74
+    }
75 75
 }
Please login to merge, or discard this patch.
core/Controller/OCSController.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -35,123 +35,123 @@
 block discarded – undo
35 35
 
36 36
 class OCSController extends \OCP\AppFramework\OCSController {
37 37
 
38
-	/** @var CapabilitiesManager */
39
-	private $capabilitiesManager;
40
-	/** @var IUserSession */
41
-	private $userSession;
42
-	/** @var IUserManager */
43
-	private $userManager;
44
-	/** @var Manager */
45
-	private $keyManager;
38
+    /** @var CapabilitiesManager */
39
+    private $capabilitiesManager;
40
+    /** @var IUserSession */
41
+    private $userSession;
42
+    /** @var IUserManager */
43
+    private $userManager;
44
+    /** @var Manager */
45
+    private $keyManager;
46 46
 
47
-	/**
48
-	 * OCSController constructor.
49
-	 *
50
-	 * @param string $appName
51
-	 * @param IRequest $request
52
-	 * @param CapabilitiesManager $capabilitiesManager
53
-	 * @param IUserSession $userSession
54
-	 * @param IUserManager $userManager
55
-	 * @param Manager $keyManager
56
-	 */
57
-	public function __construct($appName,
58
-								IRequest $request,
59
-								CapabilitiesManager $capabilitiesManager,
60
-								IUserSession $userSession,
61
-								IUserManager $userManager,
62
-								Manager $keyManager) {
63
-		parent::__construct($appName, $request);
64
-		$this->capabilitiesManager = $capabilitiesManager;
65
-		$this->userSession = $userSession;
66
-		$this->userManager = $userManager;
67
-		$this->keyManager = $keyManager;
68
-	}
47
+    /**
48
+     * OCSController constructor.
49
+     *
50
+     * @param string $appName
51
+     * @param IRequest $request
52
+     * @param CapabilitiesManager $capabilitiesManager
53
+     * @param IUserSession $userSession
54
+     * @param IUserManager $userManager
55
+     * @param Manager $keyManager
56
+     */
57
+    public function __construct($appName,
58
+                                IRequest $request,
59
+                                CapabilitiesManager $capabilitiesManager,
60
+                                IUserSession $userSession,
61
+                                IUserManager $userManager,
62
+                                Manager $keyManager) {
63
+        parent::__construct($appName, $request);
64
+        $this->capabilitiesManager = $capabilitiesManager;
65
+        $this->userSession = $userSession;
66
+        $this->userManager = $userManager;
67
+        $this->keyManager = $keyManager;
68
+    }
69 69
 
70
-	/**
71
-	 * @PublicPage
72
-	 *
73
-	 * @return DataResponse
74
-	 */
75
-	public function getConfig() {
76
-		$data = [
77
-			'version' => '1.7',
78
-			'website' => 'Nextcloud',
79
-			'host' => $this->request->getServerHost(),
80
-			'contact' => '',
81
-			'ssl' => 'false',
82
-		];
70
+    /**
71
+     * @PublicPage
72
+     *
73
+     * @return DataResponse
74
+     */
75
+    public function getConfig() {
76
+        $data = [
77
+            'version' => '1.7',
78
+            'website' => 'Nextcloud',
79
+            'host' => $this->request->getServerHost(),
80
+            'contact' => '',
81
+            'ssl' => 'false',
82
+        ];
83 83
 
84
-		return new DataResponse($data);
85
-	}
84
+        return new DataResponse($data);
85
+    }
86 86
 
87
-	/**
88
-	 * @PublicPage
89
-	 *
90
-	 * @return DataResponse
91
-	 */
92
-	public function getCapabilities() {
93
-		$result = [];
94
-		list($major, $minor, $micro) = \OCP\Util::getVersion();
95
-		$result['version'] = [
96
-			'major' => $major,
97
-			'minor' => $minor,
98
-			'micro' => $micro,
99
-			'string' => \OC_Util::getVersionString(),
100
-			'edition' => '',
101
-			'extendedSupport' => \OCP\Util::hasExtendedSupport()
102
-		];
87
+    /**
88
+     * @PublicPage
89
+     *
90
+     * @return DataResponse
91
+     */
92
+    public function getCapabilities() {
93
+        $result = [];
94
+        list($major, $minor, $micro) = \OCP\Util::getVersion();
95
+        $result['version'] = [
96
+            'major' => $major,
97
+            'minor' => $minor,
98
+            'micro' => $micro,
99
+            'string' => \OC_Util::getVersionString(),
100
+            'edition' => '',
101
+            'extendedSupport' => \OCP\Util::hasExtendedSupport()
102
+        ];
103 103
 
104
-		if($this->userSession->isLoggedIn()) {
105
-			$result['capabilities'] = $this->capabilitiesManager->getCapabilities();
106
-		} else {
107
-			$result['capabilities'] = $this->capabilitiesManager->getCapabilities(true);
108
-		}
104
+        if($this->userSession->isLoggedIn()) {
105
+            $result['capabilities'] = $this->capabilitiesManager->getCapabilities();
106
+        } else {
107
+            $result['capabilities'] = $this->capabilitiesManager->getCapabilities(true);
108
+        }
109 109
 
110
-		return new DataResponse($result);
111
-	}
110
+        return new DataResponse($result);
111
+    }
112 112
 
113
-	/**
114
-	 * @PublicPage
115
-	 * @BruteForceProtection(action=login)
116
-	 *
117
-	 * @param string $login
118
-	 * @param string $password
119
-	 * @return DataResponse
120
-	 */
121
-	public function personCheck($login = '', $password = '') {
122
-		if ($login !== '' && $password !== '') {
123
-			if ($this->userManager->checkPassword($login, $password)) {
124
-				return new DataResponse([
125
-					'person' => [
126
-						'personid' => $login
127
-					]
128
-				]);
129
-			}
113
+    /**
114
+     * @PublicPage
115
+     * @BruteForceProtection(action=login)
116
+     *
117
+     * @param string $login
118
+     * @param string $password
119
+     * @return DataResponse
120
+     */
121
+    public function personCheck($login = '', $password = '') {
122
+        if ($login !== '' && $password !== '') {
123
+            if ($this->userManager->checkPassword($login, $password)) {
124
+                return new DataResponse([
125
+                    'person' => [
126
+                        'personid' => $login
127
+                    ]
128
+                ]);
129
+            }
130 130
 
131
-			$response = new DataResponse([], 102);
132
-			$response->throttle();
133
-			return $response;
134
-		}
135
-		return new DataResponse([], 101);
136
-	}
131
+            $response = new DataResponse([], 102);
132
+            $response->throttle();
133
+            return $response;
134
+        }
135
+        return new DataResponse([], 101);
136
+    }
137 137
 
138
-	/**
139
-	 * @PublicPage
140
-	 *
141
-	 * @param string $cloudId
142
-	 * @return DataResponse
143
-	 */
144
-	public function getIdentityProof($cloudId) {
145
-		$userObject = $this->userManager->get($cloudId);
138
+    /**
139
+     * @PublicPage
140
+     *
141
+     * @param string $cloudId
142
+     * @return DataResponse
143
+     */
144
+    public function getIdentityProof($cloudId) {
145
+        $userObject = $this->userManager->get($cloudId);
146 146
 
147
-		if($userObject !== null) {
148
-			$key = $this->keyManager->getKey($userObject);
149
-			$data = [
150
-				'public' => $key->getPublic(),
151
-			];
152
-			return new DataResponse($data);
153
-		}
147
+        if($userObject !== null) {
148
+            $key = $this->keyManager->getKey($userObject);
149
+            $data = [
150
+                'public' => $key->getPublic(),
151
+            ];
152
+            return new DataResponse($data);
153
+        }
154 154
 
155
-		return new DataResponse(['User not found'], 404);
156
-	}
155
+        return new DataResponse(['User not found'], 404);
156
+    }
157 157
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 1 patch
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -69,348 +69,348 @@
 block discarded – undo
69 69
  * @package OC\Core\Controller
70 70
  */
71 71
 class LostController extends Controller {
72
-	/** @var IURLGenerator */
73
-	protected $urlGenerator;
74
-	/** @var IUserManager */
75
-	protected $userManager;
76
-	/** @var Defaults */
77
-	protected $defaults;
78
-	/** @var IL10N */
79
-	protected $l10n;
80
-	/** @var string */
81
-	protected $from;
82
-	/** @var IManager */
83
-	protected $encryptionManager;
84
-	/** @var IConfig */
85
-	protected $config;
86
-	/** @var ISecureRandom */
87
-	protected $secureRandom;
88
-	/** @var IMailer */
89
-	protected $mailer;
90
-	/** @var ITimeFactory */
91
-	protected $timeFactory;
92
-	/** @var ICrypto */
93
-	protected $crypto;
94
-	/** @var ILogger */
95
-	private $logger;
96
-	/** @var Manager */
97
-	private $twoFactorManager;
98
-	/** @var IInitialStateService */
99
-	private $initialStateService;
100
-
101
-	/**
102
-	 * @param string $appName
103
-	 * @param IRequest $request
104
-	 * @param IURLGenerator $urlGenerator
105
-	 * @param IUserManager $userManager
106
-	 * @param Defaults $defaults
107
-	 * @param IL10N $l10n
108
-	 * @param IConfig $config
109
-	 * @param ISecureRandom $secureRandom
110
-	 * @param string $defaultMailAddress
111
-	 * @param IManager $encryptionManager
112
-	 * @param IMailer $mailer
113
-	 * @param ITimeFactory $timeFactory
114
-	 * @param ICrypto $crypto
115
-	 */
116
-	public function __construct($appName,
117
-								IRequest $request,
118
-								IURLGenerator $urlGenerator,
119
-								IUserManager $userManager,
120
-								Defaults $defaults,
121
-								IL10N $l10n,
122
-								IConfig $config,
123
-								ISecureRandom $secureRandom,
124
-								$defaultMailAddress,
125
-								IManager $encryptionManager,
126
-								IMailer $mailer,
127
-								ITimeFactory $timeFactory,
128
-								ICrypto $crypto,
129
-								ILogger $logger,
130
-								Manager $twoFactorManager,
131
-								IInitialStateService $initialStateService) {
132
-		parent::__construct($appName, $request);
133
-		$this->urlGenerator = $urlGenerator;
134
-		$this->userManager = $userManager;
135
-		$this->defaults = $defaults;
136
-		$this->l10n = $l10n;
137
-		$this->secureRandom = $secureRandom;
138
-		$this->from = $defaultMailAddress;
139
-		$this->encryptionManager = $encryptionManager;
140
-		$this->config = $config;
141
-		$this->mailer = $mailer;
142
-		$this->timeFactory = $timeFactory;
143
-		$this->crypto = $crypto;
144
-		$this->logger = $logger;
145
-		$this->twoFactorManager = $twoFactorManager;
146
-		$this->initialStateService = $initialStateService;
147
-	}
148
-
149
-	/**
150
-	 * Someone wants to reset their password:
151
-	 *
152
-	 * @PublicPage
153
-	 * @NoCSRFRequired
154
-	 *
155
-	 * @param string $token
156
-	 * @param string $userId
157
-	 * @return TemplateResponse
158
-	 */
159
-	public function resetform($token, $userId) {
160
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
161
-			return new TemplateResponse('core', 'error', [
162
-					'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
163
-				],
164
-				'guest'
165
-			);
166
-		}
167
-
168
-		try {
169
-			$this->checkPasswordResetToken($token, $userId);
170
-		} catch (\Exception $e) {
171
-			return new TemplateResponse(
172
-				'core', 'error', [
173
-					"errors" => [["error" => $e->getMessage()]]
174
-				],
175
-				'guest'
176
-			);
177
-		}
178
-		$this->initialStateService->provideInitialState('core', 'resetPasswordUser', $userId);
179
-		$this->initialStateService->provideInitialState('core', 'resetPasswordTarget',
180
-			$this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', ['userId' => $userId, 'token' => $token])
181
-		);
182
-
183
-		return new TemplateResponse(
184
-			'core',
185
-			'login',
186
-			[],
187
-			'guest'
188
-		);
189
-	}
190
-
191
-	/**
192
-	 * @param string $token
193
-	 * @param string $userId
194
-	 * @throws \Exception
195
-	 */
196
-	protected function checkPasswordResetToken($token, $userId) {
197
-		$user = $this->userManager->get($userId);
198
-		if($user === null || !$user->isEnabled()) {
199
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
200
-		}
201
-
202
-		$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
203
-		if ($encryptedToken === null) {
204
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
205
-		}
206
-
207
-		try {
208
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
209
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
210
-		} catch (\Exception $e) {
211
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
212
-		}
213
-
214
-		$splittedToken = explode(':', $decryptedToken);
215
-		if(count($splittedToken) !== 2) {
216
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
217
-		}
218
-
219
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
220
-			$user->getLastLogin() > $splittedToken[0]) {
221
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
222
-		}
223
-
224
-		if (!hash_equals($splittedToken[1], $token)) {
225
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
226
-		}
227
-	}
228
-
229
-	/**
230
-	 * @param $message
231
-	 * @param array $additional
232
-	 * @return array
233
-	 */
234
-	private function error($message, array $additional=[]) {
235
-		return array_merge(['status' => 'error', 'msg' => $message], $additional);
236
-	}
237
-
238
-	/**
239
-	 * @param array $data
240
-	 * @return array
241
-	 */
242
-	private function success($data = []) {
243
-		return array_merge($data, ['status'=>'success']);
244
-	}
245
-
246
-	/**
247
-	 * @PublicPage
248
-	 * @BruteForceProtection(action=passwordResetEmail)
249
-	 * @AnonRateThrottle(limit=10, period=300)
250
-	 *
251
-	 * @param string $user
252
-	 * @return JSONResponse
253
-	 */
254
-	public function email($user){
255
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
256
-			return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
257
-		}
258
-
259
-		\OCP\Util::emitHook(
260
-			'\OCA\Files_Sharing\API\Server2Server',
261
-			'preLoginNameUsedAsUserName',
262
-			['uid' => &$user]
263
-		);
264
-
265
-		// FIXME: use HTTP error codes
266
-		try {
267
-			$this->sendEmail($user);
268
-		} catch (ResetPasswordException $e) {
269
-			// Ignore the error since we do not want to leak this info
270
-			$this->logger->warning('Could not send password reset email: ' . $e->getMessage());
271
-		} catch (\Exception $e) {
272
-			$this->logger->logException($e);
273
-		}
274
-
275
-		$response = new JSONResponse($this->success());
276
-		$response->throttle();
277
-		return $response;
278
-	}
279
-
280
-	/**
281
-	 * @PublicPage
282
-	 * @param string $token
283
-	 * @param string $userId
284
-	 * @param string $password
285
-	 * @param boolean $proceed
286
-	 * @return array
287
-	 */
288
-	public function setPassword($token, $userId, $password, $proceed) {
289
-		if ($this->config->getSystemValue('lost_password_link', '') !== '') {
290
-			return $this->error($this->l10n->t('Password reset is disabled'));
291
-		}
292
-
293
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
294
-			$encryptionModules = $this->encryptionManager->getEncryptionModules();
295
-			foreach ($encryptionModules as $module) {
296
-				/** @var IEncryptionModule $instance */
297
-				$instance = call_user_func($module['callback']);
298
-				// this way we can find out whether per-user keys are used or a system wide encryption key
299
-				if ($instance->needDetailedAccessList()) {
300
-					return $this->error('', ['encryption' => true]);
301
-				}
302
-			}
303
-		}
304
-
305
-		try {
306
-			$this->checkPasswordResetToken($token, $userId);
307
-			$user = $this->userManager->get($userId);
308
-
309
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]);
310
-
311
-			if (!$user->setPassword($password)) {
312
-				throw new \Exception();
313
-			}
314
-
315
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]);
316
-
317
-			$this->twoFactorManager->clearTwoFactorPending($userId);
318
-
319
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
320
-			@\OC::$server->getUserSession()->unsetMagicInCookie();
321
-		} catch (HintException $e){
322
-			return $this->error($e->getHint());
323
-		} catch (\Exception $e){
324
-			return $this->error($e->getMessage());
325
-		}
326
-
327
-		return $this->success(['user' => $userId]);
328
-	}
329
-
330
-	/**
331
-	 * @param string $input
332
-	 * @throws ResetPasswordException
333
-	 * @throws \OCP\PreConditionNotMetException
334
-	 */
335
-	protected function sendEmail($input) {
336
-		$user = $this->findUserByIdOrMail($input);
337
-		$email = $user->getEMailAddress();
338
-
339
-		if (empty($email)) {
340
-			throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input);
341
-		}
342
-
343
-		// Generate the token. It is stored encrypted in the database with the
344
-		// secret being the users' email address appended with the system secret.
345
-		// This makes the token automatically invalidate once the user changes
346
-		// their email address.
347
-		$token = $this->secureRandom->generate(
348
-			21,
349
-			ISecureRandom::CHAR_DIGITS.
350
-			ISecureRandom::CHAR_LOWER.
351
-			ISecureRandom::CHAR_UPPER
352
-		);
353
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
354
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
355
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
356
-
357
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
358
-
359
-		$emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
360
-			'link' => $link,
361
-		]);
362
-
363
-		$emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
364
-		$emailTemplate->addHeader();
365
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
366
-
367
-		$emailTemplate->addBodyText(
368
-			htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
369
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
370
-		);
371
-
372
-		$emailTemplate->addBodyButton(
373
-			htmlspecialchars($this->l10n->t('Reset your password')),
374
-			$link,
375
-			false
376
-		);
377
-		$emailTemplate->addFooter();
378
-
379
-		try {
380
-			$message = $this->mailer->createMessage();
381
-			$message->setTo([$email => $user->getUID()]);
382
-			$message->setFrom([$this->from => $this->defaults->getName()]);
383
-			$message->useTemplate($emailTemplate);
384
-			$this->mailer->send($message);
385
-		} catch (\Exception $e) {
386
-			// Log the exception and continue
387
-			$this->logger->logException($e);
388
-		}
389
-	}
390
-
391
-	/**
392
-	 * @param string $input
393
-	 * @return IUser
394
-	 * @throws ResetPasswordException
395
-	 */
396
-	protected function findUserByIdOrMail($input) {
397
-		$user = $this->userManager->get($input);
398
-		if ($user instanceof IUser) {
399
-			if (!$user->isEnabled()) {
400
-				throw new ResetPasswordException('User is disabled');
401
-			}
402
-
403
-			return $user;
404
-		}
405
-
406
-		$users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
407
-			return $user->isEnabled();
408
-		});
409
-
410
-		if (count($users) === 1) {
411
-			return reset($users);
412
-		}
413
-
414
-		throw new ResetPasswordException('Could not find user');
415
-	}
72
+    /** @var IURLGenerator */
73
+    protected $urlGenerator;
74
+    /** @var IUserManager */
75
+    protected $userManager;
76
+    /** @var Defaults */
77
+    protected $defaults;
78
+    /** @var IL10N */
79
+    protected $l10n;
80
+    /** @var string */
81
+    protected $from;
82
+    /** @var IManager */
83
+    protected $encryptionManager;
84
+    /** @var IConfig */
85
+    protected $config;
86
+    /** @var ISecureRandom */
87
+    protected $secureRandom;
88
+    /** @var IMailer */
89
+    protected $mailer;
90
+    /** @var ITimeFactory */
91
+    protected $timeFactory;
92
+    /** @var ICrypto */
93
+    protected $crypto;
94
+    /** @var ILogger */
95
+    private $logger;
96
+    /** @var Manager */
97
+    private $twoFactorManager;
98
+    /** @var IInitialStateService */
99
+    private $initialStateService;
100
+
101
+    /**
102
+     * @param string $appName
103
+     * @param IRequest $request
104
+     * @param IURLGenerator $urlGenerator
105
+     * @param IUserManager $userManager
106
+     * @param Defaults $defaults
107
+     * @param IL10N $l10n
108
+     * @param IConfig $config
109
+     * @param ISecureRandom $secureRandom
110
+     * @param string $defaultMailAddress
111
+     * @param IManager $encryptionManager
112
+     * @param IMailer $mailer
113
+     * @param ITimeFactory $timeFactory
114
+     * @param ICrypto $crypto
115
+     */
116
+    public function __construct($appName,
117
+                                IRequest $request,
118
+                                IURLGenerator $urlGenerator,
119
+                                IUserManager $userManager,
120
+                                Defaults $defaults,
121
+                                IL10N $l10n,
122
+                                IConfig $config,
123
+                                ISecureRandom $secureRandom,
124
+                                $defaultMailAddress,
125
+                                IManager $encryptionManager,
126
+                                IMailer $mailer,
127
+                                ITimeFactory $timeFactory,
128
+                                ICrypto $crypto,
129
+                                ILogger $logger,
130
+                                Manager $twoFactorManager,
131
+                                IInitialStateService $initialStateService) {
132
+        parent::__construct($appName, $request);
133
+        $this->urlGenerator = $urlGenerator;
134
+        $this->userManager = $userManager;
135
+        $this->defaults = $defaults;
136
+        $this->l10n = $l10n;
137
+        $this->secureRandom = $secureRandom;
138
+        $this->from = $defaultMailAddress;
139
+        $this->encryptionManager = $encryptionManager;
140
+        $this->config = $config;
141
+        $this->mailer = $mailer;
142
+        $this->timeFactory = $timeFactory;
143
+        $this->crypto = $crypto;
144
+        $this->logger = $logger;
145
+        $this->twoFactorManager = $twoFactorManager;
146
+        $this->initialStateService = $initialStateService;
147
+    }
148
+
149
+    /**
150
+     * Someone wants to reset their password:
151
+     *
152
+     * @PublicPage
153
+     * @NoCSRFRequired
154
+     *
155
+     * @param string $token
156
+     * @param string $userId
157
+     * @return TemplateResponse
158
+     */
159
+    public function resetform($token, $userId) {
160
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
161
+            return new TemplateResponse('core', 'error', [
162
+                    'errors' => [['error' => $this->l10n->t('Password reset is disabled')]]
163
+                ],
164
+                'guest'
165
+            );
166
+        }
167
+
168
+        try {
169
+            $this->checkPasswordResetToken($token, $userId);
170
+        } catch (\Exception $e) {
171
+            return new TemplateResponse(
172
+                'core', 'error', [
173
+                    "errors" => [["error" => $e->getMessage()]]
174
+                ],
175
+                'guest'
176
+            );
177
+        }
178
+        $this->initialStateService->provideInitialState('core', 'resetPasswordUser', $userId);
179
+        $this->initialStateService->provideInitialState('core', 'resetPasswordTarget',
180
+            $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', ['userId' => $userId, 'token' => $token])
181
+        );
182
+
183
+        return new TemplateResponse(
184
+            'core',
185
+            'login',
186
+            [],
187
+            'guest'
188
+        );
189
+    }
190
+
191
+    /**
192
+     * @param string $token
193
+     * @param string $userId
194
+     * @throws \Exception
195
+     */
196
+    protected function checkPasswordResetToken($token, $userId) {
197
+        $user = $this->userManager->get($userId);
198
+        if($user === null || !$user->isEnabled()) {
199
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
200
+        }
201
+
202
+        $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
203
+        if ($encryptedToken === null) {
204
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
205
+        }
206
+
207
+        try {
208
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
209
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
210
+        } catch (\Exception $e) {
211
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
212
+        }
213
+
214
+        $splittedToken = explode(':', $decryptedToken);
215
+        if(count($splittedToken) !== 2) {
216
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
217
+        }
218
+
219
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*24*7) ||
220
+            $user->getLastLogin() > $splittedToken[0]) {
221
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
222
+        }
223
+
224
+        if (!hash_equals($splittedToken[1], $token)) {
225
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
226
+        }
227
+    }
228
+
229
+    /**
230
+     * @param $message
231
+     * @param array $additional
232
+     * @return array
233
+     */
234
+    private function error($message, array $additional=[]) {
235
+        return array_merge(['status' => 'error', 'msg' => $message], $additional);
236
+    }
237
+
238
+    /**
239
+     * @param array $data
240
+     * @return array
241
+     */
242
+    private function success($data = []) {
243
+        return array_merge($data, ['status'=>'success']);
244
+    }
245
+
246
+    /**
247
+     * @PublicPage
248
+     * @BruteForceProtection(action=passwordResetEmail)
249
+     * @AnonRateThrottle(limit=10, period=300)
250
+     *
251
+     * @param string $user
252
+     * @return JSONResponse
253
+     */
254
+    public function email($user){
255
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
256
+            return new JSONResponse($this->error($this->l10n->t('Password reset is disabled')));
257
+        }
258
+
259
+        \OCP\Util::emitHook(
260
+            '\OCA\Files_Sharing\API\Server2Server',
261
+            'preLoginNameUsedAsUserName',
262
+            ['uid' => &$user]
263
+        );
264
+
265
+        // FIXME: use HTTP error codes
266
+        try {
267
+            $this->sendEmail($user);
268
+        } catch (ResetPasswordException $e) {
269
+            // Ignore the error since we do not want to leak this info
270
+            $this->logger->warning('Could not send password reset email: ' . $e->getMessage());
271
+        } catch (\Exception $e) {
272
+            $this->logger->logException($e);
273
+        }
274
+
275
+        $response = new JSONResponse($this->success());
276
+        $response->throttle();
277
+        return $response;
278
+    }
279
+
280
+    /**
281
+     * @PublicPage
282
+     * @param string $token
283
+     * @param string $userId
284
+     * @param string $password
285
+     * @param boolean $proceed
286
+     * @return array
287
+     */
288
+    public function setPassword($token, $userId, $password, $proceed) {
289
+        if ($this->config->getSystemValue('lost_password_link', '') !== '') {
290
+            return $this->error($this->l10n->t('Password reset is disabled'));
291
+        }
292
+
293
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
294
+            $encryptionModules = $this->encryptionManager->getEncryptionModules();
295
+            foreach ($encryptionModules as $module) {
296
+                /** @var IEncryptionModule $instance */
297
+                $instance = call_user_func($module['callback']);
298
+                // this way we can find out whether per-user keys are used or a system wide encryption key
299
+                if ($instance->needDetailedAccessList()) {
300
+                    return $this->error('', ['encryption' => true]);
301
+                }
302
+            }
303
+        }
304
+
305
+        try {
306
+            $this->checkPasswordResetToken($token, $userId);
307
+            $user = $this->userManager->get($userId);
308
+
309
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', ['uid' => $userId, 'password' => $password]);
310
+
311
+            if (!$user->setPassword($password)) {
312
+                throw new \Exception();
313
+            }
314
+
315
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', ['uid' => $userId, 'password' => $password]);
316
+
317
+            $this->twoFactorManager->clearTwoFactorPending($userId);
318
+
319
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
320
+            @\OC::$server->getUserSession()->unsetMagicInCookie();
321
+        } catch (HintException $e){
322
+            return $this->error($e->getHint());
323
+        } catch (\Exception $e){
324
+            return $this->error($e->getMessage());
325
+        }
326
+
327
+        return $this->success(['user' => $userId]);
328
+    }
329
+
330
+    /**
331
+     * @param string $input
332
+     * @throws ResetPasswordException
333
+     * @throws \OCP\PreConditionNotMetException
334
+     */
335
+    protected function sendEmail($input) {
336
+        $user = $this->findUserByIdOrMail($input);
337
+        $email = $user->getEMailAddress();
338
+
339
+        if (empty($email)) {
340
+            throw new ResetPasswordException('Could not send reset e-mail since there is no email for username ' . $input);
341
+        }
342
+
343
+        // Generate the token. It is stored encrypted in the database with the
344
+        // secret being the users' email address appended with the system secret.
345
+        // This makes the token automatically invalidate once the user changes
346
+        // their email address.
347
+        $token = $this->secureRandom->generate(
348
+            21,
349
+            ISecureRandom::CHAR_DIGITS.
350
+            ISecureRandom::CHAR_LOWER.
351
+            ISecureRandom::CHAR_UPPER
352
+        );
353
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
354
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
355
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
356
+
357
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $user->getUID(), 'token' => $token]);
358
+
359
+        $emailTemplate = $this->mailer->createEMailTemplate('core.ResetPassword', [
360
+            'link' => $link,
361
+        ]);
362
+
363
+        $emailTemplate->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
364
+        $emailTemplate->addHeader();
365
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
366
+
367
+        $emailTemplate->addBodyText(
368
+            htmlspecialchars($this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.')),
369
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
370
+        );
371
+
372
+        $emailTemplate->addBodyButton(
373
+            htmlspecialchars($this->l10n->t('Reset your password')),
374
+            $link,
375
+            false
376
+        );
377
+        $emailTemplate->addFooter();
378
+
379
+        try {
380
+            $message = $this->mailer->createMessage();
381
+            $message->setTo([$email => $user->getUID()]);
382
+            $message->setFrom([$this->from => $this->defaults->getName()]);
383
+            $message->useTemplate($emailTemplate);
384
+            $this->mailer->send($message);
385
+        } catch (\Exception $e) {
386
+            // Log the exception and continue
387
+            $this->logger->logException($e);
388
+        }
389
+    }
390
+
391
+    /**
392
+     * @param string $input
393
+     * @return IUser
394
+     * @throws ResetPasswordException
395
+     */
396
+    protected function findUserByIdOrMail($input) {
397
+        $user = $this->userManager->get($input);
398
+        if ($user instanceof IUser) {
399
+            if (!$user->isEnabled()) {
400
+                throw new ResetPasswordException('User is disabled');
401
+            }
402
+
403
+            return $user;
404
+        }
405
+
406
+        $users = array_filter($this->userManager->getByEmail($input), function (IUser $user) {
407
+            return $user->isEnabled();
408
+        });
409
+
410
+        if (count($users) === 1) {
411
+            return reset($users);
412
+        }
413
+
414
+        throw new ResetPasswordException('Could not find user');
415
+    }
416 416
 }
Please login to merge, or discard this patch.