Passed
Push — master ( 0ac3a6...0157e3 )
by Roeland
11:52 queued 13s
created
apps/dav/lib/Migration/Version1005Date20180530124431.php 2 patches
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -33,56 +33,56 @@
 block discarded – undo
33 33
 
34 34
 class Version1005Date20180530124431 extends SimpleMigrationStep {
35 35
 
36
-	/**
37
-	 * @param IOutput $output
38
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
39
-	 * @param array $options
40
-	 * @return null|ISchemaWrapper
41
-	 * @since 13.0.0
42
-	 */
43
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
44
-		/** @var ISchemaWrapper $schema */
45
-		$schema = $schemaClosure();
36
+    /**
37
+     * @param IOutput $output
38
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
39
+     * @param array $options
40
+     * @return null|ISchemaWrapper
41
+     * @since 13.0.0
42
+     */
43
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
44
+        /** @var ISchemaWrapper $schema */
45
+        $schema = $schemaClosure();
46 46
 
47
-		$types = ['resources', 'rooms'];
48
-		foreach ($types as $type) {
49
-			if (!$schema->hasTable('calendar_' . $type)) {
50
-				$table = $schema->createTable('calendar_' . $type);
47
+        $types = ['resources', 'rooms'];
48
+        foreach ($types as $type) {
49
+            if (!$schema->hasTable('calendar_' . $type)) {
50
+                $table = $schema->createTable('calendar_' . $type);
51 51
 
52
-				$table->addColumn('id', Types::BIGINT, [
53
-					'autoincrement' => true,
54
-					'notnull' => true,
55
-					'length' => 11,
56
-					'unsigned' => true,
57
-				]);
58
-				$table->addColumn('backend_id', Types::STRING, [
59
-					'notnull' => false,
60
-					'length' => 64,
61
-				]);
62
-				$table->addColumn('resource_id', Types::STRING, [
63
-					'notnull' => false,
64
-					'length' => 64,
65
-				]);
66
-				$table->addColumn('email', Types::STRING, [
67
-					'notnull' => false,
68
-					'length' => 255,
69
-				]);
70
-				$table->addColumn('displayname', Types::STRING, [
71
-					'notnull' => false,
72
-					'length' => 255,
73
-				]);
74
-				$table->addColumn('group_restrictions', Types::STRING, [
75
-					'notnull' => false,
76
-					'length' => 4000,
77
-				]);
52
+                $table->addColumn('id', Types::BIGINT, [
53
+                    'autoincrement' => true,
54
+                    'notnull' => true,
55
+                    'length' => 11,
56
+                    'unsigned' => true,
57
+                ]);
58
+                $table->addColumn('backend_id', Types::STRING, [
59
+                    'notnull' => false,
60
+                    'length' => 64,
61
+                ]);
62
+                $table->addColumn('resource_id', Types::STRING, [
63
+                    'notnull' => false,
64
+                    'length' => 64,
65
+                ]);
66
+                $table->addColumn('email', Types::STRING, [
67
+                    'notnull' => false,
68
+                    'length' => 255,
69
+                ]);
70
+                $table->addColumn('displayname', Types::STRING, [
71
+                    'notnull' => false,
72
+                    'length' => 255,
73
+                ]);
74
+                $table->addColumn('group_restrictions', Types::STRING, [
75
+                    'notnull' => false,
76
+                    'length' => 4000,
77
+                ]);
78 78
 
79
-				$table->setPrimaryKey(['id']);
80
-				$table->addIndex(['backend_id', 'resource_id'], 'calendar_' . $type . '_bkdrsc');
81
-				$table->addIndex(['email'], 'calendar_' . $type . '_email');
82
-				$table->addIndex(['displayname'], 'calendar_' . $type . '_name');
83
-			}
84
-		}
79
+                $table->setPrimaryKey(['id']);
80
+                $table->addIndex(['backend_id', 'resource_id'], 'calendar_' . $type . '_bkdrsc');
81
+                $table->addIndex(['email'], 'calendar_' . $type . '_email');
82
+                $table->addIndex(['displayname'], 'calendar_' . $type . '_name');
83
+            }
84
+        }
85 85
 
86
-		return $schema;
87
-	}
86
+        return $schema;
87
+    }
88 88
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -46,8 +46,8 @@  discard block
 block discarded – undo
46 46
 
47 47
 		$types = ['resources', 'rooms'];
48 48
 		foreach ($types as $type) {
49
-			if (!$schema->hasTable('calendar_' . $type)) {
50
-				$table = $schema->createTable('calendar_' . $type);
49
+			if (!$schema->hasTable('calendar_'.$type)) {
50
+				$table = $schema->createTable('calendar_'.$type);
51 51
 
52 52
 				$table->addColumn('id', Types::BIGINT, [
53 53
 					'autoincrement' => true,
@@ -77,9 +77,9 @@  discard block
 block discarded – undo
77 77
 				]);
78 78
 
79 79
 				$table->setPrimaryKey(['id']);
80
-				$table->addIndex(['backend_id', 'resource_id'], 'calendar_' . $type . '_bkdrsc');
81
-				$table->addIndex(['email'], 'calendar_' . $type . '_email');
82
-				$table->addIndex(['displayname'], 'calendar_' . $type . '_name');
80
+				$table->addIndex(['backend_id', 'resource_id'], 'calendar_'.$type.'_bkdrsc');
81
+				$table->addIndex(['email'], 'calendar_'.$type.'_email');
82
+				$table->addIndex(['displayname'], 'calendar_'.$type.'_name');
83 83
 			}
84 84
 		}
85 85
 
Please login to merge, or discard this patch.
apps/dav/lib/Migration/Version1011Date20190725113607.php 2 patches
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -37,55 +37,55 @@
 block discarded – undo
37 37
  */
38 38
 class Version1011Date20190725113607 extends SimpleMigrationStep {
39 39
 
40
-	/**
41
-	 * @param IOutput $output
42
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
43
-	 * @param array $options
44
-	 * @return null|ISchemaWrapper
45
-	 * @since 13.0.0
46
-	 */
47
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
48
-		/** @var ISchemaWrapper $schema */
49
-		$schema = $schemaClosure();
40
+    /**
41
+     * @param IOutput $output
42
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
43
+     * @param array $options
44
+     * @return null|ISchemaWrapper
45
+     * @since 13.0.0
46
+     */
47
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
48
+        /** @var ISchemaWrapper $schema */
49
+        $schema = $schemaClosure();
50 50
 
51
-		$types = ['resource', 'room'];
52
-		foreach ($types as $type) {
53
-			if (!$schema->hasTable($this->getMetadataTableName($type))) {
54
-				$table = $schema->createTable($this->getMetadataTableName($type));
51
+        $types = ['resource', 'room'];
52
+        foreach ($types as $type) {
53
+            if (!$schema->hasTable($this->getMetadataTableName($type))) {
54
+                $table = $schema->createTable($this->getMetadataTableName($type));
55 55
 
56
-				$table->addColumn('id', Types::BIGINT, [
57
-					'autoincrement' => true,
58
-					'notnull' => true,
59
-					'length' => 11,
60
-					'unsigned' => true,
61
-				]);
62
-				$table->addColumn($type . '_id', Types::BIGINT, [
63
-					'notnull' => true,
64
-					'length' => 11,
65
-					'unsigned' => true,
66
-				]);
67
-				$table->addColumn('key', Types::STRING, [
68
-					'notnull' => true,
69
-					'length' => 255,
70
-				]);
71
-				$table->addColumn('value', Types::STRING, [
72
-					'notnull' => false,
73
-					'length' => 4000,
74
-				]);
56
+                $table->addColumn('id', Types::BIGINT, [
57
+                    'autoincrement' => true,
58
+                    'notnull' => true,
59
+                    'length' => 11,
60
+                    'unsigned' => true,
61
+                ]);
62
+                $table->addColumn($type . '_id', Types::BIGINT, [
63
+                    'notnull' => true,
64
+                    'length' => 11,
65
+                    'unsigned' => true,
66
+                ]);
67
+                $table->addColumn('key', Types::STRING, [
68
+                    'notnull' => true,
69
+                    'length' => 255,
70
+                ]);
71
+                $table->addColumn('value', Types::STRING, [
72
+                    'notnull' => false,
73
+                    'length' => 4000,
74
+                ]);
75 75
 
76
-				$table->setPrimaryKey(['id']);
77
-				$table->addIndex([$type . '_id', 'key'], $this->getMetadataTableName($type) . '_idk');
78
-			}
79
-		}
76
+                $table->setPrimaryKey(['id']);
77
+                $table->addIndex([$type . '_id', 'key'], $this->getMetadataTableName($type) . '_idk');
78
+            }
79
+        }
80 80
 
81
-		return $schema;
82
-	}
81
+        return $schema;
82
+    }
83 83
 
84
-	/**
85
-	 * @param string $type
86
-	 * @return string
87
-	 */
88
-	private function getMetadataTableName(string $type):string {
89
-		return 'calendar_' . $type . 's_md';
90
-	}
84
+    /**
85
+     * @param string $type
86
+     * @return string
87
+     */
88
+    private function getMetadataTableName(string $type):string {
89
+        return 'calendar_' . $type . 's_md';
90
+    }
91 91
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 					'length' => 11,
60 60
 					'unsigned' => true,
61 61
 				]);
62
-				$table->addColumn($type . '_id', Types::BIGINT, [
62
+				$table->addColumn($type.'_id', Types::BIGINT, [
63 63
 					'notnull' => true,
64 64
 					'length' => 11,
65 65
 					'unsigned' => true,
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 				]);
75 75
 
76 76
 				$table->setPrimaryKey(['id']);
77
-				$table->addIndex([$type . '_id', 'key'], $this->getMetadataTableName($type) . '_idk');
77
+				$table->addIndex([$type.'_id', 'key'], $this->getMetadataTableName($type).'_idk');
78 78
 			}
79 79
 		}
80 80
 
@@ -86,6 +86,6 @@  discard block
 block discarded – undo
86 86
 	 * @return string
87 87
 	 */
88 88
 	private function getMetadataTableName(string $type):string {
89
-		return 'calendar_' . $type . 's_md';
89
+		return 'calendar_'.$type.'s_md';
90 90
 	}
91 91
 }
Please login to merge, or discard this patch.
apps/workflowengine/lib/Migration/Version2000Date20190808074233.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -13,117 +13,117 @@
 block discarded – undo
13 13
 
14 14
 class Version2000Date20190808074233 extends SimpleMigrationStep {
15 15
 
16
-	/**
17
-	 * @param IOutput $output
18
-	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
19
-	 * @param array $options
20
-	 * @return null|ISchemaWrapper
21
-	 */
22
-	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) {
23
-		/** @var ISchemaWrapper $schema */
24
-		$schema = $schemaClosure();
16
+    /**
17
+     * @param IOutput $output
18
+     * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
19
+     * @param array $options
20
+     * @return null|ISchemaWrapper
21
+     */
22
+    public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) {
23
+        /** @var ISchemaWrapper $schema */
24
+        $schema = $schemaClosure();
25 25
 
26
-		if (!$schema->hasTable('flow_checks')) {
27
-			$table = $schema->createTable('flow_checks');
28
-			$table->addColumn('id', Types::INTEGER, [
29
-				'autoincrement' => true,
30
-				'notnull' => true,
31
-				'length' => 4,
32
-			]);
33
-			$table->addColumn('class', Types::STRING, [
34
-				'notnull' => true,
35
-				'length' => 256,
36
-				'default' => '',
37
-			]);
38
-			$table->addColumn('operator', Types::STRING, [
39
-				'notnull' => true,
40
-				'length' => 16,
41
-				'default' => '',
42
-			]);
43
-			$table->addColumn('value', Types::TEXT, [
44
-				'notnull' => false,
45
-			]);
46
-			$table->addColumn('hash', Types::STRING, [
47
-				'notnull' => true,
48
-				'length' => 32,
49
-				'default' => '',
50
-			]);
51
-			$table->setPrimaryKey(['id']);
52
-			$table->addUniqueIndex(['hash'], 'flow_unique_hash');
53
-		}
26
+        if (!$schema->hasTable('flow_checks')) {
27
+            $table = $schema->createTable('flow_checks');
28
+            $table->addColumn('id', Types::INTEGER, [
29
+                'autoincrement' => true,
30
+                'notnull' => true,
31
+                'length' => 4,
32
+            ]);
33
+            $table->addColumn('class', Types::STRING, [
34
+                'notnull' => true,
35
+                'length' => 256,
36
+                'default' => '',
37
+            ]);
38
+            $table->addColumn('operator', Types::STRING, [
39
+                'notnull' => true,
40
+                'length' => 16,
41
+                'default' => '',
42
+            ]);
43
+            $table->addColumn('value', Types::TEXT, [
44
+                'notnull' => false,
45
+            ]);
46
+            $table->addColumn('hash', Types::STRING, [
47
+                'notnull' => true,
48
+                'length' => 32,
49
+                'default' => '',
50
+            ]);
51
+            $table->setPrimaryKey(['id']);
52
+            $table->addUniqueIndex(['hash'], 'flow_unique_hash');
53
+        }
54 54
 
55
-		if (!$schema->hasTable('flow_operations')) {
56
-			$table = $schema->createTable('flow_operations');
57
-			$table->addColumn('id', Types::INTEGER, [
58
-				'autoincrement' => true,
59
-				'notnull' => true,
60
-				'length' => 4,
61
-			]);
62
-			$table->addColumn('class', Types::STRING, [
63
-				'notnull' => true,
64
-				'length' => 256,
65
-				'default' => '',
66
-			]);
67
-			$table->addColumn('name', Types::STRING, [
68
-				'notnull' => true,
69
-				'length' => 256,
70
-				'default' => '',
71
-			]);
72
-			$table->addColumn('checks', Types::TEXT, [
73
-				'notnull' => false,
74
-			]);
75
-			$table->addColumn('operation', Types::TEXT, [
76
-				'notnull' => false,
77
-			]);
78
-			$this->ensureEntityColumns($table);
79
-			$table->setPrimaryKey(['id']);
80
-		} else {
81
-			$table = $schema->getTable('flow_operations');
82
-			$this->ensureEntityColumns($table);
83
-		}
55
+        if (!$schema->hasTable('flow_operations')) {
56
+            $table = $schema->createTable('flow_operations');
57
+            $table->addColumn('id', Types::INTEGER, [
58
+                'autoincrement' => true,
59
+                'notnull' => true,
60
+                'length' => 4,
61
+            ]);
62
+            $table->addColumn('class', Types::STRING, [
63
+                'notnull' => true,
64
+                'length' => 256,
65
+                'default' => '',
66
+            ]);
67
+            $table->addColumn('name', Types::STRING, [
68
+                'notnull' => true,
69
+                'length' => 256,
70
+                'default' => '',
71
+            ]);
72
+            $table->addColumn('checks', Types::TEXT, [
73
+                'notnull' => false,
74
+            ]);
75
+            $table->addColumn('operation', Types::TEXT, [
76
+                'notnull' => false,
77
+            ]);
78
+            $this->ensureEntityColumns($table);
79
+            $table->setPrimaryKey(['id']);
80
+        } else {
81
+            $table = $schema->getTable('flow_operations');
82
+            $this->ensureEntityColumns($table);
83
+        }
84 84
 
85
-		if (!$schema->hasTable('flow_operations_scope')) {
86
-			$table = $schema->createTable('flow_operations_scope');
87
-			$table->addColumn('id', Types::BIGINT, [
88
-				'autoincrement' => true,
89
-				'notnull' => true,
90
-				'length' => 4,
91
-			]);
92
-			$table->addColumn('operation_id', Types::INTEGER, [
93
-				'notnull' => true,
94
-				'length' => 4,
95
-				'default' => 0,
96
-			]);
97
-			$table->addColumn('type', Types::INTEGER, [
98
-				'notnull' => true,
99
-				'length' => 4,
100
-				'default' => 0,
101
-			]);
102
-			$table->addColumn('value', Types::STRING, [
103
-				'notnull' => false,
104
-				'length' => 64,
105
-				'default' => '',
106
-			]);
107
-			$table->setPrimaryKey(['id']);
108
-			$table->addUniqueIndex(['operation_id', 'type', 'value'], 'flow_unique_scope');
109
-		}
85
+        if (!$schema->hasTable('flow_operations_scope')) {
86
+            $table = $schema->createTable('flow_operations_scope');
87
+            $table->addColumn('id', Types::BIGINT, [
88
+                'autoincrement' => true,
89
+                'notnull' => true,
90
+                'length' => 4,
91
+            ]);
92
+            $table->addColumn('operation_id', Types::INTEGER, [
93
+                'notnull' => true,
94
+                'length' => 4,
95
+                'default' => 0,
96
+            ]);
97
+            $table->addColumn('type', Types::INTEGER, [
98
+                'notnull' => true,
99
+                'length' => 4,
100
+                'default' => 0,
101
+            ]);
102
+            $table->addColumn('value', Types::STRING, [
103
+                'notnull' => false,
104
+                'length' => 64,
105
+                'default' => '',
106
+            ]);
107
+            $table->setPrimaryKey(['id']);
108
+            $table->addUniqueIndex(['operation_id', 'type', 'value'], 'flow_unique_scope');
109
+        }
110 110
 
111
-		return $schema;
112
-	}
111
+        return $schema;
112
+    }
113 113
 
114
-	protected function ensureEntityColumns(Table $table) {
115
-		if (!$table->hasColumn('entity')) {
116
-			$table->addColumn('entity', Types::STRING, [
117
-				'notnull' => true,
118
-				'length' => 256,
119
-				'default' => '',
120
-			]);
121
-		}
122
-		if (!$table->hasColumn('events')) {
123
-			$table->addColumn('events', Types::TEXT, [
124
-				'notnull' => true,
125
-				'default' => '[]',
126
-			]);
127
-		}
128
-	}
114
+    protected function ensureEntityColumns(Table $table) {
115
+        if (!$table->hasColumn('entity')) {
116
+            $table->addColumn('entity', Types::STRING, [
117
+                'notnull' => true,
118
+                'length' => 256,
119
+                'default' => '',
120
+            ]);
121
+        }
122
+        if (!$table->hasColumn('events')) {
123
+            $table->addColumn('events', Types::TEXT, [
124
+                'notnull' => true,
125
+                'default' => '[]',
126
+            ]);
127
+        }
128
+    }
129 129
 }
Please login to merge, or discard this patch.
apps/settings/lib/Controller/CheckSetupController.php 2 patches
Indentation   +644 added lines, -644 removed lines patch added patch discarded remove patch
@@ -71,288 +71,288 @@  discard block
 block discarded – undo
71 71
 use Symfony\Component\EventDispatcher\GenericEvent;
72 72
 
73 73
 class CheckSetupController extends Controller {
74
-	/** @var IConfig */
75
-	private $config;
76
-	/** @var IClientService */
77
-	private $clientService;
78
-	/** @var IURLGenerator */
79
-	private $urlGenerator;
80
-	/** @var IL10N */
81
-	private $l10n;
82
-	/** @var Checker */
83
-	private $checker;
84
-	/** @var ILogger */
85
-	private $logger;
86
-	/** @var EventDispatcherInterface */
87
-	private $dispatcher;
88
-	/** @var IDBConnection|Connection */
89
-	private $db;
90
-	/** @var ILockingProvider */
91
-	private $lockingProvider;
92
-	/** @var IDateTimeFormatter */
93
-	private $dateTimeFormatter;
94
-	/** @var MemoryInfo */
95
-	private $memoryInfo;
96
-	/** @var ISecureRandom */
97
-	private $secureRandom;
98
-
99
-	public function __construct($AppName,
100
-								IRequest $request,
101
-								IConfig $config,
102
-								IClientService $clientService,
103
-								IURLGenerator $urlGenerator,
104
-								IL10N $l10n,
105
-								Checker $checker,
106
-								ILogger $logger,
107
-								EventDispatcherInterface $dispatcher,
108
-								IDBConnection $db,
109
-								ILockingProvider $lockingProvider,
110
-								IDateTimeFormatter $dateTimeFormatter,
111
-								MemoryInfo $memoryInfo,
112
-								ISecureRandom $secureRandom) {
113
-		parent::__construct($AppName, $request);
114
-		$this->config = $config;
115
-		$this->clientService = $clientService;
116
-		$this->urlGenerator = $urlGenerator;
117
-		$this->l10n = $l10n;
118
-		$this->checker = $checker;
119
-		$this->logger = $logger;
120
-		$this->dispatcher = $dispatcher;
121
-		$this->db = $db;
122
-		$this->lockingProvider = $lockingProvider;
123
-		$this->dateTimeFormatter = $dateTimeFormatter;
124
-		$this->memoryInfo = $memoryInfo;
125
-		$this->secureRandom = $secureRandom;
126
-	}
127
-
128
-	/**
129
-	 * Checks if the server can connect to the internet using HTTPS and HTTP
130
-	 * @return bool
131
-	 */
132
-	private function hasInternetConnectivityProblems(): bool {
133
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
134
-			return false;
135
-		}
136
-
137
-		$siteArray = $this->config->getSystemValue('connectivity_check_domains', [
138
-			'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org'
139
-		]);
140
-
141
-		foreach ($siteArray as $site) {
142
-			if ($this->isSiteReachable($site)) {
143
-				return false;
144
-			}
145
-		}
146
-		return true;
147
-	}
148
-
149
-	/**
150
-	 * Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
151
-	 * @return bool
152
-	 */
153
-	private function isSiteReachable($sitename) {
154
-		$httpSiteName = 'http://' . $sitename . '/';
155
-		$httpsSiteName = 'https://' . $sitename . '/';
156
-
157
-		try {
158
-			$client = $this->clientService->newClient();
159
-			$client->get($httpSiteName);
160
-			$client->get($httpsSiteName);
161
-		} catch (\Exception $e) {
162
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
163
-			return false;
164
-		}
165
-		return true;
166
-	}
167
-
168
-	/**
169
-	 * Checks whether a local memcache is installed or not
170
-	 * @return bool
171
-	 */
172
-	private function isMemcacheConfigured() {
173
-		return $this->config->getSystemValue('memcache.local', null) !== null;
174
-	}
175
-
176
-	/**
177
-	 * Whether PHP can generate "secure" pseudorandom integers
178
-	 *
179
-	 * @return bool
180
-	 */
181
-	private function isRandomnessSecure() {
182
-		try {
183
-			$this->secureRandom->generate(1);
184
-		} catch (\Exception $ex) {
185
-			return false;
186
-		}
187
-		return true;
188
-	}
189
-
190
-	/**
191
-	 * Public for the sake of unit-testing
192
-	 *
193
-	 * @return array
194
-	 */
195
-	protected function getCurlVersion() {
196
-		return curl_version();
197
-	}
198
-
199
-	/**
200
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
201
-	 * have multiple bugs which likely lead to problems in combination with
202
-	 * functionality required by ownCloud such as SNI.
203
-	 *
204
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
205
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
206
-	 * @return string
207
-	 */
208
-	private function isUsedTlsLibOutdated() {
209
-		// Don't run check when:
210
-		// 1. Server has `has_internet_connection` set to false
211
-		// 2. AppStore AND S2S is disabled
212
-		if (!$this->config->getSystemValue('has_internet_connection', true)) {
213
-			return '';
214
-		}
215
-		if (!$this->config->getSystemValue('appstoreenabled', true)
216
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
217
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
218
-			return '';
219
-		}
220
-
221
-		$versionString = $this->getCurlVersion();
222
-		if (isset($versionString['ssl_version'])) {
223
-			$versionString = $versionString['ssl_version'];
224
-		} else {
225
-			return '';
226
-		}
227
-
228
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
229
-		if (!$this->config->getSystemValue('appstoreenabled', true)) {
230
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
231
-		}
232
-
233
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
234
-		if (strpos($versionString, 'OpenSSL/') === 0) {
235
-			$majorVersion = substr($versionString, 8, 5);
236
-			$patchRelease = substr($versionString, 13, 6);
237
-
238
-			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
239
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
240
-				return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
241
-			}
242
-		}
243
-
244
-		// Check if NSS and perform heuristic check
245
-		if (strpos($versionString, 'NSS/') === 0) {
246
-			try {
247
-				$firstClient = $this->clientService->newClient();
248
-				$firstClient->get('https://nextcloud.com/');
249
-
250
-				$secondClient = $this->clientService->newClient();
251
-				$secondClient->get('https://nextcloud.com/');
252
-			} catch (ClientException $e) {
253
-				if ($e->getResponse()->getStatusCode() === 400) {
254
-					return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
255
-				}
256
-			}
257
-		}
258
-
259
-		return '';
260
-	}
261
-
262
-	/**
263
-	 * Whether the version is outdated
264
-	 *
265
-	 * @return bool
266
-	 */
267
-	protected function isPhpOutdated(): bool {
268
-		return PHP_VERSION_ID < 70300;
269
-	}
270
-
271
-	/**
272
-	 * Whether the php version is still supported (at time of release)
273
-	 * according to: https://secure.php.net/supported-versions.php
274
-	 *
275
-	 * @return array
276
-	 */
277
-	private function isPhpSupported(): array {
278
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
279
-	}
280
-
281
-	/**
282
-	 * Check if the reverse proxy configuration is working as expected
283
-	 *
284
-	 * @return bool
285
-	 */
286
-	private function forwardedForHeadersWorking() {
287
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
288
-		$remoteAddress = $this->request->getHeader('REMOTE_ADDR');
289
-
290
-		if (empty($trustedProxies) && $this->request->getHeader('X-Forwarded-Host') !== '') {
291
-			return false;
292
-		}
293
-
294
-		if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies, true)) {
295
-			return $remoteAddress !== $this->request->getRemoteAddress();
296
-		}
297
-
298
-		// either not enabled or working correctly
299
-		return true;
300
-	}
301
-
302
-	/**
303
-	 * Checks if the correct memcache module for PHP is installed. Only
304
-	 * fails if memcached is configured and the working module is not installed.
305
-	 *
306
-	 * @return bool
307
-	 */
308
-	private function isCorrectMemcachedPHPModuleInstalled() {
309
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
310
-			return true;
311
-		}
312
-
313
-		// there are two different memcached modules for PHP
314
-		// we only support memcached and not memcache
315
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
316
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
317
-	}
318
-
319
-	/**
320
-	 * Checks if set_time_limit is not disabled.
321
-	 *
322
-	 * @return bool
323
-	 */
324
-	private function isSettimelimitAvailable() {
325
-		if (function_exists('set_time_limit')
326
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
327
-			return true;
328
-		}
329
-
330
-		return false;
331
-	}
332
-
333
-	/**
334
-	 * @return RedirectResponse
335
-	 */
336
-	public function rescanFailedIntegrityCheck() {
337
-		$this->checker->runInstanceVerification();
338
-		return new RedirectResponse(
339
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'overview'])
340
-		);
341
-	}
342
-
343
-	/**
344
-	 * @NoCSRFRequired
345
-	 * @return DataResponse
346
-	 */
347
-	public function getFailedIntegrityCheckFiles() {
348
-		if (!$this->checker->isCodeCheckEnforced()) {
349
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
350
-		}
351
-
352
-		$completeResults = $this->checker->getResults();
353
-
354
-		if (!empty($completeResults)) {
355
-			$formattedTextResponse = 'Technical information
74
+    /** @var IConfig */
75
+    private $config;
76
+    /** @var IClientService */
77
+    private $clientService;
78
+    /** @var IURLGenerator */
79
+    private $urlGenerator;
80
+    /** @var IL10N */
81
+    private $l10n;
82
+    /** @var Checker */
83
+    private $checker;
84
+    /** @var ILogger */
85
+    private $logger;
86
+    /** @var EventDispatcherInterface */
87
+    private $dispatcher;
88
+    /** @var IDBConnection|Connection */
89
+    private $db;
90
+    /** @var ILockingProvider */
91
+    private $lockingProvider;
92
+    /** @var IDateTimeFormatter */
93
+    private $dateTimeFormatter;
94
+    /** @var MemoryInfo */
95
+    private $memoryInfo;
96
+    /** @var ISecureRandom */
97
+    private $secureRandom;
98
+
99
+    public function __construct($AppName,
100
+                                IRequest $request,
101
+                                IConfig $config,
102
+                                IClientService $clientService,
103
+                                IURLGenerator $urlGenerator,
104
+                                IL10N $l10n,
105
+                                Checker $checker,
106
+                                ILogger $logger,
107
+                                EventDispatcherInterface $dispatcher,
108
+                                IDBConnection $db,
109
+                                ILockingProvider $lockingProvider,
110
+                                IDateTimeFormatter $dateTimeFormatter,
111
+                                MemoryInfo $memoryInfo,
112
+                                ISecureRandom $secureRandom) {
113
+        parent::__construct($AppName, $request);
114
+        $this->config = $config;
115
+        $this->clientService = $clientService;
116
+        $this->urlGenerator = $urlGenerator;
117
+        $this->l10n = $l10n;
118
+        $this->checker = $checker;
119
+        $this->logger = $logger;
120
+        $this->dispatcher = $dispatcher;
121
+        $this->db = $db;
122
+        $this->lockingProvider = $lockingProvider;
123
+        $this->dateTimeFormatter = $dateTimeFormatter;
124
+        $this->memoryInfo = $memoryInfo;
125
+        $this->secureRandom = $secureRandom;
126
+    }
127
+
128
+    /**
129
+     * Checks if the server can connect to the internet using HTTPS and HTTP
130
+     * @return bool
131
+     */
132
+    private function hasInternetConnectivityProblems(): bool {
133
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
134
+            return false;
135
+        }
136
+
137
+        $siteArray = $this->config->getSystemValue('connectivity_check_domains', [
138
+            'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org'
139
+        ]);
140
+
141
+        foreach ($siteArray as $site) {
142
+            if ($this->isSiteReachable($site)) {
143
+                return false;
144
+            }
145
+        }
146
+        return true;
147
+    }
148
+
149
+    /**
150
+     * Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
151
+     * @return bool
152
+     */
153
+    private function isSiteReachable($sitename) {
154
+        $httpSiteName = 'http://' . $sitename . '/';
155
+        $httpsSiteName = 'https://' . $sitename . '/';
156
+
157
+        try {
158
+            $client = $this->clientService->newClient();
159
+            $client->get($httpSiteName);
160
+            $client->get($httpsSiteName);
161
+        } catch (\Exception $e) {
162
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
163
+            return false;
164
+        }
165
+        return true;
166
+    }
167
+
168
+    /**
169
+     * Checks whether a local memcache is installed or not
170
+     * @return bool
171
+     */
172
+    private function isMemcacheConfigured() {
173
+        return $this->config->getSystemValue('memcache.local', null) !== null;
174
+    }
175
+
176
+    /**
177
+     * Whether PHP can generate "secure" pseudorandom integers
178
+     *
179
+     * @return bool
180
+     */
181
+    private function isRandomnessSecure() {
182
+        try {
183
+            $this->secureRandom->generate(1);
184
+        } catch (\Exception $ex) {
185
+            return false;
186
+        }
187
+        return true;
188
+    }
189
+
190
+    /**
191
+     * Public for the sake of unit-testing
192
+     *
193
+     * @return array
194
+     */
195
+    protected function getCurlVersion() {
196
+        return curl_version();
197
+    }
198
+
199
+    /**
200
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
201
+     * have multiple bugs which likely lead to problems in combination with
202
+     * functionality required by ownCloud such as SNI.
203
+     *
204
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
205
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
206
+     * @return string
207
+     */
208
+    private function isUsedTlsLibOutdated() {
209
+        // Don't run check when:
210
+        // 1. Server has `has_internet_connection` set to false
211
+        // 2. AppStore AND S2S is disabled
212
+        if (!$this->config->getSystemValue('has_internet_connection', true)) {
213
+            return '';
214
+        }
215
+        if (!$this->config->getSystemValue('appstoreenabled', true)
216
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
217
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
218
+            return '';
219
+        }
220
+
221
+        $versionString = $this->getCurlVersion();
222
+        if (isset($versionString['ssl_version'])) {
223
+            $versionString = $versionString['ssl_version'];
224
+        } else {
225
+            return '';
226
+        }
227
+
228
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
229
+        if (!$this->config->getSystemValue('appstoreenabled', true)) {
230
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
231
+        }
232
+
233
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
234
+        if (strpos($versionString, 'OpenSSL/') === 0) {
235
+            $majorVersion = substr($versionString, 8, 5);
236
+            $patchRelease = substr($versionString, 13, 6);
237
+
238
+            if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
239
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
240
+                return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
241
+            }
242
+        }
243
+
244
+        // Check if NSS and perform heuristic check
245
+        if (strpos($versionString, 'NSS/') === 0) {
246
+            try {
247
+                $firstClient = $this->clientService->newClient();
248
+                $firstClient->get('https://nextcloud.com/');
249
+
250
+                $secondClient = $this->clientService->newClient();
251
+                $secondClient->get('https://nextcloud.com/');
252
+            } catch (ClientException $e) {
253
+                if ($e->getResponse()->getStatusCode() === 400) {
254
+                    return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
255
+                }
256
+            }
257
+        }
258
+
259
+        return '';
260
+    }
261
+
262
+    /**
263
+     * Whether the version is outdated
264
+     *
265
+     * @return bool
266
+     */
267
+    protected function isPhpOutdated(): bool {
268
+        return PHP_VERSION_ID < 70300;
269
+    }
270
+
271
+    /**
272
+     * Whether the php version is still supported (at time of release)
273
+     * according to: https://secure.php.net/supported-versions.php
274
+     *
275
+     * @return array
276
+     */
277
+    private function isPhpSupported(): array {
278
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
279
+    }
280
+
281
+    /**
282
+     * Check if the reverse proxy configuration is working as expected
283
+     *
284
+     * @return bool
285
+     */
286
+    private function forwardedForHeadersWorking() {
287
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
288
+        $remoteAddress = $this->request->getHeader('REMOTE_ADDR');
289
+
290
+        if (empty($trustedProxies) && $this->request->getHeader('X-Forwarded-Host') !== '') {
291
+            return false;
292
+        }
293
+
294
+        if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies, true)) {
295
+            return $remoteAddress !== $this->request->getRemoteAddress();
296
+        }
297
+
298
+        // either not enabled or working correctly
299
+        return true;
300
+    }
301
+
302
+    /**
303
+     * Checks if the correct memcache module for PHP is installed. Only
304
+     * fails if memcached is configured and the working module is not installed.
305
+     *
306
+     * @return bool
307
+     */
308
+    private function isCorrectMemcachedPHPModuleInstalled() {
309
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
310
+            return true;
311
+        }
312
+
313
+        // there are two different memcached modules for PHP
314
+        // we only support memcached and not memcache
315
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
316
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
317
+    }
318
+
319
+    /**
320
+     * Checks if set_time_limit is not disabled.
321
+     *
322
+     * @return bool
323
+     */
324
+    private function isSettimelimitAvailable() {
325
+        if (function_exists('set_time_limit')
326
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
327
+            return true;
328
+        }
329
+
330
+        return false;
331
+    }
332
+
333
+    /**
334
+     * @return RedirectResponse
335
+     */
336
+    public function rescanFailedIntegrityCheck() {
337
+        $this->checker->runInstanceVerification();
338
+        return new RedirectResponse(
339
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'overview'])
340
+        );
341
+    }
342
+
343
+    /**
344
+     * @NoCSRFRequired
345
+     * @return DataResponse
346
+     */
347
+    public function getFailedIntegrityCheckFiles() {
348
+        if (!$this->checker->isCodeCheckEnforced()) {
349
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
350
+        }
351
+
352
+        $completeResults = $this->checker->getResults();
353
+
354
+        if (!empty($completeResults)) {
355
+            $formattedTextResponse = 'Technical information
356 356
 =====================
357 357
 The following list covers which files have failed the integrity check. Please read
358 358
 the previous linked documentation to learn more about the errors and how to fix
@@ -361,369 +361,369 @@  discard block
 block discarded – undo
361 361
 Results
362 362
 =======
363 363
 ';
364
-			foreach ($completeResults as $context => $contextResult) {
365
-				$formattedTextResponse .= "- $context\n";
366
-
367
-				foreach ($contextResult as $category => $result) {
368
-					$formattedTextResponse .= "\t- $category\n";
369
-					if ($category !== 'EXCEPTION') {
370
-						foreach ($result as $key => $results) {
371
-							$formattedTextResponse .= "\t\t- $key\n";
372
-						}
373
-					} else {
374
-						foreach ($result as $key => $results) {
375
-							$formattedTextResponse .= "\t\t- $results\n";
376
-						}
377
-					}
378
-				}
379
-			}
380
-
381
-			$formattedTextResponse .= '
364
+            foreach ($completeResults as $context => $contextResult) {
365
+                $formattedTextResponse .= "- $context\n";
366
+
367
+                foreach ($contextResult as $category => $result) {
368
+                    $formattedTextResponse .= "\t- $category\n";
369
+                    if ($category !== 'EXCEPTION') {
370
+                        foreach ($result as $key => $results) {
371
+                            $formattedTextResponse .= "\t\t- $key\n";
372
+                        }
373
+                    } else {
374
+                        foreach ($result as $key => $results) {
375
+                            $formattedTextResponse .= "\t\t- $results\n";
376
+                        }
377
+                    }
378
+                }
379
+            }
380
+
381
+            $formattedTextResponse .= '
382 382
 Raw output
383 383
 ==========
384 384
 ';
385
-			$formattedTextResponse .= print_r($completeResults, true);
386
-		} else {
387
-			$formattedTextResponse = 'No errors have been found.';
388
-		}
389
-
390
-
391
-		$response = new DataDisplayResponse(
392
-			$formattedTextResponse,
393
-			Http::STATUS_OK,
394
-			[
395
-				'Content-Type' => 'text/plain',
396
-			]
397
-		);
398
-
399
-		return $response;
400
-	}
401
-
402
-	/**
403
-	 * Checks whether a PHP opcache is properly set up
404
-	 * @return bool
405
-	 */
406
-	protected function isOpcacheProperlySetup() {
407
-		$iniWrapper = new IniGetWrapper();
408
-
409
-		if (!$iniWrapper->getBool('opcache.enable')) {
410
-			return false;
411
-		}
412
-
413
-		if (!$iniWrapper->getBool('opcache.save_comments')) {
414
-			return false;
415
-		}
416
-
417
-		if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
418
-			return false;
419
-		}
420
-
421
-		if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
422
-			return false;
423
-		}
424
-
425
-		if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
426
-			return false;
427
-		}
428
-
429
-		return true;
430
-	}
431
-
432
-	/**
433
-	 * Check if the required FreeType functions are present
434
-	 * @return bool
435
-	 */
436
-	protected function hasFreeTypeSupport() {
437
-		return function_exists('imagettfbbox') && function_exists('imagettftext');
438
-	}
439
-
440
-	protected function hasMissingIndexes(): array {
441
-		$indexInfo = new MissingIndexInformation();
442
-		// Dispatch event so apps can also hint for pending index updates if needed
443
-		$event = new GenericEvent($indexInfo);
444
-		$this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
445
-
446
-		return $indexInfo->getListOfMissingIndexes();
447
-	}
448
-
449
-	protected function hasMissingColumns(): array {
450
-		$indexInfo = new MissingColumnInformation();
451
-		// Dispatch event so apps can also hint for pending index updates if needed
452
-		$event = new GenericEvent($indexInfo);
453
-		$this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_COLUMNS_EVENT, $event);
454
-
455
-		return $indexInfo->getListOfMissingColumns();
456
-	}
457
-
458
-	protected function isSqliteUsed() {
459
-		return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
460
-	}
461
-
462
-	protected function isReadOnlyConfig(): bool {
463
-		return \OC_Helper::isReadOnlyConfigEnabled();
464
-	}
465
-
466
-	protected function hasValidTransactionIsolationLevel(): bool {
467
-		try {
468
-			if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
469
-				return true;
470
-			}
471
-
472
-			return $this->db->getTransactionIsolation() === Connection::TRANSACTION_READ_COMMITTED;
473
-		} catch (DBALException $e) {
474
-			// ignore
475
-		}
476
-
477
-		return true;
478
-	}
479
-
480
-	protected function hasFileinfoInstalled(): bool {
481
-		return \OC_Util::fileInfoLoaded();
482
-	}
483
-
484
-	protected function hasWorkingFileLocking(): bool {
485
-		return !($this->lockingProvider instanceof NoopLockingProvider);
486
-	}
487
-
488
-	protected function getSuggestedOverwriteCliURL(): string {
489
-		$suggestedOverwriteCliUrl = '';
490
-		if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
491
-			$suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
492
-			if (!$this->config->getSystemValue('config_is_read_only', false)) {
493
-				// Set the overwrite URL when it was not set yet.
494
-				$this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
495
-				$suggestedOverwriteCliUrl = '';
496
-			}
497
-		}
498
-		return $suggestedOverwriteCliUrl;
499
-	}
500
-
501
-	protected function getLastCronInfo(): array {
502
-		$lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
503
-		return [
504
-			'diffInSeconds' => time() - $lastCronRun,
505
-			'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
506
-			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
507
-		];
508
-	}
509
-
510
-	protected function getCronErrors() {
511
-		$errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
512
-
513
-		if (is_array($errors)) {
514
-			return $errors;
515
-		}
516
-
517
-		return [];
518
-	}
519
-
520
-	protected function isPHPMailerUsed(): bool {
521
-		return $this->config->getSystemValue('mail_smtpmode', 'smtp') === 'php';
522
-	}
523
-
524
-	protected function hasOpcacheLoaded(): bool {
525
-		return extension_loaded('Zend OPcache');
526
-	}
527
-
528
-	/**
529
-	 * Iterates through the configured app roots and
530
-	 * tests if the subdirectories are owned by the same user than the current user.
531
-	 *
532
-	 * @return array
533
-	 */
534
-	protected function getAppDirsWithDifferentOwner(): array {
535
-		$currentUser = posix_getuid();
536
-		$appDirsWithDifferentOwner = [[]];
537
-
538
-		foreach (OC::$APPSROOTS as $appRoot) {
539
-			if ($appRoot['writable'] === true) {
540
-				$appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
541
-			}
542
-		}
543
-
544
-		$appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
545
-		sort($appDirsWithDifferentOwner);
546
-
547
-		return $appDirsWithDifferentOwner;
548
-	}
549
-
550
-	/**
551
-	 * Tests if the directories for one apps directory are writable by the current user.
552
-	 *
553
-	 * @param int $currentUser The current user
554
-	 * @param array $appRoot The app root config
555
-	 * @return string[] The none writable directory paths inside the app root
556
-	 */
557
-	private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
558
-		$appDirsWithDifferentOwner = [];
559
-		$appsPath = $appRoot['path'];
560
-		$appsDir = new DirectoryIterator($appRoot['path']);
561
-
562
-		foreach ($appsDir as $fileInfo) {
563
-			if ($fileInfo->isDir() && !$fileInfo->isDot()) {
564
-				$absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
565
-				$appDirUser = fileowner($absAppPath);
566
-				if ($appDirUser !== $currentUser) {
567
-					$appDirsWithDifferentOwner[] = $absAppPath;
568
-				}
569
-			}
570
-		}
571
-
572
-		return $appDirsWithDifferentOwner;
573
-	}
574
-
575
-	/**
576
-	 * Checks for potential PHP modules that would improve the instance
577
-	 *
578
-	 * @return string[] A list of PHP modules that is recommended
579
-	 */
580
-	protected function hasRecommendedPHPModules(): array {
581
-		$recommendedPHPModules = [];
582
-
583
-		if (!extension_loaded('intl')) {
584
-			$recommendedPHPModules[] = 'intl';
585
-		}
586
-
587
-		if (!extension_loaded('bcmath')) {
588
-			$recommendedPHPModules[] = 'bcmath';
589
-		}
590
-
591
-		if (!extension_loaded('gmp')) {
592
-			$recommendedPHPModules[] = 'gmp';
593
-		}
594
-
595
-		if ($this->config->getAppValue('theming', 'enabled', 'no') === 'yes') {
596
-			if (!extension_loaded('imagick')) {
597
-				$recommendedPHPModules[] = 'imagick';
598
-			}
599
-		}
600
-
601
-		return $recommendedPHPModules;
602
-	}
603
-
604
-	protected function isMysqlUsedWithoutUTF8MB4(): bool {
605
-		return ($this->config->getSystemValue('dbtype', 'sqlite') === 'mysql') && ($this->config->getSystemValue('mysql.utf8mb4', false) === false);
606
-	}
607
-
608
-	protected function hasBigIntConversionPendingColumns(): array {
609
-		// copy of ConvertFilecacheBigInt::getColumnsByTable()
610
-		$tables = [
611
-			'activity' => ['activity_id', 'object_id'],
612
-			'activity_mq' => ['mail_id'],
613
-			'authtoken' => ['id'],
614
-			'bruteforce_attempts' => ['id'],
615
-			'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
616
-			'file_locks' => ['id'],
617
-			'jobs' => ['id'],
618
-			'mimetypes' => ['id'],
619
-			'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
620
-			'storages' => ['numeric_id'],
621
-		];
622
-
623
-		$schema = new SchemaWrapper($this->db);
624
-		$isSqlite = $this->db->getDatabasePlatform() instanceof SqlitePlatform;
625
-		$pendingColumns = [];
626
-
627
-		foreach ($tables as $tableName => $columns) {
628
-			if (!$schema->hasTable($tableName)) {
629
-				continue;
630
-			}
631
-
632
-			$table = $schema->getTable($tableName);
633
-			foreach ($columns as $columnName) {
634
-				$column = $table->getColumn($columnName);
635
-				$isAutoIncrement = $column->getAutoincrement();
636
-				$isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
637
-				if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
638
-					$pendingColumns[] = $tableName . '.' . $columnName;
639
-				}
640
-			}
641
-		}
642
-
643
-		return $pendingColumns;
644
-	}
645
-
646
-	protected function isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(): bool {
647
-		$objectStore = $this->config->getSystemValue('objectstore', null);
648
-		$objectStoreMultibucket = $this->config->getSystemValue('objectstore_multibucket', null);
649
-
650
-		if (!isset($objectStoreMultibucket) && !isset($objectStore)) {
651
-			return true;
652
-		}
653
-
654
-		if (isset($objectStoreMultibucket['class']) && $objectStoreMultibucket['class'] !== 'OC\\Files\\ObjectStore\\S3') {
655
-			return true;
656
-		}
657
-
658
-		if (isset($objectStore['class']) && $objectStore['class'] !== 'OC\\Files\\ObjectStore\\S3') {
659
-			return true;
660
-		}
661
-
662
-		$tempPath = sys_get_temp_dir();
663
-		if (!is_dir($tempPath)) {
664
-			$this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: ' . $tempPath);
665
-			return false;
666
-		}
667
-		$freeSpaceInTemp = disk_free_space($tempPath);
668
-		if ($freeSpaceInTemp === false) {
669
-			$this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: ' . $tempPath);
670
-			return false;
671
-		}
672
-
673
-		$freeSpaceInTempInGB = $freeSpaceInTemp / 1024 / 1024 / 1024;
674
-		if ($freeSpaceInTempInGB > 50) {
675
-			return true;
676
-		}
677
-
678
-		$this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
679
-		return false;
680
-	}
681
-
682
-	/**
683
-	 * @return DataResponse
684
-	 */
685
-	public function check() {
686
-		return new DataResponse(
687
-			[
688
-				'isGetenvServerWorking' => !empty(getenv('PATH')),
689
-				'isReadOnlyConfig' => $this->isReadOnlyConfig(),
690
-				'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
691
-				'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
692
-				'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
693
-				'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
694
-				'cronInfo' => $this->getLastCronInfo(),
695
-				'cronErrors' => $this->getCronErrors(),
696
-				'serverHasInternetConnectionProblems' => $this->hasInternetConnectivityProblems(),
697
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
698
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
699
-				'isRandomnessSecure' => $this->isRandomnessSecure(),
700
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
701
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
702
-				'phpSupported' => $this->isPhpSupported(),
703
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
704
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
705
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
706
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
707
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
708
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
709
-				'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
710
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
711
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
712
-				'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
713
-				'missingIndexes' => $this->hasMissingIndexes(),
714
-				'missingColumns' => $this->hasMissingColumns(),
715
-				'isSqliteUsed' => $this->isSqliteUsed(),
716
-				'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
717
-				'isPHPMailerUsed' => $this->isPHPMailerUsed(),
718
-				'mailSettingsDocumentation' => $this->urlGenerator->getAbsoluteURL('index.php/settings/admin'),
719
-				'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
720
-				'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
721
-				'recommendedPHPModules' => $this->hasRecommendedPHPModules(),
722
-				'pendingBigIntConversionColumns' => $this->hasBigIntConversionPendingColumns(),
723
-				'isMysqlUsedWithoutUTF8MB4' => $this->isMysqlUsedWithoutUTF8MB4(),
724
-				'isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed' => $this->isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(),
725
-				'reverseProxyGeneratedURL' => $this->urlGenerator->getAbsoluteURL('index.php'),
726
-			]
727
-		);
728
-	}
385
+            $formattedTextResponse .= print_r($completeResults, true);
386
+        } else {
387
+            $formattedTextResponse = 'No errors have been found.';
388
+        }
389
+
390
+
391
+        $response = new DataDisplayResponse(
392
+            $formattedTextResponse,
393
+            Http::STATUS_OK,
394
+            [
395
+                'Content-Type' => 'text/plain',
396
+            ]
397
+        );
398
+
399
+        return $response;
400
+    }
401
+
402
+    /**
403
+     * Checks whether a PHP opcache is properly set up
404
+     * @return bool
405
+     */
406
+    protected function isOpcacheProperlySetup() {
407
+        $iniWrapper = new IniGetWrapper();
408
+
409
+        if (!$iniWrapper->getBool('opcache.enable')) {
410
+            return false;
411
+        }
412
+
413
+        if (!$iniWrapper->getBool('opcache.save_comments')) {
414
+            return false;
415
+        }
416
+
417
+        if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
418
+            return false;
419
+        }
420
+
421
+        if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
422
+            return false;
423
+        }
424
+
425
+        if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
426
+            return false;
427
+        }
428
+
429
+        return true;
430
+    }
431
+
432
+    /**
433
+     * Check if the required FreeType functions are present
434
+     * @return bool
435
+     */
436
+    protected function hasFreeTypeSupport() {
437
+        return function_exists('imagettfbbox') && function_exists('imagettftext');
438
+    }
439
+
440
+    protected function hasMissingIndexes(): array {
441
+        $indexInfo = new MissingIndexInformation();
442
+        // Dispatch event so apps can also hint for pending index updates if needed
443
+        $event = new GenericEvent($indexInfo);
444
+        $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
445
+
446
+        return $indexInfo->getListOfMissingIndexes();
447
+    }
448
+
449
+    protected function hasMissingColumns(): array {
450
+        $indexInfo = new MissingColumnInformation();
451
+        // Dispatch event so apps can also hint for pending index updates if needed
452
+        $event = new GenericEvent($indexInfo);
453
+        $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_COLUMNS_EVENT, $event);
454
+
455
+        return $indexInfo->getListOfMissingColumns();
456
+    }
457
+
458
+    protected function isSqliteUsed() {
459
+        return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
460
+    }
461
+
462
+    protected function isReadOnlyConfig(): bool {
463
+        return \OC_Helper::isReadOnlyConfigEnabled();
464
+    }
465
+
466
+    protected function hasValidTransactionIsolationLevel(): bool {
467
+        try {
468
+            if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
469
+                return true;
470
+            }
471
+
472
+            return $this->db->getTransactionIsolation() === Connection::TRANSACTION_READ_COMMITTED;
473
+        } catch (DBALException $e) {
474
+            // ignore
475
+        }
476
+
477
+        return true;
478
+    }
479
+
480
+    protected function hasFileinfoInstalled(): bool {
481
+        return \OC_Util::fileInfoLoaded();
482
+    }
483
+
484
+    protected function hasWorkingFileLocking(): bool {
485
+        return !($this->lockingProvider instanceof NoopLockingProvider);
486
+    }
487
+
488
+    protected function getSuggestedOverwriteCliURL(): string {
489
+        $suggestedOverwriteCliUrl = '';
490
+        if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
491
+            $suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
492
+            if (!$this->config->getSystemValue('config_is_read_only', false)) {
493
+                // Set the overwrite URL when it was not set yet.
494
+                $this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
495
+                $suggestedOverwriteCliUrl = '';
496
+            }
497
+        }
498
+        return $suggestedOverwriteCliUrl;
499
+    }
500
+
501
+    protected function getLastCronInfo(): array {
502
+        $lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
503
+        return [
504
+            'diffInSeconds' => time() - $lastCronRun,
505
+            'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
506
+            'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
507
+        ];
508
+    }
509
+
510
+    protected function getCronErrors() {
511
+        $errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
512
+
513
+        if (is_array($errors)) {
514
+            return $errors;
515
+        }
516
+
517
+        return [];
518
+    }
519
+
520
+    protected function isPHPMailerUsed(): bool {
521
+        return $this->config->getSystemValue('mail_smtpmode', 'smtp') === 'php';
522
+    }
523
+
524
+    protected function hasOpcacheLoaded(): bool {
525
+        return extension_loaded('Zend OPcache');
526
+    }
527
+
528
+    /**
529
+     * Iterates through the configured app roots and
530
+     * tests if the subdirectories are owned by the same user than the current user.
531
+     *
532
+     * @return array
533
+     */
534
+    protected function getAppDirsWithDifferentOwner(): array {
535
+        $currentUser = posix_getuid();
536
+        $appDirsWithDifferentOwner = [[]];
537
+
538
+        foreach (OC::$APPSROOTS as $appRoot) {
539
+            if ($appRoot['writable'] === true) {
540
+                $appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
541
+            }
542
+        }
543
+
544
+        $appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
545
+        sort($appDirsWithDifferentOwner);
546
+
547
+        return $appDirsWithDifferentOwner;
548
+    }
549
+
550
+    /**
551
+     * Tests if the directories for one apps directory are writable by the current user.
552
+     *
553
+     * @param int $currentUser The current user
554
+     * @param array $appRoot The app root config
555
+     * @return string[] The none writable directory paths inside the app root
556
+     */
557
+    private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
558
+        $appDirsWithDifferentOwner = [];
559
+        $appsPath = $appRoot['path'];
560
+        $appsDir = new DirectoryIterator($appRoot['path']);
561
+
562
+        foreach ($appsDir as $fileInfo) {
563
+            if ($fileInfo->isDir() && !$fileInfo->isDot()) {
564
+                $absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
565
+                $appDirUser = fileowner($absAppPath);
566
+                if ($appDirUser !== $currentUser) {
567
+                    $appDirsWithDifferentOwner[] = $absAppPath;
568
+                }
569
+            }
570
+        }
571
+
572
+        return $appDirsWithDifferentOwner;
573
+    }
574
+
575
+    /**
576
+     * Checks for potential PHP modules that would improve the instance
577
+     *
578
+     * @return string[] A list of PHP modules that is recommended
579
+     */
580
+    protected function hasRecommendedPHPModules(): array {
581
+        $recommendedPHPModules = [];
582
+
583
+        if (!extension_loaded('intl')) {
584
+            $recommendedPHPModules[] = 'intl';
585
+        }
586
+
587
+        if (!extension_loaded('bcmath')) {
588
+            $recommendedPHPModules[] = 'bcmath';
589
+        }
590
+
591
+        if (!extension_loaded('gmp')) {
592
+            $recommendedPHPModules[] = 'gmp';
593
+        }
594
+
595
+        if ($this->config->getAppValue('theming', 'enabled', 'no') === 'yes') {
596
+            if (!extension_loaded('imagick')) {
597
+                $recommendedPHPModules[] = 'imagick';
598
+            }
599
+        }
600
+
601
+        return $recommendedPHPModules;
602
+    }
603
+
604
+    protected function isMysqlUsedWithoutUTF8MB4(): bool {
605
+        return ($this->config->getSystemValue('dbtype', 'sqlite') === 'mysql') && ($this->config->getSystemValue('mysql.utf8mb4', false) === false);
606
+    }
607
+
608
+    protected function hasBigIntConversionPendingColumns(): array {
609
+        // copy of ConvertFilecacheBigInt::getColumnsByTable()
610
+        $tables = [
611
+            'activity' => ['activity_id', 'object_id'],
612
+            'activity_mq' => ['mail_id'],
613
+            'authtoken' => ['id'],
614
+            'bruteforce_attempts' => ['id'],
615
+            'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
616
+            'file_locks' => ['id'],
617
+            'jobs' => ['id'],
618
+            'mimetypes' => ['id'],
619
+            'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
620
+            'storages' => ['numeric_id'],
621
+        ];
622
+
623
+        $schema = new SchemaWrapper($this->db);
624
+        $isSqlite = $this->db->getDatabasePlatform() instanceof SqlitePlatform;
625
+        $pendingColumns = [];
626
+
627
+        foreach ($tables as $tableName => $columns) {
628
+            if (!$schema->hasTable($tableName)) {
629
+                continue;
630
+            }
631
+
632
+            $table = $schema->getTable($tableName);
633
+            foreach ($columns as $columnName) {
634
+                $column = $table->getColumn($columnName);
635
+                $isAutoIncrement = $column->getAutoincrement();
636
+                $isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
637
+                if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
638
+                    $pendingColumns[] = $tableName . '.' . $columnName;
639
+                }
640
+            }
641
+        }
642
+
643
+        return $pendingColumns;
644
+    }
645
+
646
+    protected function isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(): bool {
647
+        $objectStore = $this->config->getSystemValue('objectstore', null);
648
+        $objectStoreMultibucket = $this->config->getSystemValue('objectstore_multibucket', null);
649
+
650
+        if (!isset($objectStoreMultibucket) && !isset($objectStore)) {
651
+            return true;
652
+        }
653
+
654
+        if (isset($objectStoreMultibucket['class']) && $objectStoreMultibucket['class'] !== 'OC\\Files\\ObjectStore\\S3') {
655
+            return true;
656
+        }
657
+
658
+        if (isset($objectStore['class']) && $objectStore['class'] !== 'OC\\Files\\ObjectStore\\S3') {
659
+            return true;
660
+        }
661
+
662
+        $tempPath = sys_get_temp_dir();
663
+        if (!is_dir($tempPath)) {
664
+            $this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: ' . $tempPath);
665
+            return false;
666
+        }
667
+        $freeSpaceInTemp = disk_free_space($tempPath);
668
+        if ($freeSpaceInTemp === false) {
669
+            $this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: ' . $tempPath);
670
+            return false;
671
+        }
672
+
673
+        $freeSpaceInTempInGB = $freeSpaceInTemp / 1024 / 1024 / 1024;
674
+        if ($freeSpaceInTempInGB > 50) {
675
+            return true;
676
+        }
677
+
678
+        $this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
679
+        return false;
680
+    }
681
+
682
+    /**
683
+     * @return DataResponse
684
+     */
685
+    public function check() {
686
+        return new DataResponse(
687
+            [
688
+                'isGetenvServerWorking' => !empty(getenv('PATH')),
689
+                'isReadOnlyConfig' => $this->isReadOnlyConfig(),
690
+                'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
691
+                'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
692
+                'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
693
+                'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
694
+                'cronInfo' => $this->getLastCronInfo(),
695
+                'cronErrors' => $this->getCronErrors(),
696
+                'serverHasInternetConnectionProblems' => $this->hasInternetConnectivityProblems(),
697
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
698
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
699
+                'isRandomnessSecure' => $this->isRandomnessSecure(),
700
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
701
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
702
+                'phpSupported' => $this->isPhpSupported(),
703
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
704
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
705
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
706
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
707
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
708
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
709
+                'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
710
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
711
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
712
+                'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
713
+                'missingIndexes' => $this->hasMissingIndexes(),
714
+                'missingColumns' => $this->hasMissingColumns(),
715
+                'isSqliteUsed' => $this->isSqliteUsed(),
716
+                'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
717
+                'isPHPMailerUsed' => $this->isPHPMailerUsed(),
718
+                'mailSettingsDocumentation' => $this->urlGenerator->getAbsoluteURL('index.php/settings/admin'),
719
+                'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
720
+                'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
721
+                'recommendedPHPModules' => $this->hasRecommendedPHPModules(),
722
+                'pendingBigIntConversionColumns' => $this->hasBigIntConversionPendingColumns(),
723
+                'isMysqlUsedWithoutUTF8MB4' => $this->isMysqlUsedWithoutUTF8MB4(),
724
+                'isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed' => $this->isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(),
725
+                'reverseProxyGeneratedURL' => $this->urlGenerator->getAbsoluteURL('index.php'),
726
+            ]
727
+        );
728
+    }
729 729
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
 	 * @return bool
152 152
 	 */
153 153
 	private function isSiteReachable($sitename) {
154
-		$httpSiteName = 'http://' . $sitename . '/';
155
-		$httpsSiteName = 'https://' . $sitename . '/';
154
+		$httpSiteName = 'http://'.$sitename.'/';
155
+		$httpsSiteName = 'https://'.$sitename.'/';
156 156
 
157 157
 		try {
158 158
 			$client = $this->clientService->newClient();
@@ -225,9 +225,9 @@  discard block
 block discarded – undo
225 225
 			return '';
226 226
 		}
227 227
 
228
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
228
+		$features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
229 229
 		if (!$this->config->getSystemValue('appstoreenabled', true)) {
230
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
230
+			$features = (string) $this->l10n->t('Federated Cloud Sharing');
231 231
 		}
232 232
 
233 233
 		// Check if at least OpenSSL after 1.01d or 1.0.2b
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
 	protected function getSuggestedOverwriteCliURL(): string {
489 489
 		$suggestedOverwriteCliUrl = '';
490 490
 		if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
491
-			$suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
491
+			$suggestedOverwriteCliUrl = $this->request->getServerProtocol().'://'.$this->request->getInsecureServerHost().\OC::$WEBROOT;
492 492
 			if (!$this->config->getSystemValue('config_is_read_only', false)) {
493 493
 				// Set the overwrite URL when it was not set yet.
494 494
 				$this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 		return [
504 504
 			'diffInSeconds' => time() - $lastCronRun,
505 505
 			'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
506
-			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
506
+			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']).'#backgroundjobs',
507 507
 		];
508 508
 	}
509 509
 
@@ -561,7 +561,7 @@  discard block
 block discarded – undo
561 561
 
562 562
 		foreach ($appsDir as $fileInfo) {
563 563
 			if ($fileInfo->isDir() && !$fileInfo->isDot()) {
564
-				$absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
564
+				$absAppPath = $appsPath.DIRECTORY_SEPARATOR.$fileInfo->getFilename();
565 565
 				$appDirUser = fileowner($absAppPath);
566 566
 				if ($appDirUser !== $currentUser) {
567 567
 					$appDirsWithDifferentOwner[] = $absAppPath;
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 				$isAutoIncrement = $column->getAutoincrement();
636 636
 				$isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
637 637
 				if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
638
-					$pendingColumns[] = $tableName . '.' . $columnName;
638
+					$pendingColumns[] = $tableName.'.'.$columnName;
639 639
 				}
640 640
 			}
641 641
 		}
@@ -661,12 +661,12 @@  discard block
 block discarded – undo
661 661
 
662 662
 		$tempPath = sys_get_temp_dir();
663 663
 		if (!is_dir($tempPath)) {
664
-			$this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: ' . $tempPath);
664
+			$this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: '.$tempPath);
665 665
 			return false;
666 666
 		}
667 667
 		$freeSpaceInTemp = disk_free_space($tempPath);
668 668
 		if ($freeSpaceInTemp === false) {
669
-			$this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: ' . $tempPath);
669
+			$this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: '.$tempPath);
670 670
 			return false;
671 671
 		}
672 672
 
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 			return true;
676 676
 		}
677 677
 
678
-		$this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
678
+		$this->logger->warning('Checking the available space in the temporary path resulted in '.round($freeSpaceInTempInGB, 1).' GB instead of the recommended 50GB. Path: '.$tempPath);
679 679
 		return false;
680 680
 	}
681 681
 
Please login to merge, or discard this patch.
lib/private/DB/MigrationService.php 1 patch
Indentation   +522 added lines, -522 removed lines patch added patch discarded remove patch
@@ -46,526 +46,526 @@
 block discarded – undo
46 46
 
47 47
 class MigrationService {
48 48
 
49
-	/** @var boolean */
50
-	private $migrationTableCreated;
51
-	/** @var array */
52
-	private $migrations;
53
-	/** @var IOutput */
54
-	private $output;
55
-	/** @var Connection */
56
-	private $connection;
57
-	/** @var string */
58
-	private $appName;
59
-	/** @var bool */
60
-	private $checkOracle;
61
-
62
-	/**
63
-	 * MigrationService constructor.
64
-	 *
65
-	 * @param $appName
66
-	 * @param IDBConnection $connection
67
-	 * @param AppLocator $appLocator
68
-	 * @param IOutput|null $output
69
-	 * @throws \Exception
70
-	 */
71
-	public function __construct($appName, IDBConnection $connection, IOutput $output = null, AppLocator $appLocator = null) {
72
-		$this->appName = $appName;
73
-		$this->connection = $connection;
74
-		$this->output = $output;
75
-		if (null === $this->output) {
76
-			$this->output = new SimpleOutput(\OC::$server->getLogger(), $appName);
77
-		}
78
-
79
-		if ($appName === 'core') {
80
-			$this->migrationsPath = \OC::$SERVERROOT . '/core/Migrations';
81
-			$this->migrationsNamespace = 'OC\\Core\\Migrations';
82
-			$this->checkOracle = true;
83
-		} else {
84
-			if (null === $appLocator) {
85
-				$appLocator = new AppLocator();
86
-			}
87
-			$appPath = $appLocator->getAppPath($appName);
88
-			$namespace = App::buildAppNamespace($appName);
89
-			$this->migrationsPath = "$appPath/lib/Migration";
90
-			$this->migrationsNamespace = $namespace . '\\Migration';
91
-
92
-			$infoParser = new InfoParser();
93
-			$info = $infoParser->parse($appPath . '/appinfo/info.xml');
94
-			if (!isset($info['dependencies']['database'])) {
95
-				$this->checkOracle = true;
96
-			} else {
97
-				$this->checkOracle = false;
98
-				foreach ($info['dependencies']['database'] as $database) {
99
-					if (\is_string($database) && $database === 'oci') {
100
-						$this->checkOracle = true;
101
-					} elseif (\is_array($database) && isset($database['@value']) && $database['@value'] === 'oci') {
102
-						$this->checkOracle = true;
103
-					}
104
-				}
105
-			}
106
-		}
107
-	}
108
-
109
-	/**
110
-	 * Returns the name of the app for which this migration is executed
111
-	 *
112
-	 * @return string
113
-	 */
114
-	public function getApp() {
115
-		return $this->appName;
116
-	}
117
-
118
-	/**
119
-	 * @return bool
120
-	 * @codeCoverageIgnore - this will implicitly tested on installation
121
-	 */
122
-	private function createMigrationTable() {
123
-		if ($this->migrationTableCreated) {
124
-			return false;
125
-		}
126
-
127
-		$schema = new SchemaWrapper($this->connection);
128
-
129
-		/**
130
-		 * We drop the table when it has different columns or the definition does not
131
-		 * match. E.g. ownCloud uses a length of 177 for app and 14 for version.
132
-		 */
133
-		try {
134
-			$table = $schema->getTable('migrations');
135
-			$columns = $table->getColumns();
136
-
137
-			if (count($columns) === 2) {
138
-				try {
139
-					$column = $table->getColumn('app');
140
-					$schemaMismatch = $column->getLength() !== 255;
141
-
142
-					if (!$schemaMismatch) {
143
-						$column = $table->getColumn('version');
144
-						$schemaMismatch = $column->getLength() !== 255;
145
-					}
146
-				} catch (SchemaException $e) {
147
-					// One of the columns is missing
148
-					$schemaMismatch = true;
149
-				}
150
-
151
-				if (!$schemaMismatch) {
152
-					// Table exists and schema matches: return back!
153
-					$this->migrationTableCreated = true;
154
-					return false;
155
-				}
156
-			}
157
-
158
-			// Drop the table, when it didn't match our expectations.
159
-			$this->connection->dropTable('migrations');
160
-
161
-			// Recreate the schema after the table was dropped.
162
-			$schema = new SchemaWrapper($this->connection);
163
-		} catch (SchemaException $e) {
164
-			// Table not found, no need to panic, we will create it.
165
-		}
166
-
167
-		$table = $schema->createTable('migrations');
168
-		$table->addColumn('app', Types::STRING, ['length' => 255]);
169
-		$table->addColumn('version', Types::STRING, ['length' => 255]);
170
-		$table->setPrimaryKey(['app', 'version']);
171
-
172
-		$this->connection->migrateToSchema($schema->getWrappedSchema());
173
-
174
-		$this->migrationTableCreated = true;
175
-
176
-		return true;
177
-	}
178
-
179
-	/**
180
-	 * Returns all versions which have already been applied
181
-	 *
182
-	 * @return string[]
183
-	 * @codeCoverageIgnore - no need to test this
184
-	 */
185
-	public function getMigratedVersions() {
186
-		$this->createMigrationTable();
187
-		$qb = $this->connection->getQueryBuilder();
188
-
189
-		$qb->select('version')
190
-			->from('migrations')
191
-			->where($qb->expr()->eq('app', $qb->createNamedParameter($this->getApp())))
192
-			->orderBy('version');
193
-
194
-		$result = $qb->execute();
195
-		$rows = $result->fetchAll(\PDO::FETCH_COLUMN);
196
-		$result->closeCursor();
197
-
198
-		return $rows;
199
-	}
200
-
201
-	/**
202
-	 * Returns all versions which are available in the migration folder
203
-	 *
204
-	 * @return array
205
-	 */
206
-	public function getAvailableVersions() {
207
-		$this->ensureMigrationsAreLoaded();
208
-		return array_map('strval', array_keys($this->migrations));
209
-	}
210
-
211
-	protected function findMigrations() {
212
-		$directory = realpath($this->migrationsPath);
213
-		if ($directory === false || !file_exists($directory) || !is_dir($directory)) {
214
-			return [];
215
-		}
216
-
217
-		$iterator = new \RegexIterator(
218
-			new \RecursiveIteratorIterator(
219
-				new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
220
-				\RecursiveIteratorIterator::LEAVES_ONLY
221
-			),
222
-			'#^.+\\/Version[^\\/]{1,255}\\.php$#i',
223
-			\RegexIterator::GET_MATCH);
224
-
225
-		$files = array_keys(iterator_to_array($iterator));
226
-		uasort($files, function ($a, $b) {
227
-			preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($a), $matchA);
228
-			preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($b), $matchB);
229
-			if (!empty($matchA) && !empty($matchB)) {
230
-				if ($matchA[1] !== $matchB[1]) {
231
-					return ($matchA[1] < $matchB[1]) ? -1 : 1;
232
-				}
233
-				return ($matchA[2] < $matchB[2]) ? -1 : 1;
234
-			}
235
-			return (basename($a) < basename($b)) ? -1 : 1;
236
-		});
237
-
238
-		$migrations = [];
239
-
240
-		foreach ($files as $file) {
241
-			$className = basename($file, '.php');
242
-			$version = (string) substr($className, 7);
243
-			if ($version === '0') {
244
-				throw new \InvalidArgumentException(
245
-					"Cannot load a migrations with the name '$version' because it is a reserved number"
246
-				);
247
-			}
248
-			$migrations[$version] = sprintf('%s\\%s', $this->migrationsNamespace, $className);
249
-		}
250
-
251
-		return $migrations;
252
-	}
253
-
254
-	/**
255
-	 * @param string $to
256
-	 * @return string[]
257
-	 */
258
-	private function getMigrationsToExecute($to) {
259
-		$knownMigrations = $this->getMigratedVersions();
260
-		$availableMigrations = $this->getAvailableVersions();
261
-
262
-		$toBeExecuted = [];
263
-		foreach ($availableMigrations as $v) {
264
-			if ($to !== 'latest' && $v > $to) {
265
-				continue;
266
-			}
267
-			if ($this->shallBeExecuted($v, $knownMigrations)) {
268
-				$toBeExecuted[] = $v;
269
-			}
270
-		}
271
-
272
-		return $toBeExecuted;
273
-	}
274
-
275
-	/**
276
-	 * @param string $m
277
-	 * @param string[] $knownMigrations
278
-	 * @return bool
279
-	 */
280
-	private function shallBeExecuted($m, $knownMigrations) {
281
-		if (in_array($m, $knownMigrations)) {
282
-			return false;
283
-		}
284
-
285
-		return true;
286
-	}
287
-
288
-	/**
289
-	 * @param string $version
290
-	 */
291
-	private function markAsExecuted($version) {
292
-		$this->connection->insertIfNotExist('*PREFIX*migrations', [
293
-			'app' => $this->appName,
294
-			'version' => $version
295
-		]);
296
-	}
297
-
298
-	/**
299
-	 * Returns the name of the table which holds the already applied versions
300
-	 *
301
-	 * @return string
302
-	 */
303
-	public function getMigrationsTableName() {
304
-		return $this->connection->getPrefix() . 'migrations';
305
-	}
306
-
307
-	/**
308
-	 * Returns the namespace of the version classes
309
-	 *
310
-	 * @return string
311
-	 */
312
-	public function getMigrationsNamespace() {
313
-		return $this->migrationsNamespace;
314
-	}
315
-
316
-	/**
317
-	 * Returns the directory which holds the versions
318
-	 *
319
-	 * @return string
320
-	 */
321
-	public function getMigrationsDirectory() {
322
-		return $this->migrationsPath;
323
-	}
324
-
325
-	/**
326
-	 * Return the explicit version for the aliases; current, next, prev, latest
327
-	 *
328
-	 * @param string $alias
329
-	 * @return mixed|null|string
330
-	 */
331
-	public function getMigration($alias) {
332
-		switch ($alias) {
333
-			case 'current':
334
-				return $this->getCurrentVersion();
335
-			case 'next':
336
-				return $this->getRelativeVersion($this->getCurrentVersion(), 1);
337
-			case 'prev':
338
-				return $this->getRelativeVersion($this->getCurrentVersion(), -1);
339
-			case 'latest':
340
-				$this->ensureMigrationsAreLoaded();
341
-
342
-				$migrations = $this->getAvailableVersions();
343
-				return @end($migrations);
344
-		}
345
-		return '0';
346
-	}
347
-
348
-	/**
349
-	 * @param string $version
350
-	 * @param int $delta
351
-	 * @return null|string
352
-	 */
353
-	private function getRelativeVersion($version, $delta) {
354
-		$this->ensureMigrationsAreLoaded();
355
-
356
-		$versions = $this->getAvailableVersions();
357
-		array_unshift($versions, 0);
358
-		$offset = array_search($version, $versions, true);
359
-		if ($offset === false || !isset($versions[$offset + $delta])) {
360
-			// Unknown version or delta out of bounds.
361
-			return null;
362
-		}
363
-
364
-		return (string) $versions[$offset + $delta];
365
-	}
366
-
367
-	/**
368
-	 * @return string
369
-	 */
370
-	private function getCurrentVersion() {
371
-		$m = $this->getMigratedVersions();
372
-		if (count($m) === 0) {
373
-			return '0';
374
-		}
375
-		$migrations = array_values($m);
376
-		return @end($migrations);
377
-	}
378
-
379
-	/**
380
-	 * @param string $version
381
-	 * @return string
382
-	 * @throws \InvalidArgumentException
383
-	 */
384
-	private function getClass($version) {
385
-		$this->ensureMigrationsAreLoaded();
386
-
387
-		if (isset($this->migrations[$version])) {
388
-			return $this->migrations[$version];
389
-		}
390
-
391
-		throw new \InvalidArgumentException("Version $version is unknown.");
392
-	}
393
-
394
-	/**
395
-	 * Allows to set an IOutput implementation which is used for logging progress and messages
396
-	 *
397
-	 * @param IOutput $output
398
-	 */
399
-	public function setOutput(IOutput $output) {
400
-		$this->output = $output;
401
-	}
402
-
403
-	/**
404
-	 * Applies all not yet applied versions up to $to
405
-	 *
406
-	 * @param string $to
407
-	 * @param bool $schemaOnly
408
-	 * @throws \InvalidArgumentException
409
-	 */
410
-	public function migrate($to = 'latest', $schemaOnly = false) {
411
-		// read known migrations
412
-		$toBeExecuted = $this->getMigrationsToExecute($to);
413
-		foreach ($toBeExecuted as $version) {
414
-			$this->executeStep($version, $schemaOnly);
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * Get the human readable descriptions for the migration steps to run
420
-	 *
421
-	 * @param string $to
422
-	 * @return string[] [$name => $description]
423
-	 */
424
-	public function describeMigrationStep($to = 'latest') {
425
-		$toBeExecuted = $this->getMigrationsToExecute($to);
426
-		$description = [];
427
-		foreach ($toBeExecuted as $version) {
428
-			$migration = $this->createInstance($version);
429
-			if ($migration->name()) {
430
-				$description[$migration->name()] = $migration->description();
431
-			}
432
-		}
433
-		return $description;
434
-	}
435
-
436
-	/**
437
-	 * @param string $version
438
-	 * @return IMigrationStep
439
-	 * @throws \InvalidArgumentException
440
-	 */
441
-	protected function createInstance($version) {
442
-		$class = $this->getClass($version);
443
-		try {
444
-			$s = \OC::$server->query($class);
445
-
446
-			if (!$s instanceof IMigrationStep) {
447
-				throw new \InvalidArgumentException('Not a valid migration');
448
-			}
449
-		} catch (QueryException $e) {
450
-			if (class_exists($class)) {
451
-				$s = new $class();
452
-			} else {
453
-				throw new \InvalidArgumentException("Migration step '$class' is unknown");
454
-			}
455
-		}
456
-
457
-		return $s;
458
-	}
459
-
460
-	/**
461
-	 * Executes one explicit version
462
-	 *
463
-	 * @param string $version
464
-	 * @param bool $schemaOnly
465
-	 * @throws \InvalidArgumentException
466
-	 */
467
-	public function executeStep($version, $schemaOnly = false) {
468
-		$instance = $this->createInstance($version);
469
-
470
-		if (!$schemaOnly) {
471
-			$instance->preSchemaChange($this->output, function () {
472
-				return new SchemaWrapper($this->connection);
473
-			}, ['tablePrefix' => $this->connection->getPrefix()]);
474
-		}
475
-
476
-		$toSchema = $instance->changeSchema($this->output, function () {
477
-			return new SchemaWrapper($this->connection);
478
-		}, ['tablePrefix' => $this->connection->getPrefix()]);
479
-
480
-		if ($toSchema instanceof SchemaWrapper) {
481
-			$targetSchema = $toSchema->getWrappedSchema();
482
-			if ($this->checkOracle) {
483
-				$sourceSchema = $this->connection->createSchema();
484
-				$this->ensureOracleIdentifierLengthLimit($sourceSchema, $targetSchema, strlen($this->connection->getPrefix()));
485
-			}
486
-			$this->connection->migrateToSchema($targetSchema);
487
-			$toSchema->performDropTableCalls();
488
-		}
489
-
490
-		if (!$schemaOnly) {
491
-			$instance->postSchemaChange($this->output, function () {
492
-				return new SchemaWrapper($this->connection);
493
-			}, ['tablePrefix' => $this->connection->getPrefix()]);
494
-		}
495
-
496
-		$this->markAsExecuted($version);
497
-	}
498
-
499
-	public function ensureOracleIdentifierLengthLimit(Schema $sourceSchema, Schema $targetSchema, int $prefixLength) {
500
-		$sequences = $targetSchema->getSequences();
501
-
502
-		foreach ($targetSchema->getTables() as $table) {
503
-			try {
504
-				$sourceTable = $sourceSchema->getTable($table->getName());
505
-			} catch (SchemaException $e) {
506
-				if (\strlen($table->getName()) - $prefixLength > 27) {
507
-					throw new \InvalidArgumentException('Table name "'  . $table->getName() . '" is too long.');
508
-				}
509
-				$sourceTable = null;
510
-			}
511
-
512
-			foreach ($table->getColumns() as $thing) {
513
-				if ((!$sourceTable instanceof Table || !$sourceTable->hasColumn($thing->getName())) && \strlen($thing->getName()) > 30) {
514
-					throw new \InvalidArgumentException('Column name "'  . $table->getName() . '"."' . $thing->getName() . '" is too long.');
515
-				}
516
-			}
517
-
518
-			foreach ($table->getIndexes() as $thing) {
519
-				if ((!$sourceTable instanceof Table || !$sourceTable->hasIndex($thing->getName())) && \strlen($thing->getName()) > 30) {
520
-					throw new \InvalidArgumentException('Index name "'  . $table->getName() . '"."' . $thing->getName() . '" is too long.');
521
-				}
522
-			}
523
-
524
-			foreach ($table->getForeignKeys() as $thing) {
525
-				if ((!$sourceTable instanceof Table || !$sourceTable->hasForeignKey($thing->getName())) && \strlen($thing->getName()) > 30) {
526
-					throw new \InvalidArgumentException('Foreign key name "'  . $table->getName() . '"."' . $thing->getName() . '" is too long.');
527
-				}
528
-			}
529
-
530
-			$primaryKey = $table->getPrimaryKey();
531
-			if ($primaryKey instanceof Index && (!$sourceTable instanceof Table || !$sourceTable->hasPrimaryKey())) {
532
-				$indexName = strtolower($primaryKey->getName());
533
-				$isUsingDefaultName = $indexName === 'primary';
534
-
535
-				if ($this->connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
536
-					$defaultName = $table->getName() . '_pkey';
537
-					$isUsingDefaultName = strtolower($defaultName) === $indexName;
538
-
539
-					if ($isUsingDefaultName) {
540
-						$sequenceName = $table->getName() . '_' . implode('_', $primaryKey->getColumns()) . '_seq';
541
-						$sequences = array_filter($sequences, function (Sequence $sequence) use ($sequenceName) {
542
-							return $sequence->getName() !== $sequenceName;
543
-						});
544
-					}
545
-				} elseif ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
546
-					$defaultName = $table->getName() . '_seq';
547
-					$isUsingDefaultName = strtolower($defaultName) === $indexName;
548
-				}
549
-
550
-				if (!$isUsingDefaultName && \strlen($indexName) > 30) {
551
-					throw new \InvalidArgumentException('Primary index name  on "'  . $table->getName() . '" is too long.');
552
-				}
553
-				if ($isUsingDefaultName && \strlen($table->getName()) - $prefixLength >= 23) {
554
-					throw new \InvalidArgumentException('Primary index name  on "'  . $table->getName() . '" is too long.');
555
-				}
556
-			}
557
-		}
558
-
559
-		foreach ($sequences as $sequence) {
560
-			if (!$sourceSchema->hasSequence($sequence->getName()) && \strlen($sequence->getName()) > 30) {
561
-				throw new \InvalidArgumentException('Sequence name "'  . $sequence->getName() . '" is too long.');
562
-			}
563
-		}
564
-	}
565
-
566
-	private function ensureMigrationsAreLoaded() {
567
-		if (empty($this->migrations)) {
568
-			$this->migrations = $this->findMigrations();
569
-		}
570
-	}
49
+    /** @var boolean */
50
+    private $migrationTableCreated;
51
+    /** @var array */
52
+    private $migrations;
53
+    /** @var IOutput */
54
+    private $output;
55
+    /** @var Connection */
56
+    private $connection;
57
+    /** @var string */
58
+    private $appName;
59
+    /** @var bool */
60
+    private $checkOracle;
61
+
62
+    /**
63
+     * MigrationService constructor.
64
+     *
65
+     * @param $appName
66
+     * @param IDBConnection $connection
67
+     * @param AppLocator $appLocator
68
+     * @param IOutput|null $output
69
+     * @throws \Exception
70
+     */
71
+    public function __construct($appName, IDBConnection $connection, IOutput $output = null, AppLocator $appLocator = null) {
72
+        $this->appName = $appName;
73
+        $this->connection = $connection;
74
+        $this->output = $output;
75
+        if (null === $this->output) {
76
+            $this->output = new SimpleOutput(\OC::$server->getLogger(), $appName);
77
+        }
78
+
79
+        if ($appName === 'core') {
80
+            $this->migrationsPath = \OC::$SERVERROOT . '/core/Migrations';
81
+            $this->migrationsNamespace = 'OC\\Core\\Migrations';
82
+            $this->checkOracle = true;
83
+        } else {
84
+            if (null === $appLocator) {
85
+                $appLocator = new AppLocator();
86
+            }
87
+            $appPath = $appLocator->getAppPath($appName);
88
+            $namespace = App::buildAppNamespace($appName);
89
+            $this->migrationsPath = "$appPath/lib/Migration";
90
+            $this->migrationsNamespace = $namespace . '\\Migration';
91
+
92
+            $infoParser = new InfoParser();
93
+            $info = $infoParser->parse($appPath . '/appinfo/info.xml');
94
+            if (!isset($info['dependencies']['database'])) {
95
+                $this->checkOracle = true;
96
+            } else {
97
+                $this->checkOracle = false;
98
+                foreach ($info['dependencies']['database'] as $database) {
99
+                    if (\is_string($database) && $database === 'oci') {
100
+                        $this->checkOracle = true;
101
+                    } elseif (\is_array($database) && isset($database['@value']) && $database['@value'] === 'oci') {
102
+                        $this->checkOracle = true;
103
+                    }
104
+                }
105
+            }
106
+        }
107
+    }
108
+
109
+    /**
110
+     * Returns the name of the app for which this migration is executed
111
+     *
112
+     * @return string
113
+     */
114
+    public function getApp() {
115
+        return $this->appName;
116
+    }
117
+
118
+    /**
119
+     * @return bool
120
+     * @codeCoverageIgnore - this will implicitly tested on installation
121
+     */
122
+    private function createMigrationTable() {
123
+        if ($this->migrationTableCreated) {
124
+            return false;
125
+        }
126
+
127
+        $schema = new SchemaWrapper($this->connection);
128
+
129
+        /**
130
+         * We drop the table when it has different columns or the definition does not
131
+         * match. E.g. ownCloud uses a length of 177 for app and 14 for version.
132
+         */
133
+        try {
134
+            $table = $schema->getTable('migrations');
135
+            $columns = $table->getColumns();
136
+
137
+            if (count($columns) === 2) {
138
+                try {
139
+                    $column = $table->getColumn('app');
140
+                    $schemaMismatch = $column->getLength() !== 255;
141
+
142
+                    if (!$schemaMismatch) {
143
+                        $column = $table->getColumn('version');
144
+                        $schemaMismatch = $column->getLength() !== 255;
145
+                    }
146
+                } catch (SchemaException $e) {
147
+                    // One of the columns is missing
148
+                    $schemaMismatch = true;
149
+                }
150
+
151
+                if (!$schemaMismatch) {
152
+                    // Table exists and schema matches: return back!
153
+                    $this->migrationTableCreated = true;
154
+                    return false;
155
+                }
156
+            }
157
+
158
+            // Drop the table, when it didn't match our expectations.
159
+            $this->connection->dropTable('migrations');
160
+
161
+            // Recreate the schema after the table was dropped.
162
+            $schema = new SchemaWrapper($this->connection);
163
+        } catch (SchemaException $e) {
164
+            // Table not found, no need to panic, we will create it.
165
+        }
166
+
167
+        $table = $schema->createTable('migrations');
168
+        $table->addColumn('app', Types::STRING, ['length' => 255]);
169
+        $table->addColumn('version', Types::STRING, ['length' => 255]);
170
+        $table->setPrimaryKey(['app', 'version']);
171
+
172
+        $this->connection->migrateToSchema($schema->getWrappedSchema());
173
+
174
+        $this->migrationTableCreated = true;
175
+
176
+        return true;
177
+    }
178
+
179
+    /**
180
+     * Returns all versions which have already been applied
181
+     *
182
+     * @return string[]
183
+     * @codeCoverageIgnore - no need to test this
184
+     */
185
+    public function getMigratedVersions() {
186
+        $this->createMigrationTable();
187
+        $qb = $this->connection->getQueryBuilder();
188
+
189
+        $qb->select('version')
190
+            ->from('migrations')
191
+            ->where($qb->expr()->eq('app', $qb->createNamedParameter($this->getApp())))
192
+            ->orderBy('version');
193
+
194
+        $result = $qb->execute();
195
+        $rows = $result->fetchAll(\PDO::FETCH_COLUMN);
196
+        $result->closeCursor();
197
+
198
+        return $rows;
199
+    }
200
+
201
+    /**
202
+     * Returns all versions which are available in the migration folder
203
+     *
204
+     * @return array
205
+     */
206
+    public function getAvailableVersions() {
207
+        $this->ensureMigrationsAreLoaded();
208
+        return array_map('strval', array_keys($this->migrations));
209
+    }
210
+
211
+    protected function findMigrations() {
212
+        $directory = realpath($this->migrationsPath);
213
+        if ($directory === false || !file_exists($directory) || !is_dir($directory)) {
214
+            return [];
215
+        }
216
+
217
+        $iterator = new \RegexIterator(
218
+            new \RecursiveIteratorIterator(
219
+                new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
220
+                \RecursiveIteratorIterator::LEAVES_ONLY
221
+            ),
222
+            '#^.+\\/Version[^\\/]{1,255}\\.php$#i',
223
+            \RegexIterator::GET_MATCH);
224
+
225
+        $files = array_keys(iterator_to_array($iterator));
226
+        uasort($files, function ($a, $b) {
227
+            preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($a), $matchA);
228
+            preg_match('/^Version(\d+)Date(\d+)\\.php$/', basename($b), $matchB);
229
+            if (!empty($matchA) && !empty($matchB)) {
230
+                if ($matchA[1] !== $matchB[1]) {
231
+                    return ($matchA[1] < $matchB[1]) ? -1 : 1;
232
+                }
233
+                return ($matchA[2] < $matchB[2]) ? -1 : 1;
234
+            }
235
+            return (basename($a) < basename($b)) ? -1 : 1;
236
+        });
237
+
238
+        $migrations = [];
239
+
240
+        foreach ($files as $file) {
241
+            $className = basename($file, '.php');
242
+            $version = (string) substr($className, 7);
243
+            if ($version === '0') {
244
+                throw new \InvalidArgumentException(
245
+                    "Cannot load a migrations with the name '$version' because it is a reserved number"
246
+                );
247
+            }
248
+            $migrations[$version] = sprintf('%s\\%s', $this->migrationsNamespace, $className);
249
+        }
250
+
251
+        return $migrations;
252
+    }
253
+
254
+    /**
255
+     * @param string $to
256
+     * @return string[]
257
+     */
258
+    private function getMigrationsToExecute($to) {
259
+        $knownMigrations = $this->getMigratedVersions();
260
+        $availableMigrations = $this->getAvailableVersions();
261
+
262
+        $toBeExecuted = [];
263
+        foreach ($availableMigrations as $v) {
264
+            if ($to !== 'latest' && $v > $to) {
265
+                continue;
266
+            }
267
+            if ($this->shallBeExecuted($v, $knownMigrations)) {
268
+                $toBeExecuted[] = $v;
269
+            }
270
+        }
271
+
272
+        return $toBeExecuted;
273
+    }
274
+
275
+    /**
276
+     * @param string $m
277
+     * @param string[] $knownMigrations
278
+     * @return bool
279
+     */
280
+    private function shallBeExecuted($m, $knownMigrations) {
281
+        if (in_array($m, $knownMigrations)) {
282
+            return false;
283
+        }
284
+
285
+        return true;
286
+    }
287
+
288
+    /**
289
+     * @param string $version
290
+     */
291
+    private function markAsExecuted($version) {
292
+        $this->connection->insertIfNotExist('*PREFIX*migrations', [
293
+            'app' => $this->appName,
294
+            'version' => $version
295
+        ]);
296
+    }
297
+
298
+    /**
299
+     * Returns the name of the table which holds the already applied versions
300
+     *
301
+     * @return string
302
+     */
303
+    public function getMigrationsTableName() {
304
+        return $this->connection->getPrefix() . 'migrations';
305
+    }
306
+
307
+    /**
308
+     * Returns the namespace of the version classes
309
+     *
310
+     * @return string
311
+     */
312
+    public function getMigrationsNamespace() {
313
+        return $this->migrationsNamespace;
314
+    }
315
+
316
+    /**
317
+     * Returns the directory which holds the versions
318
+     *
319
+     * @return string
320
+     */
321
+    public function getMigrationsDirectory() {
322
+        return $this->migrationsPath;
323
+    }
324
+
325
+    /**
326
+     * Return the explicit version for the aliases; current, next, prev, latest
327
+     *
328
+     * @param string $alias
329
+     * @return mixed|null|string
330
+     */
331
+    public function getMigration($alias) {
332
+        switch ($alias) {
333
+            case 'current':
334
+                return $this->getCurrentVersion();
335
+            case 'next':
336
+                return $this->getRelativeVersion($this->getCurrentVersion(), 1);
337
+            case 'prev':
338
+                return $this->getRelativeVersion($this->getCurrentVersion(), -1);
339
+            case 'latest':
340
+                $this->ensureMigrationsAreLoaded();
341
+
342
+                $migrations = $this->getAvailableVersions();
343
+                return @end($migrations);
344
+        }
345
+        return '0';
346
+    }
347
+
348
+    /**
349
+     * @param string $version
350
+     * @param int $delta
351
+     * @return null|string
352
+     */
353
+    private function getRelativeVersion($version, $delta) {
354
+        $this->ensureMigrationsAreLoaded();
355
+
356
+        $versions = $this->getAvailableVersions();
357
+        array_unshift($versions, 0);
358
+        $offset = array_search($version, $versions, true);
359
+        if ($offset === false || !isset($versions[$offset + $delta])) {
360
+            // Unknown version or delta out of bounds.
361
+            return null;
362
+        }
363
+
364
+        return (string) $versions[$offset + $delta];
365
+    }
366
+
367
+    /**
368
+     * @return string
369
+     */
370
+    private function getCurrentVersion() {
371
+        $m = $this->getMigratedVersions();
372
+        if (count($m) === 0) {
373
+            return '0';
374
+        }
375
+        $migrations = array_values($m);
376
+        return @end($migrations);
377
+    }
378
+
379
+    /**
380
+     * @param string $version
381
+     * @return string
382
+     * @throws \InvalidArgumentException
383
+     */
384
+    private function getClass($version) {
385
+        $this->ensureMigrationsAreLoaded();
386
+
387
+        if (isset($this->migrations[$version])) {
388
+            return $this->migrations[$version];
389
+        }
390
+
391
+        throw new \InvalidArgumentException("Version $version is unknown.");
392
+    }
393
+
394
+    /**
395
+     * Allows to set an IOutput implementation which is used for logging progress and messages
396
+     *
397
+     * @param IOutput $output
398
+     */
399
+    public function setOutput(IOutput $output) {
400
+        $this->output = $output;
401
+    }
402
+
403
+    /**
404
+     * Applies all not yet applied versions up to $to
405
+     *
406
+     * @param string $to
407
+     * @param bool $schemaOnly
408
+     * @throws \InvalidArgumentException
409
+     */
410
+    public function migrate($to = 'latest', $schemaOnly = false) {
411
+        // read known migrations
412
+        $toBeExecuted = $this->getMigrationsToExecute($to);
413
+        foreach ($toBeExecuted as $version) {
414
+            $this->executeStep($version, $schemaOnly);
415
+        }
416
+    }
417
+
418
+    /**
419
+     * Get the human readable descriptions for the migration steps to run
420
+     *
421
+     * @param string $to
422
+     * @return string[] [$name => $description]
423
+     */
424
+    public function describeMigrationStep($to = 'latest') {
425
+        $toBeExecuted = $this->getMigrationsToExecute($to);
426
+        $description = [];
427
+        foreach ($toBeExecuted as $version) {
428
+            $migration = $this->createInstance($version);
429
+            if ($migration->name()) {
430
+                $description[$migration->name()] = $migration->description();
431
+            }
432
+        }
433
+        return $description;
434
+    }
435
+
436
+    /**
437
+     * @param string $version
438
+     * @return IMigrationStep
439
+     * @throws \InvalidArgumentException
440
+     */
441
+    protected function createInstance($version) {
442
+        $class = $this->getClass($version);
443
+        try {
444
+            $s = \OC::$server->query($class);
445
+
446
+            if (!$s instanceof IMigrationStep) {
447
+                throw new \InvalidArgumentException('Not a valid migration');
448
+            }
449
+        } catch (QueryException $e) {
450
+            if (class_exists($class)) {
451
+                $s = new $class();
452
+            } else {
453
+                throw new \InvalidArgumentException("Migration step '$class' is unknown");
454
+            }
455
+        }
456
+
457
+        return $s;
458
+    }
459
+
460
+    /**
461
+     * Executes one explicit version
462
+     *
463
+     * @param string $version
464
+     * @param bool $schemaOnly
465
+     * @throws \InvalidArgumentException
466
+     */
467
+    public function executeStep($version, $schemaOnly = false) {
468
+        $instance = $this->createInstance($version);
469
+
470
+        if (!$schemaOnly) {
471
+            $instance->preSchemaChange($this->output, function () {
472
+                return new SchemaWrapper($this->connection);
473
+            }, ['tablePrefix' => $this->connection->getPrefix()]);
474
+        }
475
+
476
+        $toSchema = $instance->changeSchema($this->output, function () {
477
+            return new SchemaWrapper($this->connection);
478
+        }, ['tablePrefix' => $this->connection->getPrefix()]);
479
+
480
+        if ($toSchema instanceof SchemaWrapper) {
481
+            $targetSchema = $toSchema->getWrappedSchema();
482
+            if ($this->checkOracle) {
483
+                $sourceSchema = $this->connection->createSchema();
484
+                $this->ensureOracleIdentifierLengthLimit($sourceSchema, $targetSchema, strlen($this->connection->getPrefix()));
485
+            }
486
+            $this->connection->migrateToSchema($targetSchema);
487
+            $toSchema->performDropTableCalls();
488
+        }
489
+
490
+        if (!$schemaOnly) {
491
+            $instance->postSchemaChange($this->output, function () {
492
+                return new SchemaWrapper($this->connection);
493
+            }, ['tablePrefix' => $this->connection->getPrefix()]);
494
+        }
495
+
496
+        $this->markAsExecuted($version);
497
+    }
498
+
499
+    public function ensureOracleIdentifierLengthLimit(Schema $sourceSchema, Schema $targetSchema, int $prefixLength) {
500
+        $sequences = $targetSchema->getSequences();
501
+
502
+        foreach ($targetSchema->getTables() as $table) {
503
+            try {
504
+                $sourceTable = $sourceSchema->getTable($table->getName());
505
+            } catch (SchemaException $e) {
506
+                if (\strlen($table->getName()) - $prefixLength > 27) {
507
+                    throw new \InvalidArgumentException('Table name "'  . $table->getName() . '" is too long.');
508
+                }
509
+                $sourceTable = null;
510
+            }
511
+
512
+            foreach ($table->getColumns() as $thing) {
513
+                if ((!$sourceTable instanceof Table || !$sourceTable->hasColumn($thing->getName())) && \strlen($thing->getName()) > 30) {
514
+                    throw new \InvalidArgumentException('Column name "'  . $table->getName() . '"."' . $thing->getName() . '" is too long.');
515
+                }
516
+            }
517
+
518
+            foreach ($table->getIndexes() as $thing) {
519
+                if ((!$sourceTable instanceof Table || !$sourceTable->hasIndex($thing->getName())) && \strlen($thing->getName()) > 30) {
520
+                    throw new \InvalidArgumentException('Index name "'  . $table->getName() . '"."' . $thing->getName() . '" is too long.');
521
+                }
522
+            }
523
+
524
+            foreach ($table->getForeignKeys() as $thing) {
525
+                if ((!$sourceTable instanceof Table || !$sourceTable->hasForeignKey($thing->getName())) && \strlen($thing->getName()) > 30) {
526
+                    throw new \InvalidArgumentException('Foreign key name "'  . $table->getName() . '"."' . $thing->getName() . '" is too long.');
527
+                }
528
+            }
529
+
530
+            $primaryKey = $table->getPrimaryKey();
531
+            if ($primaryKey instanceof Index && (!$sourceTable instanceof Table || !$sourceTable->hasPrimaryKey())) {
532
+                $indexName = strtolower($primaryKey->getName());
533
+                $isUsingDefaultName = $indexName === 'primary';
534
+
535
+                if ($this->connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
536
+                    $defaultName = $table->getName() . '_pkey';
537
+                    $isUsingDefaultName = strtolower($defaultName) === $indexName;
538
+
539
+                    if ($isUsingDefaultName) {
540
+                        $sequenceName = $table->getName() . '_' . implode('_', $primaryKey->getColumns()) . '_seq';
541
+                        $sequences = array_filter($sequences, function (Sequence $sequence) use ($sequenceName) {
542
+                            return $sequence->getName() !== $sequenceName;
543
+                        });
544
+                    }
545
+                } elseif ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
546
+                    $defaultName = $table->getName() . '_seq';
547
+                    $isUsingDefaultName = strtolower($defaultName) === $indexName;
548
+                }
549
+
550
+                if (!$isUsingDefaultName && \strlen($indexName) > 30) {
551
+                    throw new \InvalidArgumentException('Primary index name  on "'  . $table->getName() . '" is too long.');
552
+                }
553
+                if ($isUsingDefaultName && \strlen($table->getName()) - $prefixLength >= 23) {
554
+                    throw new \InvalidArgumentException('Primary index name  on "'  . $table->getName() . '" is too long.');
555
+                }
556
+            }
557
+        }
558
+
559
+        foreach ($sequences as $sequence) {
560
+            if (!$sourceSchema->hasSequence($sequence->getName()) && \strlen($sequence->getName()) > 30) {
561
+                throw new \InvalidArgumentException('Sequence name "'  . $sequence->getName() . '" is too long.');
562
+            }
563
+        }
564
+    }
565
+
566
+    private function ensureMigrationsAreLoaded() {
567
+        if (empty($this->migrations)) {
568
+            $this->migrations = $this->findMigrations();
569
+        }
570
+    }
571 571
 }
Please login to merge, or discard this patch.
lib/public/Migration/BigIntMigration.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -32,38 +32,38 @@
 block discarded – undo
32 32
  */
33 33
 abstract class BigIntMigration extends SimpleMigrationStep {
34 34
 
35
-	/**
36
-	 * @return array Returns an array with the following structure
37
-	 * ['table1' => ['column1', 'column2'], ...]
38
-	 * @since 13.0.0
39
-	 */
40
-	abstract protected function getColumnsByTable();
35
+    /**
36
+     * @return array Returns an array with the following structure
37
+     * ['table1' => ['column1', 'column2'], ...]
38
+     * @since 13.0.0
39
+     */
40
+    abstract protected function getColumnsByTable();
41 41
 
42
-	/**
43
-	 * @param IOutput $output
44
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
45
-	 * @param array $options
46
-	 * @return null|ISchemaWrapper
47
-	 * @since 13.0.0
48
-	 */
49
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
50
-		/** @var ISchemaWrapper $schema */
51
-		$schema = $schemaClosure();
42
+    /**
43
+     * @param IOutput $output
44
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
45
+     * @param array $options
46
+     * @return null|ISchemaWrapper
47
+     * @since 13.0.0
48
+     */
49
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
50
+        /** @var ISchemaWrapper $schema */
51
+        $schema = $schemaClosure();
52 52
 
53
-		$tables = $this->getColumnsByTable();
53
+        $tables = $this->getColumnsByTable();
54 54
 
55
-		foreach ($tables as $tableName => $columns) {
56
-			$table = $schema->getTable($tableName);
55
+        foreach ($tables as $tableName => $columns) {
56
+            $table = $schema->getTable($tableName);
57 57
 
58
-			foreach ($columns as $columnName) {
59
-				$column = $table->getColumn($columnName);
60
-				if ($column->getType()->getName() !== Types::BIGINT) {
61
-					$column->setType(Type::getType(Types::BIGINT));
62
-					$column->setOptions(['length' => 20]);
63
-				}
64
-			}
65
-		}
58
+            foreach ($columns as $columnName) {
59
+                $column = $table->getColumn($columnName);
60
+                if ($column->getType()->getName() !== Types::BIGINT) {
61
+                    $column->setType(Type::getType(Types::BIGINT));
62
+                    $column->setOptions(['length' => 20]);
63
+                }
64
+            }
65
+        }
66 66
 
67
-		return $schema;
68
-	}
67
+        return $schema;
68
+    }
69 69
 }
Please login to merge, or discard this patch.