Passed
Push — master ( d96e2c...35e3d4 )
by Morris
24:18 queued 10:44
created
core/Command/Upgrade.php 2 patches
Indentation   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -49,251 +49,251 @@
 block discarded – undo
49 49
 
50 50
 class Upgrade extends Command {
51 51
 
52
-	const ERROR_SUCCESS = 0;
53
-	const ERROR_NOT_INSTALLED = 1;
54
-	const ERROR_MAINTENANCE_MODE = 2;
55
-	const ERROR_UP_TO_DATE = 0;
56
-	const ERROR_INVALID_ARGUMENTS = 4;
57
-	const ERROR_FAILURE = 5;
52
+    const ERROR_SUCCESS = 0;
53
+    const ERROR_NOT_INSTALLED = 1;
54
+    const ERROR_MAINTENANCE_MODE = 2;
55
+    const ERROR_UP_TO_DATE = 0;
56
+    const ERROR_INVALID_ARGUMENTS = 4;
57
+    const ERROR_FAILURE = 5;
58 58
 
59
-	/** @var IConfig */
60
-	private $config;
59
+    /** @var IConfig */
60
+    private $config;
61 61
 
62
-	/** @var ILogger */
63
-	private $logger;
62
+    /** @var ILogger */
63
+    private $logger;
64 64
 
65
-	/**
66
-	 * @param IConfig $config
67
-	 * @param ILogger $logger
68
-	 * @param Installer $installer
69
-	 */
70
-	public function __construct(IConfig $config, ILogger $logger, Installer $installer) {
71
-		parent::__construct();
72
-		$this->config = $config;
73
-		$this->logger = $logger;
74
-		$this->installer = $installer;
75
-	}
65
+    /**
66
+     * @param IConfig $config
67
+     * @param ILogger $logger
68
+     * @param Installer $installer
69
+     */
70
+    public function __construct(IConfig $config, ILogger $logger, Installer $installer) {
71
+        parent::__construct();
72
+        $this->config = $config;
73
+        $this->logger = $logger;
74
+        $this->installer = $installer;
75
+    }
76 76
 
77
-	protected function configure() {
78
-		$this
79
-			->setName('upgrade')
80
-			->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.');
81
-	}
77
+    protected function configure() {
78
+        $this
79
+            ->setName('upgrade')
80
+            ->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.');
81
+    }
82 82
 
83
-	/**
84
-	 * Execute the upgrade command
85
-	 *
86
-	 * @param InputInterface $input input interface
87
-	 * @param OutputInterface $output output interface
88
-	 */
89
-	protected function execute(InputInterface $input, OutputInterface $output) {
83
+    /**
84
+     * Execute the upgrade command
85
+     *
86
+     * @param InputInterface $input input interface
87
+     * @param OutputInterface $output output interface
88
+     */
89
+    protected function execute(InputInterface $input, OutputInterface $output) {
90 90
 
91
-		if(Util::needUpgrade()) {
92
-			if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
93
-				// Prepend each line with a little timestamp
94
-				$timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
95
-				$output->setFormatter($timestampFormatter);
96
-			}
91
+        if(Util::needUpgrade()) {
92
+            if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
93
+                // Prepend each line with a little timestamp
94
+                $timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
95
+                $output->setFormatter($timestampFormatter);
96
+            }
97 97
 
98
-			$self = $this;
99
-			$updater = new Updater(
100
-					$this->config,
101
-					\OC::$server->getIntegrityCodeChecker(),
102
-					$this->logger,
103
-					$this->installer
104
-			);
98
+            $self = $this;
99
+            $updater = new Updater(
100
+                    $this->config,
101
+                    \OC::$server->getIntegrityCodeChecker(),
102
+                    $this->logger,
103
+                    $this->installer
104
+            );
105 105
 
106
-			$dispatcher = \OC::$server->getEventDispatcher();
107
-			$progress = new ProgressBar($output);
108
-			$progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
109
-			$listener = function($event) use ($progress, $output) {
110
-				if ($event instanceof GenericEvent) {
111
-					$message = $event->getSubject();
112
-					if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
113
-						$output->writeln(' Checking table ' . $message);
114
-					} else {
115
-						if (strlen($message) > 60) {
116
-							$message = substr($message, 0, 57) . '...';
117
-						}
118
-						$progress->setMessage($message);
119
-						if ($event[0] === 1) {
120
-							$output->writeln('');
121
-							$progress->start($event[1]);
122
-						}
123
-						$progress->setProgress($event[0]);
124
-						if ($event[0] === $event[1]) {
125
-							$progress->setMessage('Done');
126
-							$progress->finish();
127
-							$output->writeln('');
128
-						}
129
-					}
130
-				}
131
-			};
132
-			$repairListener = function($event) use ($progress, $output) {
133
-				if (!$event instanceof GenericEvent) {
134
-					return;
135
-				}
136
-				switch ($event->getSubject()) {
137
-					case '\OC\Repair::startProgress':
138
-						$progress->setMessage('Starting ...');
139
-						$output->writeln($event->getArgument(1));
140
-						$output->writeln('');
141
-						$progress->start($event->getArgument(0));
142
-						break;
143
-					case '\OC\Repair::advance':
144
-						$desc = $event->getArgument(1);
145
-						if (!empty($desc)) {
146
-							$progress->setMessage($desc);
147
-						}
148
-						$progress->advance($event->getArgument(0));
106
+            $dispatcher = \OC::$server->getEventDispatcher();
107
+            $progress = new ProgressBar($output);
108
+            $progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
109
+            $listener = function($event) use ($progress, $output) {
110
+                if ($event instanceof GenericEvent) {
111
+                    $message = $event->getSubject();
112
+                    if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
113
+                        $output->writeln(' Checking table ' . $message);
114
+                    } else {
115
+                        if (strlen($message) > 60) {
116
+                            $message = substr($message, 0, 57) . '...';
117
+                        }
118
+                        $progress->setMessage($message);
119
+                        if ($event[0] === 1) {
120
+                            $output->writeln('');
121
+                            $progress->start($event[1]);
122
+                        }
123
+                        $progress->setProgress($event[0]);
124
+                        if ($event[0] === $event[1]) {
125
+                            $progress->setMessage('Done');
126
+                            $progress->finish();
127
+                            $output->writeln('');
128
+                        }
129
+                    }
130
+                }
131
+            };
132
+            $repairListener = function($event) use ($progress, $output) {
133
+                if (!$event instanceof GenericEvent) {
134
+                    return;
135
+                }
136
+                switch ($event->getSubject()) {
137
+                    case '\OC\Repair::startProgress':
138
+                        $progress->setMessage('Starting ...');
139
+                        $output->writeln($event->getArgument(1));
140
+                        $output->writeln('');
141
+                        $progress->start($event->getArgument(0));
142
+                        break;
143
+                    case '\OC\Repair::advance':
144
+                        $desc = $event->getArgument(1);
145
+                        if (!empty($desc)) {
146
+                            $progress->setMessage($desc);
147
+                        }
148
+                        $progress->advance($event->getArgument(0));
149 149
 
150
-						break;
151
-					case '\OC\Repair::finishProgress':
152
-						$progress->setMessage('Done');
153
-						$progress->finish();
154
-						$output->writeln('');
155
-						break;
156
-					case '\OC\Repair::step':
157
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
158
-							$output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
159
-						}
160
-						break;
161
-					case '\OC\Repair::info':
162
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
163
-							$output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
164
-						}
165
-						break;
166
-					case '\OC\Repair::warning':
167
-						$output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
168
-						break;
169
-					case '\OC\Repair::error':
170
-						$output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
171
-						break;
172
-				}
173
-			};
150
+                        break;
151
+                    case '\OC\Repair::finishProgress':
152
+                        $progress->setMessage('Done');
153
+                        $progress->finish();
154
+                        $output->writeln('');
155
+                        break;
156
+                    case '\OC\Repair::step':
157
+                        if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
158
+                            $output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
159
+                        }
160
+                        break;
161
+                    case '\OC\Repair::info':
162
+                        if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
163
+                            $output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
164
+                        }
165
+                        break;
166
+                    case '\OC\Repair::warning':
167
+                        $output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
168
+                        break;
169
+                    case '\OC\Repair::error':
170
+                        $output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
171
+                        break;
172
+                }
173
+            };
174 174
 
175
-			$dispatcher->addListener('\OC\DB\Migrator::executeSql', $listener);
176
-			$dispatcher->addListener('\OC\DB\Migrator::checkTable', $listener);
177
-			$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
178
-			$dispatcher->addListener('\OC\Repair::advance', $repairListener);
179
-			$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
180
-			$dispatcher->addListener('\OC\Repair::step', $repairListener);
181
-			$dispatcher->addListener('\OC\Repair::info', $repairListener);
182
-			$dispatcher->addListener('\OC\Repair::warning', $repairListener);
183
-			$dispatcher->addListener('\OC\Repair::error', $repairListener);
175
+            $dispatcher->addListener('\OC\DB\Migrator::executeSql', $listener);
176
+            $dispatcher->addListener('\OC\DB\Migrator::checkTable', $listener);
177
+            $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
178
+            $dispatcher->addListener('\OC\Repair::advance', $repairListener);
179
+            $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
180
+            $dispatcher->addListener('\OC\Repair::step', $repairListener);
181
+            $dispatcher->addListener('\OC\Repair::info', $repairListener);
182
+            $dispatcher->addListener('\OC\Repair::warning', $repairListener);
183
+            $dispatcher->addListener('\OC\Repair::error', $repairListener);
184 184
 			
185 185
 
186
-			$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
187
-				$output->writeln('<info>Turned on maintenance mode</info>');
188
-			});
189
-			$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
190
-				$output->writeln('<info>Turned off maintenance mode</info>');
191
-			});
192
-			$updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
193
-				$output->writeln('<info>Maintenance mode is kept active</info>');
194
-			});
195
-			$updater->listen('\OC\Updater', 'updateEnd',
196
-				function ($success) use($output, $self) {
197
-					if ($success) {
198
-						$message = "<info>Update successful</info>";
199
-					} else {
200
-						$message = "<error>Update failed</error>";
201
-					}
202
-					$output->writeln($message);
203
-				});
204
-			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
205
-				$output->writeln('<info>Updating database schema</info>');
206
-			});
207
-			$updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
208
-				$output->writeln('<info>Updated database</info>');
209
-			});
210
-			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
211
-				$output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
212
-			});
213
-			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
214
-				$output->writeln('<info>Checked database schema update</info>');
215
-			});
216
-			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
217
-				$output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
218
-			});
219
-			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
220
-				$output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
221
-			});
222
-			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
223
-				$output->writeln('<info>Update app ' . $app . ' from appstore</info>');
224
-			});
225
-			$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
226
-				$output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
227
-			});
228
-			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
229
-				$output->writeln('<info>Checking updates of apps</info>');
230
-			});
231
-			$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
232
-				$output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
233
-			});
234
-			$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
235
-				$output->writeln('<info>Checked database schema update for apps</info>');
236
-			});
237
-			$updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
238
-				$output->writeln("<info>Updating <$app> ...</info>");
239
-			});
240
-			$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
241
-				$output->writeln("<info>Updated <$app> to $version</info>");
242
-			});
243
-			$updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
244
-				$output->writeln("<error>$message</error>");
245
-			});
246
-			$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
247
-				$output->writeln("<info>Set log level to debug</info>");
248
-			});
249
-			$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
250
-				$output->writeln("<info>Reset log level</info>");
251
-			});
252
-			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
253
-				$output->writeln("<info>Starting code integrity check...</info>");
254
-			});
255
-			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
256
-				$output->writeln("<info>Finished code integrity check</info>");
257
-			});
186
+            $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
187
+                $output->writeln('<info>Turned on maintenance mode</info>');
188
+            });
189
+            $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
190
+                $output->writeln('<info>Turned off maintenance mode</info>');
191
+            });
192
+            $updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
193
+                $output->writeln('<info>Maintenance mode is kept active</info>');
194
+            });
195
+            $updater->listen('\OC\Updater', 'updateEnd',
196
+                function ($success) use($output, $self) {
197
+                    if ($success) {
198
+                        $message = "<info>Update successful</info>";
199
+                    } else {
200
+                        $message = "<error>Update failed</error>";
201
+                    }
202
+                    $output->writeln($message);
203
+                });
204
+            $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
205
+                $output->writeln('<info>Updating database schema</info>');
206
+            });
207
+            $updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
208
+                $output->writeln('<info>Updated database</info>');
209
+            });
210
+            $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
211
+                $output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
212
+            });
213
+            $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
214
+                $output->writeln('<info>Checked database schema update</info>');
215
+            });
216
+            $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
217
+                $output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
218
+            });
219
+            $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
220
+                $output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
221
+            });
222
+            $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
223
+                $output->writeln('<info>Update app ' . $app . ' from appstore</info>');
224
+            });
225
+            $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
226
+                $output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
227
+            });
228
+            $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
229
+                $output->writeln('<info>Checking updates of apps</info>');
230
+            });
231
+            $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
232
+                $output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
233
+            });
234
+            $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
235
+                $output->writeln('<info>Checked database schema update for apps</info>');
236
+            });
237
+            $updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
238
+                $output->writeln("<info>Updating <$app> ...</info>");
239
+            });
240
+            $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
241
+                $output->writeln("<info>Updated <$app> to $version</info>");
242
+            });
243
+            $updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
244
+                $output->writeln("<error>$message</error>");
245
+            });
246
+            $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
247
+                $output->writeln("<info>Set log level to debug</info>");
248
+            });
249
+            $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
250
+                $output->writeln("<info>Reset log level</info>");
251
+            });
252
+            $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
253
+                $output->writeln("<info>Starting code integrity check...</info>");
254
+            });
255
+            $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
256
+                $output->writeln("<info>Finished code integrity check</info>");
257
+            });
258 258
 
259
-			$success = $updater->upgrade();
259
+            $success = $updater->upgrade();
260 260
 
261
-			$this->postUpgradeCheck($input, $output);
261
+            $this->postUpgradeCheck($input, $output);
262 262
 
263
-			if(!$success) {
264
-				return self::ERROR_FAILURE;
265
-			}
263
+            if(!$success) {
264
+                return self::ERROR_FAILURE;
265
+            }
266 266
 
267
-			return self::ERROR_SUCCESS;
268
-		} else if($this->config->getSystemValue('maintenance', false)) {
269
-			//Possible scenario: Nextcloud core is updated but an app failed
270
-			$output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
271
-			$output->write('<comment>Maybe an upgrade is already in process. Please check the '
272
-				. 'logfile (data/nextcloud.log). If you want to re-run the '
273
-				. 'upgrade procedure, remove the "maintenance mode" from '
274
-				. 'config.php and call this script again.</comment>'
275
-				, true);
276
-			return self::ERROR_MAINTENANCE_MODE;
277
-		} else {
278
-			$output->writeln('<info>Nextcloud is already latest version</info>');
279
-			return self::ERROR_UP_TO_DATE;
280
-		}
281
-	}
267
+            return self::ERROR_SUCCESS;
268
+        } else if($this->config->getSystemValue('maintenance', false)) {
269
+            //Possible scenario: Nextcloud core is updated but an app failed
270
+            $output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
271
+            $output->write('<comment>Maybe an upgrade is already in process. Please check the '
272
+                . 'logfile (data/nextcloud.log). If you want to re-run the '
273
+                . 'upgrade procedure, remove the "maintenance mode" from '
274
+                . 'config.php and call this script again.</comment>'
275
+                , true);
276
+            return self::ERROR_MAINTENANCE_MODE;
277
+        } else {
278
+            $output->writeln('<info>Nextcloud is already latest version</info>');
279
+            return self::ERROR_UP_TO_DATE;
280
+        }
281
+    }
282 282
 
283
-	/**
284
-	 * Perform a post upgrade check (specific to the command line tool)
285
-	 *
286
-	 * @param InputInterface $input input interface
287
-	 * @param OutputInterface $output output interface
288
-	 */
289
-	protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
290
-		$trustedDomains = $this->config->getSystemValue('trusted_domains', array());
291
-		if (empty($trustedDomains)) {
292
-			$output->write(
293
-				'<warning>The setting "trusted_domains" could not be ' .
294
-				'set automatically by the upgrade script, ' .
295
-				'please set it manually</warning>'
296
-			);
297
-		}
298
-	}
283
+    /**
284
+     * Perform a post upgrade check (specific to the command line tool)
285
+     *
286
+     * @param InputInterface $input input interface
287
+     * @param OutputInterface $output output interface
288
+     */
289
+    protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
290
+        $trustedDomains = $this->config->getSystemValue('trusted_domains', array());
291
+        if (empty($trustedDomains)) {
292
+            $output->write(
293
+                '<warning>The setting "trusted_domains" could not be ' .
294
+                'set automatically by the upgrade script, ' .
295
+                'please set it manually</warning>'
296
+            );
297
+        }
298
+    }
299 299
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	 */
89 89
 	protected function execute(InputInterface $input, OutputInterface $output) {
90 90
 
91
-		if(Util::needUpgrade()) {
91
+		if (Util::needUpgrade()) {
92 92
 			if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
93 93
 				// Prepend each line with a little timestamp
94 94
 				$timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
@@ -110,10 +110,10 @@  discard block
 block discarded – undo
110 110
 				if ($event instanceof GenericEvent) {
111 111
 					$message = $event->getSubject();
112 112
 					if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
113
-						$output->writeln(' Checking table ' . $message);
113
+						$output->writeln(' Checking table '.$message);
114 114
 					} else {
115 115
 						if (strlen($message) > 60) {
116
-							$message = substr($message, 0, 57) . '...';
116
+							$message = substr($message, 0, 57).'...';
117 117
 						}
118 118
 						$progress->setMessage($message);
119 119
 						if ($event[0] === 1) {
@@ -154,20 +154,20 @@  discard block
 block discarded – undo
154 154
 						$output->writeln('');
155 155
 						break;
156 156
 					case '\OC\Repair::step':
157
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
158
-							$output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
157
+						if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
158
+							$output->writeln('<info>Repair step: '.$event->getArgument(0).'</info>');
159 159
 						}
160 160
 						break;
161 161
 					case '\OC\Repair::info':
162
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
163
-							$output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
162
+						if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
163
+							$output->writeln('<info>Repair info: '.$event->getArgument(0).'</info>');
164 164
 						}
165 165
 						break;
166 166
 					case '\OC\Repair::warning':
167
-						$output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
167
+						$output->writeln('<error>Repair warning: '.$event->getArgument(0).'</error>');
168 168
 						break;
169 169
 					case '\OC\Repair::error':
170
-						$output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
170
+						$output->writeln('<error>Repair error: '.$event->getArgument(0).'</error>');
171 171
 						break;
172 172
 				}
173 173
 			};
@@ -183,17 +183,17 @@  discard block
 block discarded – undo
183 183
 			$dispatcher->addListener('\OC\Repair::error', $repairListener);
184 184
 			
185 185
 
186
-			$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
186
+			$updater->listen('\OC\Updater', 'maintenanceEnabled', function() use($output) {
187 187
 				$output->writeln('<info>Turned on maintenance mode</info>');
188 188
 			});
189
-			$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
189
+			$updater->listen('\OC\Updater', 'maintenanceDisabled', function() use($output) {
190 190
 				$output->writeln('<info>Turned off maintenance mode</info>');
191 191
 			});
192
-			$updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
192
+			$updater->listen('\OC\Updater', 'maintenanceActive', function() use($output) {
193 193
 				$output->writeln('<info>Maintenance mode is kept active</info>');
194 194
 			});
195 195
 			$updater->listen('\OC\Updater', 'updateEnd',
196
-				function ($success) use($output, $self) {
196
+				function($success) use($output, $self) {
197 197
 					if ($success) {
198 198
 						$message = "<info>Update successful</info>";
199 199
 					} else {
@@ -201,58 +201,58 @@  discard block
 block discarded – undo
201 201
 					}
202 202
 					$output->writeln($message);
203 203
 				});
204
-			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
204
+			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function() use($output) {
205 205
 				$output->writeln('<info>Updating database schema</info>');
206 206
 			});
207
-			$updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
207
+			$updater->listen('\OC\Updater', 'dbUpgrade', function() use($output) {
208 208
 				$output->writeln('<info>Updated database</info>');
209 209
 			});
210
-			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
210
+			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function() use($output) {
211 211
 				$output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
212 212
 			});
213
-			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
213
+			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function() use($output) {
214 214
 				$output->writeln('<info>Checked database schema update</info>');
215 215
 			});
216
-			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
217
-				$output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
216
+			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function($app) use($output) {
217
+				$output->writeln('<comment>Disabled incompatible app: '.$app.'</comment>');
218 218
 			});
219
-			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
220
-				$output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
219
+			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function($app) use($output) {
220
+				$output->writeln('<info>Checking for update of app '.$app.' in appstore</info>');
221 221
 			});
222
-			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
223
-				$output->writeln('<info>Update app ' . $app . ' from appstore</info>');
222
+			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function($app) use($output) {
223
+				$output->writeln('<info>Update app '.$app.' from appstore</info>');
224 224
 			});
225
-			$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
226
-				$output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
225
+			$updater->listen('\OC\Updater', 'checkAppStoreApp', function($app) use($output) {
226
+				$output->writeln('<info>Checked for update of app "'.$app.'" in appstore </info>');
227 227
 			});
228
-			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
228
+			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function() use ($output) {
229 229
 				$output->writeln('<info>Checking updates of apps</info>');
230 230
 			});
231
-			$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
231
+			$updater->listen('\OC\Updater', 'appSimulateUpdate', function($app) use ($output) {
232 232
 				$output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
233 233
 			});
234
-			$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
234
+			$updater->listen('\OC\Updater', 'appUpgradeCheck', function() use ($output) {
235 235
 				$output->writeln('<info>Checked database schema update for apps</info>');
236 236
 			});
237
-			$updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
237
+			$updater->listen('\OC\Updater', 'appUpgradeStarted', function($app, $version) use ($output) {
238 238
 				$output->writeln("<info>Updating <$app> ...</info>");
239 239
 			});
240
-			$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
240
+			$updater->listen('\OC\Updater', 'appUpgrade', function($app, $version) use ($output) {
241 241
 				$output->writeln("<info>Updated <$app> to $version</info>");
242 242
 			});
243
-			$updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
243
+			$updater->listen('\OC\Updater', 'failure', function($message) use($output, $self) {
244 244
 				$output->writeln("<error>$message</error>");
245 245
 			});
246
-			$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
246
+			$updater->listen('\OC\Updater', 'setDebugLogLevel', function($logLevel, $logLevelName) use($output) {
247 247
 				$output->writeln("<info>Set log level to debug</info>");
248 248
 			});
249
-			$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
249
+			$updater->listen('\OC\Updater', 'resetLogLevel', function($logLevel, $logLevelName) use($output) {
250 250
 				$output->writeln("<info>Reset log level</info>");
251 251
 			});
252
-			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
252
+			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function() use($output) {
253 253
 				$output->writeln("<info>Starting code integrity check...</info>");
254 254
 			});
255
-			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
255
+			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function() use($output) {
256 256
 				$output->writeln("<info>Finished code integrity check</info>");
257 257
 			});
258 258
 
@@ -260,12 +260,12 @@  discard block
 block discarded – undo
260 260
 
261 261
 			$this->postUpgradeCheck($input, $output);
262 262
 
263
-			if(!$success) {
263
+			if (!$success) {
264 264
 				return self::ERROR_FAILURE;
265 265
 			}
266 266
 
267 267
 			return self::ERROR_SUCCESS;
268
-		} else if($this->config->getSystemValue('maintenance', false)) {
268
+		} else if ($this->config->getSystemValue('maintenance', false)) {
269 269
 			//Possible scenario: Nextcloud core is updated but an app failed
270 270
 			$output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
271 271
 			$output->write('<comment>Maybe an upgrade is already in process. Please check the '
@@ -290,8 +290,8 @@  discard block
 block discarded – undo
290 290
 		$trustedDomains = $this->config->getSystemValue('trusted_domains', array());
291 291
 		if (empty($trustedDomains)) {
292 292
 			$output->write(
293
-				'<warning>The setting "trusted_domains" could not be ' .
294
-				'set automatically by the upgrade script, ' .
293
+				'<warning>The setting "trusted_domains" could not be '.
294
+				'set automatically by the upgrade script, '.
295 295
 				'please set it manually</warning>'
296 296
 			);
297 297
 		}
Please login to merge, or discard this patch.
lib/private/Updater.php 2 patches
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -101,12 +101,12 @@  discard block
 block discarded – undo
101 101
 		$this->logAllEvents();
102 102
 
103 103
 		$logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
104
-		$this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
104
+		$this->emit('\OC\Updater', 'setDebugLogLevel', [$logLevel, $this->logLevelNames[$logLevel]]);
105 105
 		$this->config->setSystemValue('loglevel', ILogger::DEBUG);
106 106
 
107 107
 		$wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
108 108
 
109
-		if(!$wasMaintenanceModeEnabled) {
109
+		if (!$wasMaintenanceModeEnabled) {
110 110
 			$this->config->setSystemValue('maintenance', true);
111 111
 			$this->emit('\OC\Updater', 'maintenanceEnabled');
112 112
 		}
@@ -115,31 +115,31 @@  discard block
 block discarded – undo
115 115
 
116 116
 		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
117 117
 		$currentVersion = implode('.', \OCP\Util::getVersion());
118
-		$this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
118
+		$this->log->debug('starting upgrade from '.$installedVersion.' to '.$currentVersion, array('app' => 'core'));
119 119
 
120 120
 		$success = true;
121 121
 		try {
122 122
 			$this->doUpgrade($currentVersion, $installedVersion);
123 123
 		} catch (HintException $exception) {
124 124
 			$this->log->logException($exception, ['app' => 'core']);
125
-			$this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
125
+			$this->emit('\OC\Updater', 'failure', array($exception->getMessage().': '.$exception->getHint()));
126 126
 			$success = false;
127 127
 		} catch (\Exception $exception) {
128 128
 			$this->log->logException($exception, ['app' => 'core']);
129
-			$this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
129
+			$this->emit('\OC\Updater', 'failure', array(get_class($exception).': '.$exception->getMessage()));
130 130
 			$success = false;
131 131
 		}
132 132
 
133 133
 		$this->emit('\OC\Updater', 'updateEnd', array($success));
134 134
 
135
-		if(!$wasMaintenanceModeEnabled && $success) {
135
+		if (!$wasMaintenanceModeEnabled && $success) {
136 136
 			$this->config->setSystemValue('maintenance', false);
137 137
 			$this->emit('\OC\Updater', 'maintenanceDisabled');
138 138
 		} else {
139 139
 			$this->emit('\OC\Updater', 'maintenanceActive');
140 140
 		}
141 141
 
142
-		$this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
142
+		$this->emit('\OC\Updater', 'resetLogLevel', [$logLevel, $this->logLevelNames[$logLevel]]);
143 143
 		$this->config->setSystemValue('loglevel', $logLevel);
144 144
 		$this->config->setSystemValue('installed', true);
145 145
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 	 */
154 154
 	private function getAllowedPreviousVersions() {
155 155
 		// this should really be a JSON file
156
-		require \OC::$SERVERROOT . '/version.php';
156
+		require \OC::$SERVERROOT.'/version.php';
157 157
 		/** @var array $OC_VersionCanBeUpgradedFrom */
158 158
 		return $OC_VersionCanBeUpgradedFrom;
159 159
 	}
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 	 */
166 166
 	private function getVendor() {
167 167
 		// this should really be a JSON file
168
-		require \OC::$SERVERROOT . '/version.php';
168
+		require \OC::$SERVERROOT.'/version.php';
169 169
 		/** @var string $vendor */
170 170
 		return (string) $vendor;
171 171
 	}
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 	 */
180 180
 	public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
181 181
 		$version = explode('.', $oldVersion);
182
-		$majorMinor = $version[0] . '.' . $version[1];
182
+		$majorMinor = $version[0].'.'.$version[1];
183 183
 
184 184
 		$currentVendor = $this->config->getAppValue('core', 'vendor', '');
185 185
 
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 		// create empty file in data dir, so we can later find
227 227
 		// out that this is indeed an ownCloud data directory
228 228
 		// (in case it didn't exist before)
229
-		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
229
+		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
230 230
 
231 231
 		// pre-upgrade repairs
232 232
 		$repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 		foreach ($errors as $appId => $exception) {
259 259
 			/** @var \Exception $exception */
260 260
 			$this->log->logException($exception, ['app' => $appId]);
261
-			$this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
261
+			$this->emit('\OC\Updater', 'failure', [$appId.': '.$exception->getMessage()]);
262 262
 		}
263 263
 
264 264
 		// post-upgrade repairs
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 		$this->config->setAppValue('core', 'lastupdatedat', 0);
270 270
 
271 271
 		// Check for code integrity if not disabled
272
-		if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
272
+		if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
273 273
 			$this->emit('\OC\Updater', 'startCheckCodeIntegrity');
274 274
 			$this->checker->runInstanceVerification();
275 275
 			$this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
@@ -310,12 +310,12 @@  discard block
 block discarded – undo
310 310
 				 * @link https://github.com/owncloud/core/issues/10980
311 311
 				 * @see \OC_App::updateApp
312 312
 				 */
313
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
313
+				if (file_exists(\OC_App::getAppPath($appId).'/appinfo/preupdate.php')) {
314 314
 					$this->includePreUpdate($appId);
315 315
 				}
316
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
316
+				if (file_exists(\OC_App::getAppPath($appId).'/appinfo/database.xml')) {
317 317
 					$this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
318
-					\OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
318
+					\OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId).'/appinfo/database.xml');
319 319
 				}
320 320
 			}
321 321
 		}
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 	 * @param string $appId
329 329
 	 */
330 330
 	private function includePreUpdate($appId) {
331
-		include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
331
+		include \OC_App::getAppPath($appId).'/appinfo/preupdate.php';
332 332
 	}
333 333
 
334 334
 	/**
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 		foreach ($apps as $appId) {
347 347
 			$priorityType = false;
348 348
 			foreach ($priorityTypes as $type) {
349
-				if(!isset($stacks[$type])) {
349
+				if (!isset($stacks[$type])) {
350 350
 					$stacks[$type] = array();
351 351
 				}
352 352
 				if (\OC_App::isType($appId, [$type])) {
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 					\OC_App::updateApp($appId);
367 367
 					$this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
368 368
 				}
369
-				if($type !== $pseudoOtherType) {
369
+				if ($type !== $pseudoOtherType) {
370 370
 					// load authentication, filesystem and logging apps after
371 371
 					// upgrading them. Other apps my need to rely on modifying
372 372
 					// user and/or filesystem aspects.
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 		foreach ($apps as $app) {
395 395
 			// check if the app is compatible with this version of ownCloud
396 396
 			$info = OC_App::getAppInfo($app);
397
-			if($info === null || !OC_App::isAppCompatible($version, $info)) {
397
+			if ($info === null || !OC_App::isAppCompatible($version, $info)) {
398 398
 				if ($appManager->isShipped($app)) {
399
-					throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
399
+					throw new \UnexpectedValueException('The files of the app "'.$app.'" were not correctly replaced before running the update');
400 400
 				}
401 401
 				\OC::$server->getAppManager()->disableApp($app);
402 402
 				$this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 	 * @throws \Exception
436 436
 	 */
437 437
 	private function upgradeAppStoreApps(array $disabledApps, $reenable = false) {
438
-		foreach($disabledApps as $app) {
438
+		foreach ($disabledApps as $app) {
439 439
 			try {
440 440
 				$this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
441 441
 				if ($this->installer->isUpdateAvailable($app)) {
@@ -459,22 +459,22 @@  discard block
 block discarded – undo
459 459
 	 */
460 460
 	private function emitRepairEvents() {
461 461
 		$dispatcher = \OC::$server->getEventDispatcher();
462
-		$dispatcher->addListener('\OC\Repair::warning', function ($event) {
462
+		$dispatcher->addListener('\OC\Repair::warning', function($event) {
463 463
 			if ($event instanceof GenericEvent) {
464 464
 				$this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
465 465
 			}
466 466
 		});
467
-		$dispatcher->addListener('\OC\Repair::error', function ($event) {
467
+		$dispatcher->addListener('\OC\Repair::error', function($event) {
468 468
 			if ($event instanceof GenericEvent) {
469 469
 				$this->emit('\OC\Updater', 'repairError', $event->getArguments());
470 470
 			}
471 471
 		});
472
-		$dispatcher->addListener('\OC\Repair::info', function ($event) {
472
+		$dispatcher->addListener('\OC\Repair::info', function($event) {
473 473
 			if ($event instanceof GenericEvent) {
474 474
 				$this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
475 475
 			}
476 476
 		});
477
-		$dispatcher->addListener('\OC\Repair::step', function ($event) {
477
+		$dispatcher->addListener('\OC\Repair::step', function($event) {
478 478
 			if ($event instanceof GenericEvent) {
479 479
 				$this->emit('\OC\Updater', 'repairStep', $event->getArguments());
480 480
 			}
@@ -489,13 +489,13 @@  discard block
 block discarded – undo
489 489
 			if (!$event instanceof GenericEvent) {
490 490
 				return;
491 491
 			}
492
-			$log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
492
+			$log->info('\OC\DB\Migrator::executeSql: '.$event->getSubject().' ('.$event->getArgument(0).' of '.$event->getArgument(1).')', ['app' => 'updater']);
493 493
 		});
494 494
 		$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
495 495
 			if (!$event instanceof GenericEvent) {
496 496
 				return;
497 497
 			}
498
-			$log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
498
+			$log->info('\OC\DB\Migrator::checkTable: '.$event->getSubject().' ('.$event->getArgument(0).' of '.$event->getArgument(1).')', ['app' => 'updater']);
499 499
 		});
500 500
 
501 501
 		$repairListener = function($event) use ($log) {
@@ -504,30 +504,30 @@  discard block
 block discarded – undo
504 504
 			}
505 505
 			switch ($event->getSubject()) {
506 506
 				case '\OC\Repair::startProgress':
507
-					$log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
507
+					$log->info('\OC\Repair::startProgress: Starting ... '.$event->getArgument(1).' ('.$event->getArgument(0).')', ['app' => 'updater']);
508 508
 					break;
509 509
 				case '\OC\Repair::advance':
510 510
 					$desc = $event->getArgument(1);
511 511
 					if (empty($desc)) {
512 512
 						$desc = '';
513 513
 					}
514
-					$log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
514
+					$log->info('\OC\Repair::advance: '.$desc.' ('.$event->getArgument(0).')', ['app' => 'updater']);
515 515
 
516 516
 					break;
517 517
 				case '\OC\Repair::finishProgress':
518 518
 					$log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
519 519
 					break;
520 520
 				case '\OC\Repair::step':
521
-					$log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
521
+					$log->info('\OC\Repair::step: Repair step: '.$event->getArgument(0), ['app' => 'updater']);
522 522
 					break;
523 523
 				case '\OC\Repair::info':
524
-					$log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
524
+					$log->info('\OC\Repair::info: Repair info: '.$event->getArgument(0), ['app' => 'updater']);
525 525
 					break;
526 526
 				case '\OC\Repair::warning':
527
-					$log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
527
+					$log->warning('\OC\Repair::warning: Repair warning: '.$event->getArgument(0), ['app' => 'updater']);
528 528
 					break;
529 529
 				case '\OC\Repair::error':
530
-					$log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
530
+					$log->error('\OC\Repair::error: Repair error: '.$event->getArgument(0), ['app' => 'updater']);
531 531
 					break;
532 532
 			}
533 533
 		};
@@ -541,74 +541,74 @@  discard block
 block discarded – undo
541 541
 		$dispatcher->addListener('\OC\Repair::error', $repairListener);
542 542
 
543 543
 
544
-		$this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
544
+		$this->listen('\OC\Updater', 'maintenanceEnabled', function() use($log) {
545 545
 			$log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
546 546
 		});
547
-		$this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
547
+		$this->listen('\OC\Updater', 'maintenanceDisabled', function() use($log) {
548 548
 			$log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
549 549
 		});
550
-		$this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
550
+		$this->listen('\OC\Updater', 'maintenanceActive', function() use($log) {
551 551
 			$log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
552 552
 		});
553
-		$this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
553
+		$this->listen('\OC\Updater', 'updateEnd', function($success) use($log) {
554 554
 			if ($success) {
555 555
 				$log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
556 556
 			} else {
557 557
 				$log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
558 558
 			}
559 559
 		});
560
-		$this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
560
+		$this->listen('\OC\Updater', 'dbUpgradeBefore', function() use($log) {
561 561
 			$log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
562 562
 		});
563
-		$this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
563
+		$this->listen('\OC\Updater', 'dbUpgrade', function() use($log) {
564 564
 			$log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
565 565
 		});
566
-		$this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
566
+		$this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function() use($log) {
567 567
 			$log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
568 568
 		});
569
-		$this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
569
+		$this->listen('\OC\Updater', 'dbSimulateUpgrade', function() use($log) {
570 570
 			$log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
571 571
 		});
572
-		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
573
-			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
572
+		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function($app) use($log) {
573
+			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: '.$app, ['app' => 'updater']);
574 574
 		});
575
-		$this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($log) {
576
-			$log->info('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
575
+		$this->listen('\OC\Updater', 'checkAppStoreAppBefore', function($app) use($log) {
576
+			$log->info('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "'.$app.'" in appstore', ['app' => 'updater']);
577 577
 		});
578
-		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
579
-			$log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
578
+		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function($app) use($log) {
579
+			$log->info('\OC\Updater::upgradeAppStoreApp: Update app "'.$app.'" from appstore', ['app' => 'updater']);
580 580
 		});
581
-		$this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($log) {
582
-			$log->info('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
581
+		$this->listen('\OC\Updater', 'checkAppStoreApp', function($app) use($log) {
582
+			$log->info('\OC\Updater::checkAppStoreApp: Checked for update of app "'.$app.'" in appstore', ['app' => 'updater']);
583 583
 		});
584
-		$this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
584
+		$this->listen('\OC\Updater', 'appUpgradeCheckBefore', function() use ($log) {
585 585
 			$log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
586 586
 		});
587
-		$this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
588
-			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
587
+		$this->listen('\OC\Updater', 'appSimulateUpdate', function($app) use ($log) {
588
+			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <'.$app.'> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
589 589
 		});
590
-		$this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
590
+		$this->listen('\OC\Updater', 'appUpgradeCheck', function() use ($log) {
591 591
 			$log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
592 592
 		});
593
-		$this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
594
-			$log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
593
+		$this->listen('\OC\Updater', 'appUpgradeStarted', function($app) use ($log) {
594
+			$log->info('\OC\Updater::appUpgradeStarted: Updating <'.$app.'> ...', ['app' => 'updater']);
595 595
 		});
596
-		$this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
597
-			$log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
596
+		$this->listen('\OC\Updater', 'appUpgrade', function($app, $version) use ($log) {
597
+			$log->info('\OC\Updater::appUpgrade: Updated <'.$app.'> to '.$version, ['app' => 'updater']);
598 598
 		});
599
-		$this->listen('\OC\Updater', 'failure', function ($message) use($log) {
600
-			$log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
599
+		$this->listen('\OC\Updater', 'failure', function($message) use($log) {
600
+			$log->error('\OC\Updater::failure: '.$message, ['app' => 'updater']);
601 601
 		});
602
-		$this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
602
+		$this->listen('\OC\Updater', 'setDebugLogLevel', function() use($log) {
603 603
 			$log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
604 604
 		});
605
-		$this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
606
-			$log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
605
+		$this->listen('\OC\Updater', 'resetLogLevel', function($logLevel, $logLevelName) use($log) {
606
+			$log->info('\OC\Updater::resetLogLevel: Reset log level to '.$logLevelName.'('.$logLevel.')', ['app' => 'updater']);
607 607
 		});
608
-		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
608
+		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function() use($log) {
609 609
 			$log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
610 610
 		});
611
-		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
611
+		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function() use($log) {
612 612
 			$log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
613 613
 		});
614 614
 
Please login to merge, or discard this patch.
Indentation   +558 added lines, -558 removed lines patch added patch discarded remove patch
@@ -54,564 +54,564 @@
 block discarded – undo
54 54
  */
55 55
 class Updater extends BasicEmitter {
56 56
 
57
-	/** @var ILogger $log */
58
-	private $log;
59
-
60
-	/** @var IConfig */
61
-	private $config;
62
-
63
-	/** @var Checker */
64
-	private $checker;
65
-
66
-	/** @var Installer */
67
-	private $installer;
68
-
69
-	private $logLevelNames = [
70
-		0 => 'Debug',
71
-		1 => 'Info',
72
-		2 => 'Warning',
73
-		3 => 'Error',
74
-		4 => 'Fatal',
75
-	];
76
-
77
-	/**
78
-	 * @param IConfig $config
79
-	 * @param Checker $checker
80
-	 * @param ILogger $log
81
-	 * @param Installer $installer
82
-	 */
83
-	public function __construct(IConfig $config,
84
-								Checker $checker,
85
-								ILogger $log = null,
86
-								Installer $installer) {
87
-		$this->log = $log;
88
-		$this->config = $config;
89
-		$this->checker = $checker;
90
-		$this->installer = $installer;
91
-	}
92
-
93
-	/**
94
-	 * runs the update actions in maintenance mode, does not upgrade the source files
95
-	 * except the main .htaccess file
96
-	 *
97
-	 * @return bool true if the operation succeeded, false otherwise
98
-	 */
99
-	public function upgrade() {
100
-		$this->emitRepairEvents();
101
-		$this->logAllEvents();
102
-
103
-		$logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
104
-		$this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
105
-		$this->config->setSystemValue('loglevel', ILogger::DEBUG);
106
-
107
-		$wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
108
-
109
-		if(!$wasMaintenanceModeEnabled) {
110
-			$this->config->setSystemValue('maintenance', true);
111
-			$this->emit('\OC\Updater', 'maintenanceEnabled');
112
-		}
113
-
114
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
115
-		$currentVersion = implode('.', \OCP\Util::getVersion());
116
-
117
-		$this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
118
-
119
-		$success = true;
120
-		try {
121
-			$this->doUpgrade($currentVersion, $installedVersion);
122
-		} catch (HintException $exception) {
123
-			$this->log->logException($exception, ['app' => 'core']);
124
-			$this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
125
-			$success = false;
126
-		} catch (\Exception $exception) {
127
-			$this->log->logException($exception, ['app' => 'core']);
128
-			$this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
129
-			$success = false;
130
-		}
131
-
132
-		$this->emit('\OC\Updater', 'updateEnd', array($success));
133
-
134
-		if(!$wasMaintenanceModeEnabled && $success) {
135
-			$this->config->setSystemValue('maintenance', false);
136
-			$this->emit('\OC\Updater', 'maintenanceDisabled');
137
-		} else {
138
-			$this->emit('\OC\Updater', 'maintenanceActive');
139
-		}
140
-
141
-		$this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
142
-		$this->config->setSystemValue('loglevel', $logLevel);
143
-		$this->config->setSystemValue('installed', true);
144
-
145
-		return $success;
146
-	}
147
-
148
-	/**
149
-	 * Return version from which this version is allowed to upgrade from
150
-	 *
151
-	 * @return array allowed previous versions per vendor
152
-	 */
153
-	private function getAllowedPreviousVersions() {
154
-		// this should really be a JSON file
155
-		require \OC::$SERVERROOT . '/version.php';
156
-		/** @var array $OC_VersionCanBeUpgradedFrom */
157
-		return $OC_VersionCanBeUpgradedFrom;
158
-	}
159
-
160
-	/**
161
-	 * Return vendor from which this version was published
162
-	 *
163
-	 * @return string Get the vendor
164
-	 */
165
-	private function getVendor() {
166
-		// this should really be a JSON file
167
-		require \OC::$SERVERROOT . '/version.php';
168
-		/** @var string $vendor */
169
-		return (string) $vendor;
170
-	}
171
-
172
-	/**
173
-	 * Whether an upgrade to a specified version is possible
174
-	 * @param string $oldVersion
175
-	 * @param string $newVersion
176
-	 * @param array $allowedPreviousVersions
177
-	 * @return bool
178
-	 */
179
-	public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
180
-		$version = explode('.', $oldVersion);
181
-		$majorMinor = $version[0] . '.' . $version[1];
182
-
183
-		$currentVendor = $this->config->getAppValue('core', 'vendor', '');
184
-
185
-		// Vendor was not set correctly on install, so we have to white-list known versions
186
-		if ($currentVendor === '' && isset($allowedPreviousVersions['owncloud'][$oldVersion])) {
187
-			$currentVendor = 'owncloud';
188
-		}
189
-
190
-		if ($currentVendor === 'nextcloud') {
191
-			return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
192
-				&& (version_compare($oldVersion, $newVersion, '<=') ||
193
-					$this->config->getSystemValue('debug', false));
194
-		}
195
-
196
-		// Check if the instance can be migrated
197
-		return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
198
-			isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
199
-	}
200
-
201
-	/**
202
-	 * runs the update actions in maintenance mode, does not upgrade the source files
203
-	 * except the main .htaccess file
204
-	 *
205
-	 * @param string $currentVersion current version to upgrade to
206
-	 * @param string $installedVersion previous version from which to upgrade from
207
-	 *
208
-	 * @throws \Exception
209
-	 */
210
-	private function doUpgrade($currentVersion, $installedVersion) {
211
-		// Stop update if the update is over several major versions
212
-		$allowedPreviousVersions = $this->getAllowedPreviousVersions();
213
-		if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
214
-			throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
215
-		}
216
-
217
-		// Update .htaccess files
218
-		try {
219
-			Setup::updateHtaccess();
220
-			Setup::protectDataDirectory();
221
-		} catch (\Exception $e) {
222
-			throw new \Exception($e->getMessage());
223
-		}
224
-
225
-		// create empty file in data dir, so we can later find
226
-		// out that this is indeed an ownCloud data directory
227
-		// (in case it didn't exist before)
228
-		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
229
-
230
-		// pre-upgrade repairs
231
-		$repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
232
-		$repair->run();
233
-
234
-		$this->doCoreUpgrade();
235
-
236
-		try {
237
-			// TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
238
-			Setup::installBackgroundJobs();
239
-		} catch (\Exception $e) {
240
-			throw new \Exception($e->getMessage());
241
-		}
242
-
243
-		// update all shipped apps
244
-		$this->checkAppsRequirements();
245
-		$this->doAppUpgrade();
246
-
247
-		// Update the appfetchers version so it downloads the correct list from the appstore
248
-		\OC::$server->getAppFetcher()->setVersion($currentVersion);
249
-
250
-		// upgrade appstore apps
251
-		$this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
252
-		$this->upgradeAppStoreApps(\OC_App::$autoDisabledApps, true);
253
-
254
-		// install new shipped apps on upgrade
255
-		OC_App::loadApps(['authentication']);
256
-		$errors = Installer::installShippedApps(true);
257
-		foreach ($errors as $appId => $exception) {
258
-			/** @var \Exception $exception */
259
-			$this->log->logException($exception, ['app' => $appId]);
260
-			$this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
261
-		}
262
-
263
-		// post-upgrade repairs
264
-		$repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
265
-		$repair->run();
266
-
267
-		//Invalidate update feed
268
-		$this->config->setAppValue('core', 'lastupdatedat', 0);
269
-
270
-		// Check for code integrity if not disabled
271
-		if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
272
-			$this->emit('\OC\Updater', 'startCheckCodeIntegrity');
273
-			$this->checker->runInstanceVerification();
274
-			$this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
275
-		}
276
-
277
-		// only set the final version if everything went well
278
-		$this->config->setSystemValue('version', implode('.', Util::getVersion()));
279
-		$this->config->setAppValue('core', 'vendor', $this->getVendor());
280
-	}
281
-
282
-	protected function doCoreUpgrade() {
283
-		$this->emit('\OC\Updater', 'dbUpgradeBefore');
284
-
285
-		// execute core migrations
286
-		$ms = new MigrationService('core', \OC::$server->getDatabaseConnection());
287
-		$ms->migrate();
288
-
289
-		$this->emit('\OC\Updater', 'dbUpgrade');
290
-	}
291
-
292
-	/**
293
-	 * @param string $version the oc version to check app compatibility with
294
-	 */
295
-	protected function checkAppUpgrade($version) {
296
-		$apps = \OC_App::getEnabledApps();
297
-		$this->emit('\OC\Updater', 'appUpgradeCheckBefore');
298
-
299
-		$appManager = \OC::$server->getAppManager();
300
-		foreach ($apps as $appId) {
301
-			$info = \OC_App::getAppInfo($appId);
302
-			$compatible = \OC_App::isAppCompatible($version, $info);
303
-			$isShipped = $appManager->isShipped($appId);
304
-
305
-			if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
306
-				/**
307
-				 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
308
-				 * are not possible anymore within it. - Consider this when touching the code.
309
-				 * @link https://github.com/owncloud/core/issues/10980
310
-				 * @see \OC_App::updateApp
311
-				 */
312
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
313
-					$this->includePreUpdate($appId);
314
-				}
315
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
316
-					$this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
317
-					\OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
318
-				}
319
-			}
320
-		}
321
-
322
-		$this->emit('\OC\Updater', 'appUpgradeCheck');
323
-	}
324
-
325
-	/**
326
-	 * Includes the pre-update file. Done here to prevent namespace mixups.
327
-	 * @param string $appId
328
-	 */
329
-	private function includePreUpdate($appId) {
330
-		include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
331
-	}
332
-
333
-	/**
334
-	 * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
335
-	 * (types authentication, filesystem, logging, in that order) afterwards.
336
-	 *
337
-	 * @throws NeedsUpdateException
338
-	 */
339
-	protected function doAppUpgrade() {
340
-		$apps = \OC_App::getEnabledApps();
341
-		$priorityTypes = array('authentication', 'filesystem', 'logging');
342
-		$pseudoOtherType = 'other';
343
-		$stacks = array($pseudoOtherType => array());
344
-
345
-		foreach ($apps as $appId) {
346
-			$priorityType = false;
347
-			foreach ($priorityTypes as $type) {
348
-				if(!isset($stacks[$type])) {
349
-					$stacks[$type] = array();
350
-				}
351
-				if (\OC_App::isType($appId, [$type])) {
352
-					$stacks[$type][] = $appId;
353
-					$priorityType = true;
354
-					break;
355
-				}
356
-			}
357
-			if (!$priorityType) {
358
-				$stacks[$pseudoOtherType][] = $appId;
359
-			}
360
-		}
361
-		foreach ($stacks as $type => $stack) {
362
-			foreach ($stack as $appId) {
363
-				if (\OC_App::shouldUpgrade($appId)) {
364
-					$this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
365
-					\OC_App::updateApp($appId);
366
-					$this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
367
-				}
368
-				if($type !== $pseudoOtherType) {
369
-					// load authentication, filesystem and logging apps after
370
-					// upgrading them. Other apps my need to rely on modifying
371
-					// user and/or filesystem aspects.
372
-					\OC_App::loadApp($appId);
373
-				}
374
-			}
375
-		}
376
-	}
377
-
378
-	/**
379
-	 * check if the current enabled apps are compatible with the current
380
-	 * ownCloud version. disable them if not.
381
-	 * This is important if you upgrade ownCloud and have non ported 3rd
382
-	 * party apps installed.
383
-	 *
384
-	 * @return array
385
-	 * @throws \Exception
386
-	 */
387
-	private function checkAppsRequirements() {
388
-		$isCoreUpgrade = $this->isCodeUpgrade();
389
-		$apps = OC_App::getEnabledApps();
390
-		$version = implode('.', Util::getVersion());
391
-		$disabledApps = [];
392
-		$appManager = \OC::$server->getAppManager();
393
-		foreach ($apps as $app) {
394
-			// check if the app is compatible with this version of ownCloud
395
-			$info = OC_App::getAppInfo($app);
396
-			if($info === null || !OC_App::isAppCompatible($version, $info)) {
397
-				if ($appManager->isShipped($app)) {
398
-					throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
399
-				}
400
-				\OC::$server->getAppManager()->disableApp($app);
401
-				$this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
402
-			}
403
-			// no need to disable any app in case this is a non-core upgrade
404
-			if (!$isCoreUpgrade) {
405
-				continue;
406
-			}
407
-			// shipped apps will remain enabled
408
-			if ($appManager->isShipped($app)) {
409
-				continue;
410
-			}
411
-			// authentication and session apps will remain enabled as well
412
-			if (OC_App::isType($app, ['session', 'authentication'])) {
413
-				continue;
414
-			}
415
-		}
416
-		return $disabledApps;
417
-	}
418
-
419
-	/**
420
-	 * @return bool
421
-	 */
422
-	private function isCodeUpgrade() {
423
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
424
-		$currentVersion = implode('.', Util::getVersion());
425
-		if (version_compare($currentVersion, $installedVersion, '>')) {
426
-			return true;
427
-		}
428
-		return false;
429
-	}
430
-
431
-	/**
432
-	 * @param array $disabledApps
433
-	 * @param bool $reenable
434
-	 * @throws \Exception
435
-	 */
436
-	private function upgradeAppStoreApps(array $disabledApps, $reenable = false) {
437
-		foreach($disabledApps as $app) {
438
-			try {
439
-				$this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
440
-				if ($this->installer->isUpdateAvailable($app)) {
441
-					$this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
442
-					$this->installer->updateAppstoreApp($app);
443
-				}
444
-				$this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
445
-
446
-				if ($reenable) {
447
-					$ocApp = new \OC_App();
448
-					$ocApp->enable($app);
449
-				}
450
-			} catch (\Exception $ex) {
451
-				$this->log->logException($ex, ['app' => 'core']);
452
-			}
453
-		}
454
-	}
455
-
456
-	/**
457
-	 * Forward messages emitted by the repair routine
458
-	 */
459
-	private function emitRepairEvents() {
460
-		$dispatcher = \OC::$server->getEventDispatcher();
461
-		$dispatcher->addListener('\OC\Repair::warning', function ($event) {
462
-			if ($event instanceof GenericEvent) {
463
-				$this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
464
-			}
465
-		});
466
-		$dispatcher->addListener('\OC\Repair::error', function ($event) {
467
-			if ($event instanceof GenericEvent) {
468
-				$this->emit('\OC\Updater', 'repairError', $event->getArguments());
469
-			}
470
-		});
471
-		$dispatcher->addListener('\OC\Repair::info', function ($event) {
472
-			if ($event instanceof GenericEvent) {
473
-				$this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
474
-			}
475
-		});
476
-		$dispatcher->addListener('\OC\Repair::step', function ($event) {
477
-			if ($event instanceof GenericEvent) {
478
-				$this->emit('\OC\Updater', 'repairStep', $event->getArguments());
479
-			}
480
-		});
481
-	}
482
-
483
-	private function logAllEvents() {
484
-		$log = $this->log;
485
-
486
-		$dispatcher = \OC::$server->getEventDispatcher();
487
-		$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
488
-			if (!$event instanceof GenericEvent) {
489
-				return;
490
-			}
491
-			$log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
492
-		});
493
-		$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
494
-			if (!$event instanceof GenericEvent) {
495
-				return;
496
-			}
497
-			$log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
498
-		});
499
-
500
-		$repairListener = function($event) use ($log) {
501
-			if (!$event instanceof GenericEvent) {
502
-				return;
503
-			}
504
-			switch ($event->getSubject()) {
505
-				case '\OC\Repair::startProgress':
506
-					$log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
507
-					break;
508
-				case '\OC\Repair::advance':
509
-					$desc = $event->getArgument(1);
510
-					if (empty($desc)) {
511
-						$desc = '';
512
-					}
513
-					$log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
514
-
515
-					break;
516
-				case '\OC\Repair::finishProgress':
517
-					$log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
518
-					break;
519
-				case '\OC\Repair::step':
520
-					$log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
521
-					break;
522
-				case '\OC\Repair::info':
523
-					$log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
524
-					break;
525
-				case '\OC\Repair::warning':
526
-					$log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
527
-					break;
528
-				case '\OC\Repair::error':
529
-					$log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
530
-					break;
531
-			}
532
-		};
533
-
534
-		$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
535
-		$dispatcher->addListener('\OC\Repair::advance', $repairListener);
536
-		$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
537
-		$dispatcher->addListener('\OC\Repair::step', $repairListener);
538
-		$dispatcher->addListener('\OC\Repair::info', $repairListener);
539
-		$dispatcher->addListener('\OC\Repair::warning', $repairListener);
540
-		$dispatcher->addListener('\OC\Repair::error', $repairListener);
541
-
542
-
543
-		$this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
544
-			$log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
545
-		});
546
-		$this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
547
-			$log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
548
-		});
549
-		$this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
550
-			$log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
551
-		});
552
-		$this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
553
-			if ($success) {
554
-				$log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
555
-			} else {
556
-				$log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
557
-			}
558
-		});
559
-		$this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
560
-			$log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
561
-		});
562
-		$this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
563
-			$log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
564
-		});
565
-		$this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
566
-			$log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
567
-		});
568
-		$this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
569
-			$log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
570
-		});
571
-		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
572
-			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
573
-		});
574
-		$this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($log) {
575
-			$log->info('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
576
-		});
577
-		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
578
-			$log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
579
-		});
580
-		$this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($log) {
581
-			$log->info('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
582
-		});
583
-		$this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
584
-			$log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
585
-		});
586
-		$this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
587
-			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
588
-		});
589
-		$this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
590
-			$log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
591
-		});
592
-		$this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
593
-			$log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
594
-		});
595
-		$this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
596
-			$log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
597
-		});
598
-		$this->listen('\OC\Updater', 'failure', function ($message) use($log) {
599
-			$log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
600
-		});
601
-		$this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
602
-			$log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
603
-		});
604
-		$this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
605
-			$log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
606
-		});
607
-		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
608
-			$log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
609
-		});
610
-		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
611
-			$log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
612
-		});
613
-
614
-	}
57
+    /** @var ILogger $log */
58
+    private $log;
59
+
60
+    /** @var IConfig */
61
+    private $config;
62
+
63
+    /** @var Checker */
64
+    private $checker;
65
+
66
+    /** @var Installer */
67
+    private $installer;
68
+
69
+    private $logLevelNames = [
70
+        0 => 'Debug',
71
+        1 => 'Info',
72
+        2 => 'Warning',
73
+        3 => 'Error',
74
+        4 => 'Fatal',
75
+    ];
76
+
77
+    /**
78
+     * @param IConfig $config
79
+     * @param Checker $checker
80
+     * @param ILogger $log
81
+     * @param Installer $installer
82
+     */
83
+    public function __construct(IConfig $config,
84
+                                Checker $checker,
85
+                                ILogger $log = null,
86
+                                Installer $installer) {
87
+        $this->log = $log;
88
+        $this->config = $config;
89
+        $this->checker = $checker;
90
+        $this->installer = $installer;
91
+    }
92
+
93
+    /**
94
+     * runs the update actions in maintenance mode, does not upgrade the source files
95
+     * except the main .htaccess file
96
+     *
97
+     * @return bool true if the operation succeeded, false otherwise
98
+     */
99
+    public function upgrade() {
100
+        $this->emitRepairEvents();
101
+        $this->logAllEvents();
102
+
103
+        $logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
104
+        $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
105
+        $this->config->setSystemValue('loglevel', ILogger::DEBUG);
106
+
107
+        $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
108
+
109
+        if(!$wasMaintenanceModeEnabled) {
110
+            $this->config->setSystemValue('maintenance', true);
111
+            $this->emit('\OC\Updater', 'maintenanceEnabled');
112
+        }
113
+
114
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
115
+        $currentVersion = implode('.', \OCP\Util::getVersion());
116
+
117
+        $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
118
+
119
+        $success = true;
120
+        try {
121
+            $this->doUpgrade($currentVersion, $installedVersion);
122
+        } catch (HintException $exception) {
123
+            $this->log->logException($exception, ['app' => 'core']);
124
+            $this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
125
+            $success = false;
126
+        } catch (\Exception $exception) {
127
+            $this->log->logException($exception, ['app' => 'core']);
128
+            $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
129
+            $success = false;
130
+        }
131
+
132
+        $this->emit('\OC\Updater', 'updateEnd', array($success));
133
+
134
+        if(!$wasMaintenanceModeEnabled && $success) {
135
+            $this->config->setSystemValue('maintenance', false);
136
+            $this->emit('\OC\Updater', 'maintenanceDisabled');
137
+        } else {
138
+            $this->emit('\OC\Updater', 'maintenanceActive');
139
+        }
140
+
141
+        $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
142
+        $this->config->setSystemValue('loglevel', $logLevel);
143
+        $this->config->setSystemValue('installed', true);
144
+
145
+        return $success;
146
+    }
147
+
148
+    /**
149
+     * Return version from which this version is allowed to upgrade from
150
+     *
151
+     * @return array allowed previous versions per vendor
152
+     */
153
+    private function getAllowedPreviousVersions() {
154
+        // this should really be a JSON file
155
+        require \OC::$SERVERROOT . '/version.php';
156
+        /** @var array $OC_VersionCanBeUpgradedFrom */
157
+        return $OC_VersionCanBeUpgradedFrom;
158
+    }
159
+
160
+    /**
161
+     * Return vendor from which this version was published
162
+     *
163
+     * @return string Get the vendor
164
+     */
165
+    private function getVendor() {
166
+        // this should really be a JSON file
167
+        require \OC::$SERVERROOT . '/version.php';
168
+        /** @var string $vendor */
169
+        return (string) $vendor;
170
+    }
171
+
172
+    /**
173
+     * Whether an upgrade to a specified version is possible
174
+     * @param string $oldVersion
175
+     * @param string $newVersion
176
+     * @param array $allowedPreviousVersions
177
+     * @return bool
178
+     */
179
+    public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
180
+        $version = explode('.', $oldVersion);
181
+        $majorMinor = $version[0] . '.' . $version[1];
182
+
183
+        $currentVendor = $this->config->getAppValue('core', 'vendor', '');
184
+
185
+        // Vendor was not set correctly on install, so we have to white-list known versions
186
+        if ($currentVendor === '' && isset($allowedPreviousVersions['owncloud'][$oldVersion])) {
187
+            $currentVendor = 'owncloud';
188
+        }
189
+
190
+        if ($currentVendor === 'nextcloud') {
191
+            return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
192
+                && (version_compare($oldVersion, $newVersion, '<=') ||
193
+                    $this->config->getSystemValue('debug', false));
194
+        }
195
+
196
+        // Check if the instance can be migrated
197
+        return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
198
+            isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
199
+    }
200
+
201
+    /**
202
+     * runs the update actions in maintenance mode, does not upgrade the source files
203
+     * except the main .htaccess file
204
+     *
205
+     * @param string $currentVersion current version to upgrade to
206
+     * @param string $installedVersion previous version from which to upgrade from
207
+     *
208
+     * @throws \Exception
209
+     */
210
+    private function doUpgrade($currentVersion, $installedVersion) {
211
+        // Stop update if the update is over several major versions
212
+        $allowedPreviousVersions = $this->getAllowedPreviousVersions();
213
+        if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
214
+            throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
215
+        }
216
+
217
+        // Update .htaccess files
218
+        try {
219
+            Setup::updateHtaccess();
220
+            Setup::protectDataDirectory();
221
+        } catch (\Exception $e) {
222
+            throw new \Exception($e->getMessage());
223
+        }
224
+
225
+        // create empty file in data dir, so we can later find
226
+        // out that this is indeed an ownCloud data directory
227
+        // (in case it didn't exist before)
228
+        file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
229
+
230
+        // pre-upgrade repairs
231
+        $repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
232
+        $repair->run();
233
+
234
+        $this->doCoreUpgrade();
235
+
236
+        try {
237
+            // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
238
+            Setup::installBackgroundJobs();
239
+        } catch (\Exception $e) {
240
+            throw new \Exception($e->getMessage());
241
+        }
242
+
243
+        // update all shipped apps
244
+        $this->checkAppsRequirements();
245
+        $this->doAppUpgrade();
246
+
247
+        // Update the appfetchers version so it downloads the correct list from the appstore
248
+        \OC::$server->getAppFetcher()->setVersion($currentVersion);
249
+
250
+        // upgrade appstore apps
251
+        $this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
252
+        $this->upgradeAppStoreApps(\OC_App::$autoDisabledApps, true);
253
+
254
+        // install new shipped apps on upgrade
255
+        OC_App::loadApps(['authentication']);
256
+        $errors = Installer::installShippedApps(true);
257
+        foreach ($errors as $appId => $exception) {
258
+            /** @var \Exception $exception */
259
+            $this->log->logException($exception, ['app' => $appId]);
260
+            $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
261
+        }
262
+
263
+        // post-upgrade repairs
264
+        $repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
265
+        $repair->run();
266
+
267
+        //Invalidate update feed
268
+        $this->config->setAppValue('core', 'lastupdatedat', 0);
269
+
270
+        // Check for code integrity if not disabled
271
+        if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
272
+            $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
273
+            $this->checker->runInstanceVerification();
274
+            $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
275
+        }
276
+
277
+        // only set the final version if everything went well
278
+        $this->config->setSystemValue('version', implode('.', Util::getVersion()));
279
+        $this->config->setAppValue('core', 'vendor', $this->getVendor());
280
+    }
281
+
282
+    protected function doCoreUpgrade() {
283
+        $this->emit('\OC\Updater', 'dbUpgradeBefore');
284
+
285
+        // execute core migrations
286
+        $ms = new MigrationService('core', \OC::$server->getDatabaseConnection());
287
+        $ms->migrate();
288
+
289
+        $this->emit('\OC\Updater', 'dbUpgrade');
290
+    }
291
+
292
+    /**
293
+     * @param string $version the oc version to check app compatibility with
294
+     */
295
+    protected function checkAppUpgrade($version) {
296
+        $apps = \OC_App::getEnabledApps();
297
+        $this->emit('\OC\Updater', 'appUpgradeCheckBefore');
298
+
299
+        $appManager = \OC::$server->getAppManager();
300
+        foreach ($apps as $appId) {
301
+            $info = \OC_App::getAppInfo($appId);
302
+            $compatible = \OC_App::isAppCompatible($version, $info);
303
+            $isShipped = $appManager->isShipped($appId);
304
+
305
+            if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
306
+                /**
307
+                 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
308
+                 * are not possible anymore within it. - Consider this when touching the code.
309
+                 * @link https://github.com/owncloud/core/issues/10980
310
+                 * @see \OC_App::updateApp
311
+                 */
312
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
313
+                    $this->includePreUpdate($appId);
314
+                }
315
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
316
+                    $this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
317
+                    \OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
318
+                }
319
+            }
320
+        }
321
+
322
+        $this->emit('\OC\Updater', 'appUpgradeCheck');
323
+    }
324
+
325
+    /**
326
+     * Includes the pre-update file. Done here to prevent namespace mixups.
327
+     * @param string $appId
328
+     */
329
+    private function includePreUpdate($appId) {
330
+        include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
331
+    }
332
+
333
+    /**
334
+     * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
335
+     * (types authentication, filesystem, logging, in that order) afterwards.
336
+     *
337
+     * @throws NeedsUpdateException
338
+     */
339
+    protected function doAppUpgrade() {
340
+        $apps = \OC_App::getEnabledApps();
341
+        $priorityTypes = array('authentication', 'filesystem', 'logging');
342
+        $pseudoOtherType = 'other';
343
+        $stacks = array($pseudoOtherType => array());
344
+
345
+        foreach ($apps as $appId) {
346
+            $priorityType = false;
347
+            foreach ($priorityTypes as $type) {
348
+                if(!isset($stacks[$type])) {
349
+                    $stacks[$type] = array();
350
+                }
351
+                if (\OC_App::isType($appId, [$type])) {
352
+                    $stacks[$type][] = $appId;
353
+                    $priorityType = true;
354
+                    break;
355
+                }
356
+            }
357
+            if (!$priorityType) {
358
+                $stacks[$pseudoOtherType][] = $appId;
359
+            }
360
+        }
361
+        foreach ($stacks as $type => $stack) {
362
+            foreach ($stack as $appId) {
363
+                if (\OC_App::shouldUpgrade($appId)) {
364
+                    $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
365
+                    \OC_App::updateApp($appId);
366
+                    $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
367
+                }
368
+                if($type !== $pseudoOtherType) {
369
+                    // load authentication, filesystem and logging apps after
370
+                    // upgrading them. Other apps my need to rely on modifying
371
+                    // user and/or filesystem aspects.
372
+                    \OC_App::loadApp($appId);
373
+                }
374
+            }
375
+        }
376
+    }
377
+
378
+    /**
379
+     * check if the current enabled apps are compatible with the current
380
+     * ownCloud version. disable them if not.
381
+     * This is important if you upgrade ownCloud and have non ported 3rd
382
+     * party apps installed.
383
+     *
384
+     * @return array
385
+     * @throws \Exception
386
+     */
387
+    private function checkAppsRequirements() {
388
+        $isCoreUpgrade = $this->isCodeUpgrade();
389
+        $apps = OC_App::getEnabledApps();
390
+        $version = implode('.', Util::getVersion());
391
+        $disabledApps = [];
392
+        $appManager = \OC::$server->getAppManager();
393
+        foreach ($apps as $app) {
394
+            // check if the app is compatible with this version of ownCloud
395
+            $info = OC_App::getAppInfo($app);
396
+            if($info === null || !OC_App::isAppCompatible($version, $info)) {
397
+                if ($appManager->isShipped($app)) {
398
+                    throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
399
+                }
400
+                \OC::$server->getAppManager()->disableApp($app);
401
+                $this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
402
+            }
403
+            // no need to disable any app in case this is a non-core upgrade
404
+            if (!$isCoreUpgrade) {
405
+                continue;
406
+            }
407
+            // shipped apps will remain enabled
408
+            if ($appManager->isShipped($app)) {
409
+                continue;
410
+            }
411
+            // authentication and session apps will remain enabled as well
412
+            if (OC_App::isType($app, ['session', 'authentication'])) {
413
+                continue;
414
+            }
415
+        }
416
+        return $disabledApps;
417
+    }
418
+
419
+    /**
420
+     * @return bool
421
+     */
422
+    private function isCodeUpgrade() {
423
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
424
+        $currentVersion = implode('.', Util::getVersion());
425
+        if (version_compare($currentVersion, $installedVersion, '>')) {
426
+            return true;
427
+        }
428
+        return false;
429
+    }
430
+
431
+    /**
432
+     * @param array $disabledApps
433
+     * @param bool $reenable
434
+     * @throws \Exception
435
+     */
436
+    private function upgradeAppStoreApps(array $disabledApps, $reenable = false) {
437
+        foreach($disabledApps as $app) {
438
+            try {
439
+                $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
440
+                if ($this->installer->isUpdateAvailable($app)) {
441
+                    $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
442
+                    $this->installer->updateAppstoreApp($app);
443
+                }
444
+                $this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
445
+
446
+                if ($reenable) {
447
+                    $ocApp = new \OC_App();
448
+                    $ocApp->enable($app);
449
+                }
450
+            } catch (\Exception $ex) {
451
+                $this->log->logException($ex, ['app' => 'core']);
452
+            }
453
+        }
454
+    }
455
+
456
+    /**
457
+     * Forward messages emitted by the repair routine
458
+     */
459
+    private function emitRepairEvents() {
460
+        $dispatcher = \OC::$server->getEventDispatcher();
461
+        $dispatcher->addListener('\OC\Repair::warning', function ($event) {
462
+            if ($event instanceof GenericEvent) {
463
+                $this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
464
+            }
465
+        });
466
+        $dispatcher->addListener('\OC\Repair::error', function ($event) {
467
+            if ($event instanceof GenericEvent) {
468
+                $this->emit('\OC\Updater', 'repairError', $event->getArguments());
469
+            }
470
+        });
471
+        $dispatcher->addListener('\OC\Repair::info', function ($event) {
472
+            if ($event instanceof GenericEvent) {
473
+                $this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
474
+            }
475
+        });
476
+        $dispatcher->addListener('\OC\Repair::step', function ($event) {
477
+            if ($event instanceof GenericEvent) {
478
+                $this->emit('\OC\Updater', 'repairStep', $event->getArguments());
479
+            }
480
+        });
481
+    }
482
+
483
+    private function logAllEvents() {
484
+        $log = $this->log;
485
+
486
+        $dispatcher = \OC::$server->getEventDispatcher();
487
+        $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
488
+            if (!$event instanceof GenericEvent) {
489
+                return;
490
+            }
491
+            $log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
492
+        });
493
+        $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
494
+            if (!$event instanceof GenericEvent) {
495
+                return;
496
+            }
497
+            $log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
498
+        });
499
+
500
+        $repairListener = function($event) use ($log) {
501
+            if (!$event instanceof GenericEvent) {
502
+                return;
503
+            }
504
+            switch ($event->getSubject()) {
505
+                case '\OC\Repair::startProgress':
506
+                    $log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
507
+                    break;
508
+                case '\OC\Repair::advance':
509
+                    $desc = $event->getArgument(1);
510
+                    if (empty($desc)) {
511
+                        $desc = '';
512
+                    }
513
+                    $log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
514
+
515
+                    break;
516
+                case '\OC\Repair::finishProgress':
517
+                    $log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
518
+                    break;
519
+                case '\OC\Repair::step':
520
+                    $log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
521
+                    break;
522
+                case '\OC\Repair::info':
523
+                    $log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
524
+                    break;
525
+                case '\OC\Repair::warning':
526
+                    $log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
527
+                    break;
528
+                case '\OC\Repair::error':
529
+                    $log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
530
+                    break;
531
+            }
532
+        };
533
+
534
+        $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
535
+        $dispatcher->addListener('\OC\Repair::advance', $repairListener);
536
+        $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
537
+        $dispatcher->addListener('\OC\Repair::step', $repairListener);
538
+        $dispatcher->addListener('\OC\Repair::info', $repairListener);
539
+        $dispatcher->addListener('\OC\Repair::warning', $repairListener);
540
+        $dispatcher->addListener('\OC\Repair::error', $repairListener);
541
+
542
+
543
+        $this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
544
+            $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
545
+        });
546
+        $this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
547
+            $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
548
+        });
549
+        $this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
550
+            $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
551
+        });
552
+        $this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
553
+            if ($success) {
554
+                $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
555
+            } else {
556
+                $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
557
+            }
558
+        });
559
+        $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
560
+            $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
561
+        });
562
+        $this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
563
+            $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
564
+        });
565
+        $this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
566
+            $log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
567
+        });
568
+        $this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
569
+            $log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
570
+        });
571
+        $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
572
+            $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
573
+        });
574
+        $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($log) {
575
+            $log->info('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
576
+        });
577
+        $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
578
+            $log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
579
+        });
580
+        $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($log) {
581
+            $log->info('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
582
+        });
583
+        $this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
584
+            $log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
585
+        });
586
+        $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
587
+            $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
588
+        });
589
+        $this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
590
+            $log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
591
+        });
592
+        $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
593
+            $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
594
+        });
595
+        $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
596
+            $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
597
+        });
598
+        $this->listen('\OC\Updater', 'failure', function ($message) use($log) {
599
+            $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
600
+        });
601
+        $this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
602
+            $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
603
+        });
604
+        $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
605
+            $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
606
+        });
607
+        $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
608
+            $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
609
+        });
610
+        $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
611
+            $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
612
+        });
613
+
614
+    }
615 615
 
616 616
 }
617 617
 
Please login to merge, or discard this patch.
core/ajax/update.php 2 patches
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 use Symfony\Component\EventDispatcher\GenericEvent;
34 34
 
35 35
 if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
36
-	@set_time_limit(0);
36
+    @set_time_limit(0);
37 37
 }
38 38
 
39 39
 require_once '../../lib/base.php';
@@ -47,188 +47,188 @@  discard block
 block discarded – undo
47 47
 $eventSource->send('success', (string)$l->t('Preparing update'));
48 48
 
49 49
 class FeedBackHandler {
50
-	/** @var integer */
51
-	private $progressStateMax = 100;
52
-	/** @var integer */
53
-	private $progressStateStep = 0;
54
-	/** @var string */
55
-	private $currentStep;
56
-	/** @var \OCP\IEventSource */
57
-	private $eventSource;
58
-	/** @var \OCP\IL10N */
59
-	private $l10n;
60
-
61
-	public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
62
-		$this->eventSource = $eventSource;
63
-		$this->l10n = $l10n;
64
-	}
65
-
66
-	public function handleRepairFeedback($event) {
67
-		if (!$event instanceof GenericEvent) {
68
-			return;
69
-		}
70
-
71
-		switch ($event->getSubject()) {
72
-			case '\OC\Repair::startProgress':
73
-				$this->progressStateMax = $event->getArgument(0);
74
-				$this->progressStateStep = 0;
75
-				$this->currentStep = $event->getArgument(1);
76
-				break;
77
-			case '\OC\Repair::advance':
78
-				$this->progressStateStep += $event->getArgument(0);
79
-				$desc = $event->getArgument(1);
80
-				if (empty($desc)) {
81
-					$desc = $this->currentStep;
82
-				}
83
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84
-				break;
85
-			case '\OC\Repair::finishProgress':
86
-				$this->progressStateMax = $this->progressStateStep;
87
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88
-				break;
89
-			case '\OC\Repair::step':
90
-				break;
91
-			case '\OC\Repair::info':
92
-				break;
93
-			case '\OC\Repair::warning':
94
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
95
-				break;
96
-			case '\OC\Repair::error':
97
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
98
-				break;
99
-		}
100
-	}
50
+    /** @var integer */
51
+    private $progressStateMax = 100;
52
+    /** @var integer */
53
+    private $progressStateStep = 0;
54
+    /** @var string */
55
+    private $currentStep;
56
+    /** @var \OCP\IEventSource */
57
+    private $eventSource;
58
+    /** @var \OCP\IL10N */
59
+    private $l10n;
60
+
61
+    public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
62
+        $this->eventSource = $eventSource;
63
+        $this->l10n = $l10n;
64
+    }
65
+
66
+    public function handleRepairFeedback($event) {
67
+        if (!$event instanceof GenericEvent) {
68
+            return;
69
+        }
70
+
71
+        switch ($event->getSubject()) {
72
+            case '\OC\Repair::startProgress':
73
+                $this->progressStateMax = $event->getArgument(0);
74
+                $this->progressStateStep = 0;
75
+                $this->currentStep = $event->getArgument(1);
76
+                break;
77
+            case '\OC\Repair::advance':
78
+                $this->progressStateStep += $event->getArgument(0);
79
+                $desc = $event->getArgument(1);
80
+                if (empty($desc)) {
81
+                    $desc = $this->currentStep;
82
+                }
83
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84
+                break;
85
+            case '\OC\Repair::finishProgress':
86
+                $this->progressStateMax = $this->progressStateStep;
87
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88
+                break;
89
+            case '\OC\Repair::step':
90
+                break;
91
+            case '\OC\Repair::info':
92
+                break;
93
+            case '\OC\Repair::warning':
94
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
95
+                break;
96
+            case '\OC\Repair::error':
97
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
98
+                break;
99
+        }
100
+    }
101 101
 }
102 102
 
103 103
 if (\OCP\Util::needUpgrade()) {
104 104
 
105
-	$config = \OC::$server->getSystemConfig();
106
-	if ($config->getValue('upgrade.disable-web', false)) {
107
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108
-		$eventSource->close();
109
-		exit();
110
-	}
111
-
112
-	// if a user is currently logged in, their session must be ignored to
113
-	// avoid side effects
114
-	\OC_User::setIncognitoMode(true);
115
-
116
-	$logger = \OC::$server->getLogger();
117
-	$config = \OC::$server->getConfig();
118
-	$updater = new \OC\Updater(
119
-			$config,
120
-			\OC::$server->getIntegrityCodeChecker(),
121
-			$logger,
122
-			\OC::$server->query(\OC\Installer::class)
123
-	);
124
-	$incompatibleApps = [];
125
-
126
-	$dispatcher = \OC::$server->getEventDispatcher();
127
-	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128
-		if ($event instanceof GenericEvent) {
129
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130
-		}
131
-	});
132
-	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133
-		if ($event instanceof GenericEvent) {
134
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135
-		}
136
-	});
137
-	$feedBack = new FeedBackHandler($eventSource, $l);
138
-	$dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
139
-	$dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
140
-	$dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
141
-	$dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
142
-	$dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
143
-	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144
-	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145
-
146
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
148
-	});
149
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
151
-	});
152
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
154
-	});
155
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
157
-	});
158
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
-		$eventSource->send('success', (string)$l->t('Updated database'));
160
-	});
161
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163
-	});
164
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
166
-	});
167
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
169
-	});
170
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
172
-	});
173
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
175
-	});
176
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
178
-	});
179
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181
-	});
182
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
184
-	});
185
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
-		$eventSource->send('success', (string)$l->t('Updated "%1$s" to %2$s', array($app, $version)));
187
-	});
188
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
-		$incompatibleApps[]= $app;
190
-	});
191
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
192
-		$eventSource->send('failure', $message);
193
-		$eventSource->close();
194
-		$config->setSystemValue('maintenance', false);
195
-	});
196
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
198
-	});
199
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
-		$eventSource->send('success', (string)$l->t('Reset log level'));
201
-	});
202
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
204
-	});
205
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
207
-	});
208
-
209
-	try {
210
-		$updater->upgrade();
211
-	} catch (\Exception $e) {
212
-		\OC::$server->getLogger()->logException($e, [
213
-			'level' => ILogger::ERROR,
214
-			'app' => 'update',
215
-		]);
216
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
217
-		$eventSource->close();
218
-		exit();
219
-	}
220
-
221
-	$disabledApps = [];
222
-	foreach ($incompatibleApps as $app) {
223
-		$disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
224
-	}
225
-
226
-	if (!empty($disabledApps)) {
227
-		$eventSource->send('notice',
228
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229
-	}
105
+    $config = \OC::$server->getSystemConfig();
106
+    if ($config->getValue('upgrade.disable-web', false)) {
107
+        $eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108
+        $eventSource->close();
109
+        exit();
110
+    }
111
+
112
+    // if a user is currently logged in, their session must be ignored to
113
+    // avoid side effects
114
+    \OC_User::setIncognitoMode(true);
115
+
116
+    $logger = \OC::$server->getLogger();
117
+    $config = \OC::$server->getConfig();
118
+    $updater = new \OC\Updater(
119
+            $config,
120
+            \OC::$server->getIntegrityCodeChecker(),
121
+            $logger,
122
+            \OC::$server->query(\OC\Installer::class)
123
+    );
124
+    $incompatibleApps = [];
125
+
126
+    $dispatcher = \OC::$server->getEventDispatcher();
127
+    $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128
+        if ($event instanceof GenericEvent) {
129
+            $eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130
+        }
131
+    });
132
+    $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133
+        if ($event instanceof GenericEvent) {
134
+            $eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135
+        }
136
+    });
137
+    $feedBack = new FeedBackHandler($eventSource, $l);
138
+    $dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
139
+    $dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
140
+    $dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
141
+    $dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
142
+    $dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
143
+    $dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144
+    $dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145
+
146
+    $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
+        $eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
148
+    });
149
+    $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
+        $eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
151
+    });
152
+    $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
+        $eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
154
+    });
155
+    $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
+        $eventSource->send('success', (string)$l->t('Updating database schema'));
157
+    });
158
+    $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
+        $eventSource->send('success', (string)$l->t('Updated database'));
160
+    });
161
+    $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163
+    });
164
+    $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
+        $eventSource->send('success', (string)$l->t('Checked database schema update'));
166
+    });
167
+    $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
+        $eventSource->send('success', (string)$l->t('Checking updates of apps'));
169
+    });
170
+    $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
+        $eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
172
+    });
173
+    $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
+        $eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
175
+    });
176
+    $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
+        $eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
178
+    });
179
+    $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181
+    });
182
+    $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
+        $eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
184
+    });
185
+    $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
+        $eventSource->send('success', (string)$l->t('Updated "%1$s" to %2$s', array($app, $version)));
187
+    });
188
+    $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
+        $incompatibleApps[]= $app;
190
+    });
191
+    $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
192
+        $eventSource->send('failure', $message);
193
+        $eventSource->close();
194
+        $config->setSystemValue('maintenance', false);
195
+    });
196
+    $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
+        $eventSource->send('success', (string)$l->t('Set log level to debug'));
198
+    });
199
+    $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
+        $eventSource->send('success', (string)$l->t('Reset log level'));
201
+    });
202
+    $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
+        $eventSource->send('success', (string)$l->t('Starting code integrity check'));
204
+    });
205
+    $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
+        $eventSource->send('success', (string)$l->t('Finished code integrity check'));
207
+    });
208
+
209
+    try {
210
+        $updater->upgrade();
211
+    } catch (\Exception $e) {
212
+        \OC::$server->getLogger()->logException($e, [
213
+            'level' => ILogger::ERROR,
214
+            'app' => 'update',
215
+        ]);
216
+        $eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
217
+        $eventSource->close();
218
+        exit();
219
+    }
220
+
221
+    $disabledApps = [];
222
+    foreach ($incompatibleApps as $app) {
223
+        $disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
224
+    }
225
+
226
+    if (!empty($disabledApps)) {
227
+        $eventSource->send('notice',
228
+            (string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229
+    }
230 230
 } else {
231
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
231
+    $eventSource->send('notice', (string)$l->t('Already up to date'));
232 232
 }
233 233
 
234 234
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 // need to send an initial message to force-init the event source,
45 45
 // which will then trigger its own CSRF check and produces its own CSRF error
46 46
 // message
47
-$eventSource->send('success', (string)$l->t('Preparing update'));
47
+$eventSource->send('success', (string) $l->t('Preparing update'));
48 48
 
49 49
 class FeedBackHandler {
50 50
 	/** @var integer */
@@ -80,21 +80,21 @@  discard block
 block discarded – undo
80 80
 				if (empty($desc)) {
81 81
 					$desc = $this->currentStep;
82 82
 				}
83
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
83
+				$this->eventSource->send('success', (string) $this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84 84
 				break;
85 85
 			case '\OC\Repair::finishProgress':
86 86
 				$this->progressStateMax = $this->progressStateStep;
87
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
87
+				$this->eventSource->send('success', (string) $this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88 88
 				break;
89 89
 			case '\OC\Repair::step':
90 90
 				break;
91 91
 			case '\OC\Repair::info':
92 92
 				break;
93 93
 			case '\OC\Repair::warning':
94
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
94
+				$this->eventSource->send('notice', (string) $this->l10n->t('Repair warning: ').$event->getArgument(0));
95 95
 				break;
96 96
 			case '\OC\Repair::error':
97
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
97
+				$this->eventSource->send('notice', (string) $this->l10n->t('Repair error: ').$event->getArgument(0));
98 98
 				break;
99 99
 		}
100 100
 	}
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 
105 105
 	$config = \OC::$server->getSystemConfig();
106 106
 	if ($config->getValue('upgrade.disable-web', false)) {
107
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
107
+		$eventSource->send('failure', (string) $l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108 108
 		$eventSource->close();
109 109
 		exit();
110 110
 	}
@@ -126,12 +126,12 @@  discard block
 block discarded – undo
126 126
 	$dispatcher = \OC::$server->getEventDispatcher();
127 127
 	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128 128
 		if ($event instanceof GenericEvent) {
129
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
+			$eventSource->send('success', (string) $l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130 130
 		}
131 131
 	});
132 132
 	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133 133
 		if ($event instanceof GenericEvent) {
134
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
+			$eventSource->send('success', (string) $l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135 135
 		}
136 136
 	});
137 137
 	$feedBack = new FeedBackHandler($eventSource, $l);
@@ -143,67 +143,67 @@  discard block
 block discarded – undo
143 143
 	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144 144
 	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145 145
 
146
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
146
+	$updater->listen('\OC\Updater', 'maintenanceEnabled', function() use ($eventSource, $l) {
147
+		$eventSource->send('success', (string) $l->t('Turned on maintenance mode'));
148 148
 	});
149
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
149
+	$updater->listen('\OC\Updater', 'maintenanceDisabled', function() use ($eventSource, $l) {
150
+		$eventSource->send('success', (string) $l->t('Turned off maintenance mode'));
151 151
 	});
152
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
152
+	$updater->listen('\OC\Updater', 'maintenanceActive', function() use ($eventSource, $l) {
153
+		$eventSource->send('success', (string) $l->t('Maintenance mode is kept active'));
154 154
 	});
155
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
155
+	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function() use($eventSource, $l) {
156
+		$eventSource->send('success', (string) $l->t('Updating database schema'));
157 157
 	});
158
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
-		$eventSource->send('success', (string)$l->t('Updated database'));
158
+	$updater->listen('\OC\Updater', 'dbUpgrade', function() use ($eventSource, $l) {
159
+		$eventSource->send('success', (string) $l->t('Updated database'));
160 160
 	});
161
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
161
+	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function() use($eventSource, $l) {
162
+		$eventSource->send('success', (string) $l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163 163
 	});
164
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
164
+	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function() use ($eventSource, $l) {
165
+		$eventSource->send('success', (string) $l->t('Checked database schema update'));
166 166
 	});
167
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
167
+	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function() use ($eventSource, $l) {
168
+		$eventSource->send('success', (string) $l->t('Checking updates of apps'));
169 169
 	});
170
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
170
+	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function($app) use ($eventSource, $l) {
171
+		$eventSource->send('success', (string) $l->t('Checking for update of app "%s" in appstore', [$app]));
172 172
 	});
173
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
173
+	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function($app) use ($eventSource, $l) {
174
+		$eventSource->send('success', (string) $l->t('Update app "%s" from appstore', [$app]));
175 175
 	});
176
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
176
+	$updater->listen('\OC\Updater', 'checkAppStoreApp', function($app) use ($eventSource, $l) {
177
+		$eventSource->send('success', (string) $l->t('Checked for update of app "%s" in appstore', [$app]));
178 178
 	});
179
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
179
+	$updater->listen('\OC\Updater', 'appSimulateUpdate', function($app) use ($eventSource, $l) {
180
+		$eventSource->send('success', (string) $l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181 181
 	});
182
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
182
+	$updater->listen('\OC\Updater', 'appUpgradeCheck', function() use ($eventSource, $l) {
183
+		$eventSource->send('success', (string) $l->t('Checked database schema update for apps'));
184 184
 	});
185
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
-		$eventSource->send('success', (string)$l->t('Updated "%1$s" to %2$s', array($app, $version)));
185
+	$updater->listen('\OC\Updater', 'appUpgrade', function($app, $version) use ($eventSource, $l) {
186
+		$eventSource->send('success', (string) $l->t('Updated "%1$s" to %2$s', array($app, $version)));
187 187
 	});
188
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
-		$incompatibleApps[]= $app;
188
+	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function($app) use (&$incompatibleApps) {
189
+		$incompatibleApps[] = $app;
190 190
 	});
191
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
191
+	$updater->listen('\OC\Updater', 'failure', function($message) use ($eventSource, $config) {
192 192
 		$eventSource->send('failure', $message);
193 193
 		$eventSource->close();
194 194
 		$config->setSystemValue('maintenance', false);
195 195
 	});
196
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
196
+	$updater->listen('\OC\Updater', 'setDebugLogLevel', function($logLevel, $logLevelName) use($eventSource, $l) {
197
+		$eventSource->send('success', (string) $l->t('Set log level to debug'));
198 198
 	});
199
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
-		$eventSource->send('success', (string)$l->t('Reset log level'));
199
+	$updater->listen('\OC\Updater', 'resetLogLevel', function($logLevel, $logLevelName) use($eventSource, $l) {
200
+		$eventSource->send('success', (string) $l->t('Reset log level'));
201 201
 	});
202
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
202
+	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function() use($eventSource, $l) {
203
+		$eventSource->send('success', (string) $l->t('Starting code integrity check'));
204 204
 	});
205
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
205
+	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function() use($eventSource, $l) {
206
+		$eventSource->send('success', (string) $l->t('Finished code integrity check'));
207 207
 	});
208 208
 
209 209
 	try {
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 			'level' => ILogger::ERROR,
214 214
 			'app' => 'update',
215 215
 		]);
216
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
216
+		$eventSource->send('failure', get_class($e).': '.$e->getMessage());
217 217
 		$eventSource->close();
218 218
 		exit();
219 219
 	}
@@ -225,10 +225,10 @@  discard block
 block discarded – undo
225 225
 
226 226
 	if (!empty($disabledApps)) {
227 227
 		$eventSource->send('notice',
228
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
228
+			(string) $l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229 229
 	}
230 230
 } else {
231
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
231
+	$eventSource->send('notice', (string) $l->t('Already up to date'));
232 232
 }
233 233
 
234 234
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
lib/private/BackgroundJob/JobList.php 1 patch
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -39,308 +39,308 @@
 block discarded – undo
39 39
 
40 40
 class JobList implements IJobList {
41 41
 
42
-	/** @var IDBConnection */
43
-	protected $connection;
44
-
45
-	/**@var IConfig */
46
-	protected $config;
47
-
48
-	/**@var ITimeFactory */
49
-	protected $timeFactory;
50
-
51
-	/**
52
-	 * @param IDBConnection $connection
53
-	 * @param IConfig $config
54
-	 * @param ITimeFactory $timeFactory
55
-	 */
56
-	public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
57
-		$this->connection = $connection;
58
-		$this->config = $config;
59
-		$this->timeFactory = $timeFactory;
60
-	}
61
-
62
-	/**
63
-	 * @param IJob|string $job
64
-	 * @param mixed $argument
65
-	 */
66
-	public function add($job, $argument = null) {
67
-		if (!$this->has($job, $argument)) {
68
-			if ($job instanceof IJob) {
69
-				$class = get_class($job);
70
-			} else {
71
-				$class = $job;
72
-			}
73
-
74
-			$argument = json_encode($argument);
75
-			if (strlen($argument) > 4000) {
76
-				throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
77
-			}
78
-
79
-			$query = $this->connection->getQueryBuilder();
80
-			$query->insert('jobs')
81
-				->values([
82
-					'class' => $query->createNamedParameter($class),
83
-					'argument' => $query->createNamedParameter($argument),
84
-					'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
85
-					'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
86
-				]);
87
-			$query->execute();
88
-		}
89
-	}
90
-
91
-	/**
92
-	 * @param IJob|string $job
93
-	 * @param mixed $argument
94
-	 */
95
-	public function remove($job, $argument = null) {
96
-		if ($job instanceof IJob) {
97
-			$class = get_class($job);
98
-		} else {
99
-			$class = $job;
100
-		}
101
-
102
-		$query = $this->connection->getQueryBuilder();
103
-		$query->delete('jobs')
104
-			->where($query->expr()->eq('class', $query->createNamedParameter($class)));
105
-		if (!is_null($argument)) {
106
-			$argument = json_encode($argument);
107
-			$query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)));
108
-		}
109
-		$query->execute();
110
-	}
111
-
112
-	/**
113
-	 * @param int $id
114
-	 */
115
-	protected function removeById($id) {
116
-		$query = $this->connection->getQueryBuilder();
117
-		$query->delete('jobs')
118
-			->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
119
-		$query->execute();
120
-	}
121
-
122
-	/**
123
-	 * check if a job is in the list
124
-	 *
125
-	 * @param IJob|string $job
126
-	 * @param mixed $argument
127
-	 * @return bool
128
-	 */
129
-	public function has($job, $argument) {
130
-		if ($job instanceof IJob) {
131
-			$class = get_class($job);
132
-		} else {
133
-			$class = $job;
134
-		}
135
-		$argument = json_encode($argument);
136
-
137
-		$query = $this->connection->getQueryBuilder();
138
-		$query->select('id')
139
-			->from('jobs')
140
-			->where($query->expr()->eq('class', $query->createNamedParameter($class)))
141
-			->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)))
142
-			->setMaxResults(1);
143
-
144
-		$result = $query->execute();
145
-		$row = $result->fetch();
146
-		$result->closeCursor();
147
-
148
-		return (bool) $row;
149
-	}
150
-
151
-	/**
152
-	 * get all jobs in the list
153
-	 *
154
-	 * @return IJob[]
155
-	 * @deprecated 9.0.0 - This method is dangerous since it can cause load and
156
-	 * memory problems when creating too many instances.
157
-	 */
158
-	public function getAll() {
159
-		$query = $this->connection->getQueryBuilder();
160
-		$query->select('*')
161
-			->from('jobs');
162
-		$result = $query->execute();
163
-
164
-		$jobs = [];
165
-		while ($row = $result->fetch()) {
166
-			$job = $this->buildJob($row);
167
-			if ($job) {
168
-				$jobs[] = $job;
169
-			}
170
-		}
171
-		$result->closeCursor();
172
-
173
-		return $jobs;
174
-	}
175
-
176
-	/**
177
-	 * get the next job in the list
178
-	 *
179
-	 * @return IJob|null
180
-	 * @suppress SqlInjectionChecker
181
-	 */
182
-	public function getNext() {
183
-		$query = $this->connection->getQueryBuilder();
184
-		$query->select('*')
185
-			->from('jobs')
186
-			->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
187
-			->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
188
-			->orderBy('last_checked', 'ASC')
189
-			->setMaxResults(1);
190
-
191
-		$update = $this->connection->getQueryBuilder();
192
-		$update->update('jobs')
193
-			->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
194
-			->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
195
-			->where($update->expr()->eq('id', $update->createParameter('jobid')))
196
-			->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
197
-			->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
198
-
199
-		$result = $query->execute();
200
-		$row = $result->fetch();
201
-		$result->closeCursor();
202
-
203
-		if ($row) {
204
-			$update->setParameter('jobid', $row['id']);
205
-			$update->setParameter('reserved_at', $row['reserved_at']);
206
-			$update->setParameter('last_checked', $row['last_checked']);
207
-			$count = $update->execute();
208
-
209
-			if ($count === 0) {
210
-				// Background job already executed elsewhere, try again.
211
-				return $this->getNext();
212
-			}
213
-			$job = $this->buildJob($row);
214
-
215
-			if ($job === null) {
216
-				// set the last_checked to 12h in the future to not check failing jobs all over again
217
-				$reset = $this->connection->getQueryBuilder();
218
-				$reset->update('jobs')
219
-					->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
220
-					->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
221
-					->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
222
-				$reset->execute();
223
-
224
-				// Background job from disabled app, try again.
225
-				return $this->getNext();
226
-			}
227
-
228
-			return $job;
229
-		} else {
230
-			return null;
231
-		}
232
-	}
233
-
234
-	/**
235
-	 * @param int $id
236
-	 * @return IJob|null
237
-	 */
238
-	public function getById($id) {
239
-		$query = $this->connection->getQueryBuilder();
240
-		$query->select('*')
241
-			->from('jobs')
242
-			->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
243
-		$result = $query->execute();
244
-		$row = $result->fetch();
245
-		$result->closeCursor();
246
-
247
-		if ($row) {
248
-			return $this->buildJob($row);
249
-		} else {
250
-			return null;
251
-		}
252
-	}
253
-
254
-	/**
255
-	 * get the job object from a row in the db
256
-	 *
257
-	 * @param array $row
258
-	 * @return IJob|null
259
-	 */
260
-	private function buildJob($row) {
261
-		try {
262
-			try {
263
-				// Try to load the job as a service
264
-				/** @var IJob $job */
265
-				$job = \OC::$server->query($row['class']);
266
-			} catch (QueryException $e) {
267
-				if (class_exists($row['class'])) {
268
-					$class = $row['class'];
269
-					$job = new $class();
270
-				} else {
271
-					// job from disabled app or old version of an app, no need to do anything
272
-					return null;
273
-				}
274
-			}
275
-
276
-			$job->setId($row['id']);
277
-			$job->setLastRun($row['last_run']);
278
-			$job->setArgument(json_decode($row['argument'], true));
279
-			return $job;
280
-		} catch (AutoloadNotAllowedException $e) {
281
-			// job is from a disabled app, ignore
282
-			return null;
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * set the job that was last ran
288
-	 *
289
-	 * @param IJob $job
290
-	 */
291
-	public function setLastJob(IJob $job) {
292
-		$this->unlockJob($job);
293
-		$this->config->setAppValue('backgroundjob', 'lastjob', $job->getId());
294
-	}
295
-
296
-	/**
297
-	 * Remove the reservation for a job
298
-	 *
299
-	 * @param IJob $job
300
-	 * @suppress SqlInjectionChecker
301
-	 */
302
-	public function unlockJob(IJob $job) {
303
-		$query = $this->connection->getQueryBuilder();
304
-		$query->update('jobs')
305
-			->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
306
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
307
-		$query->execute();
308
-	}
309
-
310
-	/**
311
-	 * get the id of the last ran job
312
-	 *
313
-	 * @return int
314
-	 * @deprecated 9.1.0 - The functionality behind the value is deprecated, it
315
-	 *    only tells you which job finished last, but since we now allow multiple
316
-	 *    executors to run in parallel, it's not used to calculate the next job.
317
-	 */
318
-	public function getLastJob() {
319
-		return (int) $this->config->getAppValue('backgroundjob', 'lastjob', 0);
320
-	}
321
-
322
-	/**
323
-	 * set the lastRun of $job to now
324
-	 *
325
-	 * @param IJob $job
326
-	 */
327
-	public function setLastRun(IJob $job) {
328
-		$query = $this->connection->getQueryBuilder();
329
-		$query->update('jobs')
330
-			->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
331
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
332
-		$query->execute();
333
-	}
334
-
335
-	/**
336
-	 * @param IJob $job
337
-	 * @param $timeTaken
338
-	 */
339
-	public function setExecutionTime(IJob $job, $timeTaken) {
340
-		$query = $this->connection->getQueryBuilder();
341
-		$query->update('jobs')
342
-			->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
343
-			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
344
-		$query->execute();
345
-	}
42
+    /** @var IDBConnection */
43
+    protected $connection;
44
+
45
+    /**@var IConfig */
46
+    protected $config;
47
+
48
+    /**@var ITimeFactory */
49
+    protected $timeFactory;
50
+
51
+    /**
52
+     * @param IDBConnection $connection
53
+     * @param IConfig $config
54
+     * @param ITimeFactory $timeFactory
55
+     */
56
+    public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
57
+        $this->connection = $connection;
58
+        $this->config = $config;
59
+        $this->timeFactory = $timeFactory;
60
+    }
61
+
62
+    /**
63
+     * @param IJob|string $job
64
+     * @param mixed $argument
65
+     */
66
+    public function add($job, $argument = null) {
67
+        if (!$this->has($job, $argument)) {
68
+            if ($job instanceof IJob) {
69
+                $class = get_class($job);
70
+            } else {
71
+                $class = $job;
72
+            }
73
+
74
+            $argument = json_encode($argument);
75
+            if (strlen($argument) > 4000) {
76
+                throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
77
+            }
78
+
79
+            $query = $this->connection->getQueryBuilder();
80
+            $query->insert('jobs')
81
+                ->values([
82
+                    'class' => $query->createNamedParameter($class),
83
+                    'argument' => $query->createNamedParameter($argument),
84
+                    'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
85
+                    'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
86
+                ]);
87
+            $query->execute();
88
+        }
89
+    }
90
+
91
+    /**
92
+     * @param IJob|string $job
93
+     * @param mixed $argument
94
+     */
95
+    public function remove($job, $argument = null) {
96
+        if ($job instanceof IJob) {
97
+            $class = get_class($job);
98
+        } else {
99
+            $class = $job;
100
+        }
101
+
102
+        $query = $this->connection->getQueryBuilder();
103
+        $query->delete('jobs')
104
+            ->where($query->expr()->eq('class', $query->createNamedParameter($class)));
105
+        if (!is_null($argument)) {
106
+            $argument = json_encode($argument);
107
+            $query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)));
108
+        }
109
+        $query->execute();
110
+    }
111
+
112
+    /**
113
+     * @param int $id
114
+     */
115
+    protected function removeById($id) {
116
+        $query = $this->connection->getQueryBuilder();
117
+        $query->delete('jobs')
118
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
119
+        $query->execute();
120
+    }
121
+
122
+    /**
123
+     * check if a job is in the list
124
+     *
125
+     * @param IJob|string $job
126
+     * @param mixed $argument
127
+     * @return bool
128
+     */
129
+    public function has($job, $argument) {
130
+        if ($job instanceof IJob) {
131
+            $class = get_class($job);
132
+        } else {
133
+            $class = $job;
134
+        }
135
+        $argument = json_encode($argument);
136
+
137
+        $query = $this->connection->getQueryBuilder();
138
+        $query->select('id')
139
+            ->from('jobs')
140
+            ->where($query->expr()->eq('class', $query->createNamedParameter($class)))
141
+            ->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument)))
142
+            ->setMaxResults(1);
143
+
144
+        $result = $query->execute();
145
+        $row = $result->fetch();
146
+        $result->closeCursor();
147
+
148
+        return (bool) $row;
149
+    }
150
+
151
+    /**
152
+     * get all jobs in the list
153
+     *
154
+     * @return IJob[]
155
+     * @deprecated 9.0.0 - This method is dangerous since it can cause load and
156
+     * memory problems when creating too many instances.
157
+     */
158
+    public function getAll() {
159
+        $query = $this->connection->getQueryBuilder();
160
+        $query->select('*')
161
+            ->from('jobs');
162
+        $result = $query->execute();
163
+
164
+        $jobs = [];
165
+        while ($row = $result->fetch()) {
166
+            $job = $this->buildJob($row);
167
+            if ($job) {
168
+                $jobs[] = $job;
169
+            }
170
+        }
171
+        $result->closeCursor();
172
+
173
+        return $jobs;
174
+    }
175
+
176
+    /**
177
+     * get the next job in the list
178
+     *
179
+     * @return IJob|null
180
+     * @suppress SqlInjectionChecker
181
+     */
182
+    public function getNext() {
183
+        $query = $this->connection->getQueryBuilder();
184
+        $query->select('*')
185
+            ->from('jobs')
186
+            ->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
187
+            ->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
188
+            ->orderBy('last_checked', 'ASC')
189
+            ->setMaxResults(1);
190
+
191
+        $update = $this->connection->getQueryBuilder();
192
+        $update->update('jobs')
193
+            ->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
194
+            ->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
195
+            ->where($update->expr()->eq('id', $update->createParameter('jobid')))
196
+            ->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
197
+            ->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
198
+
199
+        $result = $query->execute();
200
+        $row = $result->fetch();
201
+        $result->closeCursor();
202
+
203
+        if ($row) {
204
+            $update->setParameter('jobid', $row['id']);
205
+            $update->setParameter('reserved_at', $row['reserved_at']);
206
+            $update->setParameter('last_checked', $row['last_checked']);
207
+            $count = $update->execute();
208
+
209
+            if ($count === 0) {
210
+                // Background job already executed elsewhere, try again.
211
+                return $this->getNext();
212
+            }
213
+            $job = $this->buildJob($row);
214
+
215
+            if ($job === null) {
216
+                // set the last_checked to 12h in the future to not check failing jobs all over again
217
+                $reset = $this->connection->getQueryBuilder();
218
+                $reset->update('jobs')
219
+                    ->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
220
+                    ->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
221
+                    ->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
222
+                $reset->execute();
223
+
224
+                // Background job from disabled app, try again.
225
+                return $this->getNext();
226
+            }
227
+
228
+            return $job;
229
+        } else {
230
+            return null;
231
+        }
232
+    }
233
+
234
+    /**
235
+     * @param int $id
236
+     * @return IJob|null
237
+     */
238
+    public function getById($id) {
239
+        $query = $this->connection->getQueryBuilder();
240
+        $query->select('*')
241
+            ->from('jobs')
242
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
243
+        $result = $query->execute();
244
+        $row = $result->fetch();
245
+        $result->closeCursor();
246
+
247
+        if ($row) {
248
+            return $this->buildJob($row);
249
+        } else {
250
+            return null;
251
+        }
252
+    }
253
+
254
+    /**
255
+     * get the job object from a row in the db
256
+     *
257
+     * @param array $row
258
+     * @return IJob|null
259
+     */
260
+    private function buildJob($row) {
261
+        try {
262
+            try {
263
+                // Try to load the job as a service
264
+                /** @var IJob $job */
265
+                $job = \OC::$server->query($row['class']);
266
+            } catch (QueryException $e) {
267
+                if (class_exists($row['class'])) {
268
+                    $class = $row['class'];
269
+                    $job = new $class();
270
+                } else {
271
+                    // job from disabled app or old version of an app, no need to do anything
272
+                    return null;
273
+                }
274
+            }
275
+
276
+            $job->setId($row['id']);
277
+            $job->setLastRun($row['last_run']);
278
+            $job->setArgument(json_decode($row['argument'], true));
279
+            return $job;
280
+        } catch (AutoloadNotAllowedException $e) {
281
+            // job is from a disabled app, ignore
282
+            return null;
283
+        }
284
+    }
285
+
286
+    /**
287
+     * set the job that was last ran
288
+     *
289
+     * @param IJob $job
290
+     */
291
+    public function setLastJob(IJob $job) {
292
+        $this->unlockJob($job);
293
+        $this->config->setAppValue('backgroundjob', 'lastjob', $job->getId());
294
+    }
295
+
296
+    /**
297
+     * Remove the reservation for a job
298
+     *
299
+     * @param IJob $job
300
+     * @suppress SqlInjectionChecker
301
+     */
302
+    public function unlockJob(IJob $job) {
303
+        $query = $this->connection->getQueryBuilder();
304
+        $query->update('jobs')
305
+            ->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
306
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
307
+        $query->execute();
308
+    }
309
+
310
+    /**
311
+     * get the id of the last ran job
312
+     *
313
+     * @return int
314
+     * @deprecated 9.1.0 - The functionality behind the value is deprecated, it
315
+     *    only tells you which job finished last, but since we now allow multiple
316
+     *    executors to run in parallel, it's not used to calculate the next job.
317
+     */
318
+    public function getLastJob() {
319
+        return (int) $this->config->getAppValue('backgroundjob', 'lastjob', 0);
320
+    }
321
+
322
+    /**
323
+     * set the lastRun of $job to now
324
+     *
325
+     * @param IJob $job
326
+     */
327
+    public function setLastRun(IJob $job) {
328
+        $query = $this->connection->getQueryBuilder();
329
+        $query->update('jobs')
330
+            ->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
331
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
332
+        $query->execute();
333
+    }
334
+
335
+    /**
336
+     * @param IJob $job
337
+     * @param $timeTaken
338
+     */
339
+    public function setExecutionTime(IJob $job, $timeTaken) {
340
+        $query = $this->connection->getQueryBuilder();
341
+        $query->update('jobs')
342
+            ->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
343
+            ->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
344
+        $query->execute();
345
+    }
346 346
 }
Please login to merge, or discard this patch.