Completed
Pull Request — master (#4212)
by Individual IT
33:24
created
lib/private/Files/Storage/Flysystem.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -54,6 +54,9 @@
 block discarded – undo
54 54
 		$this->flysystem->addPlugin(new GetWithMetadata());
55 55
 	}
56 56
 
57
+	/**
58
+	 * @param string $path
59
+	 */
57 60
 	protected function buildPath($path) {
58 61
 		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59 62
 		return ltrim($fullPath, '/');
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -35,223 +35,223 @@
 block discarded – undo
35 35
  * To use: subclass and call $this->buildFlysystem with the flysystem adapter of choice
36 36
  */
37 37
 abstract class Flysystem extends Common {
38
-	/**
39
-	 * @var Filesystem
40
-	 */
41
-	protected $flysystem;
38
+    /**
39
+     * @var Filesystem
40
+     */
41
+    protected $flysystem;
42 42
 
43
-	/**
44
-	 * @var string
45
-	 */
46
-	protected $root = '';
43
+    /**
44
+     * @var string
45
+     */
46
+    protected $root = '';
47 47
 
48
-	/**
49
-	 * Initialize the storage backend with a flyssytem adapter
50
-	 *
51
-	 * @param \League\Flysystem\AdapterInterface $adapter
52
-	 */
53
-	protected function buildFlySystem(AdapterInterface $adapter) {
54
-		$this->flysystem = new Filesystem($adapter);
55
-		$this->flysystem->addPlugin(new GetWithMetadata());
56
-	}
48
+    /**
49
+     * Initialize the storage backend with a flyssytem adapter
50
+     *
51
+     * @param \League\Flysystem\AdapterInterface $adapter
52
+     */
53
+    protected function buildFlySystem(AdapterInterface $adapter) {
54
+        $this->flysystem = new Filesystem($adapter);
55
+        $this->flysystem->addPlugin(new GetWithMetadata());
56
+    }
57 57
 
58
-	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
-		return ltrim($fullPath, '/');
61
-	}
58
+    protected function buildPath($path) {
59
+        $fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
+        return ltrim($fullPath, '/');
61
+    }
62 62
 
63
-	/**
64
-	 * {@inheritdoc}
65
-	 */
66
-	public function file_get_contents($path) {
67
-		return $this->flysystem->read($this->buildPath($path));
68
-	}
63
+    /**
64
+     * {@inheritdoc}
65
+     */
66
+    public function file_get_contents($path) {
67
+        return $this->flysystem->read($this->buildPath($path));
68
+    }
69 69
 
70
-	/**
71
-	 * {@inheritdoc}
72
-	 */
73
-	public function file_put_contents($path, $data) {
74
-		return $this->flysystem->put($this->buildPath($path), $data);
75
-	}
70
+    /**
71
+     * {@inheritdoc}
72
+     */
73
+    public function file_put_contents($path, $data) {
74
+        return $this->flysystem->put($this->buildPath($path), $data);
75
+    }
76 76
 
77
-	/**
78
-	 * {@inheritdoc}
79
-	 */
80
-	public function file_exists($path) {
81
-		return $this->flysystem->has($this->buildPath($path));
82
-	}
77
+    /**
78
+     * {@inheritdoc}
79
+     */
80
+    public function file_exists($path) {
81
+        return $this->flysystem->has($this->buildPath($path));
82
+    }
83 83
 
84
-	/**
85
-	 * {@inheritdoc}
86
-	 */
87
-	public function unlink($path) {
88
-		if ($this->is_dir($path)) {
89
-			return $this->rmdir($path);
90
-		}
91
-		try {
92
-			return $this->flysystem->delete($this->buildPath($path));
93
-		} catch (FileNotFoundException $e) {
94
-			return false;
95
-		}
96
-	}
84
+    /**
85
+     * {@inheritdoc}
86
+     */
87
+    public function unlink($path) {
88
+        if ($this->is_dir($path)) {
89
+            return $this->rmdir($path);
90
+        }
91
+        try {
92
+            return $this->flysystem->delete($this->buildPath($path));
93
+        } catch (FileNotFoundException $e) {
94
+            return false;
95
+        }
96
+    }
97 97
 
98
-	/**
99
-	 * {@inheritdoc}
100
-	 */
101
-	public function rename($source, $target) {
102
-		if ($this->file_exists($target)) {
103
-			$this->unlink($target);
104
-		}
105
-		return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
-	}
98
+    /**
99
+     * {@inheritdoc}
100
+     */
101
+    public function rename($source, $target) {
102
+        if ($this->file_exists($target)) {
103
+            $this->unlink($target);
104
+        }
105
+        return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
+    }
107 107
 
108
-	/**
109
-	 * {@inheritdoc}
110
-	 */
111
-	public function copy($source, $target) {
112
-		if ($this->file_exists($target)) {
113
-			$this->unlink($target);
114
-		}
115
-		return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
-	}
108
+    /**
109
+     * {@inheritdoc}
110
+     */
111
+    public function copy($source, $target) {
112
+        if ($this->file_exists($target)) {
113
+            $this->unlink($target);
114
+        }
115
+        return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
+    }
117 117
 
118
-	/**
119
-	 * {@inheritdoc}
120
-	 */
121
-	public function filesize($path) {
122
-		if ($this->is_dir($path)) {
123
-			return 0;
124
-		} else {
125
-			return $this->flysystem->getSize($this->buildPath($path));
126
-		}
127
-	}
118
+    /**
119
+     * {@inheritdoc}
120
+     */
121
+    public function filesize($path) {
122
+        if ($this->is_dir($path)) {
123
+            return 0;
124
+        } else {
125
+            return $this->flysystem->getSize($this->buildPath($path));
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * {@inheritdoc}
131
-	 */
132
-	public function mkdir($path) {
133
-		if ($this->file_exists($path)) {
134
-			return false;
135
-		}
136
-		return $this->flysystem->createDir($this->buildPath($path));
137
-	}
129
+    /**
130
+     * {@inheritdoc}
131
+     */
132
+    public function mkdir($path) {
133
+        if ($this->file_exists($path)) {
134
+            return false;
135
+        }
136
+        return $this->flysystem->createDir($this->buildPath($path));
137
+    }
138 138
 
139
-	/**
140
-	 * {@inheritdoc}
141
-	 */
142
-	public function filemtime($path) {
143
-		return $this->flysystem->getTimestamp($this->buildPath($path));
144
-	}
139
+    /**
140
+     * {@inheritdoc}
141
+     */
142
+    public function filemtime($path) {
143
+        return $this->flysystem->getTimestamp($this->buildPath($path));
144
+    }
145 145
 
146
-	/**
147
-	 * {@inheritdoc}
148
-	 */
149
-	public function rmdir($path) {
150
-		try {
151
-			return @$this->flysystem->deleteDir($this->buildPath($path));
152
-		} catch (FileNotFoundException $e) {
153
-			return false;
154
-		}
155
-	}
146
+    /**
147
+     * {@inheritdoc}
148
+     */
149
+    public function rmdir($path) {
150
+        try {
151
+            return @$this->flysystem->deleteDir($this->buildPath($path));
152
+        } catch (FileNotFoundException $e) {
153
+            return false;
154
+        }
155
+    }
156 156
 
157
-	/**
158
-	 * {@inheritdoc}
159
-	 */
160
-	public function opendir($path) {
161
-		try {
162
-			$content = $this->flysystem->listContents($this->buildPath($path));
163
-		} catch (FileNotFoundException $e) {
164
-			return false;
165
-		}
166
-		$names = array_map(function ($object) {
167
-			return $object['basename'];
168
-		}, $content);
169
-		return IteratorDirectory::wrap($names);
170
-	}
157
+    /**
158
+     * {@inheritdoc}
159
+     */
160
+    public function opendir($path) {
161
+        try {
162
+            $content = $this->flysystem->listContents($this->buildPath($path));
163
+        } catch (FileNotFoundException $e) {
164
+            return false;
165
+        }
166
+        $names = array_map(function ($object) {
167
+            return $object['basename'];
168
+        }, $content);
169
+        return IteratorDirectory::wrap($names);
170
+    }
171 171
 
172
-	/**
173
-	 * {@inheritdoc}
174
-	 */
175
-	public function fopen($path, $mode) {
176
-		$fullPath = $this->buildPath($path);
177
-		$useExisting = true;
178
-		switch ($mode) {
179
-			case 'r':
180
-			case 'rb':
181
-				try {
182
-					return $this->flysystem->readStream($fullPath);
183
-				} catch (FileNotFoundException $e) {
184
-					return false;
185
-				}
186
-			case 'w':
187
-			case 'w+':
188
-			case 'wb':
189
-			case 'wb+':
190
-				$useExisting = false;
191
-			case 'a':
192
-			case 'ab':
193
-			case 'r+':
194
-			case 'a+':
195
-			case 'x':
196
-			case 'x+':
197
-			case 'c':
198
-			case 'c+':
199
-				//emulate these
200
-				if ($useExisting and $this->file_exists($path)) {
201
-					if (!$this->isUpdatable($path)) {
202
-						return false;
203
-					}
204
-					$tmpFile = $this->getCachedFile($path);
205
-				} else {
206
-					if (!$this->isCreatable(dirname($path))) {
207
-						return false;
208
-					}
209
-					$tmpFile = \OCP\Files::tmpFile();
210
-				}
211
-				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
-					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
-					unlink($tmpFile);
215
-				});
216
-		}
217
-		return false;
218
-	}
172
+    /**
173
+     * {@inheritdoc}
174
+     */
175
+    public function fopen($path, $mode) {
176
+        $fullPath = $this->buildPath($path);
177
+        $useExisting = true;
178
+        switch ($mode) {
179
+            case 'r':
180
+            case 'rb':
181
+                try {
182
+                    return $this->flysystem->readStream($fullPath);
183
+                } catch (FileNotFoundException $e) {
184
+                    return false;
185
+                }
186
+            case 'w':
187
+            case 'w+':
188
+            case 'wb':
189
+            case 'wb+':
190
+                $useExisting = false;
191
+            case 'a':
192
+            case 'ab':
193
+            case 'r+':
194
+            case 'a+':
195
+            case 'x':
196
+            case 'x+':
197
+            case 'c':
198
+            case 'c+':
199
+                //emulate these
200
+                if ($useExisting and $this->file_exists($path)) {
201
+                    if (!$this->isUpdatable($path)) {
202
+                        return false;
203
+                    }
204
+                    $tmpFile = $this->getCachedFile($path);
205
+                } else {
206
+                    if (!$this->isCreatable(dirname($path))) {
207
+                        return false;
208
+                    }
209
+                    $tmpFile = \OCP\Files::tmpFile();
210
+                }
211
+                $source = fopen($tmpFile, $mode);
212
+                return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
+                    $this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
+                    unlink($tmpFile);
215
+                });
216
+        }
217
+        return false;
218
+    }
219 219
 
220
-	/**
221
-	 * {@inheritdoc}
222
-	 */
223
-	public function touch($path, $mtime = null) {
224
-		if ($this->file_exists($path)) {
225
-			return false;
226
-		} else {
227
-			$this->file_put_contents($path, '');
228
-			return true;
229
-		}
230
-	}
220
+    /**
221
+     * {@inheritdoc}
222
+     */
223
+    public function touch($path, $mtime = null) {
224
+        if ($this->file_exists($path)) {
225
+            return false;
226
+        } else {
227
+            $this->file_put_contents($path, '');
228
+            return true;
229
+        }
230
+    }
231 231
 
232
-	/**
233
-	 * {@inheritdoc}
234
-	 */
235
-	public function stat($path) {
236
-		$info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
-		return [
238
-			'mtime' => $info['timestamp'],
239
-			'size' => $info['size']
240
-		];
241
-	}
232
+    /**
233
+     * {@inheritdoc}
234
+     */
235
+    public function stat($path) {
236
+        $info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
+        return [
238
+            'mtime' => $info['timestamp'],
239
+            'size' => $info['size']
240
+        ];
241
+    }
242 242
 
243
-	/**
244
-	 * {@inheritdoc}
245
-	 */
246
-	public function filetype($path) {
247
-		if ($path === '' or $path === '/' or $path === '.') {
248
-			return 'dir';
249
-		}
250
-		try {
251
-			$info = $this->flysystem->getMetadata($this->buildPath($path));
252
-		} catch (FileNotFoundException $e) {
253
-			return false;
254
-		}
255
-		return $info['type'];
256
-	}
243
+    /**
244
+     * {@inheritdoc}
245
+     */
246
+    public function filetype($path) {
247
+        if ($path === '' or $path === '/' or $path === '.') {
248
+            return 'dir';
249
+        }
250
+        try {
251
+            $info = $this->flysystem->getMetadata($this->buildPath($path));
252
+        } catch (FileNotFoundException $e) {
253
+            return false;
254
+        }
255
+        return $info['type'];
256
+    }
257 257
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	}
57 57
 
58 58
 	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59
+		$fullPath = \OC\Files\Filesystem::normalizePath($this->root.'/'.$path);
60 60
 		return ltrim($fullPath, '/');
61 61
 	}
62 62
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		} catch (FileNotFoundException $e) {
164 164
 			return false;
165 165
 		}
166
-		$names = array_map(function ($object) {
166
+		$names = array_map(function($object) {
167 167
 			return $object['basename'];
168 168
 		}, $content);
169 169
 		return IteratorDirectory::wrap($names);
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 					$tmpFile = \OCP\Files::tmpFile();
210 210
 				}
211 211
 				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
212
+				return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath) {
213 213
 					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214 214
 					unlink($tmpFile);
215 215
 				});
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Quota.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@
 block discarded – undo
159 159
 	 * Checks whether the given path is a part file
160 160
 	 *
161 161
 	 * @param string $path Path that may identify a .part file
162
-	 * @return string File path without .part extension
162
+	 * @return boolean File path without .part extension
163 163
 	 * @note this is needed for reusing keys
164 164
 	 */
165 165
 	private function isPartFile($path) {
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -30,172 +30,172 @@
 block discarded – undo
30 30
 
31 31
 class Quota extends Wrapper {
32 32
 
33
-	/**
34
-	 * @var int $quota
35
-	 */
36
-	protected $quota;
37
-
38
-	/**
39
-	 * @var string $sizeRoot
40
-	 */
41
-	protected $sizeRoot;
42
-
43
-	/**
44
-	 * @param array $parameters
45
-	 */
46
-	public function __construct($parameters) {
47
-		$this->storage = $parameters['storage'];
48
-		$this->quota = $parameters['quota'];
49
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
-	}
51
-
52
-	/**
53
-	 * @return int quota value
54
-	 */
55
-	public function getQuota() {
56
-		return $this->quota;
57
-	}
58
-
59
-	/**
60
-	 * @param string $path
61
-	 * @param \OC\Files\Storage\Storage $storage
62
-	 */
63
-	protected function getSize($path, $storage = null) {
64
-		if (is_null($storage)) {
65
-			$cache = $this->getCache();
66
-		} else {
67
-			$cache = $storage->getCache();
68
-		}
69
-		$data = $cache->get($path);
70
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
71
-			return $data['size'];
72
-		} else {
73
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * Get free space as limited by the quota
79
-	 *
80
-	 * @param string $path
81
-	 * @return int
82
-	 */
83
-	public function free_space($path) {
84
-		if ($this->quota < 0) {
85
-			return $this->storage->free_space($path);
86
-		} else {
87
-			$used = $this->getSize($this->sizeRoot);
88
-			if ($used < 0) {
89
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
-			} else {
91
-				$free = $this->storage->free_space($path);
92
-				$quotaFree = max($this->quota - $used, 0);
93
-				// if free space is known
94
-				if ($free >= 0) {
95
-					$free = min($free, $quotaFree);
96
-				} else {
97
-					$free = $quotaFree;
98
-				}
99
-				return $free;
100
-			}
101
-		}
102
-	}
103
-
104
-	/**
105
-	 * see http://php.net/manual/en/function.file_put_contents.php
106
-	 *
107
-	 * @param string $path
108
-	 * @param string $data
109
-	 * @return bool
110
-	 */
111
-	public function file_put_contents($path, $data) {
112
-		$free = $this->free_space('');
113
-		if ($free < 0 or strlen($data) < $free) {
114
-			return $this->storage->file_put_contents($path, $data);
115
-		} else {
116
-			return false;
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * see http://php.net/manual/en/function.copy.php
122
-	 *
123
-	 * @param string $source
124
-	 * @param string $target
125
-	 * @return bool
126
-	 */
127
-	public function copy($source, $target) {
128
-		$free = $this->free_space('');
129
-		if ($free < 0 or $this->getSize($source) < $free) {
130
-			return $this->storage->copy($source, $target);
131
-		} else {
132
-			return false;
133
-		}
134
-	}
135
-
136
-	/**
137
-	 * see http://php.net/manual/en/function.fopen.php
138
-	 *
139
-	 * @param string $path
140
-	 * @param string $mode
141
-	 * @return resource
142
-	 */
143
-	public function fopen($path, $mode) {
144
-		$source = $this->storage->fopen($path, $mode);
145
-
146
-		// don't apply quota for part files
147
-		if (!$this->isPartFile($path)) {
148
-			$free = $this->free_space('');
149
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
-				// only apply quota for files, not metadata, trash or others
151
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
-					return \OC\Files\Stream\Quota::wrap($source, $free);
153
-				}
154
-			}
155
-		}
156
-		return $source;
157
-	}
158
-
159
-	/**
160
-	 * Checks whether the given path is a part file
161
-	 *
162
-	 * @param string $path Path that may identify a .part file
163
-	 * @return string File path without .part extension
164
-	 * @note this is needed for reusing keys
165
-	 */
166
-	private function isPartFile($path) {
167
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
168
-
169
-		return ($extension === 'part');
170
-	}
171
-
172
-	/**
173
-	 * @param \OCP\Files\Storage $sourceStorage
174
-	 * @param string $sourceInternalPath
175
-	 * @param string $targetInternalPath
176
-	 * @return bool
177
-	 */
178
-	public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
-		$free = $this->free_space('');
180
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
-		} else {
183
-			return false;
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * @param \OCP\Files\Storage $sourceStorage
189
-	 * @param string $sourceInternalPath
190
-	 * @param string $targetInternalPath
191
-	 * @return bool
192
-	 */
193
-	public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
-		$free = $this->free_space('');
195
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
-		} else {
198
-			return false;
199
-		}
200
-	}
33
+    /**
34
+     * @var int $quota
35
+     */
36
+    protected $quota;
37
+
38
+    /**
39
+     * @var string $sizeRoot
40
+     */
41
+    protected $sizeRoot;
42
+
43
+    /**
44
+     * @param array $parameters
45
+     */
46
+    public function __construct($parameters) {
47
+        $this->storage = $parameters['storage'];
48
+        $this->quota = $parameters['quota'];
49
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
+    }
51
+
52
+    /**
53
+     * @return int quota value
54
+     */
55
+    public function getQuota() {
56
+        return $this->quota;
57
+    }
58
+
59
+    /**
60
+     * @param string $path
61
+     * @param \OC\Files\Storage\Storage $storage
62
+     */
63
+    protected function getSize($path, $storage = null) {
64
+        if (is_null($storage)) {
65
+            $cache = $this->getCache();
66
+        } else {
67
+            $cache = $storage->getCache();
68
+        }
69
+        $data = $cache->get($path);
70
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
71
+            return $data['size'];
72
+        } else {
73
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
+        }
75
+    }
76
+
77
+    /**
78
+     * Get free space as limited by the quota
79
+     *
80
+     * @param string $path
81
+     * @return int
82
+     */
83
+    public function free_space($path) {
84
+        if ($this->quota < 0) {
85
+            return $this->storage->free_space($path);
86
+        } else {
87
+            $used = $this->getSize($this->sizeRoot);
88
+            if ($used < 0) {
89
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
+            } else {
91
+                $free = $this->storage->free_space($path);
92
+                $quotaFree = max($this->quota - $used, 0);
93
+                // if free space is known
94
+                if ($free >= 0) {
95
+                    $free = min($free, $quotaFree);
96
+                } else {
97
+                    $free = $quotaFree;
98
+                }
99
+                return $free;
100
+            }
101
+        }
102
+    }
103
+
104
+    /**
105
+     * see http://php.net/manual/en/function.file_put_contents.php
106
+     *
107
+     * @param string $path
108
+     * @param string $data
109
+     * @return bool
110
+     */
111
+    public function file_put_contents($path, $data) {
112
+        $free = $this->free_space('');
113
+        if ($free < 0 or strlen($data) < $free) {
114
+            return $this->storage->file_put_contents($path, $data);
115
+        } else {
116
+            return false;
117
+        }
118
+    }
119
+
120
+    /**
121
+     * see http://php.net/manual/en/function.copy.php
122
+     *
123
+     * @param string $source
124
+     * @param string $target
125
+     * @return bool
126
+     */
127
+    public function copy($source, $target) {
128
+        $free = $this->free_space('');
129
+        if ($free < 0 or $this->getSize($source) < $free) {
130
+            return $this->storage->copy($source, $target);
131
+        } else {
132
+            return false;
133
+        }
134
+    }
135
+
136
+    /**
137
+     * see http://php.net/manual/en/function.fopen.php
138
+     *
139
+     * @param string $path
140
+     * @param string $mode
141
+     * @return resource
142
+     */
143
+    public function fopen($path, $mode) {
144
+        $source = $this->storage->fopen($path, $mode);
145
+
146
+        // don't apply quota for part files
147
+        if (!$this->isPartFile($path)) {
148
+            $free = $this->free_space('');
149
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
+                // only apply quota for files, not metadata, trash or others
151
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
153
+                }
154
+            }
155
+        }
156
+        return $source;
157
+    }
158
+
159
+    /**
160
+     * Checks whether the given path is a part file
161
+     *
162
+     * @param string $path Path that may identify a .part file
163
+     * @return string File path without .part extension
164
+     * @note this is needed for reusing keys
165
+     */
166
+    private function isPartFile($path) {
167
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
168
+
169
+        return ($extension === 'part');
170
+    }
171
+
172
+    /**
173
+     * @param \OCP\Files\Storage $sourceStorage
174
+     * @param string $sourceInternalPath
175
+     * @param string $targetInternalPath
176
+     * @return bool
177
+     */
178
+    public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
+        $free = $this->free_space('');
180
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
+        } else {
183
+            return false;
184
+        }
185
+    }
186
+
187
+    /**
188
+     * @param \OCP\Files\Storage $sourceStorage
189
+     * @param string $sourceInternalPath
190
+     * @param string $targetInternalPath
191
+     * @return bool
192
+     */
193
+    public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
+        $free = $this->free_space('');
195
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
+        } else {
198
+            return false;
199
+        }
200
+    }
201 201
 }
Please login to merge, or discard this patch.
lib/private/Files/Type/Loader.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,6 @@
 block discarded – undo
23 23
 
24 24
 use OCP\Files\IMimeTypeLoader;
25 25
 use OCP\IDBConnection;
26
-
27 26
 use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
28 27
 
29 28
 /**
Please login to merge, or discard this patch.
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -34,141 +34,141 @@
 block discarded – undo
34 34
  */
35 35
 class Loader implements IMimeTypeLoader {
36 36
 
37
-	/** @var IDBConnection */
38
-	private $dbConnection;
39
-
40
-	/** @var array [id => mimetype] */
41
-	protected $mimetypes;
42
-
43
-	/** @var array [mimetype => id] */
44
-	protected $mimetypeIds;
45
-
46
-	/**
47
-	 * @param IDBConnection $dbConnection
48
-	 */
49
-	public function __construct(IDBConnection $dbConnection) {
50
-		$this->dbConnection = $dbConnection;
51
-		$this->mimetypes = [];
52
-		$this->mimetypeIds = [];
53
-	}
54
-
55
-	/**
56
-	 * Get a mimetype from its ID
57
-	 *
58
-	 * @param int $id
59
-	 * @return string|null
60
-	 */
61
-	public function getMimetypeById($id) {
62
-		if (!$this->mimetypes) {
63
-			$this->loadMimetypes();
64
-		}
65
-		if (isset($this->mimetypes[$id])) {
66
-			return $this->mimetypes[$id];
67
-		}
68
-		return null;
69
-	}
70
-
71
-	/**
72
-	 * Get a mimetype ID, adding the mimetype to the DB if it does not exist
73
-	 *
74
-	 * @param string $mimetype
75
-	 * @return int
76
-	 */
77
-	public function getId($mimetype) {
78
-		if (!$this->mimetypeIds) {
79
-			$this->loadMimetypes();
80
-		}
81
-		if (isset($this->mimetypeIds[$mimetype])) {
82
-			return $this->mimetypeIds[$mimetype];
83
-		}
84
-		return $this->store($mimetype);
85
-	}
86
-
87
-	/**
88
-	 * Test if a mimetype exists in the database
89
-	 *
90
-	 * @param string $mimetype
91
-	 * @return bool
92
-	 */
93
-	public function exists($mimetype) {
94
-		if (!$this->mimetypeIds) {
95
-			$this->loadMimetypes();
96
-		}
97
-		return isset($this->mimetypeIds[$mimetype]);
98
-	}
99
-
100
-	/**
101
-	 * Clear all loaded mimetypes, allow for re-loading
102
-	 */
103
-	public function reset() {
104
-		$this->mimetypes = [];
105
-		$this->mimetypeIds = [];
106
-	}
107
-
108
-	/**
109
-	 * Store a mimetype in the DB
110
-	 *
111
-	 * @param string $mimetype
112
-	 * @param int inserted ID
113
-	 */
114
-	protected function store($mimetype) {
115
-		try {
116
-			$qb = $this->dbConnection->getQueryBuilder();
117
-			$qb->insert('mimetypes')
118
-				->values([
119
-					'mimetype' => $qb->createNamedParameter($mimetype)
120
-				]);
121
-			$qb->execute();
122
-		} catch (UniqueConstraintViolationException $e) {
123
-			// something inserted it before us
124
-		}
125
-
126
-		$fetch = $this->dbConnection->getQueryBuilder();
127
-		$fetch->select('id')
128
-			->from('mimetypes')
129
-			->where(
130
-				$fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
131
-			));
132
-		$row = $fetch->execute()->fetch();
133
-
134
-		$this->mimetypes[$row['id']] = $mimetype;
135
-		$this->mimetypeIds[$mimetype] = $row['id'];
136
-		return $row['id'];
137
-	}
138
-
139
-	/**
140
-	 * Load all mimetypes from DB
141
-	 */
142
-	private function loadMimetypes() {
143
-		$qb = $this->dbConnection->getQueryBuilder();
144
-		$qb->select('id', 'mimetype')
145
-			->from('mimetypes');
146
-		$results = $qb->execute()->fetchAll();
147
-
148
-		foreach ($results as $row) {
149
-			$this->mimetypes[$row['id']] = $row['mimetype'];
150
-			$this->mimetypeIds[$row['mimetype']] = $row['id'];
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * Update filecache mimetype based on file extension
156
-	 *
157
-	 * @param string $ext file extension
158
-	 * @param int $mimetypeId
159
-	 * @return int number of changed rows
160
-	 */
161
-	public function updateFilecache($ext, $mimetypeId) {
162
-		$update = $this->dbConnection->getQueryBuilder();
163
-		$update->update('filecache')
164
-			->set('mimetype', $update->createNamedParameter($mimetypeId))
165
-			->where($update->expr()->neq(
166
-				'mimetype', $update->createNamedParameter($mimetypeId)
167
-			))
168
-			->andWhere($update->expr()->like(
169
-				$update->createFunction('LOWER(`name`)'), $update->createNamedParameter($ext)
170
-			));
171
-		return $update->execute();
172
-	}
37
+    /** @var IDBConnection */
38
+    private $dbConnection;
39
+
40
+    /** @var array [id => mimetype] */
41
+    protected $mimetypes;
42
+
43
+    /** @var array [mimetype => id] */
44
+    protected $mimetypeIds;
45
+
46
+    /**
47
+     * @param IDBConnection $dbConnection
48
+     */
49
+    public function __construct(IDBConnection $dbConnection) {
50
+        $this->dbConnection = $dbConnection;
51
+        $this->mimetypes = [];
52
+        $this->mimetypeIds = [];
53
+    }
54
+
55
+    /**
56
+     * Get a mimetype from its ID
57
+     *
58
+     * @param int $id
59
+     * @return string|null
60
+     */
61
+    public function getMimetypeById($id) {
62
+        if (!$this->mimetypes) {
63
+            $this->loadMimetypes();
64
+        }
65
+        if (isset($this->mimetypes[$id])) {
66
+            return $this->mimetypes[$id];
67
+        }
68
+        return null;
69
+    }
70
+
71
+    /**
72
+     * Get a mimetype ID, adding the mimetype to the DB if it does not exist
73
+     *
74
+     * @param string $mimetype
75
+     * @return int
76
+     */
77
+    public function getId($mimetype) {
78
+        if (!$this->mimetypeIds) {
79
+            $this->loadMimetypes();
80
+        }
81
+        if (isset($this->mimetypeIds[$mimetype])) {
82
+            return $this->mimetypeIds[$mimetype];
83
+        }
84
+        return $this->store($mimetype);
85
+    }
86
+
87
+    /**
88
+     * Test if a mimetype exists in the database
89
+     *
90
+     * @param string $mimetype
91
+     * @return bool
92
+     */
93
+    public function exists($mimetype) {
94
+        if (!$this->mimetypeIds) {
95
+            $this->loadMimetypes();
96
+        }
97
+        return isset($this->mimetypeIds[$mimetype]);
98
+    }
99
+
100
+    /**
101
+     * Clear all loaded mimetypes, allow for re-loading
102
+     */
103
+    public function reset() {
104
+        $this->mimetypes = [];
105
+        $this->mimetypeIds = [];
106
+    }
107
+
108
+    /**
109
+     * Store a mimetype in the DB
110
+     *
111
+     * @param string $mimetype
112
+     * @param int inserted ID
113
+     */
114
+    protected function store($mimetype) {
115
+        try {
116
+            $qb = $this->dbConnection->getQueryBuilder();
117
+            $qb->insert('mimetypes')
118
+                ->values([
119
+                    'mimetype' => $qb->createNamedParameter($mimetype)
120
+                ]);
121
+            $qb->execute();
122
+        } catch (UniqueConstraintViolationException $e) {
123
+            // something inserted it before us
124
+        }
125
+
126
+        $fetch = $this->dbConnection->getQueryBuilder();
127
+        $fetch->select('id')
128
+            ->from('mimetypes')
129
+            ->where(
130
+                $fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
131
+            ));
132
+        $row = $fetch->execute()->fetch();
133
+
134
+        $this->mimetypes[$row['id']] = $mimetype;
135
+        $this->mimetypeIds[$mimetype] = $row['id'];
136
+        return $row['id'];
137
+    }
138
+
139
+    /**
140
+     * Load all mimetypes from DB
141
+     */
142
+    private function loadMimetypes() {
143
+        $qb = $this->dbConnection->getQueryBuilder();
144
+        $qb->select('id', 'mimetype')
145
+            ->from('mimetypes');
146
+        $results = $qb->execute()->fetchAll();
147
+
148
+        foreach ($results as $row) {
149
+            $this->mimetypes[$row['id']] = $row['mimetype'];
150
+            $this->mimetypeIds[$row['mimetype']] = $row['id'];
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Update filecache mimetype based on file extension
156
+     *
157
+     * @param string $ext file extension
158
+     * @param int $mimetypeId
159
+     * @return int number of changed rows
160
+     */
161
+    public function updateFilecache($ext, $mimetypeId) {
162
+        $update = $this->dbConnection->getQueryBuilder();
163
+        $update->update('filecache')
164
+            ->set('mimetype', $update->createNamedParameter($mimetypeId))
165
+            ->where($update->expr()->neq(
166
+                'mimetype', $update->createNamedParameter($mimetypeId)
167
+            ))
168
+            ->andWhere($update->expr()->like(
169
+                $update->createFunction('LOWER(`name`)'), $update->createNamedParameter($ext)
170
+            ));
171
+        return $update->execute();
172
+    }
173 173
 
174 174
 }
Please login to merge, or discard this patch.
lib/private/L10N/L10N.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@
 block discarded – undo
176 176
 	 * Returns an associative array with all translations
177 177
 	 *
178 178
 	 * Called by \OC_L10N_String
179
-	 * @return array
179
+	 * @return string[]
180 180
 	 */
181 181
 	public function getTranslations() {
182 182
 		return $this->translations;
Please login to merge, or discard this patch.
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -28,190 +28,190 @@
 block discarded – undo
28 28
 
29 29
 class L10N implements IL10N {
30 30
 
31
-	/** @var IFactory */
32
-	protected $factory;
33
-
34
-	/** @var string App of this object */
35
-	protected $app;
36
-
37
-	/** @var string Language of this object */
38
-	protected $lang;
39
-
40
-	/** @var string Plural forms (string) */
41
-	private $pluralFormString = 'nplurals=2; plural=(n != 1);';
42
-
43
-	/** @var string Plural forms (function) */
44
-	private $pluralFormFunction = null;
45
-
46
-	/** @var string[] */
47
-	private $translations = [];
48
-
49
-	/**
50
-	 * @param IFactory $factory
51
-	 * @param string $app
52
-	 * @param string $lang
53
-	 * @param array $files
54
-	 */
55
-	public function __construct(IFactory $factory, $app, $lang, array $files) {
56
-		$this->factory = $factory;
57
-		$this->app = $app;
58
-		$this->lang = $lang;
59
-
60
-		$this->translations = [];
61
-		foreach ($files as $languageFile) {
62
-			$this->load($languageFile);
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * The code (en, de, ...) of the language that is used for this instance
68
-	 *
69
-	 * @return string language
70
-	 */
71
-	public function getLanguageCode() {
72
-		return $this->lang;
73
-	}
74
-
75
-	/**
76
-	 * Translating
77
-	 * @param string $text The text we need a translation for
78
-	 * @param array $parameters default:array() Parameters for sprintf
79
-	 * @return string Translation or the same text
80
-	 *
81
-	 * Returns the translation. If no translation is found, $text will be
82
-	 * returned.
83
-	 */
84
-	public function t($text, $parameters = array()) {
85
-		return (string) new \OC_L10N_String($this, $text, $parameters);
86
-	}
87
-
88
-	/**
89
-	 * Translating
90
-	 * @param string $text_singular the string to translate for exactly one object
91
-	 * @param string $text_plural the string to translate for n objects
92
-	 * @param integer $count Number of objects
93
-	 * @param array $parameters default:array() Parameters for sprintf
94
-	 * @return string Translation or the same text
95
-	 *
96
-	 * Returns the translation. If no translation is found, $text will be
97
-	 * returned. %n will be replaced with the number of objects.
98
-	 *
99
-	 * The correct plural is determined by the plural_forms-function
100
-	 * provided by the po file.
101
-	 *
102
-	 */
103
-	public function n($text_singular, $text_plural, $count, $parameters = array()) {
104
-		$identifier = "_${text_singular}_::_${text_plural}_";
105
-		if (isset($this->translations[$identifier])) {
106
-			return (string) new \OC_L10N_String($this, $identifier, $parameters, $count);
107
-		} else {
108
-			if ($count === 1) {
109
-				return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count);
110
-			} else {
111
-				return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count);
112
-			}
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * Localization
118
-	 * @param string $type Type of localization
119
-	 * @param \DateTime|int|string $data parameters for this localization
120
-	 * @param array $options
121
-	 * @return string|int|false
122
-	 *
123
-	 * Returns the localized data.
124
-	 *
125
-	 * Implemented types:
126
-	 *  - date
127
-	 *    - Creates a date
128
-	 *    - params: timestamp (int/string)
129
-	 *  - datetime
130
-	 *    - Creates date and time
131
-	 *    - params: timestamp (int/string)
132
-	 *  - time
133
-	 *    - Creates a time
134
-	 *    - params: timestamp (int/string)
135
-	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
136
-	 *  - jsdate: Returns the short JS date format
137
-	 */
138
-	public function l($type, $data = null, $options = array()) {
139
-		// Use the language of the instance
140
-		$locale = $this->getLanguageCode();
141
-		if ($locale === 'sr@latin') {
142
-			$locale = 'sr_latn';
143
-		}
144
-
145
-		if ($type === 'firstday') {
146
-			return (int) Calendar::getFirstWeekday($locale);
147
-		}
148
-		if ($type === 'jsdate') {
149
-			return (string) Calendar::getDateFormat('short', $locale);
150
-		}
151
-
152
-		$value = new \DateTime();
153
-		if ($data instanceof \DateTime) {
154
-			$value = $data;
155
-		} else if (is_string($data) && !is_numeric($data)) {
156
-			$data = strtotime($data);
157
-			$value->setTimestamp($data);
158
-		} else if ($data !== null) {
159
-			$value->setTimestamp($data);
160
-		}
161
-
162
-		$options = array_merge(array('width' => 'long'), $options);
163
-		$width = $options['width'];
164
-		switch ($type) {
165
-			case 'date':
166
-				return (string) Calendar::formatDate($value, $width, $locale);
167
-			case 'datetime':
168
-				return (string) Calendar::formatDatetime($value, $width, $locale);
169
-			case 'time':
170
-				return (string) Calendar::formatTime($value, $width, $locale);
171
-			default:
172
-				return false;
173
-		}
174
-	}
175
-
176
-	/**
177
-	 * Returns an associative array with all translations
178
-	 *
179
-	 * Called by \OC_L10N_String
180
-	 * @return array
181
-	 */
182
-	public function getTranslations() {
183
-		return $this->translations;
184
-	}
185
-
186
-	/**
187
-	 * Returnsed function accepts the argument $n
188
-	 *
189
-	 * Called by \OC_L10N_String
190
-	 * @return string the plural form function
191
-	 */
192
-	public function getPluralFormFunction() {
193
-		if (is_null($this->pluralFormFunction)) {
194
-			$this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString);
195
-		}
196
-		return $this->pluralFormFunction;
197
-	}
198
-
199
-	/**
200
-	 * @param $translationFile
201
-	 * @return bool
202
-	 */
203
-	protected function load($translationFile) {
204
-		$json = json_decode(file_get_contents($translationFile), true);
205
-		if (!is_array($json)) {
206
-			$jsonError = json_last_error();
207
-			\OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
208
-			return false;
209
-		}
210
-
211
-		if (!empty($json['pluralForm'])) {
212
-			$this->pluralFormString = $json['pluralForm'];
213
-		}
214
-		$this->translations = array_merge($this->translations, $json['translations']);
215
-		return true;
216
-	}
31
+    /** @var IFactory */
32
+    protected $factory;
33
+
34
+    /** @var string App of this object */
35
+    protected $app;
36
+
37
+    /** @var string Language of this object */
38
+    protected $lang;
39
+
40
+    /** @var string Plural forms (string) */
41
+    private $pluralFormString = 'nplurals=2; plural=(n != 1);';
42
+
43
+    /** @var string Plural forms (function) */
44
+    private $pluralFormFunction = null;
45
+
46
+    /** @var string[] */
47
+    private $translations = [];
48
+
49
+    /**
50
+     * @param IFactory $factory
51
+     * @param string $app
52
+     * @param string $lang
53
+     * @param array $files
54
+     */
55
+    public function __construct(IFactory $factory, $app, $lang, array $files) {
56
+        $this->factory = $factory;
57
+        $this->app = $app;
58
+        $this->lang = $lang;
59
+
60
+        $this->translations = [];
61
+        foreach ($files as $languageFile) {
62
+            $this->load($languageFile);
63
+        }
64
+    }
65
+
66
+    /**
67
+     * The code (en, de, ...) of the language that is used for this instance
68
+     *
69
+     * @return string language
70
+     */
71
+    public function getLanguageCode() {
72
+        return $this->lang;
73
+    }
74
+
75
+    /**
76
+     * Translating
77
+     * @param string $text The text we need a translation for
78
+     * @param array $parameters default:array() Parameters for sprintf
79
+     * @return string Translation or the same text
80
+     *
81
+     * Returns the translation. If no translation is found, $text will be
82
+     * returned.
83
+     */
84
+    public function t($text, $parameters = array()) {
85
+        return (string) new \OC_L10N_String($this, $text, $parameters);
86
+    }
87
+
88
+    /**
89
+     * Translating
90
+     * @param string $text_singular the string to translate for exactly one object
91
+     * @param string $text_plural the string to translate for n objects
92
+     * @param integer $count Number of objects
93
+     * @param array $parameters default:array() Parameters for sprintf
94
+     * @return string Translation or the same text
95
+     *
96
+     * Returns the translation. If no translation is found, $text will be
97
+     * returned. %n will be replaced with the number of objects.
98
+     *
99
+     * The correct plural is determined by the plural_forms-function
100
+     * provided by the po file.
101
+     *
102
+     */
103
+    public function n($text_singular, $text_plural, $count, $parameters = array()) {
104
+        $identifier = "_${text_singular}_::_${text_plural}_";
105
+        if (isset($this->translations[$identifier])) {
106
+            return (string) new \OC_L10N_String($this, $identifier, $parameters, $count);
107
+        } else {
108
+            if ($count === 1) {
109
+                return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count);
110
+            } else {
111
+                return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count);
112
+            }
113
+        }
114
+    }
115
+
116
+    /**
117
+     * Localization
118
+     * @param string $type Type of localization
119
+     * @param \DateTime|int|string $data parameters for this localization
120
+     * @param array $options
121
+     * @return string|int|false
122
+     *
123
+     * Returns the localized data.
124
+     *
125
+     * Implemented types:
126
+     *  - date
127
+     *    - Creates a date
128
+     *    - params: timestamp (int/string)
129
+     *  - datetime
130
+     *    - Creates date and time
131
+     *    - params: timestamp (int/string)
132
+     *  - time
133
+     *    - Creates a time
134
+     *    - params: timestamp (int/string)
135
+     *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
136
+     *  - jsdate: Returns the short JS date format
137
+     */
138
+    public function l($type, $data = null, $options = array()) {
139
+        // Use the language of the instance
140
+        $locale = $this->getLanguageCode();
141
+        if ($locale === 'sr@latin') {
142
+            $locale = 'sr_latn';
143
+        }
144
+
145
+        if ($type === 'firstday') {
146
+            return (int) Calendar::getFirstWeekday($locale);
147
+        }
148
+        if ($type === 'jsdate') {
149
+            return (string) Calendar::getDateFormat('short', $locale);
150
+        }
151
+
152
+        $value = new \DateTime();
153
+        if ($data instanceof \DateTime) {
154
+            $value = $data;
155
+        } else if (is_string($data) && !is_numeric($data)) {
156
+            $data = strtotime($data);
157
+            $value->setTimestamp($data);
158
+        } else if ($data !== null) {
159
+            $value->setTimestamp($data);
160
+        }
161
+
162
+        $options = array_merge(array('width' => 'long'), $options);
163
+        $width = $options['width'];
164
+        switch ($type) {
165
+            case 'date':
166
+                return (string) Calendar::formatDate($value, $width, $locale);
167
+            case 'datetime':
168
+                return (string) Calendar::formatDatetime($value, $width, $locale);
169
+            case 'time':
170
+                return (string) Calendar::formatTime($value, $width, $locale);
171
+            default:
172
+                return false;
173
+        }
174
+    }
175
+
176
+    /**
177
+     * Returns an associative array with all translations
178
+     *
179
+     * Called by \OC_L10N_String
180
+     * @return array
181
+     */
182
+    public function getTranslations() {
183
+        return $this->translations;
184
+    }
185
+
186
+    /**
187
+     * Returnsed function accepts the argument $n
188
+     *
189
+     * Called by \OC_L10N_String
190
+     * @return string the plural form function
191
+     */
192
+    public function getPluralFormFunction() {
193
+        if (is_null($this->pluralFormFunction)) {
194
+            $this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString);
195
+        }
196
+        return $this->pluralFormFunction;
197
+    }
198
+
199
+    /**
200
+     * @param $translationFile
201
+     * @return bool
202
+     */
203
+    protected function load($translationFile) {
204
+        $json = json_decode(file_get_contents($translationFile), true);
205
+        if (!is_array($json)) {
206
+            $jsonError = json_last_error();
207
+            \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
208
+            return false;
209
+        }
210
+
211
+        if (!empty($json['pluralForm'])) {
212
+            $this->pluralFormString = $json['pluralForm'];
213
+        }
214
+        $this->translations = array_merge($this->translations, $json['translations']);
215
+        return true;
216
+    }
217 217
 }
Please login to merge, or discard this patch.
lib/private/legacy/api.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -331,7 +331,7 @@
 block discarded – undo
331 331
 
332 332
 	/**
333 333
 	 * http basic auth
334
-	 * @return string|false (username, or false on failure)
334
+	 * @return string (username, or false on failure)
335 335
 	 */
336 336
 	private static function loginUser() {
337 337
 		if(self::$isLoggedIn === true) {
Please login to merge, or discard this patch.
Indentation   +462 added lines, -462 removed lines patch added patch discarded remove patch
@@ -37,467 +37,467 @@
 block discarded – undo
37 37
 
38 38
 class OC_API {
39 39
 
40
-	/**
41
-	 * API authentication levels
42
-	 */
43
-
44
-	/** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
-	const GUEST_AUTH = 0;
46
-
47
-	/** @deprecated Use \OCP\API::USER_AUTH instead */
48
-	const USER_AUTH = 1;
49
-
50
-	/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
-	const SUBADMIN_AUTH = 2;
52
-
53
-	/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
-	const ADMIN_AUTH = 3;
55
-
56
-	/**
57
-	 * API Response Codes
58
-	 */
59
-
60
-	/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
-	const RESPOND_UNAUTHORISED = 997;
62
-
63
-	/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
-	const RESPOND_SERVER_ERROR = 996;
65
-
66
-	/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
-	const RESPOND_NOT_FOUND = 998;
68
-
69
-	/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
-	const RESPOND_UNKNOWN_ERROR = 999;
71
-
72
-	/**
73
-	 * api actions
74
-	 */
75
-	protected static $actions = array();
76
-	private static $logoutRequired = false;
77
-	private static $isLoggedIn = false;
78
-
79
-	/**
80
-	 * registers an api call
81
-	 * @param string $method the http method
82
-	 * @param string $url the url to match
83
-	 * @param callable $action the function to run
84
-	 * @param string $app the id of the app registering the call
85
-	 * @param int $authLevel the level of authentication required for the call
86
-	 * @param array $defaults
87
-	 * @param array $requirements
88
-	 */
89
-	public static function register($method, $url, $action, $app,
90
-				$authLevel = API::USER_AUTH,
91
-				$defaults = array(),
92
-				$requirements = array()) {
93
-		$name = strtolower($method).$url;
94
-		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
96
-			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
-			OC::$server->getRouter()->useCollection('ocs');
98
-			OC::$server->getRouter()->create($name, $url)
99
-				->method($method)
100
-				->defaults($defaults)
101
-				->requirements($requirements)
102
-				->action('OC_API', 'call');
103
-			self::$actions[$name] = array();
104
-			OC::$server->getRouter()->useCollection($oldCollection);
105
-		}
106
-		self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
-	}
108
-
109
-	/**
110
-	 * handles an api call
111
-	 * @param array $parameters
112
-	 */
113
-	public static function call($parameters) {
114
-		$request = \OC::$server->getRequest();
115
-		$method = $request->getMethod();
116
-
117
-		// Prepare the request variables
118
-		if($method === 'PUT') {
119
-			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
121
-			$parameters['_delete'] = $request->getParams();
122
-		}
123
-		$name = $parameters['_route'];
124
-		// Foreach registered action
125
-		$responses = array();
126
-		foreach(self::$actions[$name] as $action) {
127
-			// Check authentication and availability
128
-			if(!self::isAuthorised($action)) {
129
-				$responses[] = array(
130
-					'app' => $action['app'],
131
-					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
132
-					'shipped' => OC_App::isShipped($action['app']),
133
-					);
134
-				continue;
135
-			}
136
-			if(!is_callable($action['action'])) {
137
-				$responses[] = array(
138
-					'app' => $action['app'],
139
-					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
140
-					'shipped' => OC_App::isShipped($action['app']),
141
-					);
142
-				continue;
143
-			}
144
-			// Run the action
145
-			$responses[] = array(
146
-				'app' => $action['app'],
147
-				'response' => call_user_func($action['action'], $parameters),
148
-				'shipped' => OC_App::isShipped($action['app']),
149
-				);
150
-		}
151
-		$response = self::mergeResponses($responses);
152
-		$format = self::requestedFormat();
153
-		if (self::$logoutRequired) {
154
-			\OC::$server->getUserSession()->logout();
155
-		}
156
-
157
-		self::respond($response, $format);
158
-	}
159
-
160
-	/**
161
-	 * merge the returned result objects into one response
162
-	 * @param array $responses
163
-	 * @return OC_OCS_Result
164
-	 */
165
-	public static function mergeResponses($responses) {
166
-		// Sort into shipped and third-party
167
-		$shipped = array(
168
-			'succeeded' => array(),
169
-			'failed' => array(),
170
-			);
171
-		$thirdparty = array(
172
-			'succeeded' => array(),
173
-			'failed' => array(),
174
-			);
175
-
176
-		foreach($responses as $response) {
177
-			if($response['shipped'] || ($response['app'] === 'core')) {
178
-				if($response['response']->succeeded()) {
179
-					$shipped['succeeded'][$response['app']] = $response;
180
-				} else {
181
-					$shipped['failed'][$response['app']] = $response;
182
-				}
183
-			} else {
184
-				if($response['response']->succeeded()) {
185
-					$thirdparty['succeeded'][$response['app']] = $response;
186
-				} else {
187
-					$thirdparty['failed'][$response['app']] = $response;
188
-				}
189
-			}
190
-		}
191
-
192
-		// Remove any error responses if there is one shipped response that succeeded
193
-		if(!empty($shipped['failed'])) {
194
-			// Which shipped response do we use if they all failed?
195
-			// They may have failed for different reasons (different status codes)
196
-			// Which response code should we return?
197
-			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198
-			// Merge failed responses if more than one
199
-			$data = array();
200
-			foreach($shipped['failed'] as $failure) {
201
-				$data = array_merge_recursive($data, $failure['response']->getData());
202
-			}
203
-			$picked = reset($shipped['failed']);
204
-			$code = $picked['response']->getStatusCode();
205
-			$meta = $picked['response']->getMeta();
206
-			$headers = $picked['response']->getHeaders();
207
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208
-			return $response;
209
-		} elseif(!empty($shipped['succeeded'])) {
210
-			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
-		} elseif(!empty($thirdparty['failed'])) {
212
-			// Merge failed responses if more than one
213
-			$data = array();
214
-			foreach($thirdparty['failed'] as $failure) {
215
-				$data = array_merge_recursive($data, $failure['response']->getData());
216
-			}
217
-			$picked = reset($thirdparty['failed']);
218
-			$code = $picked['response']->getStatusCode();
219
-			$meta = $picked['response']->getMeta();
220
-			$headers = $picked['response']->getHeaders();
221
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
222
-			return $response;
223
-		} else {
224
-			$responses = $thirdparty['succeeded'];
225
-		}
226
-		// Merge the successful responses
227
-		$data = [];
228
-		$codes = [];
229
-		$header = [];
230
-
231
-		foreach($responses as $response) {
232
-			if($response['shipped']) {
233
-				$data = array_merge_recursive($response['response']->getData(), $data);
234
-			} else {
235
-				$data = array_merge_recursive($data, $response['response']->getData());
236
-			}
237
-			$header = array_merge_recursive($header, $response['response']->getHeaders());
238
-			$codes[] = ['code' => $response['response']->getStatusCode(),
239
-				'meta' => $response['response']->getMeta()];
240
-		}
241
-
242
-		// Use any non 100 status codes
243
-		$statusCode = 100;
244
-		$statusMessage = null;
245
-		foreach($codes as $code) {
246
-			if($code['code'] != 100) {
247
-				$statusCode = $code['code'];
248
-				$statusMessage = $code['meta']['message'];
249
-				break;
250
-			}
251
-		}
252
-
253
-		return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
254
-	}
255
-
256
-	/**
257
-	 * authenticate the api call
258
-	 * @param array $action the action details as supplied to OC_API::register()
259
-	 * @return bool
260
-	 */
261
-	private static function isAuthorised($action) {
262
-		$level = $action['authlevel'];
263
-		switch($level) {
264
-			case API::GUEST_AUTH:
265
-				// Anyone can access
266
-				return true;
267
-			case API::USER_AUTH:
268
-				// User required
269
-				return self::loginUser();
270
-			case API::SUBADMIN_AUTH:
271
-				// Check for subadmin
272
-				$user = self::loginUser();
273
-				if(!$user) {
274
-					return false;
275
-				} else {
276
-					$userObject = \OC::$server->getUserSession()->getUser();
277
-					if($userObject === null) {
278
-						return false;
279
-					}
280
-					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281
-					$admin = OC_User::isAdminUser($user);
282
-					if($isSubAdmin || $admin) {
283
-						return true;
284
-					} else {
285
-						return false;
286
-					}
287
-				}
288
-			case API::ADMIN_AUTH:
289
-				// Check for admin
290
-				$user = self::loginUser();
291
-				if(!$user) {
292
-					return false;
293
-				} else {
294
-					return OC_User::isAdminUser($user);
295
-				}
296
-			default:
297
-				// oops looks like invalid level supplied
298
-				return false;
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * http basic auth
304
-	 * @return string|false (username, or false on failure)
305
-	 */
306
-	private static function loginUser() {
307
-		if(self::$isLoggedIn === true) {
308
-			return \OC_User::getUser();
309
-		}
310
-
311
-		// reuse existing login
312
-		$loggedIn = \OC::$server->getUserSession()->isLoggedIn();
313
-		if ($loggedIn === true) {
314
-			if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
315
-				// Do not allow access to OCS until the 2FA challenge was solved successfully
316
-				return false;
317
-			}
318
-			$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
319
-			if ($ocsApiRequest) {
320
-
321
-				// initialize the user's filesystem
322
-				\OC_Util::setupFS(\OC_User::getUser());
323
-				self::$isLoggedIn = true;
324
-
325
-				return OC_User::getUser();
326
-			}
327
-			return false;
328
-		}
329
-
330
-		// basic auth - because OC_User::login will create a new session we shall only try to login
331
-		// if user and pass are set
332
-		$userSession = \OC::$server->getUserSession();
333
-		$request = \OC::$server->getRequest();
334
-		try {
335
-			$loginSuccess = $userSession->tryTokenLogin($request);
336
-			if (!$loginSuccess) {
337
-				$loginSuccess = $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler());
338
-			}
339
-		} catch (\OC\User\LoginException $e) {
340
-			return false;
341
-		}
40
+    /**
41
+     * API authentication levels
42
+     */
43
+
44
+    /** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
+    const GUEST_AUTH = 0;
46
+
47
+    /** @deprecated Use \OCP\API::USER_AUTH instead */
48
+    const USER_AUTH = 1;
49
+
50
+    /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
+    const SUBADMIN_AUTH = 2;
52
+
53
+    /** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
+    const ADMIN_AUTH = 3;
55
+
56
+    /**
57
+     * API Response Codes
58
+     */
59
+
60
+    /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
+    const RESPOND_UNAUTHORISED = 997;
62
+
63
+    /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
+    const RESPOND_SERVER_ERROR = 996;
65
+
66
+    /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
+    const RESPOND_NOT_FOUND = 998;
68
+
69
+    /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
+    const RESPOND_UNKNOWN_ERROR = 999;
71
+
72
+    /**
73
+     * api actions
74
+     */
75
+    protected static $actions = array();
76
+    private static $logoutRequired = false;
77
+    private static $isLoggedIn = false;
78
+
79
+    /**
80
+     * registers an api call
81
+     * @param string $method the http method
82
+     * @param string $url the url to match
83
+     * @param callable $action the function to run
84
+     * @param string $app the id of the app registering the call
85
+     * @param int $authLevel the level of authentication required for the call
86
+     * @param array $defaults
87
+     * @param array $requirements
88
+     */
89
+    public static function register($method, $url, $action, $app,
90
+                $authLevel = API::USER_AUTH,
91
+                $defaults = array(),
92
+                $requirements = array()) {
93
+        $name = strtolower($method).$url;
94
+        $name = str_replace(array('/', '{', '}'), '_', $name);
95
+        if(!isset(self::$actions[$name])) {
96
+            $oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
+            OC::$server->getRouter()->useCollection('ocs');
98
+            OC::$server->getRouter()->create($name, $url)
99
+                ->method($method)
100
+                ->defaults($defaults)
101
+                ->requirements($requirements)
102
+                ->action('OC_API', 'call');
103
+            self::$actions[$name] = array();
104
+            OC::$server->getRouter()->useCollection($oldCollection);
105
+        }
106
+        self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
+    }
108
+
109
+    /**
110
+     * handles an api call
111
+     * @param array $parameters
112
+     */
113
+    public static function call($parameters) {
114
+        $request = \OC::$server->getRequest();
115
+        $method = $request->getMethod();
116
+
117
+        // Prepare the request variables
118
+        if($method === 'PUT') {
119
+            $parameters['_put'] = $request->getParams();
120
+        } else if($method === 'DELETE') {
121
+            $parameters['_delete'] = $request->getParams();
122
+        }
123
+        $name = $parameters['_route'];
124
+        // Foreach registered action
125
+        $responses = array();
126
+        foreach(self::$actions[$name] as $action) {
127
+            // Check authentication and availability
128
+            if(!self::isAuthorised($action)) {
129
+                $responses[] = array(
130
+                    'app' => $action['app'],
131
+                    'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
132
+                    'shipped' => OC_App::isShipped($action['app']),
133
+                    );
134
+                continue;
135
+            }
136
+            if(!is_callable($action['action'])) {
137
+                $responses[] = array(
138
+                    'app' => $action['app'],
139
+                    'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
140
+                    'shipped' => OC_App::isShipped($action['app']),
141
+                    );
142
+                continue;
143
+            }
144
+            // Run the action
145
+            $responses[] = array(
146
+                'app' => $action['app'],
147
+                'response' => call_user_func($action['action'], $parameters),
148
+                'shipped' => OC_App::isShipped($action['app']),
149
+                );
150
+        }
151
+        $response = self::mergeResponses($responses);
152
+        $format = self::requestedFormat();
153
+        if (self::$logoutRequired) {
154
+            \OC::$server->getUserSession()->logout();
155
+        }
156
+
157
+        self::respond($response, $format);
158
+    }
159
+
160
+    /**
161
+     * merge the returned result objects into one response
162
+     * @param array $responses
163
+     * @return OC_OCS_Result
164
+     */
165
+    public static function mergeResponses($responses) {
166
+        // Sort into shipped and third-party
167
+        $shipped = array(
168
+            'succeeded' => array(),
169
+            'failed' => array(),
170
+            );
171
+        $thirdparty = array(
172
+            'succeeded' => array(),
173
+            'failed' => array(),
174
+            );
175
+
176
+        foreach($responses as $response) {
177
+            if($response['shipped'] || ($response['app'] === 'core')) {
178
+                if($response['response']->succeeded()) {
179
+                    $shipped['succeeded'][$response['app']] = $response;
180
+                } else {
181
+                    $shipped['failed'][$response['app']] = $response;
182
+                }
183
+            } else {
184
+                if($response['response']->succeeded()) {
185
+                    $thirdparty['succeeded'][$response['app']] = $response;
186
+                } else {
187
+                    $thirdparty['failed'][$response['app']] = $response;
188
+                }
189
+            }
190
+        }
191
+
192
+        // Remove any error responses if there is one shipped response that succeeded
193
+        if(!empty($shipped['failed'])) {
194
+            // Which shipped response do we use if they all failed?
195
+            // They may have failed for different reasons (different status codes)
196
+            // Which response code should we return?
197
+            // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198
+            // Merge failed responses if more than one
199
+            $data = array();
200
+            foreach($shipped['failed'] as $failure) {
201
+                $data = array_merge_recursive($data, $failure['response']->getData());
202
+            }
203
+            $picked = reset($shipped['failed']);
204
+            $code = $picked['response']->getStatusCode();
205
+            $meta = $picked['response']->getMeta();
206
+            $headers = $picked['response']->getHeaders();
207
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208
+            return $response;
209
+        } elseif(!empty($shipped['succeeded'])) {
210
+            $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
+        } elseif(!empty($thirdparty['failed'])) {
212
+            // Merge failed responses if more than one
213
+            $data = array();
214
+            foreach($thirdparty['failed'] as $failure) {
215
+                $data = array_merge_recursive($data, $failure['response']->getData());
216
+            }
217
+            $picked = reset($thirdparty['failed']);
218
+            $code = $picked['response']->getStatusCode();
219
+            $meta = $picked['response']->getMeta();
220
+            $headers = $picked['response']->getHeaders();
221
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
222
+            return $response;
223
+        } else {
224
+            $responses = $thirdparty['succeeded'];
225
+        }
226
+        // Merge the successful responses
227
+        $data = [];
228
+        $codes = [];
229
+        $header = [];
230
+
231
+        foreach($responses as $response) {
232
+            if($response['shipped']) {
233
+                $data = array_merge_recursive($response['response']->getData(), $data);
234
+            } else {
235
+                $data = array_merge_recursive($data, $response['response']->getData());
236
+            }
237
+            $header = array_merge_recursive($header, $response['response']->getHeaders());
238
+            $codes[] = ['code' => $response['response']->getStatusCode(),
239
+                'meta' => $response['response']->getMeta()];
240
+        }
241
+
242
+        // Use any non 100 status codes
243
+        $statusCode = 100;
244
+        $statusMessage = null;
245
+        foreach($codes as $code) {
246
+            if($code['code'] != 100) {
247
+                $statusCode = $code['code'];
248
+                $statusMessage = $code['meta']['message'];
249
+                break;
250
+            }
251
+        }
252
+
253
+        return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
254
+    }
255
+
256
+    /**
257
+     * authenticate the api call
258
+     * @param array $action the action details as supplied to OC_API::register()
259
+     * @return bool
260
+     */
261
+    private static function isAuthorised($action) {
262
+        $level = $action['authlevel'];
263
+        switch($level) {
264
+            case API::GUEST_AUTH:
265
+                // Anyone can access
266
+                return true;
267
+            case API::USER_AUTH:
268
+                // User required
269
+                return self::loginUser();
270
+            case API::SUBADMIN_AUTH:
271
+                // Check for subadmin
272
+                $user = self::loginUser();
273
+                if(!$user) {
274
+                    return false;
275
+                } else {
276
+                    $userObject = \OC::$server->getUserSession()->getUser();
277
+                    if($userObject === null) {
278
+                        return false;
279
+                    }
280
+                    $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281
+                    $admin = OC_User::isAdminUser($user);
282
+                    if($isSubAdmin || $admin) {
283
+                        return true;
284
+                    } else {
285
+                        return false;
286
+                    }
287
+                }
288
+            case API::ADMIN_AUTH:
289
+                // Check for admin
290
+                $user = self::loginUser();
291
+                if(!$user) {
292
+                    return false;
293
+                } else {
294
+                    return OC_User::isAdminUser($user);
295
+                }
296
+            default:
297
+                // oops looks like invalid level supplied
298
+                return false;
299
+        }
300
+    }
301
+
302
+    /**
303
+     * http basic auth
304
+     * @return string|false (username, or false on failure)
305
+     */
306
+    private static function loginUser() {
307
+        if(self::$isLoggedIn === true) {
308
+            return \OC_User::getUser();
309
+        }
310
+
311
+        // reuse existing login
312
+        $loggedIn = \OC::$server->getUserSession()->isLoggedIn();
313
+        if ($loggedIn === true) {
314
+            if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
315
+                // Do not allow access to OCS until the 2FA challenge was solved successfully
316
+                return false;
317
+            }
318
+            $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
319
+            if ($ocsApiRequest) {
320
+
321
+                // initialize the user's filesystem
322
+                \OC_Util::setupFS(\OC_User::getUser());
323
+                self::$isLoggedIn = true;
324
+
325
+                return OC_User::getUser();
326
+            }
327
+            return false;
328
+        }
329
+
330
+        // basic auth - because OC_User::login will create a new session we shall only try to login
331
+        // if user and pass are set
332
+        $userSession = \OC::$server->getUserSession();
333
+        $request = \OC::$server->getRequest();
334
+        try {
335
+            $loginSuccess = $userSession->tryTokenLogin($request);
336
+            if (!$loginSuccess) {
337
+                $loginSuccess = $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler());
338
+            }
339
+        } catch (\OC\User\LoginException $e) {
340
+            return false;
341
+        }
342 342
 	
343
-		if ($loginSuccess === true) {
344
-			self::$logoutRequired = true;
345
-
346
-			// initialize the user's filesystem
347
-			\OC_Util::setupFS(\OC_User::getUser());
348
-			self::$isLoggedIn = true;
349
-
350
-			return \OC_User::getUser();
351
-		}
352
-
353
-		return false;
354
-	}
355
-
356
-	/**
357
-	 * respond to a call
358
-	 * @param OC_OCS_Result $result
359
-	 * @param string $format the format xml|json
360
-	 */
361
-	public static function respond($result, $format='xml') {
362
-		$request = \OC::$server->getRequest();
363
-
364
-		// Send 401 headers if unauthorised
365
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
366
-			// If request comes from JS return dummy auth request
367
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
368
-				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
369
-			} else {
370
-				header('WWW-Authenticate: Basic realm="Authorisation Required"');
371
-			}
372
-			header('HTTP/1.0 401 Unauthorized');
373
-		}
374
-
375
-		foreach($result->getHeaders() as $name => $value) {
376
-			header($name . ': ' . $value);
377
-		}
378
-
379
-		$meta = $result->getMeta();
380
-		$data = $result->getData();
381
-		if (self::isV2($request)) {
382
-			$statusCode = self::mapStatusCodes($result->getStatusCode());
383
-			if (!is_null($statusCode)) {
384
-				$meta['statuscode'] = $statusCode;
385
-				OC_Response::setStatus($statusCode);
386
-			}
387
-		}
388
-
389
-		self::setContentType($format);
390
-		$body = self::renderResult($format, $meta, $data);
391
-		echo $body;
392
-	}
393
-
394
-	/**
395
-	 * @param XMLWriter $writer
396
-	 */
397
-	private static function toXML($array, $writer) {
398
-		foreach($array as $k => $v) {
399
-			if ($k[0] === '@') {
400
-				$writer->writeAttribute(substr($k, 1), $v);
401
-				continue;
402
-			} else if (is_numeric($k)) {
403
-				$k = 'element';
404
-			}
405
-			if(is_array($v)) {
406
-				$writer->startElement($k);
407
-				self::toXML($v, $writer);
408
-				$writer->endElement();
409
-			} else {
410
-				$writer->writeElement($k, $v);
411
-			}
412
-		}
413
-	}
414
-
415
-	/**
416
-	 * @return string
417
-	 */
418
-	public static function requestedFormat() {
419
-		$formats = array('json', 'xml');
420
-
421
-		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
422
-		return $format;
423
-	}
424
-
425
-	/**
426
-	 * Based on the requested format the response content type is set
427
-	 * @param string $format
428
-	 */
429
-	public static function setContentType($format = null) {
430
-		$format = is_null($format) ? self::requestedFormat() : $format;
431
-		if ($format === 'xml') {
432
-			header('Content-type: text/xml; charset=UTF-8');
433
-			return;
434
-		}
435
-
436
-		if ($format === 'json') {
437
-			header('Content-Type: application/json; charset=utf-8');
438
-			return;
439
-		}
440
-
441
-		header('Content-Type: application/octet-stream; charset=utf-8');
442
-	}
443
-
444
-	/**
445
-	 * @param \OCP\IRequest $request
446
-	 * @return bool
447
-	 */
448
-	protected static function isV2(\OCP\IRequest $request) {
449
-		$script = $request->getScriptName();
450
-
451
-		return substr($script, -11) === '/ocs/v2.php';
452
-	}
453
-
454
-	/**
455
-	 * @param integer $sc
456
-	 * @return int
457
-	 */
458
-	public static function mapStatusCodes($sc) {
459
-		switch ($sc) {
460
-			case API::RESPOND_NOT_FOUND:
461
-				return Http::STATUS_NOT_FOUND;
462
-			case API::RESPOND_SERVER_ERROR:
463
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
464
-			case API::RESPOND_UNKNOWN_ERROR:
465
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
466
-			case API::RESPOND_UNAUTHORISED:
467
-				// already handled for v1
468
-				return null;
469
-			case 100:
470
-				return Http::STATUS_OK;
471
-		}
472
-		// any 2xx, 4xx and 5xx will be used as is
473
-		if ($sc >= 200 && $sc < 600) {
474
-			return $sc;
475
-		}
476
-
477
-		return Http::STATUS_BAD_REQUEST;
478
-	}
479
-
480
-	/**
481
-	 * @param string $format
482
-	 * @return string
483
-	 */
484
-	public static function renderResult($format, $meta, $data) {
485
-		$response = array(
486
-			'ocs' => array(
487
-				'meta' => $meta,
488
-				'data' => $data,
489
-			),
490
-		);
491
-		if ($format == 'json') {
492
-			return OC_JSON::encode($response);
493
-		}
494
-
495
-		$writer = new XMLWriter();
496
-		$writer->openMemory();
497
-		$writer->setIndent(true);
498
-		$writer->startDocument();
499
-		self::toXML($response, $writer);
500
-		$writer->endDocument();
501
-		return $writer->outputMemory(true);
502
-	}
343
+        if ($loginSuccess === true) {
344
+            self::$logoutRequired = true;
345
+
346
+            // initialize the user's filesystem
347
+            \OC_Util::setupFS(\OC_User::getUser());
348
+            self::$isLoggedIn = true;
349
+
350
+            return \OC_User::getUser();
351
+        }
352
+
353
+        return false;
354
+    }
355
+
356
+    /**
357
+     * respond to a call
358
+     * @param OC_OCS_Result $result
359
+     * @param string $format the format xml|json
360
+     */
361
+    public static function respond($result, $format='xml') {
362
+        $request = \OC::$server->getRequest();
363
+
364
+        // Send 401 headers if unauthorised
365
+        if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
366
+            // If request comes from JS return dummy auth request
367
+            if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
368
+                header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
369
+            } else {
370
+                header('WWW-Authenticate: Basic realm="Authorisation Required"');
371
+            }
372
+            header('HTTP/1.0 401 Unauthorized');
373
+        }
374
+
375
+        foreach($result->getHeaders() as $name => $value) {
376
+            header($name . ': ' . $value);
377
+        }
378
+
379
+        $meta = $result->getMeta();
380
+        $data = $result->getData();
381
+        if (self::isV2($request)) {
382
+            $statusCode = self::mapStatusCodes($result->getStatusCode());
383
+            if (!is_null($statusCode)) {
384
+                $meta['statuscode'] = $statusCode;
385
+                OC_Response::setStatus($statusCode);
386
+            }
387
+        }
388
+
389
+        self::setContentType($format);
390
+        $body = self::renderResult($format, $meta, $data);
391
+        echo $body;
392
+    }
393
+
394
+    /**
395
+     * @param XMLWriter $writer
396
+     */
397
+    private static function toXML($array, $writer) {
398
+        foreach($array as $k => $v) {
399
+            if ($k[0] === '@') {
400
+                $writer->writeAttribute(substr($k, 1), $v);
401
+                continue;
402
+            } else if (is_numeric($k)) {
403
+                $k = 'element';
404
+            }
405
+            if(is_array($v)) {
406
+                $writer->startElement($k);
407
+                self::toXML($v, $writer);
408
+                $writer->endElement();
409
+            } else {
410
+                $writer->writeElement($k, $v);
411
+            }
412
+        }
413
+    }
414
+
415
+    /**
416
+     * @return string
417
+     */
418
+    public static function requestedFormat() {
419
+        $formats = array('json', 'xml');
420
+
421
+        $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
422
+        return $format;
423
+    }
424
+
425
+    /**
426
+     * Based on the requested format the response content type is set
427
+     * @param string $format
428
+     */
429
+    public static function setContentType($format = null) {
430
+        $format = is_null($format) ? self::requestedFormat() : $format;
431
+        if ($format === 'xml') {
432
+            header('Content-type: text/xml; charset=UTF-8');
433
+            return;
434
+        }
435
+
436
+        if ($format === 'json') {
437
+            header('Content-Type: application/json; charset=utf-8');
438
+            return;
439
+        }
440
+
441
+        header('Content-Type: application/octet-stream; charset=utf-8');
442
+    }
443
+
444
+    /**
445
+     * @param \OCP\IRequest $request
446
+     * @return bool
447
+     */
448
+    protected static function isV2(\OCP\IRequest $request) {
449
+        $script = $request->getScriptName();
450
+
451
+        return substr($script, -11) === '/ocs/v2.php';
452
+    }
453
+
454
+    /**
455
+     * @param integer $sc
456
+     * @return int
457
+     */
458
+    public static function mapStatusCodes($sc) {
459
+        switch ($sc) {
460
+            case API::RESPOND_NOT_FOUND:
461
+                return Http::STATUS_NOT_FOUND;
462
+            case API::RESPOND_SERVER_ERROR:
463
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
464
+            case API::RESPOND_UNKNOWN_ERROR:
465
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
466
+            case API::RESPOND_UNAUTHORISED:
467
+                // already handled for v1
468
+                return null;
469
+            case 100:
470
+                return Http::STATUS_OK;
471
+        }
472
+        // any 2xx, 4xx and 5xx will be used as is
473
+        if ($sc >= 200 && $sc < 600) {
474
+            return $sc;
475
+        }
476
+
477
+        return Http::STATUS_BAD_REQUEST;
478
+    }
479
+
480
+    /**
481
+     * @param string $format
482
+     * @return string
483
+     */
484
+    public static function renderResult($format, $meta, $data) {
485
+        $response = array(
486
+            'ocs' => array(
487
+                'meta' => $meta,
488
+                'data' => $data,
489
+            ),
490
+        );
491
+        if ($format == 'json') {
492
+            return OC_JSON::encode($response);
493
+        }
494
+
495
+        $writer = new XMLWriter();
496
+        $writer->openMemory();
497
+        $writer->setIndent(true);
498
+        $writer->startDocument();
499
+        self::toXML($response, $writer);
500
+        $writer->endDocument();
501
+        return $writer->outputMemory(true);
502
+    }
503 503
 }
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 				$requirements = array()) {
93 93
 		$name = strtolower($method).$url;
94 94
 		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
95
+		if (!isset(self::$actions[$name])) {
96 96
 			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97 97
 			OC::$server->getRouter()->useCollection('ocs');
98 98
 			OC::$server->getRouter()->create($name, $url)
@@ -115,17 +115,17 @@  discard block
 block discarded – undo
115 115
 		$method = $request->getMethod();
116 116
 
117 117
 		// Prepare the request variables
118
-		if($method === 'PUT') {
118
+		if ($method === 'PUT') {
119 119
 			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
120
+		} else if ($method === 'DELETE') {
121 121
 			$parameters['_delete'] = $request->getParams();
122 122
 		}
123 123
 		$name = $parameters['_route'];
124 124
 		// Foreach registered action
125 125
 		$responses = array();
126
-		foreach(self::$actions[$name] as $action) {
126
+		foreach (self::$actions[$name] as $action) {
127 127
 			// Check authentication and availability
128
-			if(!self::isAuthorised($action)) {
128
+			if (!self::isAuthorised($action)) {
129 129
 				$responses[] = array(
130 130
 					'app' => $action['app'],
131 131
 					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 					);
134 134
 				continue;
135 135
 			}
136
-			if(!is_callable($action['action'])) {
136
+			if (!is_callable($action['action'])) {
137 137
 				$responses[] = array(
138 138
 					'app' => $action['app'],
139 139
 					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
@@ -173,15 +173,15 @@  discard block
 block discarded – undo
173 173
 			'failed' => array(),
174 174
 			);
175 175
 
176
-		foreach($responses as $response) {
177
-			if($response['shipped'] || ($response['app'] === 'core')) {
178
-				if($response['response']->succeeded()) {
176
+		foreach ($responses as $response) {
177
+			if ($response['shipped'] || ($response['app'] === 'core')) {
178
+				if ($response['response']->succeeded()) {
179 179
 					$shipped['succeeded'][$response['app']] = $response;
180 180
 				} else {
181 181
 					$shipped['failed'][$response['app']] = $response;
182 182
 				}
183 183
 			} else {
184
-				if($response['response']->succeeded()) {
184
+				if ($response['response']->succeeded()) {
185 185
 					$thirdparty['succeeded'][$response['app']] = $response;
186 186
 				} else {
187 187
 					$thirdparty['failed'][$response['app']] = $response;
@@ -190,14 +190,14 @@  discard block
 block discarded – undo
190 190
 		}
191 191
 
192 192
 		// Remove any error responses if there is one shipped response that succeeded
193
-		if(!empty($shipped['failed'])) {
193
+		if (!empty($shipped['failed'])) {
194 194
 			// Which shipped response do we use if they all failed?
195 195
 			// They may have failed for different reasons (different status codes)
196 196
 			// Which response code should we return?
197 197
 			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198 198
 			// Merge failed responses if more than one
199 199
 			$data = array();
200
-			foreach($shipped['failed'] as $failure) {
200
+			foreach ($shipped['failed'] as $failure) {
201 201
 				$data = array_merge_recursive($data, $failure['response']->getData());
202 202
 			}
203 203
 			$picked = reset($shipped['failed']);
@@ -206,12 +206,12 @@  discard block
 block discarded – undo
206 206
 			$headers = $picked['response']->getHeaders();
207 207
 			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208 208
 			return $response;
209
-		} elseif(!empty($shipped['succeeded'])) {
209
+		} elseif (!empty($shipped['succeeded'])) {
210 210
 			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
-		} elseif(!empty($thirdparty['failed'])) {
211
+		} elseif (!empty($thirdparty['failed'])) {
212 212
 			// Merge failed responses if more than one
213 213
 			$data = array();
214
-			foreach($thirdparty['failed'] as $failure) {
214
+			foreach ($thirdparty['failed'] as $failure) {
215 215
 				$data = array_merge_recursive($data, $failure['response']->getData());
216 216
 			}
217 217
 			$picked = reset($thirdparty['failed']);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
 		$codes = [];
229 229
 		$header = [];
230 230
 
231
-		foreach($responses as $response) {
232
-			if($response['shipped']) {
231
+		foreach ($responses as $response) {
232
+			if ($response['shipped']) {
233 233
 				$data = array_merge_recursive($response['response']->getData(), $data);
234 234
 			} else {
235 235
 				$data = array_merge_recursive($data, $response['response']->getData());
@@ -242,8 +242,8 @@  discard block
 block discarded – undo
242 242
 		// Use any non 100 status codes
243 243
 		$statusCode = 100;
244 244
 		$statusMessage = null;
245
-		foreach($codes as $code) {
246
-			if($code['code'] != 100) {
245
+		foreach ($codes as $code) {
246
+			if ($code['code'] != 100) {
247 247
 				$statusCode = $code['code'];
248 248
 				$statusMessage = $code['meta']['message'];
249 249
 				break;
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 	 */
261 261
 	private static function isAuthorised($action) {
262 262
 		$level = $action['authlevel'];
263
-		switch($level) {
263
+		switch ($level) {
264 264
 			case API::GUEST_AUTH:
265 265
 				// Anyone can access
266 266
 				return true;
@@ -270,16 +270,16 @@  discard block
 block discarded – undo
270 270
 			case API::SUBADMIN_AUTH:
271 271
 				// Check for subadmin
272 272
 				$user = self::loginUser();
273
-				if(!$user) {
273
+				if (!$user) {
274 274
 					return false;
275 275
 				} else {
276 276
 					$userObject = \OC::$server->getUserSession()->getUser();
277
-					if($userObject === null) {
277
+					if ($userObject === null) {
278 278
 						return false;
279 279
 					}
280 280
 					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281 281
 					$admin = OC_User::isAdminUser($user);
282
-					if($isSubAdmin || $admin) {
282
+					if ($isSubAdmin || $admin) {
283 283
 						return true;
284 284
 					} else {
285 285
 						return false;
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			case API::ADMIN_AUTH:
289 289
 				// Check for admin
290 290
 				$user = self::loginUser();
291
-				if(!$user) {
291
+				if (!$user) {
292 292
 					return false;
293 293
 				} else {
294 294
 					return OC_User::isAdminUser($user);
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 	 * @return string|false (username, or false on failure)
305 305
 	 */
306 306
 	private static function loginUser() {
307
-		if(self::$isLoggedIn === true) {
307
+		if (self::$isLoggedIn === true) {
308 308
 			return \OC_User::getUser();
309 309
 		}
310 310
 
@@ -358,13 +358,13 @@  discard block
 block discarded – undo
358 358
 	 * @param OC_OCS_Result $result
359 359
 	 * @param string $format the format xml|json
360 360
 	 */
361
-	public static function respond($result, $format='xml') {
361
+	public static function respond($result, $format = 'xml') {
362 362
 		$request = \OC::$server->getRequest();
363 363
 
364 364
 		// Send 401 headers if unauthorised
365
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
365
+		if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
366 366
 			// If request comes from JS return dummy auth request
367
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
367
+			if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
368 368
 				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
369 369
 			} else {
370 370
 				header('WWW-Authenticate: Basic realm="Authorisation Required"');
@@ -372,8 +372,8 @@  discard block
 block discarded – undo
372 372
 			header('HTTP/1.0 401 Unauthorized');
373 373
 		}
374 374
 
375
-		foreach($result->getHeaders() as $name => $value) {
376
-			header($name . ': ' . $value);
375
+		foreach ($result->getHeaders() as $name => $value) {
376
+			header($name.': '.$value);
377 377
 		}
378 378
 
379 379
 		$meta = $result->getMeta();
@@ -395,14 +395,14 @@  discard block
 block discarded – undo
395 395
 	 * @param XMLWriter $writer
396 396
 	 */
397 397
 	private static function toXML($array, $writer) {
398
-		foreach($array as $k => $v) {
398
+		foreach ($array as $k => $v) {
399 399
 			if ($k[0] === '@') {
400 400
 				$writer->writeAttribute(substr($k, 1), $v);
401 401
 				continue;
402 402
 			} else if (is_numeric($k)) {
403 403
 				$k = 'element';
404 404
 			}
405
-			if(is_array($v)) {
405
+			if (is_array($v)) {
406 406
 				$writer->startElement($k);
407 407
 				self::toXML($v, $writer);
408 408
 				$writer->endElement();
Please login to merge, or discard this patch.
lib/private/legacy/eventsource.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@
 block discarded – undo
88 88
 	 * send a message to the client
89 89
 	 *
90 90
 	 * @param string $type
91
-	 * @param mixed $data
91
+	 * @param string $data
92 92
 	 *
93 93
 	 * @throws \BadMethodCallException
94 94
 	 * if only one parameter is given, a typeless message will be send with that parameter as data
Please login to merge, or discard this patch.
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -33,98 +33,98 @@
 block discarded – undo
33 33
  * use server side events with caution, to many open requests can hang the server
34 34
  */
35 35
 class OC_EventSource implements \OCP\IEventSource {
36
-	/**
37
-	 * @var bool
38
-	 */
39
-	private $fallback;
36
+    /**
37
+     * @var bool
38
+     */
39
+    private $fallback;
40 40
 
41
-	/**
42
-	 * @var int
43
-	 */
44
-	private $fallBackId = 0;
41
+    /**
42
+     * @var int
43
+     */
44
+    private $fallBackId = 0;
45 45
 
46
-	/**
47
-	 * @var bool
48
-	 */
49
-	private $started = false;
46
+    /**
47
+     * @var bool
48
+     */
49
+    private $started = false;
50 50
 
51
-	protected function init() {
52
-		if ($this->started) {
53
-			return;
54
-		}
55
-		$this->started = true;
51
+    protected function init() {
52
+        if ($this->started) {
53
+            return;
54
+        }
55
+        $this->started = true;
56 56
 
57
-		// prevent php output buffering, caching and nginx buffering
58
-		OC_Util::obEnd();
59
-		header('Cache-Control: no-cache');
60
-		header('X-Accel-Buffering: no');
61
-		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
-		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
64
-			/**
65
-			 * FIXME: The default content-security-policy of ownCloud forbids inline
66
-			 * JavaScript for security reasons. IE starting on Windows 10 will
67
-			 * however also obey the CSP which will break the event source fallback.
68
-			 *
69
-			 * As a workaround thus we set a custom policy which allows the execution
70
-			 * of inline JavaScript.
71
-			 *
72
-			 * @link https://github.com/owncloud/core/issues/14286
73
-			 */
74
-			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
-			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
-		} else {
78
-			header("Content-Type: text/event-stream");
79
-		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
-			header('Location: '.\OC::$WEBROOT);
82
-			exit();
83
-		}
84
-		if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
-			$this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
-			$this->close();
87
-			exit();
88
-		}
89
-		flush();
90
-	}
57
+        // prevent php output buffering, caching and nginx buffering
58
+        OC_Util::obEnd();
59
+        header('Cache-Control: no-cache');
60
+        header('X-Accel-Buffering: no');
61
+        $this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
+        if ($this->fallback) {
63
+            $this->fallBackId = (int)$_GET['fallback_id'];
64
+            /**
65
+             * FIXME: The default content-security-policy of ownCloud forbids inline
66
+             * JavaScript for security reasons. IE starting on Windows 10 will
67
+             * however also obey the CSP which will break the event source fallback.
68
+             *
69
+             * As a workaround thus we set a custom policy which allows the execution
70
+             * of inline JavaScript.
71
+             *
72
+             * @link https://github.com/owncloud/core/issues/14286
73
+             */
74
+            header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
+            header("Content-Type: text/html");
76
+            echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
+        } else {
78
+            header("Content-Type: text/event-stream");
79
+        }
80
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
+            header('Location: '.\OC::$WEBROOT);
82
+            exit();
83
+        }
84
+        if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
+            $this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
+            $this->close();
87
+            exit();
88
+        }
89
+        flush();
90
+    }
91 91
 
92
-	/**
93
-	 * send a message to the client
94
-	 *
95
-	 * @param string $type
96
-	 * @param mixed $data
97
-	 *
98
-	 * @throws \BadMethodCallException
99
-	 * if only one parameter is given, a typeless message will be send with that parameter as data
100
-	 */
101
-	public function send($type, $data = null) {
102
-		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
-		}
105
-		$this->init();
106
-		if (is_null($data)) {
107
-			$data = $type;
108
-			$type = null;
109
-		}
110
-		if ($this->fallback) {
111
-			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
-			echo $response;
114
-		} else {
115
-			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
117
-			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
-		}
120
-		echo PHP_EOL;
121
-		flush();
122
-	}
92
+    /**
93
+     * send a message to the client
94
+     *
95
+     * @param string $type
96
+     * @param mixed $data
97
+     *
98
+     * @throws \BadMethodCallException
99
+     * if only one parameter is given, a typeless message will be send with that parameter as data
100
+     */
101
+    public function send($type, $data = null) {
102
+        if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
+            throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
+        }
105
+        $this->init();
106
+        if (is_null($data)) {
107
+            $data = $type;
108
+            $type = null;
109
+        }
110
+        if ($this->fallback) {
111
+            $response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
+                . $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
+            echo $response;
114
+        } else {
115
+            if ($type) {
116
+                echo 'event: ' . $type . PHP_EOL;
117
+            }
118
+            echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
+        }
120
+        echo PHP_EOL;
121
+        flush();
122
+    }
123 123
 
124
-	/**
125
-	 * close the connection of the event source
126
-	 */
127
-	public function close() {
128
-		$this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
-	}
124
+    /**
125
+     * close the connection of the event source
126
+     */
127
+    public function close() {
128
+        $this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
+    }
130 130
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 		header('X-Accel-Buffering: no');
61 61
 		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62 62
 		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
63
+			$this->fallBackId = (int) $_GET['fallback_id'];
64 64
 			/**
65 65
 			 * FIXME: The default content-security-policy of ownCloud forbids inline
66 66
 			 * JavaScript for security reasons. IE starting on Windows 10 will
@@ -73,11 +73,11 @@  discard block
 block discarded – undo
73 73
 			 */
74 74
 			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75 75
 			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
76
+			echo str_repeat('<span></span>'.PHP_EOL, 10); //dummy data to keep IE happy
77 77
 		} else {
78 78
 			header("Content-Type: text/event-stream");
79 79
 		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
80
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81 81
 			header('Location: '.\OC::$WEBROOT);
82 82
 			exit();
83 83
 		}
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function send($type, $data = null) {
102 102
 		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
103
+			throw new BadMethodCallException('Type needs to be alphanumeric ('.$type.')');
104 104
 		}
105 105
 		$this->init();
106 106
 		if (is_null($data)) {
@@ -109,13 +109,13 @@  discard block
 block discarded – undo
109 109
 		}
110 110
 		if ($this->fallback) {
111 111
 			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
112
+				. $this->fallBackId.',"'.$type.'",'.OCP\JSON::encode($data).')</script>'.PHP_EOL;
113 113
 			echo $response;
114 114
 		} else {
115 115
 			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
116
+				echo 'event: '.$type.PHP_EOL;
117 117
 			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
118
+			echo 'data: '.OCP\JSON::encode($data).PHP_EOL;
119 119
 		}
120 120
 		echo PHP_EOL;
121 121
 		flush();
Please login to merge, or discard this patch.
lib/private/legacy/helper.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -560,7 +560,7 @@
 block discarded – undo
560 560
 	 *
561 561
 	 * @param string $path
562 562
 	 * @param \OCP\Files\FileInfo $rootInfo (optional)
563
-	 * @return array
563
+	 * @return string
564 564
 	 * @throws \OCP\Files\NotFoundException
565 565
 	 */
566 566
 	public static function getStorageInfo($path, $rootInfo = null) {
Please login to merge, or discard this patch.
Indentation   +602 added lines, -602 removed lines patch added patch discarded remove patch
@@ -48,606 +48,606 @@
 block discarded – undo
48 48
  * Collection of useful functions
49 49
  */
50 50
 class OC_Helper {
51
-	private static $templateManager;
52
-
53
-	/**
54
-	 * Creates an absolute url for public use
55
-	 * @param string $service id
56
-	 * @param bool $add_slash
57
-	 * @return string the url
58
-	 *
59
-	 * Returns a absolute url to the given service.
60
-	 */
61
-	public static function linkToPublic($service, $add_slash = false) {
62
-		if ($service === 'files') {
63
-			$url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
64
-		} else {
65
-			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66
-		}
67
-		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68
-	}
69
-
70
-	/**
71
-	 * Make a human file size
72
-	 * @param int $bytes file size in bytes
73
-	 * @return string a human readable file size
74
-	 *
75
-	 * Makes 2048 to 2 kB.
76
-	 */
77
-	public static function humanFileSize($bytes) {
78
-		if ($bytes < 0) {
79
-			return "?";
80
-		}
81
-		if ($bytes < 1024) {
82
-			return "$bytes B";
83
-		}
84
-		$bytes = round($bytes / 1024, 0);
85
-		if ($bytes < 1024) {
86
-			return "$bytes KB";
87
-		}
88
-		$bytes = round($bytes / 1024, 1);
89
-		if ($bytes < 1024) {
90
-			return "$bytes MB";
91
-		}
92
-		$bytes = round($bytes / 1024, 1);
93
-		if ($bytes < 1024) {
94
-			return "$bytes GB";
95
-		}
96
-		$bytes = round($bytes / 1024, 1);
97
-		if ($bytes < 1024) {
98
-			return "$bytes TB";
99
-		}
100
-
101
-		$bytes = round($bytes / 1024, 1);
102
-		return "$bytes PB";
103
-	}
104
-
105
-	/**
106
-	 * Make a php file size
107
-	 * @param int $bytes file size in bytes
108
-	 * @return string a php parseable file size
109
-	 *
110
-	 * Makes 2048 to 2k and 2^41 to 2048G
111
-	 */
112
-	public static function phpFileSize($bytes) {
113
-		if ($bytes < 0) {
114
-			return "?";
115
-		}
116
-		if ($bytes < 1024) {
117
-			return $bytes . "B";
118
-		}
119
-		$bytes = round($bytes / 1024, 1);
120
-		if ($bytes < 1024) {
121
-			return $bytes . "K";
122
-		}
123
-		$bytes = round($bytes / 1024, 1);
124
-		if ($bytes < 1024) {
125
-			return $bytes . "M";
126
-		}
127
-		$bytes = round($bytes / 1024, 1);
128
-		return $bytes . "G";
129
-	}
130
-
131
-	/**
132
-	 * Make a computer file size
133
-	 * @param string $str file size in human readable format
134
-	 * @return float a file size in bytes
135
-	 *
136
-	 * Makes 2kB to 2048.
137
-	 *
138
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
139
-	 */
140
-	public static function computerFileSize($str) {
141
-		$str = strtolower($str);
142
-		if (is_numeric($str)) {
143
-			return floatval($str);
144
-		}
145
-
146
-		$bytes_array = array(
147
-			'b' => 1,
148
-			'k' => 1024,
149
-			'kb' => 1024,
150
-			'mb' => 1024 * 1024,
151
-			'm' => 1024 * 1024,
152
-			'gb' => 1024 * 1024 * 1024,
153
-			'g' => 1024 * 1024 * 1024,
154
-			'tb' => 1024 * 1024 * 1024 * 1024,
155
-			't' => 1024 * 1024 * 1024 * 1024,
156
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
157
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
158
-		);
159
-
160
-		$bytes = floatval($str);
161
-
162
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
163
-			$bytes *= $bytes_array[$matches[1]];
164
-		} else {
165
-			return false;
166
-		}
167
-
168
-		$bytes = round($bytes);
169
-
170
-		return $bytes;
171
-	}
172
-
173
-	/**
174
-	 * Recursive copying of folders
175
-	 * @param string $src source folder
176
-	 * @param string $dest target folder
177
-	 *
178
-	 */
179
-	static function copyr($src, $dest) {
180
-		if (is_dir($src)) {
181
-			if (!is_dir($dest)) {
182
-				mkdir($dest);
183
-			}
184
-			$files = scandir($src);
185
-			foreach ($files as $file) {
186
-				if ($file != "." && $file != "..") {
187
-					self::copyr("$src/$file", "$dest/$file");
188
-				}
189
-			}
190
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
191
-			copy($src, $dest);
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * Recursive deletion of folders
197
-	 * @param string $dir path to the folder
198
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
199
-	 * @return bool
200
-	 */
201
-	static function rmdirr($dir, $deleteSelf = true) {
202
-		if (is_dir($dir)) {
203
-			$files = new RecursiveIteratorIterator(
204
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
205
-				RecursiveIteratorIterator::CHILD_FIRST
206
-			);
207
-
208
-			foreach ($files as $fileInfo) {
209
-				/** @var SplFileInfo $fileInfo */
210
-				if ($fileInfo->isLink()) {
211
-					unlink($fileInfo->getPathname());
212
-				} else if ($fileInfo->isDir()) {
213
-					rmdir($fileInfo->getRealPath());
214
-				} else {
215
-					unlink($fileInfo->getRealPath());
216
-				}
217
-			}
218
-			if ($deleteSelf) {
219
-				rmdir($dir);
220
-			}
221
-		} elseif (file_exists($dir)) {
222
-			if ($deleteSelf) {
223
-				unlink($dir);
224
-			}
225
-		}
226
-		if (!$deleteSelf) {
227
-			return true;
228
-		}
229
-
230
-		return !file_exists($dir);
231
-	}
232
-
233
-	/**
234
-	 * @return \OC\Files\Type\TemplateManager
235
-	 */
236
-	static public function getFileTemplateManager() {
237
-		if (!self::$templateManager) {
238
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
239
-		}
240
-		return self::$templateManager;
241
-	}
242
-
243
-	/**
244
-	 * detect if a given program is found in the search PATH
245
-	 *
246
-	 * @param string $name
247
-	 * @param bool $path
248
-	 * @internal param string $program name
249
-	 * @internal param string $optional search path, defaults to $PATH
250
-	 * @return bool    true if executable program found in path
251
-	 */
252
-	public static function canExecute($name, $path = false) {
253
-		// path defaults to PATH from environment if not set
254
-		if ($path === false) {
255
-			$path = getenv("PATH");
256
-		}
257
-		// we look for an executable file of that name
258
-		$exts = [""];
259
-		$check_fn = "is_executable";
260
-		// Default check will be done with $path directories :
261
-		$dirs = explode(PATH_SEPARATOR, $path);
262
-		// WARNING : We have to check if open_basedir is enabled :
263
-		$obd = OC::$server->getIniWrapper()->getString('open_basedir');
264
-		if ($obd != "none") {
265
-			$obd_values = explode(PATH_SEPARATOR, $obd);
266
-			if (count($obd_values) > 0 and $obd_values[0]) {
267
-				// open_basedir is in effect !
268
-				// We need to check if the program is in one of these dirs :
269
-				$dirs = $obd_values;
270
-			}
271
-		}
272
-		foreach ($dirs as $dir) {
273
-			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
275
-					return true;
276
-			}
277
-		}
278
-		return false;
279
-	}
280
-
281
-	/**
282
-	 * copy the contents of one stream to another
283
-	 *
284
-	 * @param resource $source
285
-	 * @param resource $target
286
-	 * @return array the number of bytes copied and result
287
-	 */
288
-	public static function streamCopy($source, $target) {
289
-		if (!$source or !$target) {
290
-			return array(0, false);
291
-		}
292
-		$bufSize = 8192;
293
-		$result = true;
294
-		$count = 0;
295
-		while (!feof($source)) {
296
-			$buf = fread($source, $bufSize);
297
-			$bytesWritten = fwrite($target, $buf);
298
-			if ($bytesWritten !== false) {
299
-				$count += $bytesWritten;
300
-			}
301
-			// note: strlen is expensive so only use it when necessary,
302
-			// on the last block
303
-			if ($bytesWritten === false
304
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
305
-			) {
306
-				// write error, could be disk full ?
307
-				$result = false;
308
-				break;
309
-			}
310
-		}
311
-		return array($count, $result);
312
-	}
313
-
314
-	/**
315
-	 * Adds a suffix to the name in case the file exists
316
-	 *
317
-	 * @param string $path
318
-	 * @param string $filename
319
-	 * @return string
320
-	 */
321
-	public static function buildNotExistingFileName($path, $filename) {
322
-		$view = \OC\Files\Filesystem::getView();
323
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
324
-	}
325
-
326
-	/**
327
-	 * Adds a suffix to the name in case the file exists
328
-	 *
329
-	 * @param string $path
330
-	 * @param string $filename
331
-	 * @return string
332
-	 */
333
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
334
-		if ($path === '/') {
335
-			$path = '';
336
-		}
337
-		if ($pos = strrpos($filename, '.')) {
338
-			$name = substr($filename, 0, $pos);
339
-			$ext = substr($filename, $pos);
340
-		} else {
341
-			$name = $filename;
342
-			$ext = '';
343
-		}
344
-
345
-		$newpath = $path . '/' . $filename;
346
-		if ($view->file_exists($newpath)) {
347
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
348
-				//Replace the last "(number)" with "(number+1)"
349
-				$last_match = count($matches[0]) - 1;
350
-				$counter = $matches[1][$last_match][0] + 1;
351
-				$offset = $matches[0][$last_match][1];
352
-				$match_length = strlen($matches[0][$last_match][0]);
353
-			} else {
354
-				$counter = 2;
355
-				$match_length = 0;
356
-				$offset = false;
357
-			}
358
-			do {
359
-				if ($offset) {
360
-					//Replace the last "(number)" with "(number+1)"
361
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
362
-				} else {
363
-					$newname = $name . ' (' . $counter . ')';
364
-				}
365
-				$newpath = $path . '/' . $newname . $ext;
366
-				$counter++;
367
-			} while ($view->file_exists($newpath));
368
-		}
369
-
370
-		return $newpath;
371
-	}
372
-
373
-	/**
374
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
375
-	 *
376
-	 * @param array $input The array to work on
377
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
378
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
379
-	 * @return array
380
-	 *
381
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
382
-	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
383
-	 *
384
-	 */
385
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
386
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
387
-		$ret = array();
388
-		foreach ($input as $k => $v) {
389
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
390
-		}
391
-		return $ret;
392
-	}
393
-
394
-	/**
395
-	 * performs a search in a nested array
396
-	 * @param array $haystack the array to be searched
397
-	 * @param string $needle the search string
398
-	 * @param string $index optional, only search this key name
399
-	 * @return mixed the key of the matching field, otherwise false
400
-	 *
401
-	 * performs a search in a nested array
402
-	 *
403
-	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
404
-	 */
405
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
406
-		$aIt = new RecursiveArrayIterator($haystack);
407
-		$it = new RecursiveIteratorIterator($aIt);
408
-
409
-		while ($it->valid()) {
410
-			if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
411
-				return $aIt->key();
412
-			}
413
-
414
-			$it->next();
415
-		}
416
-
417
-		return false;
418
-	}
419
-
420
-	/**
421
-	 * calculates the maximum upload size respecting system settings, free space and user quota
422
-	 *
423
-	 * @param string $dir the current folder where the user currently operates
424
-	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
425
-	 * @return int number of bytes representing
426
-	 */
427
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
428
-		if (is_null($freeSpace) || $freeSpace < 0){
429
-			$freeSpace = self::freeSpace($dir);
430
-		}
431
-		return min($freeSpace, self::uploadLimit());
432
-	}
433
-
434
-	/**
435
-	 * Calculate free space left within user quota
436
-	 *
437
-	 * @param string $dir the current folder where the user currently operates
438
-	 * @return int number of bytes representing
439
-	 */
440
-	public static function freeSpace($dir) {
441
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
442
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
443
-			$freeSpace = max($freeSpace, 0);
444
-			return $freeSpace;
445
-		} else {
446
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * Calculate PHP upload limit
452
-	 *
453
-	 * @return int PHP upload file size limit
454
-	 */
455
-	public static function uploadLimit() {
456
-		$ini = \OC::$server->getIniWrapper();
457
-		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
458
-		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
459
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
460
-			return INF;
461
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
462
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
463
-		} else {
464
-			return min($upload_max_filesize, $post_max_size);
465
-		}
466
-	}
467
-
468
-	/**
469
-	 * Checks if a function is available
470
-	 *
471
-	 * @param string $function_name
472
-	 * @return bool
473
-	 */
474
-	public static function is_function_enabled($function_name) {
475
-		if (!function_exists($function_name)) {
476
-			return false;
477
-		}
478
-		$ini = \OC::$server->getIniWrapper();
479
-		$disabled = explode(',', $ini->get('disable_functions'));
480
-		$disabled = array_map('trim', $disabled);
481
-		if (in_array($function_name, $disabled)) {
482
-			return false;
483
-		}
484
-		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
485
-		$disabled = array_map('trim', $disabled);
486
-		if (in_array($function_name, $disabled)) {
487
-			return false;
488
-		}
489
-		return true;
490
-	}
491
-
492
-	/**
493
-	 * Try to find a program
494
-	 *
495
-	 * @param string $program
496
-	 * @return null|string
497
-	 */
498
-	public static function findBinaryPath($program) {
499
-		$memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
500
-		if ($memcache->hasKey($program)) {
501
-			return $memcache->get($program);
502
-		}
503
-		$result = null;
504
-		if (self::is_function_enabled('exec')) {
505
-			$exeSniffer = new ExecutableFinder();
506
-			// Returns null if nothing is found
507
-			$result = $exeSniffer->find($program);
508
-			if (empty($result)) {
509
-				$paths = getenv('PATH');
510
-				if (empty($paths)) {
511
-					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
512
-				} else {
513
-					$paths = str_replace(':',' ',getenv('PATH'));
514
-				}
515
-				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
516
-				exec($command, $output, $returnCode);
517
-				if (count($output) > 0) {
518
-					$result = escapeshellcmd($output[0]);
519
-				}
520
-			}
521
-		}
522
-		// store the value for 5 minutes
523
-		$memcache->set($program, $result, 300);
524
-		return $result;
525
-	}
526
-
527
-	/**
528
-	 * Calculate the disc space for the given path
529
-	 *
530
-	 * @param string $path
531
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
532
-	 * @return array
533
-	 * @throws \OCP\Files\NotFoundException
534
-	 */
535
-	public static function getStorageInfo($path, $rootInfo = null) {
536
-		// return storage info without adding mount points
537
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
538
-
539
-		if (!$rootInfo) {
540
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
541
-		}
542
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
543
-			throw new \OCP\Files\NotFoundException();
544
-		}
545
-		$used = $rootInfo->getSize();
546
-		if ($used < 0) {
547
-			$used = 0;
548
-		}
549
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
550
-		$storage = $rootInfo->getStorage();
551
-		$sourceStorage = $storage;
552
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
553
-			$includeExtStorage = false;
554
-			$sourceStorage = $storage->getSourceStorage();
555
-		}
556
-		if ($includeExtStorage) {
557
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
558
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
559
-			) {
560
-				/** @var \OC\Files\Storage\Home $storage */
561
-				$user = $storage->getUser();
562
-			} else {
563
-				$user = \OC::$server->getUserSession()->getUser()->getUID();
564
-			}
565
-			if ($user) {
566
-				$quota = OC_Util::getUserQuota($user);
567
-			} else {
568
-				$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
569
-			}
570
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
571
-				// always get free space / total space from root + mount points
572
-				return self::getGlobalStorageInfo();
573
-			}
574
-		}
575
-
576
-		// TODO: need a better way to get total space from storage
577
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
578
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
579
-			$quota = $sourceStorage->getQuota();
580
-		}
581
-		$free = $sourceStorage->free_space($rootInfo->getInternalPath());
582
-		if ($free >= 0) {
583
-			$total = $free + $used;
584
-		} else {
585
-			$total = $free; //either unknown or unlimited
586
-		}
587
-		if ($total > 0) {
588
-			if ($quota > 0 && $total > $quota) {
589
-				$total = $quota;
590
-			}
591
-			// prevent division by zero or error codes (negative values)
592
-			$relative = round(($used / $total) * 10000) / 100;
593
-		} else {
594
-			$relative = 0;
595
-		}
596
-
597
-		$ownerId = $storage->getOwner($path);
598
-		$ownerDisplayName = '';
599
-		$owner = \OC::$server->getUserManager()->get($ownerId);
600
-		if($owner) {
601
-			$ownerDisplayName = $owner->getDisplayName();
602
-		}
603
-
604
-		return [
605
-			'free' => $free,
606
-			'used' => $used,
607
-			'quota' => $quota,
608
-			'total' => $total,
609
-			'relative' => $relative,
610
-			'owner' => $ownerId,
611
-			'ownerDisplayName' => $ownerDisplayName,
612
-		];
613
-	}
614
-
615
-	/**
616
-	 * Get storage info including all mount points and quota
617
-	 *
618
-	 * @return array
619
-	 */
620
-	private static function getGlobalStorageInfo() {
621
-		$quota = OC_Util::getUserQuota(\OCP\User::getUser());
622
-
623
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
624
-		$used = $rootInfo['size'];
625
-		if ($used < 0) {
626
-			$used = 0;
627
-		}
628
-
629
-		$total = $quota;
630
-		$free = $quota - $used;
631
-
632
-		if ($total > 0) {
633
-			if ($quota > 0 && $total > $quota) {
634
-				$total = $quota;
635
-			}
636
-			// prevent division by zero or error codes (negative values)
637
-			$relative = round(($used / $total) * 10000) / 100;
638
-		} else {
639
-			$relative = 0;
640
-		}
641
-
642
-		return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
643
-
644
-	}
645
-
646
-	/**
647
-	 * Returns whether the config file is set manually to read-only
648
-	 * @return bool
649
-	 */
650
-	public static function isReadOnlyConfigEnabled() {
651
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
652
-	}
51
+    private static $templateManager;
52
+
53
+    /**
54
+     * Creates an absolute url for public use
55
+     * @param string $service id
56
+     * @param bool $add_slash
57
+     * @return string the url
58
+     *
59
+     * Returns a absolute url to the given service.
60
+     */
61
+    public static function linkToPublic($service, $add_slash = false) {
62
+        if ($service === 'files') {
63
+            $url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
64
+        } else {
65
+            $url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66
+        }
67
+        return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68
+    }
69
+
70
+    /**
71
+     * Make a human file size
72
+     * @param int $bytes file size in bytes
73
+     * @return string a human readable file size
74
+     *
75
+     * Makes 2048 to 2 kB.
76
+     */
77
+    public static function humanFileSize($bytes) {
78
+        if ($bytes < 0) {
79
+            return "?";
80
+        }
81
+        if ($bytes < 1024) {
82
+            return "$bytes B";
83
+        }
84
+        $bytes = round($bytes / 1024, 0);
85
+        if ($bytes < 1024) {
86
+            return "$bytes KB";
87
+        }
88
+        $bytes = round($bytes / 1024, 1);
89
+        if ($bytes < 1024) {
90
+            return "$bytes MB";
91
+        }
92
+        $bytes = round($bytes / 1024, 1);
93
+        if ($bytes < 1024) {
94
+            return "$bytes GB";
95
+        }
96
+        $bytes = round($bytes / 1024, 1);
97
+        if ($bytes < 1024) {
98
+            return "$bytes TB";
99
+        }
100
+
101
+        $bytes = round($bytes / 1024, 1);
102
+        return "$bytes PB";
103
+    }
104
+
105
+    /**
106
+     * Make a php file size
107
+     * @param int $bytes file size in bytes
108
+     * @return string a php parseable file size
109
+     *
110
+     * Makes 2048 to 2k and 2^41 to 2048G
111
+     */
112
+    public static function phpFileSize($bytes) {
113
+        if ($bytes < 0) {
114
+            return "?";
115
+        }
116
+        if ($bytes < 1024) {
117
+            return $bytes . "B";
118
+        }
119
+        $bytes = round($bytes / 1024, 1);
120
+        if ($bytes < 1024) {
121
+            return $bytes . "K";
122
+        }
123
+        $bytes = round($bytes / 1024, 1);
124
+        if ($bytes < 1024) {
125
+            return $bytes . "M";
126
+        }
127
+        $bytes = round($bytes / 1024, 1);
128
+        return $bytes . "G";
129
+    }
130
+
131
+    /**
132
+     * Make a computer file size
133
+     * @param string $str file size in human readable format
134
+     * @return float a file size in bytes
135
+     *
136
+     * Makes 2kB to 2048.
137
+     *
138
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
139
+     */
140
+    public static function computerFileSize($str) {
141
+        $str = strtolower($str);
142
+        if (is_numeric($str)) {
143
+            return floatval($str);
144
+        }
145
+
146
+        $bytes_array = array(
147
+            'b' => 1,
148
+            'k' => 1024,
149
+            'kb' => 1024,
150
+            'mb' => 1024 * 1024,
151
+            'm' => 1024 * 1024,
152
+            'gb' => 1024 * 1024 * 1024,
153
+            'g' => 1024 * 1024 * 1024,
154
+            'tb' => 1024 * 1024 * 1024 * 1024,
155
+            't' => 1024 * 1024 * 1024 * 1024,
156
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
157
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
158
+        );
159
+
160
+        $bytes = floatval($str);
161
+
162
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
163
+            $bytes *= $bytes_array[$matches[1]];
164
+        } else {
165
+            return false;
166
+        }
167
+
168
+        $bytes = round($bytes);
169
+
170
+        return $bytes;
171
+    }
172
+
173
+    /**
174
+     * Recursive copying of folders
175
+     * @param string $src source folder
176
+     * @param string $dest target folder
177
+     *
178
+     */
179
+    static function copyr($src, $dest) {
180
+        if (is_dir($src)) {
181
+            if (!is_dir($dest)) {
182
+                mkdir($dest);
183
+            }
184
+            $files = scandir($src);
185
+            foreach ($files as $file) {
186
+                if ($file != "." && $file != "..") {
187
+                    self::copyr("$src/$file", "$dest/$file");
188
+                }
189
+            }
190
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
191
+            copy($src, $dest);
192
+        }
193
+    }
194
+
195
+    /**
196
+     * Recursive deletion of folders
197
+     * @param string $dir path to the folder
198
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
199
+     * @return bool
200
+     */
201
+    static function rmdirr($dir, $deleteSelf = true) {
202
+        if (is_dir($dir)) {
203
+            $files = new RecursiveIteratorIterator(
204
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
205
+                RecursiveIteratorIterator::CHILD_FIRST
206
+            );
207
+
208
+            foreach ($files as $fileInfo) {
209
+                /** @var SplFileInfo $fileInfo */
210
+                if ($fileInfo->isLink()) {
211
+                    unlink($fileInfo->getPathname());
212
+                } else if ($fileInfo->isDir()) {
213
+                    rmdir($fileInfo->getRealPath());
214
+                } else {
215
+                    unlink($fileInfo->getRealPath());
216
+                }
217
+            }
218
+            if ($deleteSelf) {
219
+                rmdir($dir);
220
+            }
221
+        } elseif (file_exists($dir)) {
222
+            if ($deleteSelf) {
223
+                unlink($dir);
224
+            }
225
+        }
226
+        if (!$deleteSelf) {
227
+            return true;
228
+        }
229
+
230
+        return !file_exists($dir);
231
+    }
232
+
233
+    /**
234
+     * @return \OC\Files\Type\TemplateManager
235
+     */
236
+    static public function getFileTemplateManager() {
237
+        if (!self::$templateManager) {
238
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
239
+        }
240
+        return self::$templateManager;
241
+    }
242
+
243
+    /**
244
+     * detect if a given program is found in the search PATH
245
+     *
246
+     * @param string $name
247
+     * @param bool $path
248
+     * @internal param string $program name
249
+     * @internal param string $optional search path, defaults to $PATH
250
+     * @return bool    true if executable program found in path
251
+     */
252
+    public static function canExecute($name, $path = false) {
253
+        // path defaults to PATH from environment if not set
254
+        if ($path === false) {
255
+            $path = getenv("PATH");
256
+        }
257
+        // we look for an executable file of that name
258
+        $exts = [""];
259
+        $check_fn = "is_executable";
260
+        // Default check will be done with $path directories :
261
+        $dirs = explode(PATH_SEPARATOR, $path);
262
+        // WARNING : We have to check if open_basedir is enabled :
263
+        $obd = OC::$server->getIniWrapper()->getString('open_basedir');
264
+        if ($obd != "none") {
265
+            $obd_values = explode(PATH_SEPARATOR, $obd);
266
+            if (count($obd_values) > 0 and $obd_values[0]) {
267
+                // open_basedir is in effect !
268
+                // We need to check if the program is in one of these dirs :
269
+                $dirs = $obd_values;
270
+            }
271
+        }
272
+        foreach ($dirs as $dir) {
273
+            foreach ($exts as $ext) {
274
+                if ($check_fn("$dir/$name" . $ext))
275
+                    return true;
276
+            }
277
+        }
278
+        return false;
279
+    }
280
+
281
+    /**
282
+     * copy the contents of one stream to another
283
+     *
284
+     * @param resource $source
285
+     * @param resource $target
286
+     * @return array the number of bytes copied and result
287
+     */
288
+    public static function streamCopy($source, $target) {
289
+        if (!$source or !$target) {
290
+            return array(0, false);
291
+        }
292
+        $bufSize = 8192;
293
+        $result = true;
294
+        $count = 0;
295
+        while (!feof($source)) {
296
+            $buf = fread($source, $bufSize);
297
+            $bytesWritten = fwrite($target, $buf);
298
+            if ($bytesWritten !== false) {
299
+                $count += $bytesWritten;
300
+            }
301
+            // note: strlen is expensive so only use it when necessary,
302
+            // on the last block
303
+            if ($bytesWritten === false
304
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
305
+            ) {
306
+                // write error, could be disk full ?
307
+                $result = false;
308
+                break;
309
+            }
310
+        }
311
+        return array($count, $result);
312
+    }
313
+
314
+    /**
315
+     * Adds a suffix to the name in case the file exists
316
+     *
317
+     * @param string $path
318
+     * @param string $filename
319
+     * @return string
320
+     */
321
+    public static function buildNotExistingFileName($path, $filename) {
322
+        $view = \OC\Files\Filesystem::getView();
323
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
324
+    }
325
+
326
+    /**
327
+     * Adds a suffix to the name in case the file exists
328
+     *
329
+     * @param string $path
330
+     * @param string $filename
331
+     * @return string
332
+     */
333
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
334
+        if ($path === '/') {
335
+            $path = '';
336
+        }
337
+        if ($pos = strrpos($filename, '.')) {
338
+            $name = substr($filename, 0, $pos);
339
+            $ext = substr($filename, $pos);
340
+        } else {
341
+            $name = $filename;
342
+            $ext = '';
343
+        }
344
+
345
+        $newpath = $path . '/' . $filename;
346
+        if ($view->file_exists($newpath)) {
347
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
348
+                //Replace the last "(number)" with "(number+1)"
349
+                $last_match = count($matches[0]) - 1;
350
+                $counter = $matches[1][$last_match][0] + 1;
351
+                $offset = $matches[0][$last_match][1];
352
+                $match_length = strlen($matches[0][$last_match][0]);
353
+            } else {
354
+                $counter = 2;
355
+                $match_length = 0;
356
+                $offset = false;
357
+            }
358
+            do {
359
+                if ($offset) {
360
+                    //Replace the last "(number)" with "(number+1)"
361
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
362
+                } else {
363
+                    $newname = $name . ' (' . $counter . ')';
364
+                }
365
+                $newpath = $path . '/' . $newname . $ext;
366
+                $counter++;
367
+            } while ($view->file_exists($newpath));
368
+        }
369
+
370
+        return $newpath;
371
+    }
372
+
373
+    /**
374
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
375
+     *
376
+     * @param array $input The array to work on
377
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
378
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
379
+     * @return array
380
+     *
381
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
382
+     * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
383
+     *
384
+     */
385
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
386
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
387
+        $ret = array();
388
+        foreach ($input as $k => $v) {
389
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
390
+        }
391
+        return $ret;
392
+    }
393
+
394
+    /**
395
+     * performs a search in a nested array
396
+     * @param array $haystack the array to be searched
397
+     * @param string $needle the search string
398
+     * @param string $index optional, only search this key name
399
+     * @return mixed the key of the matching field, otherwise false
400
+     *
401
+     * performs a search in a nested array
402
+     *
403
+     * taken from http://www.php.net/manual/en/function.array-search.php#97645
404
+     */
405
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
406
+        $aIt = new RecursiveArrayIterator($haystack);
407
+        $it = new RecursiveIteratorIterator($aIt);
408
+
409
+        while ($it->valid()) {
410
+            if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
411
+                return $aIt->key();
412
+            }
413
+
414
+            $it->next();
415
+        }
416
+
417
+        return false;
418
+    }
419
+
420
+    /**
421
+     * calculates the maximum upload size respecting system settings, free space and user quota
422
+     *
423
+     * @param string $dir the current folder where the user currently operates
424
+     * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
425
+     * @return int number of bytes representing
426
+     */
427
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
428
+        if (is_null($freeSpace) || $freeSpace < 0){
429
+            $freeSpace = self::freeSpace($dir);
430
+        }
431
+        return min($freeSpace, self::uploadLimit());
432
+    }
433
+
434
+    /**
435
+     * Calculate free space left within user quota
436
+     *
437
+     * @param string $dir the current folder where the user currently operates
438
+     * @return int number of bytes representing
439
+     */
440
+    public static function freeSpace($dir) {
441
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
442
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
443
+            $freeSpace = max($freeSpace, 0);
444
+            return $freeSpace;
445
+        } else {
446
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
447
+        }
448
+    }
449
+
450
+    /**
451
+     * Calculate PHP upload limit
452
+     *
453
+     * @return int PHP upload file size limit
454
+     */
455
+    public static function uploadLimit() {
456
+        $ini = \OC::$server->getIniWrapper();
457
+        $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
458
+        $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
459
+        if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
460
+            return INF;
461
+        } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
462
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
463
+        } else {
464
+            return min($upload_max_filesize, $post_max_size);
465
+        }
466
+    }
467
+
468
+    /**
469
+     * Checks if a function is available
470
+     *
471
+     * @param string $function_name
472
+     * @return bool
473
+     */
474
+    public static function is_function_enabled($function_name) {
475
+        if (!function_exists($function_name)) {
476
+            return false;
477
+        }
478
+        $ini = \OC::$server->getIniWrapper();
479
+        $disabled = explode(',', $ini->get('disable_functions'));
480
+        $disabled = array_map('trim', $disabled);
481
+        if (in_array($function_name, $disabled)) {
482
+            return false;
483
+        }
484
+        $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
485
+        $disabled = array_map('trim', $disabled);
486
+        if (in_array($function_name, $disabled)) {
487
+            return false;
488
+        }
489
+        return true;
490
+    }
491
+
492
+    /**
493
+     * Try to find a program
494
+     *
495
+     * @param string $program
496
+     * @return null|string
497
+     */
498
+    public static function findBinaryPath($program) {
499
+        $memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
500
+        if ($memcache->hasKey($program)) {
501
+            return $memcache->get($program);
502
+        }
503
+        $result = null;
504
+        if (self::is_function_enabled('exec')) {
505
+            $exeSniffer = new ExecutableFinder();
506
+            // Returns null if nothing is found
507
+            $result = $exeSniffer->find($program);
508
+            if (empty($result)) {
509
+                $paths = getenv('PATH');
510
+                if (empty($paths)) {
511
+                    $paths = '/usr/local/bin /usr/bin /opt/bin /bin';
512
+                } else {
513
+                    $paths = str_replace(':',' ',getenv('PATH'));
514
+                }
515
+                $command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
516
+                exec($command, $output, $returnCode);
517
+                if (count($output) > 0) {
518
+                    $result = escapeshellcmd($output[0]);
519
+                }
520
+            }
521
+        }
522
+        // store the value for 5 minutes
523
+        $memcache->set($program, $result, 300);
524
+        return $result;
525
+    }
526
+
527
+    /**
528
+     * Calculate the disc space for the given path
529
+     *
530
+     * @param string $path
531
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
532
+     * @return array
533
+     * @throws \OCP\Files\NotFoundException
534
+     */
535
+    public static function getStorageInfo($path, $rootInfo = null) {
536
+        // return storage info without adding mount points
537
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
538
+
539
+        if (!$rootInfo) {
540
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
541
+        }
542
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
543
+            throw new \OCP\Files\NotFoundException();
544
+        }
545
+        $used = $rootInfo->getSize();
546
+        if ($used < 0) {
547
+            $used = 0;
548
+        }
549
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
550
+        $storage = $rootInfo->getStorage();
551
+        $sourceStorage = $storage;
552
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
553
+            $includeExtStorage = false;
554
+            $sourceStorage = $storage->getSourceStorage();
555
+        }
556
+        if ($includeExtStorage) {
557
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
558
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
559
+            ) {
560
+                /** @var \OC\Files\Storage\Home $storage */
561
+                $user = $storage->getUser();
562
+            } else {
563
+                $user = \OC::$server->getUserSession()->getUser()->getUID();
564
+            }
565
+            if ($user) {
566
+                $quota = OC_Util::getUserQuota($user);
567
+            } else {
568
+                $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
569
+            }
570
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
571
+                // always get free space / total space from root + mount points
572
+                return self::getGlobalStorageInfo();
573
+            }
574
+        }
575
+
576
+        // TODO: need a better way to get total space from storage
577
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
578
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
579
+            $quota = $sourceStorage->getQuota();
580
+        }
581
+        $free = $sourceStorage->free_space($rootInfo->getInternalPath());
582
+        if ($free >= 0) {
583
+            $total = $free + $used;
584
+        } else {
585
+            $total = $free; //either unknown or unlimited
586
+        }
587
+        if ($total > 0) {
588
+            if ($quota > 0 && $total > $quota) {
589
+                $total = $quota;
590
+            }
591
+            // prevent division by zero or error codes (negative values)
592
+            $relative = round(($used / $total) * 10000) / 100;
593
+        } else {
594
+            $relative = 0;
595
+        }
596
+
597
+        $ownerId = $storage->getOwner($path);
598
+        $ownerDisplayName = '';
599
+        $owner = \OC::$server->getUserManager()->get($ownerId);
600
+        if($owner) {
601
+            $ownerDisplayName = $owner->getDisplayName();
602
+        }
603
+
604
+        return [
605
+            'free' => $free,
606
+            'used' => $used,
607
+            'quota' => $quota,
608
+            'total' => $total,
609
+            'relative' => $relative,
610
+            'owner' => $ownerId,
611
+            'ownerDisplayName' => $ownerDisplayName,
612
+        ];
613
+    }
614
+
615
+    /**
616
+     * Get storage info including all mount points and quota
617
+     *
618
+     * @return array
619
+     */
620
+    private static function getGlobalStorageInfo() {
621
+        $quota = OC_Util::getUserQuota(\OCP\User::getUser());
622
+
623
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
624
+        $used = $rootInfo['size'];
625
+        if ($used < 0) {
626
+            $used = 0;
627
+        }
628
+
629
+        $total = $quota;
630
+        $free = $quota - $used;
631
+
632
+        if ($total > 0) {
633
+            if ($quota > 0 && $total > $quota) {
634
+                $total = $quota;
635
+            }
636
+            // prevent division by zero or error codes (negative values)
637
+            $relative = round(($used / $total) * 10000) / 100;
638
+        } else {
639
+            $relative = 0;
640
+        }
641
+
642
+        return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
643
+
644
+    }
645
+
646
+    /**
647
+     * Returns whether the config file is set manually to read-only
648
+     * @return bool
649
+     */
650
+    public static function isReadOnlyConfigEnabled() {
651
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
652
+    }
653 653
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		} else {
65 65
 			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66 66
 		}
67
-		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
67
+		return $url.(($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68 68
 	}
69 69
 
70 70
 	/**
@@ -114,18 +114,18 @@  discard block
 block discarded – undo
114 114
 			return "?";
115 115
 		}
116 116
 		if ($bytes < 1024) {
117
-			return $bytes . "B";
117
+			return $bytes."B";
118 118
 		}
119 119
 		$bytes = round($bytes / 1024, 1);
120 120
 		if ($bytes < 1024) {
121
-			return $bytes . "K";
121
+			return $bytes."K";
122 122
 		}
123 123
 		$bytes = round($bytes / 1024, 1);
124 124
 		if ($bytes < 1024) {
125
-			return $bytes . "M";
125
+			return $bytes."M";
126 126
 		}
127 127
 		$bytes = round($bytes / 1024, 1);
128
-		return $bytes . "G";
128
+		return $bytes."G";
129 129
 	}
130 130
 
131 131
 	/**
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 		}
272 272
 		foreach ($dirs as $dir) {
273 273
 			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
274
+				if ($check_fn("$dir/$name".$ext))
275 275
 					return true;
276 276
 			}
277 277
 		}
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 			$ext = '';
343 343
 		}
344 344
 
345
-		$newpath = $path . '/' . $filename;
345
+		$newpath = $path.'/'.$filename;
346 346
 		if ($view->file_exists($newpath)) {
347 347
 			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
348 348
 				//Replace the last "(number)" with "(number+1)"
@@ -358,11 +358,11 @@  discard block
 block discarded – undo
358 358
 			do {
359 359
 				if ($offset) {
360 360
 					//Replace the last "(number)" with "(number+1)"
361
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
361
+					$newname = substr_replace($name, '('.$counter.')', $offset, $match_length);
362 362
 				} else {
363
-					$newname = $name . ' (' . $counter . ')';
363
+					$newname = $name.' ('.$counter.')';
364 364
 				}
365
-				$newpath = $path . '/' . $newname . $ext;
365
+				$newpath = $path.'/'.$newname.$ext;
366 366
 				$counter++;
367 367
 			} while ($view->file_exists($newpath));
368 368
 		}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 	 * @return int number of bytes representing
426 426
 	 */
427 427
 	public static function maxUploadFilesize($dir, $freeSpace = null) {
428
-		if (is_null($freeSpace) || $freeSpace < 0){
428
+		if (is_null($freeSpace) || $freeSpace < 0) {
429 429
 			$freeSpace = self::freeSpace($dir);
430 430
 		}
431 431
 		return min($freeSpace, self::uploadLimit());
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 			$freeSpace = max($freeSpace, 0);
444 444
 			return $freeSpace;
445 445
 		} else {
446
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
446
+			return (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
447 447
 		}
448 448
 	}
449 449
 
@@ -456,9 +456,9 @@  discard block
 block discarded – undo
456 456
 		$ini = \OC::$server->getIniWrapper();
457 457
 		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
458 458
 		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
459
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
459
+		if ((int) $upload_max_filesize === 0 and (int) $post_max_size === 0) {
460 460
 			return INF;
461
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
461
+		} elseif ((int) $upload_max_filesize === 0 or (int) $post_max_size === 0) {
462 462
 			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
463 463
 		} else {
464 464
 			return min($upload_max_filesize, $post_max_size);
@@ -510,9 +510,9 @@  discard block
 block discarded – undo
510 510
 				if (empty($paths)) {
511 511
 					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
512 512
 				} else {
513
-					$paths = str_replace(':',' ',getenv('PATH'));
513
+					$paths = str_replace(':', ' ', getenv('PATH'));
514 514
 				}
515
-				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
515
+				$command = 'find '.$paths.' -name '.escapeshellarg($program).' 2> /dev/null';
516 516
 				exec($command, $output, $returnCode);
517 517
 				if (count($output) > 0) {
518 518
 					$result = escapeshellcmd($output[0]);
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
 		$ownerId = $storage->getOwner($path);
598 598
 		$ownerDisplayName = '';
599 599
 		$owner = \OC::$server->getUserManager()->get($ownerId);
600
-		if($owner) {
600
+		if ($owner) {
601 601
 			$ownerDisplayName = $owner->getDisplayName();
602 602
 		}
603 603
 
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -271,8 +271,9 @@
 block discarded – undo
271 271
 		}
272 272
 		foreach ($dirs as $dir) {
273 273
 			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
275
-					return true;
274
+				if ($check_fn("$dir/$name" . $ext)) {
275
+									return true;
276
+				}
276 277
 			}
277 278
 		}
278 279
 		return false;
Please login to merge, or discard this patch.
lib/private/Mail/Message.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -162,7 +162,7 @@
 block discarded – undo
162 162
 	/**
163 163
 	 * Set the BCC recipients of this message.
164 164
 	 *
165
-	 * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
165
+	 * @param string[] $recipients Example: array('[email protected]', '[email protected]' => 'A name')
166 166
 	 * @return $this
167 167
 	 */
168 168
 	public function setBcc(array $recipients) {
Please login to merge, or discard this patch.
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -31,223 +31,223 @@
 block discarded – undo
31 31
  * @package OC\Mail
32 32
  */
33 33
 class Message {
34
-	/** @var Swift_Message */
35
-	private $swiftMessage;
36
-
37
-	/**
38
-	 * @param Swift_Message $swiftMessage
39
-	 */
40
-	function __construct(Swift_Message $swiftMessage) {
41
-		$this->swiftMessage = $swiftMessage;
42
-	}
43
-
44
-	/**
45
-	 * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains
46
-	 * FIXME: Remove this once SwiftMailer supports IDN
47
-	 *
48
-	 * @param array $addresses Array of mail addresses, key will get converted
49
-	 * @return array Converted addresses if `idn_to_ascii` exists
50
-	 */
51
-	protected function convertAddresses($addresses) {
52
-		if (!function_exists('idn_to_ascii')) {
53
-			return $addresses;
54
-		}
55
-
56
-		$convertedAddresses = array();
57
-
58
-		foreach($addresses as $email => $readableName) {
59
-			if(!is_numeric($email)) {
60
-				list($name, $domain) = explode('@', $email, 2);
61
-				$domain = idn_to_ascii($domain);
62
-				$convertedAddresses[$name.'@'.$domain] = $readableName;
63
-			} else {
64
-				list($name, $domain) = explode('@', $readableName, 2);
65
-				$domain = idn_to_ascii($domain);
66
-				$convertedAddresses[$email] = $name.'@'.$domain;
67
-			}
68
-		}
69
-
70
-		return $convertedAddresses;
71
-	}
72
-
73
-	/**
74
-	 * Set the from address of this message.
75
-	 *
76
-	 * If no "From" address is used \OC\Mail\Mailer will use mail_from_address and mail_domain from config.php
77
-	 *
78
-	 * @param array $addresses Example: array('[email protected]', '[email protected]' => 'A name')
79
-	 * @return $this
80
-	 */
81
-	public function setFrom(array $addresses) {
82
-		$addresses = $this->convertAddresses($addresses);
83
-
84
-		$this->swiftMessage->setFrom($addresses);
85
-		return $this;
86
-	}
87
-
88
-	/**
89
-	 * Get the from address of this message.
90
-	 *
91
-	 * @return array
92
-	 */
93
-	public function getFrom() {
94
-		return $this->swiftMessage->getFrom();
95
-	}
96
-
97
-	/**
98
-	 * Set the Reply-To address of this message
99
-	 *
100
-	 * @param array $addresses
101
-	 * @return $this
102
-	 */
103
-	public function setReplyTo(array $addresses) {
104
-		$addresses = $this->convertAddresses($addresses);
105
-
106
-		$this->swiftMessage->setReplyTo($addresses);
107
-		return $this;
108
-	}
109
-
110
-	/**
111
-	 * Returns the Reply-To address of this message
112
-	 *
113
-	 * @return array
114
-	 */
115
-	public function getReplyTo() {
116
-		return $this->swiftMessage->getReplyTo();
117
-	}
118
-
119
-	/**
120
-	 * Set the to addresses of this message.
121
-	 *
122
-	 * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
123
-	 * @return $this
124
-	 */
125
-	public function setTo(array $recipients) {
126
-		$recipients = $this->convertAddresses($recipients);
127
-
128
-		$this->swiftMessage->setTo($recipients);
129
-		return $this;
130
-	}
131
-
132
-	/**
133
-	 * Get the to address of this message.
134
-	 *
135
-	 * @return array
136
-	 */
137
-	public function getTo() {
138
-		return $this->swiftMessage->getTo();
139
-	}
140
-
141
-	/**
142
-	 * Set the CC recipients of this message.
143
-	 *
144
-	 * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
145
-	 * @return $this
146
-	 */
147
-	public function setCc(array $recipients) {
148
-		$recipients = $this->convertAddresses($recipients);
149
-
150
-		$this->swiftMessage->setCc($recipients);
151
-		return $this;
152
-	}
153
-
154
-	/**
155
-	 * Get the cc address of this message.
156
-	 *
157
-	 * @return array
158
-	 */
159
-	public function getCc() {
160
-		return $this->swiftMessage->getCc();
161
-	}
162
-
163
-	/**
164
-	 * Set the BCC recipients of this message.
165
-	 *
166
-	 * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
167
-	 * @return $this
168
-	 */
169
-	public function setBcc(array $recipients) {
170
-		$recipients = $this->convertAddresses($recipients);
171
-
172
-		$this->swiftMessage->setBcc($recipients);
173
-		return $this;
174
-	}
175
-
176
-	/**
177
-	 * Get the Bcc address of this message.
178
-	 *
179
-	 * @return array
180
-	 */
181
-	public function getBcc() {
182
-		return $this->swiftMessage->getBcc();
183
-	}
184
-
185
-	/**
186
-	 * Set the subject of this message.
187
-	 *
188
-	 * @param $subject
189
-	 * @return $this
190
-	 */
191
-	public function setSubject($subject) {
192
-		$this->swiftMessage->setSubject($subject);
193
-		return $this;
194
-	}
195
-
196
-	/**
197
-	 * Get the from subject of this message.
198
-	 *
199
-	 * @return string
200
-	 */
201
-	public function getSubject() {
202
-		return $this->swiftMessage->getSubject();
203
-	}
204
-
205
-	/**
206
-	 * Set the plain-text body of this message.
207
-	 *
208
-	 * @param string $body
209
-	 * @return $this
210
-	 */
211
-	public function setPlainBody($body) {
212
-		$this->swiftMessage->setBody($body);
213
-		return $this;
214
-	}
215
-
216
-	/**
217
-	 * Get the plain body of this message.
218
-	 *
219
-	 * @return string
220
-	 */
221
-	public function getPlainBody() {
222
-		return $this->swiftMessage->getBody();
223
-	}
224
-
225
-	/**
226
-	 * Set the HTML body of this message. Consider also sending a plain-text body instead of only an HTML one.
227
-	 *
228
-	 * @param string $body
229
-	 * @return $this
230
-	 */
231
-	public function setHtmlBody($body) {
232
-		$this->swiftMessage->addPart($body, 'text/html');
233
-		return $this;
234
-	}
235
-
236
-	/**
237
-	 * Get's the underlying SwiftMessage
238
-	 * @return Swift_Message
239
-	 */
240
-	public function getSwiftMessage() {
241
-		return $this->swiftMessage;
242
-	}
243
-
244
-	/**
245
-	 * @param string $body
246
-	 * @param string $contentType
247
-	 * @return $this
248
-	 */
249
-	public function setBody($body, $contentType) {
250
-		$this->swiftMessage->setBody($body, $contentType);
251
-		return $this;
252
-	}
34
+    /** @var Swift_Message */
35
+    private $swiftMessage;
36
+
37
+    /**
38
+     * @param Swift_Message $swiftMessage
39
+     */
40
+    function __construct(Swift_Message $swiftMessage) {
41
+        $this->swiftMessage = $swiftMessage;
42
+    }
43
+
44
+    /**
45
+     * SwiftMailer does currently not work with IDN domains, this function therefore converts the domains
46
+     * FIXME: Remove this once SwiftMailer supports IDN
47
+     *
48
+     * @param array $addresses Array of mail addresses, key will get converted
49
+     * @return array Converted addresses if `idn_to_ascii` exists
50
+     */
51
+    protected function convertAddresses($addresses) {
52
+        if (!function_exists('idn_to_ascii')) {
53
+            return $addresses;
54
+        }
55
+
56
+        $convertedAddresses = array();
57
+
58
+        foreach($addresses as $email => $readableName) {
59
+            if(!is_numeric($email)) {
60
+                list($name, $domain) = explode('@', $email, 2);
61
+                $domain = idn_to_ascii($domain);
62
+                $convertedAddresses[$name.'@'.$domain] = $readableName;
63
+            } else {
64
+                list($name, $domain) = explode('@', $readableName, 2);
65
+                $domain = idn_to_ascii($domain);
66
+                $convertedAddresses[$email] = $name.'@'.$domain;
67
+            }
68
+        }
69
+
70
+        return $convertedAddresses;
71
+    }
72
+
73
+    /**
74
+     * Set the from address of this message.
75
+     *
76
+     * If no "From" address is used \OC\Mail\Mailer will use mail_from_address and mail_domain from config.php
77
+     *
78
+     * @param array $addresses Example: array('[email protected]', '[email protected]' => 'A name')
79
+     * @return $this
80
+     */
81
+    public function setFrom(array $addresses) {
82
+        $addresses = $this->convertAddresses($addresses);
83
+
84
+        $this->swiftMessage->setFrom($addresses);
85
+        return $this;
86
+    }
87
+
88
+    /**
89
+     * Get the from address of this message.
90
+     *
91
+     * @return array
92
+     */
93
+    public function getFrom() {
94
+        return $this->swiftMessage->getFrom();
95
+    }
96
+
97
+    /**
98
+     * Set the Reply-To address of this message
99
+     *
100
+     * @param array $addresses
101
+     * @return $this
102
+     */
103
+    public function setReplyTo(array $addresses) {
104
+        $addresses = $this->convertAddresses($addresses);
105
+
106
+        $this->swiftMessage->setReplyTo($addresses);
107
+        return $this;
108
+    }
109
+
110
+    /**
111
+     * Returns the Reply-To address of this message
112
+     *
113
+     * @return array
114
+     */
115
+    public function getReplyTo() {
116
+        return $this->swiftMessage->getReplyTo();
117
+    }
118
+
119
+    /**
120
+     * Set the to addresses of this message.
121
+     *
122
+     * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
123
+     * @return $this
124
+     */
125
+    public function setTo(array $recipients) {
126
+        $recipients = $this->convertAddresses($recipients);
127
+
128
+        $this->swiftMessage->setTo($recipients);
129
+        return $this;
130
+    }
131
+
132
+    /**
133
+     * Get the to address of this message.
134
+     *
135
+     * @return array
136
+     */
137
+    public function getTo() {
138
+        return $this->swiftMessage->getTo();
139
+    }
140
+
141
+    /**
142
+     * Set the CC recipients of this message.
143
+     *
144
+     * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
145
+     * @return $this
146
+     */
147
+    public function setCc(array $recipients) {
148
+        $recipients = $this->convertAddresses($recipients);
149
+
150
+        $this->swiftMessage->setCc($recipients);
151
+        return $this;
152
+    }
153
+
154
+    /**
155
+     * Get the cc address of this message.
156
+     *
157
+     * @return array
158
+     */
159
+    public function getCc() {
160
+        return $this->swiftMessage->getCc();
161
+    }
162
+
163
+    /**
164
+     * Set the BCC recipients of this message.
165
+     *
166
+     * @param array $recipients Example: array('[email protected]', '[email protected]' => 'A name')
167
+     * @return $this
168
+     */
169
+    public function setBcc(array $recipients) {
170
+        $recipients = $this->convertAddresses($recipients);
171
+
172
+        $this->swiftMessage->setBcc($recipients);
173
+        return $this;
174
+    }
175
+
176
+    /**
177
+     * Get the Bcc address of this message.
178
+     *
179
+     * @return array
180
+     */
181
+    public function getBcc() {
182
+        return $this->swiftMessage->getBcc();
183
+    }
184
+
185
+    /**
186
+     * Set the subject of this message.
187
+     *
188
+     * @param $subject
189
+     * @return $this
190
+     */
191
+    public function setSubject($subject) {
192
+        $this->swiftMessage->setSubject($subject);
193
+        return $this;
194
+    }
195
+
196
+    /**
197
+     * Get the from subject of this message.
198
+     *
199
+     * @return string
200
+     */
201
+    public function getSubject() {
202
+        return $this->swiftMessage->getSubject();
203
+    }
204
+
205
+    /**
206
+     * Set the plain-text body of this message.
207
+     *
208
+     * @param string $body
209
+     * @return $this
210
+     */
211
+    public function setPlainBody($body) {
212
+        $this->swiftMessage->setBody($body);
213
+        return $this;
214
+    }
215
+
216
+    /**
217
+     * Get the plain body of this message.
218
+     *
219
+     * @return string
220
+     */
221
+    public function getPlainBody() {
222
+        return $this->swiftMessage->getBody();
223
+    }
224
+
225
+    /**
226
+     * Set the HTML body of this message. Consider also sending a plain-text body instead of only an HTML one.
227
+     *
228
+     * @param string $body
229
+     * @return $this
230
+     */
231
+    public function setHtmlBody($body) {
232
+        $this->swiftMessage->addPart($body, 'text/html');
233
+        return $this;
234
+    }
235
+
236
+    /**
237
+     * Get's the underlying SwiftMessage
238
+     * @return Swift_Message
239
+     */
240
+    public function getSwiftMessage() {
241
+        return $this->swiftMessage;
242
+    }
243
+
244
+    /**
245
+     * @param string $body
246
+     * @param string $contentType
247
+     * @return $this
248
+     */
249
+    public function setBody($body, $contentType) {
250
+        $this->swiftMessage->setBody($body, $contentType);
251
+        return $this;
252
+    }
253 253
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -55,8 +55,8 @@
 block discarded – undo
55 55
 
56 56
 		$convertedAddresses = array();
57 57
 
58
-		foreach($addresses as $email => $readableName) {
59
-			if(!is_numeric($email)) {
58
+		foreach ($addresses as $email => $readableName) {
59
+			if (!is_numeric($email)) {
60 60
 				list($name, $domain) = explode('@', $email, 2);
61 61
 				$domain = idn_to_ascii($domain);
62 62
 				$convertedAddresses[$name.'@'.$domain] = $readableName;
Please login to merge, or discard this patch.
lib/private/Memcache/Memcached.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@
 block discarded – undo
155 155
 	 * Set a value in the cache if it's not already stored
156 156
 	 *
157 157
 	 * @param string $key
158
-	 * @param mixed $value
158
+	 * @param integer $value
159 159
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
160 160
 	 * @return bool
161 161
 	 * @throws \Exception
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -33,193 +33,193 @@
 block discarded – undo
33 33
 use OCP\IMemcache;
34 34
 
35 35
 class Memcached extends Cache implements IMemcache {
36
-	use CASTrait;
37
-
38
-	/**
39
-	 * @var \Memcached $cache
40
-	 */
41
-	private static $cache = null;
42
-
43
-	use CADTrait;
44
-
45
-	public function __construct($prefix = '') {
46
-		parent::__construct($prefix);
47
-		if (is_null(self::$cache)) {
48
-			self::$cache = new \Memcached();
49
-
50
-			$defaultOptions = [
51
-				\Memcached::OPT_CONNECT_TIMEOUT => 50,
52
-				\Memcached::OPT_RETRY_TIMEOUT =>   50,
53
-				\Memcached::OPT_SEND_TIMEOUT =>    50,
54
-				\Memcached::OPT_RECV_TIMEOUT =>    50,
55
-				\Memcached::OPT_POLL_TIMEOUT =>    50,
56
-
57
-				// Enable compression
58
-				\Memcached::OPT_COMPRESSION =>          true,
59
-
60
-				// Turn on consistent hashing
61
-				\Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
62
-
63
-				// Enable Binary Protocol
64
-				//\Memcached::OPT_BINARY_PROTOCOL =>      true,
65
-			];
66
-			// by default enable igbinary serializer if available
67
-			if (\Memcached::HAVE_IGBINARY) {
68
-				$defaultOptions[\Memcached::OPT_SERIALIZER] =
69
-					\Memcached::SERIALIZER_IGBINARY;
70
-			}
71
-			$options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
72
-			if (is_array($options)) {
73
-				$options = $options + $defaultOptions;
74
-				self::$cache->setOptions($options);
75
-			} else {
76
-				throw new HintException("Expected 'memcached_options' config to be an array, got $options");
77
-			}
78
-
79
-			$servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
80
-			if (!$servers) {
81
-				$server = \OC::$server->getSystemConfig()->getValue('memcached_server');
82
-				if ($server) {
83
-					$servers = [$server];
84
-				} else {
85
-					$servers = [['localhost', 11211]];
86
-				}
87
-			}
88
-			self::$cache->addServers($servers);
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
94
-	 */
95
-	protected function getNameSpace() {
96
-		return $this->prefix;
97
-	}
98
-
99
-	public function get($key) {
100
-		$result = self::$cache->get($this->getNamespace() . $key);
101
-		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
102
-			return null;
103
-		} else {
104
-			return $result;
105
-		}
106
-	}
107
-
108
-	public function set($key, $value, $ttl = 0) {
109
-		if ($ttl > 0) {
110
-			$result =  self::$cache->set($this->getNamespace() . $key, $value, $ttl);
111
-		} else {
112
-			$result = self::$cache->set($this->getNamespace() . $key, $value);
113
-		}
114
-		if ($result !== true) {
115
-			$this->verifyReturnCode();
116
-		}
117
-		return $result;
118
-	}
119
-
120
-	public function hasKey($key) {
121
-		self::$cache->get($this->getNamespace() . $key);
122
-		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
123
-	}
124
-
125
-	public function remove($key) {
126
-		$result= self::$cache->delete($this->getNamespace() . $key);
127
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
128
-			$this->verifyReturnCode();
129
-		}
130
-		return $result;
131
-	}
132
-
133
-	public function clear($prefix = '') {
134
-		$prefix = $this->getNamespace() . $prefix;
135
-		$allKeys = self::$cache->getAllKeys();
136
-		if ($allKeys === false) {
137
-			// newer Memcached doesn't like getAllKeys(), flush everything
138
-			self::$cache->flush();
139
-			return true;
140
-		}
141
-		$keys = array();
142
-		$prefixLength = strlen($prefix);
143
-		foreach ($allKeys as $key) {
144
-			if (substr($key, 0, $prefixLength) === $prefix) {
145
-				$keys[] = $key;
146
-			}
147
-		}
148
-		if (method_exists(self::$cache, 'deleteMulti')) {
149
-			self::$cache->deleteMulti($keys);
150
-		} else {
151
-			foreach ($keys as $key) {
152
-				self::$cache->delete($key);
153
-			}
154
-		}
155
-		return true;
156
-	}
157
-
158
-	/**
159
-	 * Set a value in the cache if it's not already stored
160
-	 *
161
-	 * @param string $key
162
-	 * @param mixed $value
163
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
164
-	 * @return bool
165
-	 * @throws \Exception
166
-	 */
167
-	public function add($key, $value, $ttl = 0) {
168
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
169
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
170
-			$this->verifyReturnCode();
171
-		}
172
-		return $result;
173
-	}
174
-
175
-	/**
176
-	 * Increase a stored number
177
-	 *
178
-	 * @param string $key
179
-	 * @param int $step
180
-	 * @return int | bool
181
-	 */
182
-	public function inc($key, $step = 1) {
183
-		$this->add($key, 0);
184
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
185
-
186
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
187
-			return false;
188
-		}
189
-
190
-		return $result;
191
-	}
192
-
193
-	/**
194
-	 * Decrease a stored number
195
-	 *
196
-	 * @param string $key
197
-	 * @param int $step
198
-	 * @return int | bool
199
-	 */
200
-	public function dec($key, $step = 1) {
201
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
202
-
203
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
204
-			return false;
205
-		}
206
-
207
-		return $result;
208
-	}
209
-
210
-	static public function isAvailable() {
211
-		return extension_loaded('memcached');
212
-	}
213
-
214
-	/**
215
-	 * @throws \Exception
216
-	 */
217
-	private function verifyReturnCode() {
218
-		$code = self::$cache->getResultCode();
219
-		if ($code === \Memcached::RES_SUCCESS) {
220
-			return;
221
-		}
222
-		$message = self::$cache->getResultMessage();
223
-		throw new \Exception("Error $code interacting with memcached : $message");
224
-	}
36
+    use CASTrait;
37
+
38
+    /**
39
+     * @var \Memcached $cache
40
+     */
41
+    private static $cache = null;
42
+
43
+    use CADTrait;
44
+
45
+    public function __construct($prefix = '') {
46
+        parent::__construct($prefix);
47
+        if (is_null(self::$cache)) {
48
+            self::$cache = new \Memcached();
49
+
50
+            $defaultOptions = [
51
+                \Memcached::OPT_CONNECT_TIMEOUT => 50,
52
+                \Memcached::OPT_RETRY_TIMEOUT =>   50,
53
+                \Memcached::OPT_SEND_TIMEOUT =>    50,
54
+                \Memcached::OPT_RECV_TIMEOUT =>    50,
55
+                \Memcached::OPT_POLL_TIMEOUT =>    50,
56
+
57
+                // Enable compression
58
+                \Memcached::OPT_COMPRESSION =>          true,
59
+
60
+                // Turn on consistent hashing
61
+                \Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
62
+
63
+                // Enable Binary Protocol
64
+                //\Memcached::OPT_BINARY_PROTOCOL =>      true,
65
+            ];
66
+            // by default enable igbinary serializer if available
67
+            if (\Memcached::HAVE_IGBINARY) {
68
+                $defaultOptions[\Memcached::OPT_SERIALIZER] =
69
+                    \Memcached::SERIALIZER_IGBINARY;
70
+            }
71
+            $options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
72
+            if (is_array($options)) {
73
+                $options = $options + $defaultOptions;
74
+                self::$cache->setOptions($options);
75
+            } else {
76
+                throw new HintException("Expected 'memcached_options' config to be an array, got $options");
77
+            }
78
+
79
+            $servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
80
+            if (!$servers) {
81
+                $server = \OC::$server->getSystemConfig()->getValue('memcached_server');
82
+                if ($server) {
83
+                    $servers = [$server];
84
+                } else {
85
+                    $servers = [['localhost', 11211]];
86
+                }
87
+            }
88
+            self::$cache->addServers($servers);
89
+        }
90
+    }
91
+
92
+    /**
93
+     * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
94
+     */
95
+    protected function getNameSpace() {
96
+        return $this->prefix;
97
+    }
98
+
99
+    public function get($key) {
100
+        $result = self::$cache->get($this->getNamespace() . $key);
101
+        if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
102
+            return null;
103
+        } else {
104
+            return $result;
105
+        }
106
+    }
107
+
108
+    public function set($key, $value, $ttl = 0) {
109
+        if ($ttl > 0) {
110
+            $result =  self::$cache->set($this->getNamespace() . $key, $value, $ttl);
111
+        } else {
112
+            $result = self::$cache->set($this->getNamespace() . $key, $value);
113
+        }
114
+        if ($result !== true) {
115
+            $this->verifyReturnCode();
116
+        }
117
+        return $result;
118
+    }
119
+
120
+    public function hasKey($key) {
121
+        self::$cache->get($this->getNamespace() . $key);
122
+        return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
123
+    }
124
+
125
+    public function remove($key) {
126
+        $result= self::$cache->delete($this->getNamespace() . $key);
127
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
128
+            $this->verifyReturnCode();
129
+        }
130
+        return $result;
131
+    }
132
+
133
+    public function clear($prefix = '') {
134
+        $prefix = $this->getNamespace() . $prefix;
135
+        $allKeys = self::$cache->getAllKeys();
136
+        if ($allKeys === false) {
137
+            // newer Memcached doesn't like getAllKeys(), flush everything
138
+            self::$cache->flush();
139
+            return true;
140
+        }
141
+        $keys = array();
142
+        $prefixLength = strlen($prefix);
143
+        foreach ($allKeys as $key) {
144
+            if (substr($key, 0, $prefixLength) === $prefix) {
145
+                $keys[] = $key;
146
+            }
147
+        }
148
+        if (method_exists(self::$cache, 'deleteMulti')) {
149
+            self::$cache->deleteMulti($keys);
150
+        } else {
151
+            foreach ($keys as $key) {
152
+                self::$cache->delete($key);
153
+            }
154
+        }
155
+        return true;
156
+    }
157
+
158
+    /**
159
+     * Set a value in the cache if it's not already stored
160
+     *
161
+     * @param string $key
162
+     * @param mixed $value
163
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
164
+     * @return bool
165
+     * @throws \Exception
166
+     */
167
+    public function add($key, $value, $ttl = 0) {
168
+        $result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
169
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
170
+            $this->verifyReturnCode();
171
+        }
172
+        return $result;
173
+    }
174
+
175
+    /**
176
+     * Increase a stored number
177
+     *
178
+     * @param string $key
179
+     * @param int $step
180
+     * @return int | bool
181
+     */
182
+    public function inc($key, $step = 1) {
183
+        $this->add($key, 0);
184
+        $result = self::$cache->increment($this->getPrefix() . $key, $step);
185
+
186
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
187
+            return false;
188
+        }
189
+
190
+        return $result;
191
+    }
192
+
193
+    /**
194
+     * Decrease a stored number
195
+     *
196
+     * @param string $key
197
+     * @param int $step
198
+     * @return int | bool
199
+     */
200
+    public function dec($key, $step = 1) {
201
+        $result = self::$cache->decrement($this->getPrefix() . $key, $step);
202
+
203
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
204
+            return false;
205
+        }
206
+
207
+        return $result;
208
+    }
209
+
210
+    static public function isAvailable() {
211
+        return extension_loaded('memcached');
212
+    }
213
+
214
+    /**
215
+     * @throws \Exception
216
+     */
217
+    private function verifyReturnCode() {
218
+        $code = self::$cache->getResultCode();
219
+        if ($code === \Memcached::RES_SUCCESS) {
220
+            return;
221
+        }
222
+        $message = self::$cache->getResultMessage();
223
+        throw new \Exception("Error $code interacting with memcached : $message");
224
+    }
225 225
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 	}
98 98
 
99 99
 	public function get($key) {
100
-		$result = self::$cache->get($this->getNamespace() . $key);
100
+		$result = self::$cache->get($this->getNamespace().$key);
101 101
 		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
102 102
 			return null;
103 103
 		} else {
@@ -107,9 +107,9 @@  discard block
 block discarded – undo
107 107
 
108 108
 	public function set($key, $value, $ttl = 0) {
109 109
 		if ($ttl > 0) {
110
-			$result =  self::$cache->set($this->getNamespace() . $key, $value, $ttl);
110
+			$result = self::$cache->set($this->getNamespace().$key, $value, $ttl);
111 111
 		} else {
112
-			$result = self::$cache->set($this->getNamespace() . $key, $value);
112
+			$result = self::$cache->set($this->getNamespace().$key, $value);
113 113
 		}
114 114
 		if ($result !== true) {
115 115
 			$this->verifyReturnCode();
@@ -118,12 +118,12 @@  discard block
 block discarded – undo
118 118
 	}
119 119
 
120 120
 	public function hasKey($key) {
121
-		self::$cache->get($this->getNamespace() . $key);
121
+		self::$cache->get($this->getNamespace().$key);
122 122
 		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
123 123
 	}
124 124
 
125 125
 	public function remove($key) {
126
-		$result= self::$cache->delete($this->getNamespace() . $key);
126
+		$result = self::$cache->delete($this->getNamespace().$key);
127 127
 		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
128 128
 			$this->verifyReturnCode();
129 129
 		}
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	}
132 132
 
133 133
 	public function clear($prefix = '') {
134
-		$prefix = $this->getNamespace() . $prefix;
134
+		$prefix = $this->getNamespace().$prefix;
135 135
 		$allKeys = self::$cache->getAllKeys();
136 136
 		if ($allKeys === false) {
137 137
 			// newer Memcached doesn't like getAllKeys(), flush everything
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 	 * @throws \Exception
166 166
 	 */
167 167
 	public function add($key, $value, $ttl = 0) {
168
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
168
+		$result = self::$cache->add($this->getPrefix().$key, $value, $ttl);
169 169
 		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
170 170
 			$this->verifyReturnCode();
171 171
 		}
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 	 */
182 182
 	public function inc($key, $step = 1) {
183 183
 		$this->add($key, 0);
184
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
184
+		$result = self::$cache->increment($this->getPrefix().$key, $step);
185 185
 
186 186
 		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
187 187
 			return false;
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 	 * @return int | bool
199 199
 	 */
200 200
 	public function dec($key, $step = 1) {
201
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
201
+		$result = self::$cache->decrement($this->getPrefix().$key, $step);
202 202
 
203 203
 		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
204 204
 			return false;
Please login to merge, or discard this patch.