@@ -16,175 +16,175 @@ |
||
16 | 16 | use Psr\Log\LoggerInterface; |
17 | 17 | |
18 | 18 | class File implements ICache { |
19 | - /** @var View */ |
|
20 | - protected $storage; |
|
19 | + /** @var View */ |
|
20 | + protected $storage; |
|
21 | 21 | |
22 | - /** |
|
23 | - * Returns the cache storage for the logged in user |
|
24 | - * |
|
25 | - * @return \OC\Files\View cache storage |
|
26 | - * @throws \OC\ForbiddenException |
|
27 | - * @throws \OC\User\NoUserException |
|
28 | - */ |
|
29 | - protected function getStorage() { |
|
30 | - if ($this->storage !== null) { |
|
31 | - return $this->storage; |
|
32 | - } |
|
33 | - $session = Server::get(IUserSession::class); |
|
34 | - if ($session->isLoggedIn()) { |
|
35 | - $rootView = new View(); |
|
36 | - $userId = $session->getUser()->getUID(); |
|
37 | - Filesystem::initMountPoints($userId); |
|
38 | - if (!$rootView->file_exists('/' . $userId . '/cache')) { |
|
39 | - $rootView->mkdir('/' . $userId . '/cache'); |
|
40 | - } |
|
41 | - $this->storage = new View('/' . $userId . '/cache'); |
|
42 | - return $this->storage; |
|
43 | - } else { |
|
44 | - Server::get(LoggerInterface::class)->error('Can\'t get cache storage, user not logged in', ['app' => 'core']); |
|
45 | - throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in'); |
|
46 | - } |
|
47 | - } |
|
22 | + /** |
|
23 | + * Returns the cache storage for the logged in user |
|
24 | + * |
|
25 | + * @return \OC\Files\View cache storage |
|
26 | + * @throws \OC\ForbiddenException |
|
27 | + * @throws \OC\User\NoUserException |
|
28 | + */ |
|
29 | + protected function getStorage() { |
|
30 | + if ($this->storage !== null) { |
|
31 | + return $this->storage; |
|
32 | + } |
|
33 | + $session = Server::get(IUserSession::class); |
|
34 | + if ($session->isLoggedIn()) { |
|
35 | + $rootView = new View(); |
|
36 | + $userId = $session->getUser()->getUID(); |
|
37 | + Filesystem::initMountPoints($userId); |
|
38 | + if (!$rootView->file_exists('/' . $userId . '/cache')) { |
|
39 | + $rootView->mkdir('/' . $userId . '/cache'); |
|
40 | + } |
|
41 | + $this->storage = new View('/' . $userId . '/cache'); |
|
42 | + return $this->storage; |
|
43 | + } else { |
|
44 | + Server::get(LoggerInterface::class)->error('Can\'t get cache storage, user not logged in', ['app' => 'core']); |
|
45 | + throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in'); |
|
46 | + } |
|
47 | + } |
|
48 | 48 | |
49 | - /** |
|
50 | - * @param string $key |
|
51 | - * @return mixed|null |
|
52 | - * @throws \OC\ForbiddenException |
|
53 | - */ |
|
54 | - public function get($key) { |
|
55 | - $result = null; |
|
56 | - if ($this->hasKey($key)) { |
|
57 | - $storage = $this->getStorage(); |
|
58 | - $result = $storage->file_get_contents($key); |
|
59 | - } |
|
60 | - return $result; |
|
61 | - } |
|
49 | + /** |
|
50 | + * @param string $key |
|
51 | + * @return mixed|null |
|
52 | + * @throws \OC\ForbiddenException |
|
53 | + */ |
|
54 | + public function get($key) { |
|
55 | + $result = null; |
|
56 | + if ($this->hasKey($key)) { |
|
57 | + $storage = $this->getStorage(); |
|
58 | + $result = $storage->file_get_contents($key); |
|
59 | + } |
|
60 | + return $result; |
|
61 | + } |
|
62 | 62 | |
63 | - /** |
|
64 | - * Returns the size of the stored/cached data |
|
65 | - * |
|
66 | - * @param string $key |
|
67 | - * @return int |
|
68 | - */ |
|
69 | - public function size($key) { |
|
70 | - $result = 0; |
|
71 | - if ($this->hasKey($key)) { |
|
72 | - $storage = $this->getStorage(); |
|
73 | - $result = $storage->filesize($key); |
|
74 | - } |
|
75 | - return $result; |
|
76 | - } |
|
63 | + /** |
|
64 | + * Returns the size of the stored/cached data |
|
65 | + * |
|
66 | + * @param string $key |
|
67 | + * @return int |
|
68 | + */ |
|
69 | + public function size($key) { |
|
70 | + $result = 0; |
|
71 | + if ($this->hasKey($key)) { |
|
72 | + $storage = $this->getStorage(); |
|
73 | + $result = $storage->filesize($key); |
|
74 | + } |
|
75 | + return $result; |
|
76 | + } |
|
77 | 77 | |
78 | - /** |
|
79 | - * @param string $key |
|
80 | - * @param mixed $value |
|
81 | - * @param int $ttl |
|
82 | - * @return bool|mixed |
|
83 | - * @throws \OC\ForbiddenException |
|
84 | - */ |
|
85 | - public function set($key, $value, $ttl = 0) { |
|
86 | - $storage = $this->getStorage(); |
|
87 | - $result = false; |
|
88 | - // unique id to avoid chunk collision, just in case |
|
89 | - $uniqueId = Server::get(ISecureRandom::class)->generate( |
|
90 | - 16, |
|
91 | - ISecureRandom::CHAR_ALPHANUMERIC |
|
92 | - ); |
|
78 | + /** |
|
79 | + * @param string $key |
|
80 | + * @param mixed $value |
|
81 | + * @param int $ttl |
|
82 | + * @return bool|mixed |
|
83 | + * @throws \OC\ForbiddenException |
|
84 | + */ |
|
85 | + public function set($key, $value, $ttl = 0) { |
|
86 | + $storage = $this->getStorage(); |
|
87 | + $result = false; |
|
88 | + // unique id to avoid chunk collision, just in case |
|
89 | + $uniqueId = Server::get(ISecureRandom::class)->generate( |
|
90 | + 16, |
|
91 | + ISecureRandom::CHAR_ALPHANUMERIC |
|
92 | + ); |
|
93 | 93 | |
94 | - // use part file to prevent hasKey() to find the key |
|
95 | - // while it is being written |
|
96 | - $keyPart = $key . '.' . $uniqueId . '.part'; |
|
97 | - if ($storage && $storage->file_put_contents($keyPart, $value)) { |
|
98 | - if ($ttl === 0) { |
|
99 | - $ttl = 86400; // 60*60*24 |
|
100 | - } |
|
101 | - $result = $storage->touch($keyPart, time() + $ttl); |
|
102 | - $result &= $storage->rename($keyPart, $key); |
|
103 | - } |
|
104 | - return $result; |
|
105 | - } |
|
94 | + // use part file to prevent hasKey() to find the key |
|
95 | + // while it is being written |
|
96 | + $keyPart = $key . '.' . $uniqueId . '.part'; |
|
97 | + if ($storage && $storage->file_put_contents($keyPart, $value)) { |
|
98 | + if ($ttl === 0) { |
|
99 | + $ttl = 86400; // 60*60*24 |
|
100 | + } |
|
101 | + $result = $storage->touch($keyPart, time() + $ttl); |
|
102 | + $result &= $storage->rename($keyPart, $key); |
|
103 | + } |
|
104 | + return $result; |
|
105 | + } |
|
106 | 106 | |
107 | - /** |
|
108 | - * @param string $key |
|
109 | - * @return bool |
|
110 | - * @throws \OC\ForbiddenException |
|
111 | - */ |
|
112 | - public function hasKey($key) { |
|
113 | - $storage = $this->getStorage(); |
|
114 | - if ($storage && $storage->is_file($key) && $storage->isReadable($key)) { |
|
115 | - return true; |
|
116 | - } |
|
117 | - return false; |
|
118 | - } |
|
107 | + /** |
|
108 | + * @param string $key |
|
109 | + * @return bool |
|
110 | + * @throws \OC\ForbiddenException |
|
111 | + */ |
|
112 | + public function hasKey($key) { |
|
113 | + $storage = $this->getStorage(); |
|
114 | + if ($storage && $storage->is_file($key) && $storage->isReadable($key)) { |
|
115 | + return true; |
|
116 | + } |
|
117 | + return false; |
|
118 | + } |
|
119 | 119 | |
120 | - /** |
|
121 | - * @param string $key |
|
122 | - * @return bool|mixed |
|
123 | - * @throws \OC\ForbiddenException |
|
124 | - */ |
|
125 | - public function remove($key) { |
|
126 | - $storage = $this->getStorage(); |
|
127 | - if (!$storage) { |
|
128 | - return false; |
|
129 | - } |
|
130 | - return $storage->unlink($key); |
|
131 | - } |
|
120 | + /** |
|
121 | + * @param string $key |
|
122 | + * @return bool|mixed |
|
123 | + * @throws \OC\ForbiddenException |
|
124 | + */ |
|
125 | + public function remove($key) { |
|
126 | + $storage = $this->getStorage(); |
|
127 | + if (!$storage) { |
|
128 | + return false; |
|
129 | + } |
|
130 | + return $storage->unlink($key); |
|
131 | + } |
|
132 | 132 | |
133 | - /** |
|
134 | - * @param string $prefix |
|
135 | - * @return bool |
|
136 | - * @throws \OC\ForbiddenException |
|
137 | - */ |
|
138 | - public function clear($prefix = '') { |
|
139 | - $storage = $this->getStorage(); |
|
140 | - if ($storage && $storage->is_dir('/')) { |
|
141 | - $dh = $storage->opendir('/'); |
|
142 | - if (is_resource($dh)) { |
|
143 | - while (($file = readdir($dh)) !== false) { |
|
144 | - if ($file !== '.' && $file !== '..' && ($prefix === '' || str_starts_with($file, $prefix))) { |
|
145 | - $storage->unlink('/' . $file); |
|
146 | - } |
|
147 | - } |
|
148 | - } |
|
149 | - } |
|
150 | - return true; |
|
151 | - } |
|
133 | + /** |
|
134 | + * @param string $prefix |
|
135 | + * @return bool |
|
136 | + * @throws \OC\ForbiddenException |
|
137 | + */ |
|
138 | + public function clear($prefix = '') { |
|
139 | + $storage = $this->getStorage(); |
|
140 | + if ($storage && $storage->is_dir('/')) { |
|
141 | + $dh = $storage->opendir('/'); |
|
142 | + if (is_resource($dh)) { |
|
143 | + while (($file = readdir($dh)) !== false) { |
|
144 | + if ($file !== '.' && $file !== '..' && ($prefix === '' || str_starts_with($file, $prefix))) { |
|
145 | + $storage->unlink('/' . $file); |
|
146 | + } |
|
147 | + } |
|
148 | + } |
|
149 | + } |
|
150 | + return true; |
|
151 | + } |
|
152 | 152 | |
153 | - /** |
|
154 | - * Runs GC |
|
155 | - * @throws \OC\ForbiddenException |
|
156 | - */ |
|
157 | - public function gc() { |
|
158 | - $storage = $this->getStorage(); |
|
159 | - if ($storage) { |
|
160 | - // extra hour safety, in case of stray part chunks that take longer to write, |
|
161 | - // because touch() is only called after the chunk was finished |
|
162 | - $now = time() - 3600; |
|
163 | - $dh = $storage->opendir('/'); |
|
164 | - if (!is_resource($dh)) { |
|
165 | - return null; |
|
166 | - } |
|
167 | - while (($file = readdir($dh)) !== false) { |
|
168 | - if ($file !== '.' && $file !== '..') { |
|
169 | - try { |
|
170 | - $mtime = $storage->filemtime('/' . $file); |
|
171 | - if ($mtime < $now) { |
|
172 | - $storage->unlink('/' . $file); |
|
173 | - } |
|
174 | - } catch (\OCP\Lock\LockedException $e) { |
|
175 | - // ignore locked chunks |
|
176 | - Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); |
|
177 | - } catch (\OCP\Files\ForbiddenException $e) { |
|
178 | - Server::get(LoggerInterface::class)->debug('Could not cleanup forbidden chunk "' . $file . '"', ['app' => 'core']); |
|
179 | - } catch (\OCP\Files\LockNotAcquiredException $e) { |
|
180 | - Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); |
|
181 | - } |
|
182 | - } |
|
183 | - } |
|
184 | - } |
|
185 | - } |
|
153 | + /** |
|
154 | + * Runs GC |
|
155 | + * @throws \OC\ForbiddenException |
|
156 | + */ |
|
157 | + public function gc() { |
|
158 | + $storage = $this->getStorage(); |
|
159 | + if ($storage) { |
|
160 | + // extra hour safety, in case of stray part chunks that take longer to write, |
|
161 | + // because touch() is only called after the chunk was finished |
|
162 | + $now = time() - 3600; |
|
163 | + $dh = $storage->opendir('/'); |
|
164 | + if (!is_resource($dh)) { |
|
165 | + return null; |
|
166 | + } |
|
167 | + while (($file = readdir($dh)) !== false) { |
|
168 | + if ($file !== '.' && $file !== '..') { |
|
169 | + try { |
|
170 | + $mtime = $storage->filemtime('/' . $file); |
|
171 | + if ($mtime < $now) { |
|
172 | + $storage->unlink('/' . $file); |
|
173 | + } |
|
174 | + } catch (\OCP\Lock\LockedException $e) { |
|
175 | + // ignore locked chunks |
|
176 | + Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); |
|
177 | + } catch (\OCP\Files\ForbiddenException $e) { |
|
178 | + Server::get(LoggerInterface::class)->debug('Could not cleanup forbidden chunk "' . $file . '"', ['app' => 'core']); |
|
179 | + } catch (\OCP\Files\LockNotAcquiredException $e) { |
|
180 | + Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); |
|
181 | + } |
|
182 | + } |
|
183 | + } |
|
184 | + } |
|
185 | + } |
|
186 | 186 | |
187 | - public static function isAvailable(): bool { |
|
188 | - return true; |
|
189 | - } |
|
187 | + public static function isAvailable(): bool { |
|
188 | + return true; |
|
189 | + } |
|
190 | 190 | } |
@@ -35,10 +35,10 @@ discard block |
||
35 | 35 | $rootView = new View(); |
36 | 36 | $userId = $session->getUser()->getUID(); |
37 | 37 | Filesystem::initMountPoints($userId); |
38 | - if (!$rootView->file_exists('/' . $userId . '/cache')) { |
|
39 | - $rootView->mkdir('/' . $userId . '/cache'); |
|
38 | + if (!$rootView->file_exists('/'.$userId.'/cache')) { |
|
39 | + $rootView->mkdir('/'.$userId.'/cache'); |
|
40 | 40 | } |
41 | - $this->storage = new View('/' . $userId . '/cache'); |
|
41 | + $this->storage = new View('/'.$userId.'/cache'); |
|
42 | 42 | return $this->storage; |
43 | 43 | } else { |
44 | 44 | Server::get(LoggerInterface::class)->error('Can\'t get cache storage, user not logged in', ['app' => 'core']); |
@@ -93,7 +93,7 @@ discard block |
||
93 | 93 | |
94 | 94 | // use part file to prevent hasKey() to find the key |
95 | 95 | // while it is being written |
96 | - $keyPart = $key . '.' . $uniqueId . '.part'; |
|
96 | + $keyPart = $key.'.'.$uniqueId.'.part'; |
|
97 | 97 | if ($storage && $storage->file_put_contents($keyPart, $value)) { |
98 | 98 | if ($ttl === 0) { |
99 | 99 | $ttl = 86400; // 60*60*24 |
@@ -142,7 +142,7 @@ discard block |
||
142 | 142 | if (is_resource($dh)) { |
143 | 143 | while (($file = readdir($dh)) !== false) { |
144 | 144 | if ($file !== '.' && $file !== '..' && ($prefix === '' || str_starts_with($file, $prefix))) { |
145 | - $storage->unlink('/' . $file); |
|
145 | + $storage->unlink('/'.$file); |
|
146 | 146 | } |
147 | 147 | } |
148 | 148 | } |
@@ -167,17 +167,17 @@ discard block |
||
167 | 167 | while (($file = readdir($dh)) !== false) { |
168 | 168 | if ($file !== '.' && $file !== '..') { |
169 | 169 | try { |
170 | - $mtime = $storage->filemtime('/' . $file); |
|
170 | + $mtime = $storage->filemtime('/'.$file); |
|
171 | 171 | if ($mtime < $now) { |
172 | - $storage->unlink('/' . $file); |
|
172 | + $storage->unlink('/'.$file); |
|
173 | 173 | } |
174 | 174 | } catch (\OCP\Lock\LockedException $e) { |
175 | 175 | // ignore locked chunks |
176 | - Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); |
|
176 | + Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "'.$file.'"', ['app' => 'core']); |
|
177 | 177 | } catch (\OCP\Files\ForbiddenException $e) { |
178 | - Server::get(LoggerInterface::class)->debug('Could not cleanup forbidden chunk "' . $file . '"', ['app' => 'core']); |
|
178 | + Server::get(LoggerInterface::class)->debug('Could not cleanup forbidden chunk "'.$file.'"', ['app' => 'core']); |
|
179 | 179 | } catch (\OCP\Files\LockNotAcquiredException $e) { |
180 | - Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "' . $file . '"', ['app' => 'core']); |
|
180 | + Server::get(LoggerInterface::class)->debug('Could not cleanup locked chunk "'.$file.'"', ['app' => 'core']); |
|
181 | 181 | } |
182 | 182 | } |
183 | 183 | } |
@@ -17,93 +17,93 @@ |
||
17 | 17 | * @deprecated 25.0.0 use OCP\Cache\CappedMemoryCache instead |
18 | 18 | */ |
19 | 19 | class CappedMemoryCache implements ICache, \ArrayAccess { |
20 | - private $capacity; |
|
21 | - /** @var T[] */ |
|
22 | - private $cache = []; |
|
23 | - |
|
24 | - public function __construct($capacity = 512) { |
|
25 | - $this->capacity = $capacity; |
|
26 | - } |
|
27 | - |
|
28 | - public function hasKey($key): bool { |
|
29 | - return isset($this->cache[$key]); |
|
30 | - } |
|
31 | - |
|
32 | - /** |
|
33 | - * @return ?T |
|
34 | - */ |
|
35 | - public function get($key) { |
|
36 | - return $this->cache[$key] ?? null; |
|
37 | - } |
|
38 | - |
|
39 | - /** |
|
40 | - * @param string $key |
|
41 | - * @param T $value |
|
42 | - * @param int $ttl |
|
43 | - * @return bool |
|
44 | - */ |
|
45 | - public function set($key, $value, $ttl = 0): bool { |
|
46 | - if (is_null($key)) { |
|
47 | - $this->cache[] = $value; |
|
48 | - } else { |
|
49 | - $this->cache[$key] = $value; |
|
50 | - } |
|
51 | - $this->garbageCollect(); |
|
52 | - return true; |
|
53 | - } |
|
54 | - |
|
55 | - public function remove($key) { |
|
56 | - unset($this->cache[$key]); |
|
57 | - return true; |
|
58 | - } |
|
59 | - |
|
60 | - public function clear($prefix = '') { |
|
61 | - $this->cache = []; |
|
62 | - return true; |
|
63 | - } |
|
64 | - |
|
65 | - public function offsetExists($offset): bool { |
|
66 | - return $this->hasKey($offset); |
|
67 | - } |
|
68 | - |
|
69 | - /** |
|
70 | - * @return T |
|
71 | - */ |
|
72 | - #[\ReturnTypeWillChange] |
|
73 | - public function &offsetGet($offset) { |
|
74 | - return $this->cache[$offset]; |
|
75 | - } |
|
76 | - |
|
77 | - /** |
|
78 | - * @param string $offset |
|
79 | - * @param T $value |
|
80 | - * @return void |
|
81 | - */ |
|
82 | - public function offsetSet($offset, $value): void { |
|
83 | - $this->set($offset, $value); |
|
84 | - } |
|
85 | - |
|
86 | - public function offsetUnset($offset): void { |
|
87 | - $this->remove($offset); |
|
88 | - } |
|
89 | - |
|
90 | - /** |
|
91 | - * @return T[] |
|
92 | - */ |
|
93 | - public function getData() { |
|
94 | - return $this->cache; |
|
95 | - } |
|
96 | - |
|
97 | - |
|
98 | - private function garbageCollect() { |
|
99 | - while (count($this->cache) > $this->capacity) { |
|
100 | - reset($this->cache); |
|
101 | - $key = key($this->cache); |
|
102 | - $this->remove($key); |
|
103 | - } |
|
104 | - } |
|
105 | - |
|
106 | - public static function isAvailable(): bool { |
|
107 | - return true; |
|
108 | - } |
|
20 | + private $capacity; |
|
21 | + /** @var T[] */ |
|
22 | + private $cache = []; |
|
23 | + |
|
24 | + public function __construct($capacity = 512) { |
|
25 | + $this->capacity = $capacity; |
|
26 | + } |
|
27 | + |
|
28 | + public function hasKey($key): bool { |
|
29 | + return isset($this->cache[$key]); |
|
30 | + } |
|
31 | + |
|
32 | + /** |
|
33 | + * @return ?T |
|
34 | + */ |
|
35 | + public function get($key) { |
|
36 | + return $this->cache[$key] ?? null; |
|
37 | + } |
|
38 | + |
|
39 | + /** |
|
40 | + * @param string $key |
|
41 | + * @param T $value |
|
42 | + * @param int $ttl |
|
43 | + * @return bool |
|
44 | + */ |
|
45 | + public function set($key, $value, $ttl = 0): bool { |
|
46 | + if (is_null($key)) { |
|
47 | + $this->cache[] = $value; |
|
48 | + } else { |
|
49 | + $this->cache[$key] = $value; |
|
50 | + } |
|
51 | + $this->garbageCollect(); |
|
52 | + return true; |
|
53 | + } |
|
54 | + |
|
55 | + public function remove($key) { |
|
56 | + unset($this->cache[$key]); |
|
57 | + return true; |
|
58 | + } |
|
59 | + |
|
60 | + public function clear($prefix = '') { |
|
61 | + $this->cache = []; |
|
62 | + return true; |
|
63 | + } |
|
64 | + |
|
65 | + public function offsetExists($offset): bool { |
|
66 | + return $this->hasKey($offset); |
|
67 | + } |
|
68 | + |
|
69 | + /** |
|
70 | + * @return T |
|
71 | + */ |
|
72 | + #[\ReturnTypeWillChange] |
|
73 | + public function &offsetGet($offset) { |
|
74 | + return $this->cache[$offset]; |
|
75 | + } |
|
76 | + |
|
77 | + /** |
|
78 | + * @param string $offset |
|
79 | + * @param T $value |
|
80 | + * @return void |
|
81 | + */ |
|
82 | + public function offsetSet($offset, $value): void { |
|
83 | + $this->set($offset, $value); |
|
84 | + } |
|
85 | + |
|
86 | + public function offsetUnset($offset): void { |
|
87 | + $this->remove($offset); |
|
88 | + } |
|
89 | + |
|
90 | + /** |
|
91 | + * @return T[] |
|
92 | + */ |
|
93 | + public function getData() { |
|
94 | + return $this->cache; |
|
95 | + } |
|
96 | + |
|
97 | + |
|
98 | + private function garbageCollect() { |
|
99 | + while (count($this->cache) > $this->capacity) { |
|
100 | + reset($this->cache); |
|
101 | + $key = key($this->cache); |
|
102 | + $this->remove($key); |
|
103 | + } |
|
104 | + } |
|
105 | + |
|
106 | + public static function isAvailable(): bool { |
|
107 | + return true; |
|
108 | + } |
|
109 | 109 | } |
@@ -6,7 +6,7 @@ discard block |
||
6 | 6 | use Behat\Gherkin\Node\TableNode; |
7 | 7 | use PHPUnit\Framework\Assert; |
8 | 8 | |
9 | -require __DIR__ . '/../../vendor/autoload.php'; |
|
9 | +require __DIR__.'/../../vendor/autoload.php'; |
|
10 | 10 | |
11 | 11 | trait Avatar { |
12 | 12 | /** @var string * */ |
@@ -46,7 +46,7 @@ discard block |
||
46 | 46 | */ |
47 | 47 | public function userGetsAvatarForUserWithSize(string $user, string $userAvatar, string $size) { |
48 | 48 | $this->asAn($user); |
49 | - $this->sendingToDirectUrl('GET', '/index.php/avatar/' . $userAvatar . '/' . $size); |
|
49 | + $this->sendingToDirectUrl('GET', '/index.php/avatar/'.$userAvatar.'/'.$size); |
|
50 | 50 | $this->theHTTPStatusCodeShouldBe('200'); |
51 | 51 | |
52 | 52 | $this->getLastAvatar(); |
@@ -60,7 +60,7 @@ discard block |
||
60 | 60 | */ |
61 | 61 | public function userGetsAvatarForGuest(string $user, string $guestAvatar) { |
62 | 62 | $this->asAn($user); |
63 | - $this->sendingToDirectUrl('GET', '/index.php/avatar/guest/' . $guestAvatar . '/128'); |
|
63 | + $this->sendingToDirectUrl('GET', '/index.php/avatar/guest/'.$guestAvatar.'/128'); |
|
64 | 64 | $this->theHTTPStatusCodeShouldBe('201'); |
65 | 65 | |
66 | 66 | $this->getLastAvatar(); |
@@ -111,7 +111,7 @@ discard block |
||
111 | 111 | * @param string $path |
112 | 112 | */ |
113 | 113 | public function loggedInUserPostsTemporaryAvatarFromInternalPath(string $path) { |
114 | - $this->sendingAToWithRequesttoken('POST', '/index.php/avatar?path=' . $path); |
|
114 | + $this->sendingAToWithRequesttoken('POST', '/index.php/avatar?path='.$path); |
|
115 | 115 | $this->theHTTPStatusCodeShouldBe('200'); |
116 | 116 | } |
117 | 117 | |
@@ -133,10 +133,10 @@ discard block |
||
133 | 133 | public function loggedInUserCropsTemporaryAvatarWith(string $statusCode, TableNode $crop) { |
134 | 134 | $parameters = []; |
135 | 135 | foreach ($crop->getRowsHash() as $key => $value) { |
136 | - $parameters[] = 'crop[' . $key . ']=' . $value; |
|
136 | + $parameters[] = 'crop['.$key.']='.$value; |
|
137 | 137 | } |
138 | 138 | |
139 | - $this->sendingAToWithRequesttoken('POST', '/index.php/avatar/cropped?' . implode('&', $parameters)); |
|
139 | + $this->sendingAToWithRequesttoken('POST', '/index.php/avatar/cropped?'.implode('&', $parameters)); |
|
140 | 140 | $this->theHTTPStatusCodeShouldBe($statusCode); |
141 | 141 | } |
142 | 142 | |
@@ -187,7 +187,7 @@ discard block |
||
187 | 187 | $colorFromLastAvatar = $this->getColorFromLastAvatar(); |
188 | 188 | |
189 | 189 | Assert::assertTrue($this->isSameColor($expectedColor, $colorFromLastAvatar), |
190 | - $this->rgbColorToHexString($colorFromLastAvatar) . ' does not match expected ' . $color); |
|
190 | + $this->rgbColorToHexString($colorFromLastAvatar).' does not match expected '.$color); |
|
191 | 191 | } |
192 | 192 | |
193 | 193 | private function hexStringToRgbColor($hexString) { |
@@ -209,7 +209,7 @@ discard block |
||
209 | 209 | private function rgbColorToHexString($rgbColor) { |
210 | 210 | $rgbColorInt = ($rgbColor['red'] << 16) + ($rgbColor['green'] << 8) + ($rgbColor['blue']); |
211 | 211 | |
212 | - return '#' . str_pad(strtoupper(dechex($rgbColorInt)), 6, '0', STR_PAD_LEFT); |
|
212 | + return '#'.str_pad(strtoupper(dechex($rgbColorInt)), 6, '0', STR_PAD_LEFT); |
|
213 | 213 | } |
214 | 214 | |
215 | 215 | private function getColorFromLastAvatar() { |
@@ -10,253 +10,253 @@ |
||
10 | 10 | require __DIR__ . '/../../vendor/autoload.php'; |
11 | 11 | |
12 | 12 | trait Avatar { |
13 | - /** @var string * */ |
|
14 | - private $lastAvatar; |
|
15 | - |
|
16 | - /** @AfterScenario **/ |
|
17 | - public function cleanupLastAvatar() { |
|
18 | - $this->lastAvatar = null; |
|
19 | - } |
|
20 | - |
|
21 | - private function getLastAvatar() { |
|
22 | - $this->lastAvatar = ''; |
|
23 | - |
|
24 | - $body = $this->response->getBody(); |
|
25 | - while (!$body->eof()) { |
|
26 | - $this->lastAvatar .= $body->read(8192); |
|
27 | - } |
|
28 | - $body->close(); |
|
29 | - } |
|
30 | - |
|
31 | - /** |
|
32 | - * @When user :user gets avatar for user :userAvatar |
|
33 | - * |
|
34 | - * @param string $user |
|
35 | - * @param string $userAvatar |
|
36 | - */ |
|
37 | - public function userGetsAvatarForUser(string $user, string $userAvatar) { |
|
38 | - $this->userGetsAvatarForUserWithSize($user, $userAvatar, '128'); |
|
39 | - } |
|
40 | - |
|
41 | - /** |
|
42 | - * @When user :user gets avatar for user :userAvatar with size :size |
|
43 | - * |
|
44 | - * @param string $user |
|
45 | - * @param string $userAvatar |
|
46 | - * @param string $size |
|
47 | - */ |
|
48 | - public function userGetsAvatarForUserWithSize(string $user, string $userAvatar, string $size) { |
|
49 | - $this->asAn($user); |
|
50 | - $this->sendingToDirectUrl('GET', '/index.php/avatar/' . $userAvatar . '/' . $size); |
|
51 | - $this->theHTTPStatusCodeShouldBe('200'); |
|
52 | - |
|
53 | - $this->getLastAvatar(); |
|
54 | - } |
|
55 | - |
|
56 | - /** |
|
57 | - * @When user :user gets avatar for guest :guestAvatar |
|
58 | - * |
|
59 | - * @param string $user |
|
60 | - * @param string $guestAvatar |
|
61 | - */ |
|
62 | - public function userGetsAvatarForGuest(string $user, string $guestAvatar) { |
|
63 | - $this->asAn($user); |
|
64 | - $this->sendingToDirectUrl('GET', '/index.php/avatar/guest/' . $guestAvatar . '/128'); |
|
65 | - $this->theHTTPStatusCodeShouldBe('201'); |
|
66 | - |
|
67 | - $this->getLastAvatar(); |
|
68 | - } |
|
69 | - |
|
70 | - /** |
|
71 | - * @When logged in user gets temporary avatar |
|
72 | - */ |
|
73 | - public function loggedInUserGetsTemporaryAvatar() { |
|
74 | - $this->loggedInUserGetsTemporaryAvatarWith('200'); |
|
75 | - } |
|
76 | - |
|
77 | - /** |
|
78 | - * @When logged in user gets temporary avatar with :statusCode |
|
79 | - * |
|
80 | - * @param string $statusCode |
|
81 | - */ |
|
82 | - public function loggedInUserGetsTemporaryAvatarWith(string $statusCode) { |
|
83 | - $this->sendingAToWithRequesttoken('GET', '/index.php/avatar/tmp'); |
|
84 | - $this->theHTTPStatusCodeShouldBe($statusCode); |
|
85 | - |
|
86 | - $this->getLastAvatar(); |
|
87 | - } |
|
88 | - |
|
89 | - /** |
|
90 | - * @When logged in user posts temporary avatar from file :source |
|
91 | - * |
|
92 | - * @param string $source |
|
93 | - */ |
|
94 | - public function loggedInUserPostsTemporaryAvatarFromFile(string $source) { |
|
95 | - $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r')); |
|
96 | - |
|
97 | - $this->sendingAToWithRequesttoken('POST', '/index.php/avatar', |
|
98 | - [ |
|
99 | - 'multipart' => [ |
|
100 | - [ |
|
101 | - 'name' => 'files[]', |
|
102 | - 'contents' => $file |
|
103 | - ] |
|
104 | - ] |
|
105 | - ]); |
|
106 | - $this->theHTTPStatusCodeShouldBe('200'); |
|
107 | - } |
|
108 | - |
|
109 | - /** |
|
110 | - * @When logged in user posts temporary avatar from internal path :path |
|
111 | - * |
|
112 | - * @param string $path |
|
113 | - */ |
|
114 | - public function loggedInUserPostsTemporaryAvatarFromInternalPath(string $path) { |
|
115 | - $this->sendingAToWithRequesttoken('POST', '/index.php/avatar?path=' . $path); |
|
116 | - $this->theHTTPStatusCodeShouldBe('200'); |
|
117 | - } |
|
118 | - |
|
119 | - /** |
|
120 | - * @When logged in user crops temporary avatar |
|
121 | - * |
|
122 | - * @param TableNode $crop |
|
123 | - */ |
|
124 | - public function loggedInUserCropsTemporaryAvatar(TableNode $crop) { |
|
125 | - $this->loggedInUserCropsTemporaryAvatarWith('200', $crop); |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * @When logged in user crops temporary avatar with :statusCode |
|
130 | - * |
|
131 | - * @param string $statusCode |
|
132 | - * @param TableNode $crop |
|
133 | - */ |
|
134 | - public function loggedInUserCropsTemporaryAvatarWith(string $statusCode, TableNode $crop) { |
|
135 | - $parameters = []; |
|
136 | - foreach ($crop->getRowsHash() as $key => $value) { |
|
137 | - $parameters[] = 'crop[' . $key . ']=' . $value; |
|
138 | - } |
|
139 | - |
|
140 | - $this->sendingAToWithRequesttoken('POST', '/index.php/avatar/cropped?' . implode('&', $parameters)); |
|
141 | - $this->theHTTPStatusCodeShouldBe($statusCode); |
|
142 | - } |
|
143 | - |
|
144 | - /** |
|
145 | - * @When logged in user deletes the user avatar |
|
146 | - */ |
|
147 | - public function loggedInUserDeletesTheUserAvatar() { |
|
148 | - $this->sendingAToWithRequesttoken('DELETE', '/index.php/avatar'); |
|
149 | - $this->theHTTPStatusCodeShouldBe('200'); |
|
150 | - } |
|
151 | - |
|
152 | - /** |
|
153 | - * @Then last avatar is a square of size :size |
|
154 | - * |
|
155 | - * @param string size |
|
156 | - */ |
|
157 | - public function lastAvatarIsASquareOfSize(string $size) { |
|
158 | - [$width, $height] = getimagesizefromstring($this->lastAvatar); |
|
159 | - |
|
160 | - Assert::assertEquals($width, $height, 'Expected avatar to be a square'); |
|
161 | - Assert::assertEquals($size, $width); |
|
162 | - } |
|
163 | - |
|
164 | - /** |
|
165 | - * @Then last avatar is not a square |
|
166 | - */ |
|
167 | - public function lastAvatarIsNotASquare() { |
|
168 | - [$width, $height] = getimagesizefromstring($this->lastAvatar); |
|
169 | - |
|
170 | - Assert::assertNotEquals($width, $height, 'Expected avatar to not be a square'); |
|
171 | - } |
|
172 | - |
|
173 | - /** |
|
174 | - * @Then last avatar is not a single color |
|
175 | - */ |
|
176 | - public function lastAvatarIsNotASingleColor() { |
|
177 | - Assert::assertEquals(null, $this->getColorFromLastAvatar()); |
|
178 | - } |
|
179 | - |
|
180 | - /** |
|
181 | - * @Then last avatar is a single :color color |
|
182 | - * |
|
183 | - * @param string $color |
|
184 | - * @param string $size |
|
185 | - */ |
|
186 | - public function lastAvatarIsASingleColor(string $color) { |
|
187 | - $expectedColor = $this->hexStringToRgbColor($color); |
|
188 | - $colorFromLastAvatar = $this->getColorFromLastAvatar(); |
|
189 | - |
|
190 | - Assert::assertTrue($this->isSameColor($expectedColor, $colorFromLastAvatar), |
|
191 | - $this->rgbColorToHexString($colorFromLastAvatar) . ' does not match expected ' . $color); |
|
192 | - } |
|
193 | - |
|
194 | - private function hexStringToRgbColor($hexString) { |
|
195 | - // Strip initial "#" |
|
196 | - $hexString = substr($hexString, 1); |
|
197 | - |
|
198 | - $rgbColorInt = hexdec($hexString); |
|
199 | - |
|
200 | - // RGBA hex strings are not supported; the given string is assumed to be |
|
201 | - // an RGB hex string. |
|
202 | - return [ |
|
203 | - 'red' => ($rgbColorInt >> 16) & 0xFF, |
|
204 | - 'green' => ($rgbColorInt >> 8) & 0xFF, |
|
205 | - 'blue' => $rgbColorInt & 0xFF, |
|
206 | - 'alpha' => 0 |
|
207 | - ]; |
|
208 | - } |
|
209 | - |
|
210 | - private function rgbColorToHexString($rgbColor) { |
|
211 | - $rgbColorInt = ($rgbColor['red'] << 16) + ($rgbColor['green'] << 8) + ($rgbColor['blue']); |
|
212 | - |
|
213 | - return '#' . str_pad(strtoupper(dechex($rgbColorInt)), 6, '0', STR_PAD_LEFT); |
|
214 | - } |
|
215 | - |
|
216 | - private function getColorFromLastAvatar() { |
|
217 | - $image = imagecreatefromstring($this->lastAvatar); |
|
218 | - |
|
219 | - $firstPixelColorIndex = imagecolorat($image, 0, 0); |
|
220 | - $firstPixelColor = imagecolorsforindex($image, $firstPixelColorIndex); |
|
221 | - |
|
222 | - for ($i = 0; $i < imagesx($image); $i++) { |
|
223 | - for ($j = 0; $j < imagesx($image); $j++) { |
|
224 | - $currentPixelColorIndex = imagecolorat($image, $i, $j); |
|
225 | - $currentPixelColor = imagecolorsforindex($image, $currentPixelColorIndex); |
|
226 | - |
|
227 | - // The colors are compared with a small allowed delta, as even |
|
228 | - // on solid color images the resizing can cause some small |
|
229 | - // artifacts that slightly modify the color of certain pixels. |
|
230 | - if (!$this->isSameColor($firstPixelColor, $currentPixelColor)) { |
|
231 | - imagedestroy($image); |
|
232 | - |
|
233 | - return null; |
|
234 | - } |
|
235 | - } |
|
236 | - } |
|
237 | - |
|
238 | - imagedestroy($image); |
|
239 | - |
|
240 | - return $firstPixelColor; |
|
241 | - } |
|
242 | - |
|
243 | - private function isSameColor(array $firstColor, array $secondColor, int $allowedDelta = 1) { |
|
244 | - if ($this->isSameColorComponent($firstColor['red'], $secondColor['red'], $allowedDelta) |
|
245 | - && $this->isSameColorComponent($firstColor['green'], $secondColor['green'], $allowedDelta) |
|
246 | - && $this->isSameColorComponent($firstColor['blue'], $secondColor['blue'], $allowedDelta) |
|
247 | - && $this->isSameColorComponent($firstColor['alpha'], $secondColor['alpha'], $allowedDelta)) { |
|
248 | - return true; |
|
249 | - } |
|
250 | - |
|
251 | - return false; |
|
252 | - } |
|
253 | - |
|
254 | - private function isSameColorComponent(int $firstColorComponent, int $secondColorComponent, int $allowedDelta) { |
|
255 | - if ($firstColorComponent >= ($secondColorComponent - $allowedDelta) |
|
256 | - && $firstColorComponent <= ($secondColorComponent + $allowedDelta)) { |
|
257 | - return true; |
|
258 | - } |
|
259 | - |
|
260 | - return false; |
|
261 | - } |
|
13 | + /** @var string * */ |
|
14 | + private $lastAvatar; |
|
15 | + |
|
16 | + /** @AfterScenario **/ |
|
17 | + public function cleanupLastAvatar() { |
|
18 | + $this->lastAvatar = null; |
|
19 | + } |
|
20 | + |
|
21 | + private function getLastAvatar() { |
|
22 | + $this->lastAvatar = ''; |
|
23 | + |
|
24 | + $body = $this->response->getBody(); |
|
25 | + while (!$body->eof()) { |
|
26 | + $this->lastAvatar .= $body->read(8192); |
|
27 | + } |
|
28 | + $body->close(); |
|
29 | + } |
|
30 | + |
|
31 | + /** |
|
32 | + * @When user :user gets avatar for user :userAvatar |
|
33 | + * |
|
34 | + * @param string $user |
|
35 | + * @param string $userAvatar |
|
36 | + */ |
|
37 | + public function userGetsAvatarForUser(string $user, string $userAvatar) { |
|
38 | + $this->userGetsAvatarForUserWithSize($user, $userAvatar, '128'); |
|
39 | + } |
|
40 | + |
|
41 | + /** |
|
42 | + * @When user :user gets avatar for user :userAvatar with size :size |
|
43 | + * |
|
44 | + * @param string $user |
|
45 | + * @param string $userAvatar |
|
46 | + * @param string $size |
|
47 | + */ |
|
48 | + public function userGetsAvatarForUserWithSize(string $user, string $userAvatar, string $size) { |
|
49 | + $this->asAn($user); |
|
50 | + $this->sendingToDirectUrl('GET', '/index.php/avatar/' . $userAvatar . '/' . $size); |
|
51 | + $this->theHTTPStatusCodeShouldBe('200'); |
|
52 | + |
|
53 | + $this->getLastAvatar(); |
|
54 | + } |
|
55 | + |
|
56 | + /** |
|
57 | + * @When user :user gets avatar for guest :guestAvatar |
|
58 | + * |
|
59 | + * @param string $user |
|
60 | + * @param string $guestAvatar |
|
61 | + */ |
|
62 | + public function userGetsAvatarForGuest(string $user, string $guestAvatar) { |
|
63 | + $this->asAn($user); |
|
64 | + $this->sendingToDirectUrl('GET', '/index.php/avatar/guest/' . $guestAvatar . '/128'); |
|
65 | + $this->theHTTPStatusCodeShouldBe('201'); |
|
66 | + |
|
67 | + $this->getLastAvatar(); |
|
68 | + } |
|
69 | + |
|
70 | + /** |
|
71 | + * @When logged in user gets temporary avatar |
|
72 | + */ |
|
73 | + public function loggedInUserGetsTemporaryAvatar() { |
|
74 | + $this->loggedInUserGetsTemporaryAvatarWith('200'); |
|
75 | + } |
|
76 | + |
|
77 | + /** |
|
78 | + * @When logged in user gets temporary avatar with :statusCode |
|
79 | + * |
|
80 | + * @param string $statusCode |
|
81 | + */ |
|
82 | + public function loggedInUserGetsTemporaryAvatarWith(string $statusCode) { |
|
83 | + $this->sendingAToWithRequesttoken('GET', '/index.php/avatar/tmp'); |
|
84 | + $this->theHTTPStatusCodeShouldBe($statusCode); |
|
85 | + |
|
86 | + $this->getLastAvatar(); |
|
87 | + } |
|
88 | + |
|
89 | + /** |
|
90 | + * @When logged in user posts temporary avatar from file :source |
|
91 | + * |
|
92 | + * @param string $source |
|
93 | + */ |
|
94 | + public function loggedInUserPostsTemporaryAvatarFromFile(string $source) { |
|
95 | + $file = \GuzzleHttp\Psr7\Utils::streamFor(fopen($source, 'r')); |
|
96 | + |
|
97 | + $this->sendingAToWithRequesttoken('POST', '/index.php/avatar', |
|
98 | + [ |
|
99 | + 'multipart' => [ |
|
100 | + [ |
|
101 | + 'name' => 'files[]', |
|
102 | + 'contents' => $file |
|
103 | + ] |
|
104 | + ] |
|
105 | + ]); |
|
106 | + $this->theHTTPStatusCodeShouldBe('200'); |
|
107 | + } |
|
108 | + |
|
109 | + /** |
|
110 | + * @When logged in user posts temporary avatar from internal path :path |
|
111 | + * |
|
112 | + * @param string $path |
|
113 | + */ |
|
114 | + public function loggedInUserPostsTemporaryAvatarFromInternalPath(string $path) { |
|
115 | + $this->sendingAToWithRequesttoken('POST', '/index.php/avatar?path=' . $path); |
|
116 | + $this->theHTTPStatusCodeShouldBe('200'); |
|
117 | + } |
|
118 | + |
|
119 | + /** |
|
120 | + * @When logged in user crops temporary avatar |
|
121 | + * |
|
122 | + * @param TableNode $crop |
|
123 | + */ |
|
124 | + public function loggedInUserCropsTemporaryAvatar(TableNode $crop) { |
|
125 | + $this->loggedInUserCropsTemporaryAvatarWith('200', $crop); |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * @When logged in user crops temporary avatar with :statusCode |
|
130 | + * |
|
131 | + * @param string $statusCode |
|
132 | + * @param TableNode $crop |
|
133 | + */ |
|
134 | + public function loggedInUserCropsTemporaryAvatarWith(string $statusCode, TableNode $crop) { |
|
135 | + $parameters = []; |
|
136 | + foreach ($crop->getRowsHash() as $key => $value) { |
|
137 | + $parameters[] = 'crop[' . $key . ']=' . $value; |
|
138 | + } |
|
139 | + |
|
140 | + $this->sendingAToWithRequesttoken('POST', '/index.php/avatar/cropped?' . implode('&', $parameters)); |
|
141 | + $this->theHTTPStatusCodeShouldBe($statusCode); |
|
142 | + } |
|
143 | + |
|
144 | + /** |
|
145 | + * @When logged in user deletes the user avatar |
|
146 | + */ |
|
147 | + public function loggedInUserDeletesTheUserAvatar() { |
|
148 | + $this->sendingAToWithRequesttoken('DELETE', '/index.php/avatar'); |
|
149 | + $this->theHTTPStatusCodeShouldBe('200'); |
|
150 | + } |
|
151 | + |
|
152 | + /** |
|
153 | + * @Then last avatar is a square of size :size |
|
154 | + * |
|
155 | + * @param string size |
|
156 | + */ |
|
157 | + public function lastAvatarIsASquareOfSize(string $size) { |
|
158 | + [$width, $height] = getimagesizefromstring($this->lastAvatar); |
|
159 | + |
|
160 | + Assert::assertEquals($width, $height, 'Expected avatar to be a square'); |
|
161 | + Assert::assertEquals($size, $width); |
|
162 | + } |
|
163 | + |
|
164 | + /** |
|
165 | + * @Then last avatar is not a square |
|
166 | + */ |
|
167 | + public function lastAvatarIsNotASquare() { |
|
168 | + [$width, $height] = getimagesizefromstring($this->lastAvatar); |
|
169 | + |
|
170 | + Assert::assertNotEquals($width, $height, 'Expected avatar to not be a square'); |
|
171 | + } |
|
172 | + |
|
173 | + /** |
|
174 | + * @Then last avatar is not a single color |
|
175 | + */ |
|
176 | + public function lastAvatarIsNotASingleColor() { |
|
177 | + Assert::assertEquals(null, $this->getColorFromLastAvatar()); |
|
178 | + } |
|
179 | + |
|
180 | + /** |
|
181 | + * @Then last avatar is a single :color color |
|
182 | + * |
|
183 | + * @param string $color |
|
184 | + * @param string $size |
|
185 | + */ |
|
186 | + public function lastAvatarIsASingleColor(string $color) { |
|
187 | + $expectedColor = $this->hexStringToRgbColor($color); |
|
188 | + $colorFromLastAvatar = $this->getColorFromLastAvatar(); |
|
189 | + |
|
190 | + Assert::assertTrue($this->isSameColor($expectedColor, $colorFromLastAvatar), |
|
191 | + $this->rgbColorToHexString($colorFromLastAvatar) . ' does not match expected ' . $color); |
|
192 | + } |
|
193 | + |
|
194 | + private function hexStringToRgbColor($hexString) { |
|
195 | + // Strip initial "#" |
|
196 | + $hexString = substr($hexString, 1); |
|
197 | + |
|
198 | + $rgbColorInt = hexdec($hexString); |
|
199 | + |
|
200 | + // RGBA hex strings are not supported; the given string is assumed to be |
|
201 | + // an RGB hex string. |
|
202 | + return [ |
|
203 | + 'red' => ($rgbColorInt >> 16) & 0xFF, |
|
204 | + 'green' => ($rgbColorInt >> 8) & 0xFF, |
|
205 | + 'blue' => $rgbColorInt & 0xFF, |
|
206 | + 'alpha' => 0 |
|
207 | + ]; |
|
208 | + } |
|
209 | + |
|
210 | + private function rgbColorToHexString($rgbColor) { |
|
211 | + $rgbColorInt = ($rgbColor['red'] << 16) + ($rgbColor['green'] << 8) + ($rgbColor['blue']); |
|
212 | + |
|
213 | + return '#' . str_pad(strtoupper(dechex($rgbColorInt)), 6, '0', STR_PAD_LEFT); |
|
214 | + } |
|
215 | + |
|
216 | + private function getColorFromLastAvatar() { |
|
217 | + $image = imagecreatefromstring($this->lastAvatar); |
|
218 | + |
|
219 | + $firstPixelColorIndex = imagecolorat($image, 0, 0); |
|
220 | + $firstPixelColor = imagecolorsforindex($image, $firstPixelColorIndex); |
|
221 | + |
|
222 | + for ($i = 0; $i < imagesx($image); $i++) { |
|
223 | + for ($j = 0; $j < imagesx($image); $j++) { |
|
224 | + $currentPixelColorIndex = imagecolorat($image, $i, $j); |
|
225 | + $currentPixelColor = imagecolorsforindex($image, $currentPixelColorIndex); |
|
226 | + |
|
227 | + // The colors are compared with a small allowed delta, as even |
|
228 | + // on solid color images the resizing can cause some small |
|
229 | + // artifacts that slightly modify the color of certain pixels. |
|
230 | + if (!$this->isSameColor($firstPixelColor, $currentPixelColor)) { |
|
231 | + imagedestroy($image); |
|
232 | + |
|
233 | + return null; |
|
234 | + } |
|
235 | + } |
|
236 | + } |
|
237 | + |
|
238 | + imagedestroy($image); |
|
239 | + |
|
240 | + return $firstPixelColor; |
|
241 | + } |
|
242 | + |
|
243 | + private function isSameColor(array $firstColor, array $secondColor, int $allowedDelta = 1) { |
|
244 | + if ($this->isSameColorComponent($firstColor['red'], $secondColor['red'], $allowedDelta) |
|
245 | + && $this->isSameColorComponent($firstColor['green'], $secondColor['green'], $allowedDelta) |
|
246 | + && $this->isSameColorComponent($firstColor['blue'], $secondColor['blue'], $allowedDelta) |
|
247 | + && $this->isSameColorComponent($firstColor['alpha'], $secondColor['alpha'], $allowedDelta)) { |
|
248 | + return true; |
|
249 | + } |
|
250 | + |
|
251 | + return false; |
|
252 | + } |
|
253 | + |
|
254 | + private function isSameColorComponent(int $firstColorComponent, int $secondColorComponent, int $allowedDelta) { |
|
255 | + if ($firstColorComponent >= ($secondColorComponent - $allowedDelta) |
|
256 | + && $firstColorComponent <= ($secondColorComponent + $allowedDelta)) { |
|
257 | + return true; |
|
258 | + } |
|
259 | + |
|
260 | + return false; |
|
261 | + } |
|
262 | 262 | } |
@@ -33,214 +33,214 @@ |
||
33 | 33 | * Base class for sharing tests. |
34 | 34 | */ |
35 | 35 | abstract class TestCase extends \Test\TestCase { |
36 | - use MountProviderTrait; |
|
37 | - |
|
38 | - public const TEST_FILES_SHARING_API_USER1 = 'test-share-user1'; |
|
39 | - public const TEST_FILES_SHARING_API_USER2 = 'test-share-user2'; |
|
40 | - public const TEST_FILES_SHARING_API_USER3 = 'test-share-user3'; |
|
41 | - public const TEST_FILES_SHARING_API_USER4 = 'test-share-user4'; |
|
42 | - |
|
43 | - public const TEST_FILES_SHARING_API_GROUP1 = 'test-share-group1'; |
|
44 | - |
|
45 | - public $filename; |
|
46 | - public $data; |
|
47 | - /** |
|
48 | - * @var View |
|
49 | - */ |
|
50 | - public $view; |
|
51 | - /** |
|
52 | - * @var View |
|
53 | - */ |
|
54 | - public $view2; |
|
55 | - public $folder; |
|
56 | - public $subfolder; |
|
57 | - |
|
58 | - /** @var \OCP\Share\IManager */ |
|
59 | - protected $shareManager; |
|
60 | - /** @var IRootFolder */ |
|
61 | - protected $rootFolder; |
|
62 | - |
|
63 | - public static function setUpBeforeClass(): void { |
|
64 | - parent::setUpBeforeClass(); |
|
65 | - |
|
66 | - $app = new Application(); |
|
67 | - $app->registerMountProviders( |
|
68 | - Server::get(IMountProviderCollection::class), |
|
69 | - Server::get(MountProvider::class), |
|
70 | - Server::get(ExternalMountProvider::class), |
|
71 | - ); |
|
72 | - |
|
73 | - // reset backend |
|
74 | - Server::get(IUserManager::class)->clearBackends(); |
|
75 | - Server::get(IGroupManager::class)->clearBackends(); |
|
76 | - |
|
77 | - // clear share hooks |
|
78 | - \OC_Hook::clear('OCP\\Share'); |
|
79 | - \OC::registerShareHooks(Server::get(SystemConfig::class)); |
|
80 | - |
|
81 | - // create users |
|
82 | - $backend = new \Test\Util\User\Dummy(); |
|
83 | - Server::get(IUserManager::class)->registerBackend($backend); |
|
84 | - $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); |
|
85 | - $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); |
|
86 | - $backend->createUser(self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER3); |
|
87 | - $backend->createUser(self::TEST_FILES_SHARING_API_USER4, self::TEST_FILES_SHARING_API_USER4); |
|
88 | - |
|
89 | - // create group |
|
90 | - $groupBackend = new \Test\Util\Group\Dummy(); |
|
91 | - $groupBackend->createGroup(self::TEST_FILES_SHARING_API_GROUP1); |
|
92 | - $groupBackend->createGroup('group'); |
|
93 | - $groupBackend->createGroup('group1'); |
|
94 | - $groupBackend->createGroup('group2'); |
|
95 | - $groupBackend->createGroup('group3'); |
|
96 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER1, 'group'); |
|
97 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, 'group'); |
|
98 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER3, 'group'); |
|
99 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, 'group1'); |
|
100 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER3, 'group2'); |
|
101 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER4, 'group3'); |
|
102 | - $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_GROUP1); |
|
103 | - Server::get(IGroupManager::class)->addBackend($groupBackend); |
|
104 | - } |
|
105 | - |
|
106 | - protected function setUp(): void { |
|
107 | - parent::setUp(); |
|
108 | - Server::get(DisplayNameCache::class)->clear(); |
|
109 | - |
|
110 | - //login as user1 |
|
111 | - $this->loginHelper(self::TEST_FILES_SHARING_API_USER1); |
|
112 | - |
|
113 | - $this->data = 'foobar'; |
|
114 | - $this->view = new View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files'); |
|
115 | - $this->view2 = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); |
|
116 | - |
|
117 | - $this->shareManager = Server::get(\OCP\Share\IManager::class); |
|
118 | - $this->rootFolder = Server::get(IRootFolder::class); |
|
119 | - } |
|
120 | - |
|
121 | - protected function tearDown(): void { |
|
122 | - $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
123 | - $qb->delete('share'); |
|
124 | - $qb->execute(); |
|
125 | - |
|
126 | - $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
127 | - $qb->delete('mounts'); |
|
128 | - $qb->execute(); |
|
129 | - |
|
130 | - $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
131 | - $qb->delete('filecache')->runAcrossAllShards(); |
|
132 | - $qb->execute(); |
|
133 | - |
|
134 | - parent::tearDown(); |
|
135 | - } |
|
136 | - |
|
137 | - public static function tearDownAfterClass(): void { |
|
138 | - // cleanup users |
|
139 | - $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER1); |
|
140 | - if ($user !== null) { |
|
141 | - $user->delete(); |
|
142 | - } |
|
143 | - $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER2); |
|
144 | - if ($user !== null) { |
|
145 | - $user->delete(); |
|
146 | - } |
|
147 | - $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER3); |
|
148 | - if ($user !== null) { |
|
149 | - $user->delete(); |
|
150 | - } |
|
151 | - |
|
152 | - // delete group |
|
153 | - $group = Server::get(IGroupManager::class)->get(self::TEST_FILES_SHARING_API_GROUP1); |
|
154 | - if ($group) { |
|
155 | - $group->delete(); |
|
156 | - } |
|
157 | - |
|
158 | - \OC_Util::tearDownFS(); |
|
159 | - \OC_User::setUserId(''); |
|
160 | - Filesystem::tearDown(); |
|
161 | - |
|
162 | - // reset backend |
|
163 | - Server::get(IUserManager::class)->clearBackends(); |
|
164 | - Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
165 | - Server::get(IGroupManager::class)->clearBackends(); |
|
166 | - Server::get(IGroupManager::class)->addBackend(new Database()); |
|
167 | - |
|
168 | - parent::tearDownAfterClass(); |
|
169 | - } |
|
170 | - |
|
171 | - /** |
|
172 | - * @param string $user |
|
173 | - * @param bool $create |
|
174 | - * @param bool $password |
|
175 | - */ |
|
176 | - protected function loginHelper($user, $create = false, $password = false) { |
|
177 | - if ($password === false) { |
|
178 | - $password = $user; |
|
179 | - } |
|
180 | - |
|
181 | - if ($create) { |
|
182 | - $userManager = Server::get(IUserManager::class); |
|
183 | - $groupManager = Server::get(IGroupManager::class); |
|
184 | - |
|
185 | - $userObject = $userManager->createUser($user, $password); |
|
186 | - $group = $groupManager->createGroup('group'); |
|
187 | - |
|
188 | - if ($group && $userObject) { |
|
189 | - $group->addUser($userObject); |
|
190 | - } |
|
191 | - } |
|
192 | - |
|
193 | - \OC_Util::tearDownFS(); |
|
194 | - Storage::getGlobalCache()->clearCache(); |
|
195 | - Server::get(IUserSession::class)->setUser(null); |
|
196 | - Filesystem::tearDown(); |
|
197 | - Server::get(IUserSession::class)->login($user, $password); |
|
198 | - \OC::$server->getUserFolder($user); |
|
199 | - |
|
200 | - \OC_Util::setupFS($user); |
|
201 | - } |
|
202 | - |
|
203 | - /** |
|
204 | - * get some information from a given share |
|
205 | - * @param int $shareID |
|
206 | - * @return array with: item_source, share_type, share_with, item_type, permissions |
|
207 | - */ |
|
208 | - protected function getShareFromId($shareID) { |
|
209 | - $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
210 | - $qb->select('item_source', '`share_type', 'share_with', 'item_type', 'permissions') |
|
211 | - ->from('share') |
|
212 | - ->where( |
|
213 | - $qb->expr()->eq('id', $qb->createNamedParameter($shareID)) |
|
214 | - ); |
|
215 | - $result = $qb->execute(); |
|
216 | - $share = $result->fetch(); |
|
217 | - $result->closeCursor(); |
|
218 | - |
|
219 | - return $share; |
|
220 | - } |
|
221 | - |
|
222 | - /** |
|
223 | - * @param int $type The share type |
|
224 | - * @param string $path The path to share relative to $initiators root |
|
225 | - * @param string $initiator |
|
226 | - * @param string $recipient |
|
227 | - * @param int $permissions |
|
228 | - * @return IShare |
|
229 | - */ |
|
230 | - protected function share($type, $path, $initiator, $recipient, $permissions) { |
|
231 | - $userFolder = $this->rootFolder->getUserFolder($initiator); |
|
232 | - $node = $userFolder->get($path); |
|
233 | - |
|
234 | - $share = $this->shareManager->newShare(); |
|
235 | - $share->setShareType($type) |
|
236 | - ->setSharedWith($recipient) |
|
237 | - ->setSharedBy($initiator) |
|
238 | - ->setNode($node) |
|
239 | - ->setPermissions($permissions); |
|
240 | - $share = $this->shareManager->createShare($share); |
|
241 | - $share->setStatus(IShare::STATUS_ACCEPTED); |
|
242 | - $share = $this->shareManager->updateShare($share); |
|
243 | - |
|
244 | - return $share; |
|
245 | - } |
|
36 | + use MountProviderTrait; |
|
37 | + |
|
38 | + public const TEST_FILES_SHARING_API_USER1 = 'test-share-user1'; |
|
39 | + public const TEST_FILES_SHARING_API_USER2 = 'test-share-user2'; |
|
40 | + public const TEST_FILES_SHARING_API_USER3 = 'test-share-user3'; |
|
41 | + public const TEST_FILES_SHARING_API_USER4 = 'test-share-user4'; |
|
42 | + |
|
43 | + public const TEST_FILES_SHARING_API_GROUP1 = 'test-share-group1'; |
|
44 | + |
|
45 | + public $filename; |
|
46 | + public $data; |
|
47 | + /** |
|
48 | + * @var View |
|
49 | + */ |
|
50 | + public $view; |
|
51 | + /** |
|
52 | + * @var View |
|
53 | + */ |
|
54 | + public $view2; |
|
55 | + public $folder; |
|
56 | + public $subfolder; |
|
57 | + |
|
58 | + /** @var \OCP\Share\IManager */ |
|
59 | + protected $shareManager; |
|
60 | + /** @var IRootFolder */ |
|
61 | + protected $rootFolder; |
|
62 | + |
|
63 | + public static function setUpBeforeClass(): void { |
|
64 | + parent::setUpBeforeClass(); |
|
65 | + |
|
66 | + $app = new Application(); |
|
67 | + $app->registerMountProviders( |
|
68 | + Server::get(IMountProviderCollection::class), |
|
69 | + Server::get(MountProvider::class), |
|
70 | + Server::get(ExternalMountProvider::class), |
|
71 | + ); |
|
72 | + |
|
73 | + // reset backend |
|
74 | + Server::get(IUserManager::class)->clearBackends(); |
|
75 | + Server::get(IGroupManager::class)->clearBackends(); |
|
76 | + |
|
77 | + // clear share hooks |
|
78 | + \OC_Hook::clear('OCP\\Share'); |
|
79 | + \OC::registerShareHooks(Server::get(SystemConfig::class)); |
|
80 | + |
|
81 | + // create users |
|
82 | + $backend = new \Test\Util\User\Dummy(); |
|
83 | + Server::get(IUserManager::class)->registerBackend($backend); |
|
84 | + $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); |
|
85 | + $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); |
|
86 | + $backend->createUser(self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER3); |
|
87 | + $backend->createUser(self::TEST_FILES_SHARING_API_USER4, self::TEST_FILES_SHARING_API_USER4); |
|
88 | + |
|
89 | + // create group |
|
90 | + $groupBackend = new \Test\Util\Group\Dummy(); |
|
91 | + $groupBackend->createGroup(self::TEST_FILES_SHARING_API_GROUP1); |
|
92 | + $groupBackend->createGroup('group'); |
|
93 | + $groupBackend->createGroup('group1'); |
|
94 | + $groupBackend->createGroup('group2'); |
|
95 | + $groupBackend->createGroup('group3'); |
|
96 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER1, 'group'); |
|
97 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, 'group'); |
|
98 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER3, 'group'); |
|
99 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, 'group1'); |
|
100 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER3, 'group2'); |
|
101 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER4, 'group3'); |
|
102 | + $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_GROUP1); |
|
103 | + Server::get(IGroupManager::class)->addBackend($groupBackend); |
|
104 | + } |
|
105 | + |
|
106 | + protected function setUp(): void { |
|
107 | + parent::setUp(); |
|
108 | + Server::get(DisplayNameCache::class)->clear(); |
|
109 | + |
|
110 | + //login as user1 |
|
111 | + $this->loginHelper(self::TEST_FILES_SHARING_API_USER1); |
|
112 | + |
|
113 | + $this->data = 'foobar'; |
|
114 | + $this->view = new View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files'); |
|
115 | + $this->view2 = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); |
|
116 | + |
|
117 | + $this->shareManager = Server::get(\OCP\Share\IManager::class); |
|
118 | + $this->rootFolder = Server::get(IRootFolder::class); |
|
119 | + } |
|
120 | + |
|
121 | + protected function tearDown(): void { |
|
122 | + $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
123 | + $qb->delete('share'); |
|
124 | + $qb->execute(); |
|
125 | + |
|
126 | + $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
127 | + $qb->delete('mounts'); |
|
128 | + $qb->execute(); |
|
129 | + |
|
130 | + $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
131 | + $qb->delete('filecache')->runAcrossAllShards(); |
|
132 | + $qb->execute(); |
|
133 | + |
|
134 | + parent::tearDown(); |
|
135 | + } |
|
136 | + |
|
137 | + public static function tearDownAfterClass(): void { |
|
138 | + // cleanup users |
|
139 | + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER1); |
|
140 | + if ($user !== null) { |
|
141 | + $user->delete(); |
|
142 | + } |
|
143 | + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER2); |
|
144 | + if ($user !== null) { |
|
145 | + $user->delete(); |
|
146 | + } |
|
147 | + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER3); |
|
148 | + if ($user !== null) { |
|
149 | + $user->delete(); |
|
150 | + } |
|
151 | + |
|
152 | + // delete group |
|
153 | + $group = Server::get(IGroupManager::class)->get(self::TEST_FILES_SHARING_API_GROUP1); |
|
154 | + if ($group) { |
|
155 | + $group->delete(); |
|
156 | + } |
|
157 | + |
|
158 | + \OC_Util::tearDownFS(); |
|
159 | + \OC_User::setUserId(''); |
|
160 | + Filesystem::tearDown(); |
|
161 | + |
|
162 | + // reset backend |
|
163 | + Server::get(IUserManager::class)->clearBackends(); |
|
164 | + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
165 | + Server::get(IGroupManager::class)->clearBackends(); |
|
166 | + Server::get(IGroupManager::class)->addBackend(new Database()); |
|
167 | + |
|
168 | + parent::tearDownAfterClass(); |
|
169 | + } |
|
170 | + |
|
171 | + /** |
|
172 | + * @param string $user |
|
173 | + * @param bool $create |
|
174 | + * @param bool $password |
|
175 | + */ |
|
176 | + protected function loginHelper($user, $create = false, $password = false) { |
|
177 | + if ($password === false) { |
|
178 | + $password = $user; |
|
179 | + } |
|
180 | + |
|
181 | + if ($create) { |
|
182 | + $userManager = Server::get(IUserManager::class); |
|
183 | + $groupManager = Server::get(IGroupManager::class); |
|
184 | + |
|
185 | + $userObject = $userManager->createUser($user, $password); |
|
186 | + $group = $groupManager->createGroup('group'); |
|
187 | + |
|
188 | + if ($group && $userObject) { |
|
189 | + $group->addUser($userObject); |
|
190 | + } |
|
191 | + } |
|
192 | + |
|
193 | + \OC_Util::tearDownFS(); |
|
194 | + Storage::getGlobalCache()->clearCache(); |
|
195 | + Server::get(IUserSession::class)->setUser(null); |
|
196 | + Filesystem::tearDown(); |
|
197 | + Server::get(IUserSession::class)->login($user, $password); |
|
198 | + \OC::$server->getUserFolder($user); |
|
199 | + |
|
200 | + \OC_Util::setupFS($user); |
|
201 | + } |
|
202 | + |
|
203 | + /** |
|
204 | + * get some information from a given share |
|
205 | + * @param int $shareID |
|
206 | + * @return array with: item_source, share_type, share_with, item_type, permissions |
|
207 | + */ |
|
208 | + protected function getShareFromId($shareID) { |
|
209 | + $qb = Server::get(IDBConnection::class)->getQueryBuilder(); |
|
210 | + $qb->select('item_source', '`share_type', 'share_with', 'item_type', 'permissions') |
|
211 | + ->from('share') |
|
212 | + ->where( |
|
213 | + $qb->expr()->eq('id', $qb->createNamedParameter($shareID)) |
|
214 | + ); |
|
215 | + $result = $qb->execute(); |
|
216 | + $share = $result->fetch(); |
|
217 | + $result->closeCursor(); |
|
218 | + |
|
219 | + return $share; |
|
220 | + } |
|
221 | + |
|
222 | + /** |
|
223 | + * @param int $type The share type |
|
224 | + * @param string $path The path to share relative to $initiators root |
|
225 | + * @param string $initiator |
|
226 | + * @param string $recipient |
|
227 | + * @param int $permissions |
|
228 | + * @return IShare |
|
229 | + */ |
|
230 | + protected function share($type, $path, $initiator, $recipient, $permissions) { |
|
231 | + $userFolder = $this->rootFolder->getUserFolder($initiator); |
|
232 | + $node = $userFolder->get($path); |
|
233 | + |
|
234 | + $share = $this->shareManager->newShare(); |
|
235 | + $share->setShareType($type) |
|
236 | + ->setSharedWith($recipient) |
|
237 | + ->setSharedBy($initiator) |
|
238 | + ->setNode($node) |
|
239 | + ->setPermissions($permissions); |
|
240 | + $share = $this->shareManager->createShare($share); |
|
241 | + $share->setStatus(IShare::STATUS_ACCEPTED); |
|
242 | + $share = $this->shareManager->updateShare($share); |
|
243 | + |
|
244 | + return $share; |
|
245 | + } |
|
246 | 246 | } |
@@ -74,12 +74,12 @@ discard block |
||
74 | 74 | public function getAvatarDark(string $userId, int $size, bool $guestFallback = false) { |
75 | 75 | if ($size <= 64) { |
76 | 76 | if ($size !== 64) { |
77 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
77 | + $this->logger->debug('Avatar requested in deprecated size '.$size); |
|
78 | 78 | } |
79 | 79 | $size = 64; |
80 | 80 | } else { |
81 | 81 | if ($size !== 512) { |
82 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
82 | + $this->logger->debug('Avatar requested in deprecated size '.$size); |
|
83 | 83 | } |
84 | 84 | $size = 512; |
85 | 85 | } |
@@ -90,7 +90,7 @@ discard block |
||
90 | 90 | $response = new FileDisplayResponse( |
91 | 91 | $avatarFile, |
92 | 92 | Http::STATUS_OK, |
93 | - ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()] |
|
93 | + ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int) $avatar->isCustomAvatar()] |
|
94 | 94 | ); |
95 | 95 | } catch (\Exception $e) { |
96 | 96 | if ($guestFallback) { |
@@ -126,12 +126,12 @@ discard block |
||
126 | 126 | public function getAvatar(string $userId, int $size, bool $guestFallback = false) { |
127 | 127 | if ($size <= 64) { |
128 | 128 | if ($size !== 64) { |
129 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
129 | + $this->logger->debug('Avatar requested in deprecated size '.$size); |
|
130 | 130 | } |
131 | 131 | $size = 64; |
132 | 132 | } else { |
133 | 133 | if ($size !== 512) { |
134 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
134 | + $this->logger->debug('Avatar requested in deprecated size '.$size); |
|
135 | 135 | } |
136 | 136 | $size = 512; |
137 | 137 | } |
@@ -142,7 +142,7 @@ discard block |
||
142 | 142 | $response = new FileDisplayResponse( |
143 | 143 | $avatarFile, |
144 | 144 | Http::STATUS_OK, |
145 | - ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()] |
|
145 | + ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int) $avatar->isCustomAvatar()] |
|
146 | 146 | ); |
147 | 147 | } catch (\Exception $e) { |
148 | 148 | if ($guestFallback) { |
@@ -311,7 +311,7 @@ discard block |
||
311 | 311 | Http::STATUS_OK, |
312 | 312 | ['Content-Type' => $image->mimeType()]); |
313 | 313 | |
314 | - $resp->setETag((string)crc32($image->data() ?? '')); |
|
314 | + $resp->setETag((string) crc32($image->data() ?? '')); |
|
315 | 315 | $resp->cacheFor(0); |
316 | 316 | $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT'))); |
317 | 317 | return $resp; |
@@ -340,7 +340,7 @@ discard block |
||
340 | 340 | |
341 | 341 | $image = new Image(); |
342 | 342 | $image->loadFromData($tmpAvatar); |
343 | - $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h'])); |
|
343 | + $image->crop($crop['x'], $crop['y'], (int) round($crop['w']), (int) round($crop['h'])); |
|
344 | 344 | try { |
345 | 345 | $avatar = $this->avatarManager->getAvatar($this->userId); |
346 | 346 | $avatar->set($image); |
@@ -37,322 +37,322 @@ |
||
37 | 37 | * @package OC\Core\Controller |
38 | 38 | */ |
39 | 39 | class AvatarController extends Controller { |
40 | - public function __construct( |
|
41 | - string $appName, |
|
42 | - IRequest $request, |
|
43 | - protected IAvatarManager $avatarManager, |
|
44 | - protected ICache $cache, |
|
45 | - protected IL10N $l10n, |
|
46 | - protected IUserManager $userManager, |
|
47 | - protected IRootFolder $rootFolder, |
|
48 | - protected LoggerInterface $logger, |
|
49 | - protected ?string $userId, |
|
50 | - protected TimeFactory $timeFactory, |
|
51 | - protected GuestAvatarController $guestAvatarController, |
|
52 | - ) { |
|
53 | - parent::__construct($appName, $request); |
|
54 | - } |
|
40 | + public function __construct( |
|
41 | + string $appName, |
|
42 | + IRequest $request, |
|
43 | + protected IAvatarManager $avatarManager, |
|
44 | + protected ICache $cache, |
|
45 | + protected IL10N $l10n, |
|
46 | + protected IUserManager $userManager, |
|
47 | + protected IRootFolder $rootFolder, |
|
48 | + protected LoggerInterface $logger, |
|
49 | + protected ?string $userId, |
|
50 | + protected TimeFactory $timeFactory, |
|
51 | + protected GuestAvatarController $guestAvatarController, |
|
52 | + ) { |
|
53 | + parent::__construct($appName, $request); |
|
54 | + } |
|
55 | 55 | |
56 | - /** |
|
57 | - * @NoSameSiteCookieRequired |
|
58 | - * |
|
59 | - * Get the dark avatar |
|
60 | - * |
|
61 | - * @param string $userId ID of the user |
|
62 | - * @param 64|512 $size Size of the avatar |
|
63 | - * @param bool $guestFallback Fallback to guest avatar if not found |
|
64 | - * @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, list<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}> |
|
65 | - * |
|
66 | - * 200: Avatar returned |
|
67 | - * 201: Avatar returned |
|
68 | - * 404: Avatar not found |
|
69 | - */ |
|
70 | - #[NoCSRFRequired] |
|
71 | - #[PublicPage] |
|
72 | - #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}/dark')] |
|
73 | - #[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)] |
|
74 | - public function getAvatarDark(string $userId, int $size, bool $guestFallback = false) { |
|
75 | - if ($size <= 64) { |
|
76 | - if ($size !== 64) { |
|
77 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
78 | - } |
|
79 | - $size = 64; |
|
80 | - } else { |
|
81 | - if ($size !== 512) { |
|
82 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
83 | - } |
|
84 | - $size = 512; |
|
85 | - } |
|
56 | + /** |
|
57 | + * @NoSameSiteCookieRequired |
|
58 | + * |
|
59 | + * Get the dark avatar |
|
60 | + * |
|
61 | + * @param string $userId ID of the user |
|
62 | + * @param 64|512 $size Size of the avatar |
|
63 | + * @param bool $guestFallback Fallback to guest avatar if not found |
|
64 | + * @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, list<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}> |
|
65 | + * |
|
66 | + * 200: Avatar returned |
|
67 | + * 201: Avatar returned |
|
68 | + * 404: Avatar not found |
|
69 | + */ |
|
70 | + #[NoCSRFRequired] |
|
71 | + #[PublicPage] |
|
72 | + #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}/dark')] |
|
73 | + #[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)] |
|
74 | + public function getAvatarDark(string $userId, int $size, bool $guestFallback = false) { |
|
75 | + if ($size <= 64) { |
|
76 | + if ($size !== 64) { |
|
77 | + $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
78 | + } |
|
79 | + $size = 64; |
|
80 | + } else { |
|
81 | + if ($size !== 512) { |
|
82 | + $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
83 | + } |
|
84 | + $size = 512; |
|
85 | + } |
|
86 | 86 | |
87 | - try { |
|
88 | - $avatar = $this->avatarManager->getAvatar($userId); |
|
89 | - $avatarFile = $avatar->getFile($size, true); |
|
90 | - $response = new FileDisplayResponse( |
|
91 | - $avatarFile, |
|
92 | - Http::STATUS_OK, |
|
93 | - ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()] |
|
94 | - ); |
|
95 | - } catch (\Exception $e) { |
|
96 | - if ($guestFallback) { |
|
97 | - return $this->guestAvatarController->getAvatarDark($userId, $size); |
|
98 | - } |
|
99 | - return new JSONResponse([], Http::STATUS_NOT_FOUND); |
|
100 | - } |
|
87 | + try { |
|
88 | + $avatar = $this->avatarManager->getAvatar($userId); |
|
89 | + $avatarFile = $avatar->getFile($size, true); |
|
90 | + $response = new FileDisplayResponse( |
|
91 | + $avatarFile, |
|
92 | + Http::STATUS_OK, |
|
93 | + ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()] |
|
94 | + ); |
|
95 | + } catch (\Exception $e) { |
|
96 | + if ($guestFallback) { |
|
97 | + return $this->guestAvatarController->getAvatarDark($userId, $size); |
|
98 | + } |
|
99 | + return new JSONResponse([], Http::STATUS_NOT_FOUND); |
|
100 | + } |
|
101 | 101 | |
102 | - // Cache for 1 day |
|
103 | - $response->cacheFor(60 * 60 * 24, false, true); |
|
104 | - return $response; |
|
105 | - } |
|
102 | + // Cache for 1 day |
|
103 | + $response->cacheFor(60 * 60 * 24, false, true); |
|
104 | + return $response; |
|
105 | + } |
|
106 | 106 | |
107 | 107 | |
108 | - /** |
|
109 | - * @NoSameSiteCookieRequired |
|
110 | - * |
|
111 | - * Get the avatar |
|
112 | - * |
|
113 | - * @param string $userId ID of the user |
|
114 | - * @param 64|512 $size Size of the avatar |
|
115 | - * @param bool $guestFallback Fallback to guest avatar if not found |
|
116 | - * @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, list<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}> |
|
117 | - * |
|
118 | - * 200: Avatar returned |
|
119 | - * 201: Avatar returned |
|
120 | - * 404: Avatar not found |
|
121 | - */ |
|
122 | - #[NoCSRFRequired] |
|
123 | - #[PublicPage] |
|
124 | - #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}')] |
|
125 | - #[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)] |
|
126 | - public function getAvatar(string $userId, int $size, bool $guestFallback = false) { |
|
127 | - if ($size <= 64) { |
|
128 | - if ($size !== 64) { |
|
129 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
130 | - } |
|
131 | - $size = 64; |
|
132 | - } else { |
|
133 | - if ($size !== 512) { |
|
134 | - $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
135 | - } |
|
136 | - $size = 512; |
|
137 | - } |
|
108 | + /** |
|
109 | + * @NoSameSiteCookieRequired |
|
110 | + * |
|
111 | + * Get the avatar |
|
112 | + * |
|
113 | + * @param string $userId ID of the user |
|
114 | + * @param 64|512 $size Size of the avatar |
|
115 | + * @param bool $guestFallback Fallback to guest avatar if not found |
|
116 | + * @return FileDisplayResponse<Http::STATUS_OK|Http::STATUS_CREATED, array{Content-Type: string, X-NC-IsCustomAvatar: int}>|JSONResponse<Http::STATUS_NOT_FOUND, list<empty>, array{}>|Response<Http::STATUS_INTERNAL_SERVER_ERROR, array{}> |
|
117 | + * |
|
118 | + * 200: Avatar returned |
|
119 | + * 201: Avatar returned |
|
120 | + * 404: Avatar not found |
|
121 | + */ |
|
122 | + #[NoCSRFRequired] |
|
123 | + #[PublicPage] |
|
124 | + #[FrontpageRoute(verb: 'GET', url: '/avatar/{userId}/{size}')] |
|
125 | + #[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT)] |
|
126 | + public function getAvatar(string $userId, int $size, bool $guestFallback = false) { |
|
127 | + if ($size <= 64) { |
|
128 | + if ($size !== 64) { |
|
129 | + $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
130 | + } |
|
131 | + $size = 64; |
|
132 | + } else { |
|
133 | + if ($size !== 512) { |
|
134 | + $this->logger->debug('Avatar requested in deprecated size ' . $size); |
|
135 | + } |
|
136 | + $size = 512; |
|
137 | + } |
|
138 | 138 | |
139 | - try { |
|
140 | - $avatar = $this->avatarManager->getAvatar($userId); |
|
141 | - $avatarFile = $avatar->getFile($size); |
|
142 | - $response = new FileDisplayResponse( |
|
143 | - $avatarFile, |
|
144 | - Http::STATUS_OK, |
|
145 | - ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()] |
|
146 | - ); |
|
147 | - } catch (\Exception $e) { |
|
148 | - if ($guestFallback) { |
|
149 | - return $this->guestAvatarController->getAvatar($userId, $size); |
|
150 | - } |
|
151 | - return new JSONResponse([], Http::STATUS_NOT_FOUND); |
|
152 | - } |
|
139 | + try { |
|
140 | + $avatar = $this->avatarManager->getAvatar($userId); |
|
141 | + $avatarFile = $avatar->getFile($size); |
|
142 | + $response = new FileDisplayResponse( |
|
143 | + $avatarFile, |
|
144 | + Http::STATUS_OK, |
|
145 | + ['Content-Type' => $avatarFile->getMimeType(), 'X-NC-IsCustomAvatar' => (int)$avatar->isCustomAvatar()] |
|
146 | + ); |
|
147 | + } catch (\Exception $e) { |
|
148 | + if ($guestFallback) { |
|
149 | + return $this->guestAvatarController->getAvatar($userId, $size); |
|
150 | + } |
|
151 | + return new JSONResponse([], Http::STATUS_NOT_FOUND); |
|
152 | + } |
|
153 | 153 | |
154 | - // Cache for 1 day |
|
155 | - $response->cacheFor(60 * 60 * 24, false, true); |
|
156 | - return $response; |
|
157 | - } |
|
154 | + // Cache for 1 day |
|
155 | + $response->cacheFor(60 * 60 * 24, false, true); |
|
156 | + return $response; |
|
157 | + } |
|
158 | 158 | |
159 | - #[NoAdminRequired] |
|
160 | - #[FrontpageRoute(verb: 'POST', url: '/avatar/')] |
|
161 | - public function postAvatar(?string $path = null): JSONResponse { |
|
162 | - $files = $this->request->getUploadedFile('files'); |
|
159 | + #[NoAdminRequired] |
|
160 | + #[FrontpageRoute(verb: 'POST', url: '/avatar/')] |
|
161 | + public function postAvatar(?string $path = null): JSONResponse { |
|
162 | + $files = $this->request->getUploadedFile('files'); |
|
163 | 163 | |
164 | - if (isset($path)) { |
|
165 | - $path = stripslashes($path); |
|
166 | - $userFolder = $this->rootFolder->getUserFolder($this->userId); |
|
167 | - /** @var File $node */ |
|
168 | - $node = $userFolder->get($path); |
|
169 | - if (!($node instanceof File)) { |
|
170 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('Please select a file.')]]); |
|
171 | - } |
|
172 | - if ($node->getSize() > 20 * 1024 * 1024) { |
|
173 | - return new JSONResponse( |
|
174 | - ['data' => ['message' => $this->l10n->t('File is too big')]], |
|
175 | - Http::STATUS_BAD_REQUEST |
|
176 | - ); |
|
177 | - } |
|
164 | + if (isset($path)) { |
|
165 | + $path = stripslashes($path); |
|
166 | + $userFolder = $this->rootFolder->getUserFolder($this->userId); |
|
167 | + /** @var File $node */ |
|
168 | + $node = $userFolder->get($path); |
|
169 | + if (!($node instanceof File)) { |
|
170 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('Please select a file.')]]); |
|
171 | + } |
|
172 | + if ($node->getSize() > 20 * 1024 * 1024) { |
|
173 | + return new JSONResponse( |
|
174 | + ['data' => ['message' => $this->l10n->t('File is too big')]], |
|
175 | + Http::STATUS_BAD_REQUEST |
|
176 | + ); |
|
177 | + } |
|
178 | 178 | |
179 | - if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') { |
|
180 | - return new JSONResponse( |
|
181 | - ['data' => ['message' => $this->l10n->t('The selected file is not an image.')]], |
|
182 | - Http::STATUS_BAD_REQUEST |
|
183 | - ); |
|
184 | - } |
|
179 | + if ($node->getMimeType() !== 'image/jpeg' && $node->getMimeType() !== 'image/png') { |
|
180 | + return new JSONResponse( |
|
181 | + ['data' => ['message' => $this->l10n->t('The selected file is not an image.')]], |
|
182 | + Http::STATUS_BAD_REQUEST |
|
183 | + ); |
|
184 | + } |
|
185 | 185 | |
186 | - try { |
|
187 | - $content = $node->getContent(); |
|
188 | - } catch (NotPermittedException $e) { |
|
189 | - return new JSONResponse( |
|
190 | - ['data' => ['message' => $this->l10n->t('The selected file cannot be read.')]], |
|
191 | - Http::STATUS_BAD_REQUEST |
|
192 | - ); |
|
193 | - } |
|
194 | - } elseif (!is_null($files)) { |
|
195 | - if ( |
|
196 | - $files['error'][0] === 0 |
|
197 | - && is_uploaded_file($files['tmp_name'][0]) |
|
198 | - ) { |
|
199 | - if ($files['size'][0] > 20 * 1024 * 1024) { |
|
200 | - return new JSONResponse( |
|
201 | - ['data' => ['message' => $this->l10n->t('File is too big')]], |
|
202 | - Http::STATUS_BAD_REQUEST |
|
203 | - ); |
|
204 | - } |
|
205 | - $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200); |
|
206 | - $content = $this->cache->get('avatar_upload'); |
|
207 | - unlink($files['tmp_name'][0]); |
|
208 | - } else { |
|
209 | - $phpFileUploadErrors = [ |
|
210 | - UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'), |
|
211 | - UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'), |
|
212 | - UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'), |
|
213 | - UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'), |
|
214 | - UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'), |
|
215 | - UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'), |
|
216 | - UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'), |
|
217 | - UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'), |
|
218 | - ]; |
|
219 | - $message = $phpFileUploadErrors[$files['error'][0]] ?? $this->l10n->t('Invalid file provided'); |
|
220 | - $this->logger->warning($message, ['app' => 'core']); |
|
221 | - return new JSONResponse( |
|
222 | - ['data' => ['message' => $message]], |
|
223 | - Http::STATUS_BAD_REQUEST |
|
224 | - ); |
|
225 | - } |
|
226 | - } else { |
|
227 | - //Add imgfile |
|
228 | - return new JSONResponse( |
|
229 | - ['data' => ['message' => $this->l10n->t('No image or file provided')]], |
|
230 | - Http::STATUS_BAD_REQUEST |
|
231 | - ); |
|
232 | - } |
|
186 | + try { |
|
187 | + $content = $node->getContent(); |
|
188 | + } catch (NotPermittedException $e) { |
|
189 | + return new JSONResponse( |
|
190 | + ['data' => ['message' => $this->l10n->t('The selected file cannot be read.')]], |
|
191 | + Http::STATUS_BAD_REQUEST |
|
192 | + ); |
|
193 | + } |
|
194 | + } elseif (!is_null($files)) { |
|
195 | + if ( |
|
196 | + $files['error'][0] === 0 |
|
197 | + && is_uploaded_file($files['tmp_name'][0]) |
|
198 | + ) { |
|
199 | + if ($files['size'][0] > 20 * 1024 * 1024) { |
|
200 | + return new JSONResponse( |
|
201 | + ['data' => ['message' => $this->l10n->t('File is too big')]], |
|
202 | + Http::STATUS_BAD_REQUEST |
|
203 | + ); |
|
204 | + } |
|
205 | + $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200); |
|
206 | + $content = $this->cache->get('avatar_upload'); |
|
207 | + unlink($files['tmp_name'][0]); |
|
208 | + } else { |
|
209 | + $phpFileUploadErrors = [ |
|
210 | + UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'), |
|
211 | + UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'), |
|
212 | + UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'), |
|
213 | + UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'), |
|
214 | + UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'), |
|
215 | + UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'), |
|
216 | + UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'), |
|
217 | + UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'), |
|
218 | + ]; |
|
219 | + $message = $phpFileUploadErrors[$files['error'][0]] ?? $this->l10n->t('Invalid file provided'); |
|
220 | + $this->logger->warning($message, ['app' => 'core']); |
|
221 | + return new JSONResponse( |
|
222 | + ['data' => ['message' => $message]], |
|
223 | + Http::STATUS_BAD_REQUEST |
|
224 | + ); |
|
225 | + } |
|
226 | + } else { |
|
227 | + //Add imgfile |
|
228 | + return new JSONResponse( |
|
229 | + ['data' => ['message' => $this->l10n->t('No image or file provided')]], |
|
230 | + Http::STATUS_BAD_REQUEST |
|
231 | + ); |
|
232 | + } |
|
233 | 233 | |
234 | - try { |
|
235 | - $image = new Image(); |
|
236 | - $image->loadFromData($content); |
|
237 | - $image->readExif($content); |
|
238 | - $image->fixOrientation(); |
|
234 | + try { |
|
235 | + $image = new Image(); |
|
236 | + $image->loadFromData($content); |
|
237 | + $image->readExif($content); |
|
238 | + $image->fixOrientation(); |
|
239 | 239 | |
240 | - if ($image->valid()) { |
|
241 | - $mimeType = $image->mimeType(); |
|
242 | - if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') { |
|
243 | - return new JSONResponse( |
|
244 | - ['data' => ['message' => $this->l10n->t('Unknown filetype')]], |
|
245 | - Http::STATUS_OK |
|
246 | - ); |
|
247 | - } |
|
240 | + if ($image->valid()) { |
|
241 | + $mimeType = $image->mimeType(); |
|
242 | + if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') { |
|
243 | + return new JSONResponse( |
|
244 | + ['data' => ['message' => $this->l10n->t('Unknown filetype')]], |
|
245 | + Http::STATUS_OK |
|
246 | + ); |
|
247 | + } |
|
248 | 248 | |
249 | - if ($image->width() === $image->height()) { |
|
250 | - try { |
|
251 | - $avatar = $this->avatarManager->getAvatar($this->userId); |
|
252 | - $avatar->set($image); |
|
253 | - // Clean up |
|
254 | - $this->cache->remove('tmpAvatar'); |
|
255 | - return new JSONResponse(['status' => 'success']); |
|
256 | - } catch (\Throwable $e) { |
|
257 | - $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
258 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST); |
|
259 | - } |
|
260 | - } |
|
249 | + if ($image->width() === $image->height()) { |
|
250 | + try { |
|
251 | + $avatar = $this->avatarManager->getAvatar($this->userId); |
|
252 | + $avatar->set($image); |
|
253 | + // Clean up |
|
254 | + $this->cache->remove('tmpAvatar'); |
|
255 | + return new JSONResponse(['status' => 'success']); |
|
256 | + } catch (\Throwable $e) { |
|
257 | + $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
258 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST); |
|
259 | + } |
|
260 | + } |
|
261 | 261 | |
262 | - $this->cache->set('tmpAvatar', $image->data(), 7200); |
|
263 | - return new JSONResponse( |
|
264 | - ['data' => 'notsquare'], |
|
265 | - Http::STATUS_OK |
|
266 | - ); |
|
267 | - } else { |
|
268 | - return new JSONResponse( |
|
269 | - ['data' => ['message' => $this->l10n->t('Invalid image')]], |
|
270 | - Http::STATUS_OK |
|
271 | - ); |
|
272 | - } |
|
273 | - } catch (\Exception $e) { |
|
274 | - $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
275 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK); |
|
276 | - } |
|
277 | - } |
|
262 | + $this->cache->set('tmpAvatar', $image->data(), 7200); |
|
263 | + return new JSONResponse( |
|
264 | + ['data' => 'notsquare'], |
|
265 | + Http::STATUS_OK |
|
266 | + ); |
|
267 | + } else { |
|
268 | + return new JSONResponse( |
|
269 | + ['data' => ['message' => $this->l10n->t('Invalid image')]], |
|
270 | + Http::STATUS_OK |
|
271 | + ); |
|
272 | + } |
|
273 | + } catch (\Exception $e) { |
|
274 | + $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
275 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_OK); |
|
276 | + } |
|
277 | + } |
|
278 | 278 | |
279 | - #[NoAdminRequired] |
|
280 | - #[FrontpageRoute(verb: 'DELETE', url: '/avatar/')] |
|
281 | - public function deleteAvatar(): JSONResponse { |
|
282 | - try { |
|
283 | - $avatar = $this->avatarManager->getAvatar($this->userId); |
|
284 | - $avatar->remove(); |
|
285 | - return new JSONResponse(); |
|
286 | - } catch (\Exception $e) { |
|
287 | - $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
288 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST); |
|
289 | - } |
|
290 | - } |
|
279 | + #[NoAdminRequired] |
|
280 | + #[FrontpageRoute(verb: 'DELETE', url: '/avatar/')] |
|
281 | + public function deleteAvatar(): JSONResponse { |
|
282 | + try { |
|
283 | + $avatar = $this->avatarManager->getAvatar($this->userId); |
|
284 | + $avatar->remove(); |
|
285 | + return new JSONResponse(); |
|
286 | + } catch (\Exception $e) { |
|
287 | + $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
288 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST); |
|
289 | + } |
|
290 | + } |
|
291 | 291 | |
292 | - /** |
|
293 | - * @return JSONResponse|DataDisplayResponse |
|
294 | - */ |
|
295 | - #[NoAdminRequired] |
|
296 | - #[FrontpageRoute(verb: 'GET', url: '/avatar/tmp')] |
|
297 | - public function getTmpAvatar() { |
|
298 | - $tmpAvatar = $this->cache->get('tmpAvatar'); |
|
299 | - if (is_null($tmpAvatar)) { |
|
300 | - return new JSONResponse(['data' => [ |
|
301 | - 'message' => $this->l10n->t('No temporary profile picture available, try again') |
|
302 | - ]], |
|
303 | - Http::STATUS_NOT_FOUND); |
|
304 | - } |
|
292 | + /** |
|
293 | + * @return JSONResponse|DataDisplayResponse |
|
294 | + */ |
|
295 | + #[NoAdminRequired] |
|
296 | + #[FrontpageRoute(verb: 'GET', url: '/avatar/tmp')] |
|
297 | + public function getTmpAvatar() { |
|
298 | + $tmpAvatar = $this->cache->get('tmpAvatar'); |
|
299 | + if (is_null($tmpAvatar)) { |
|
300 | + return new JSONResponse(['data' => [ |
|
301 | + 'message' => $this->l10n->t('No temporary profile picture available, try again') |
|
302 | + ]], |
|
303 | + Http::STATUS_NOT_FOUND); |
|
304 | + } |
|
305 | 305 | |
306 | - $image = new Image(); |
|
307 | - $image->loadFromData($tmpAvatar); |
|
306 | + $image = new Image(); |
|
307 | + $image->loadFromData($tmpAvatar); |
|
308 | 308 | |
309 | - $resp = new DataDisplayResponse( |
|
310 | - $image->data() ?? '', |
|
311 | - Http::STATUS_OK, |
|
312 | - ['Content-Type' => $image->mimeType()]); |
|
309 | + $resp = new DataDisplayResponse( |
|
310 | + $image->data() ?? '', |
|
311 | + Http::STATUS_OK, |
|
312 | + ['Content-Type' => $image->mimeType()]); |
|
313 | 313 | |
314 | - $resp->setETag((string)crc32($image->data() ?? '')); |
|
315 | - $resp->cacheFor(0); |
|
316 | - $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT'))); |
|
317 | - return $resp; |
|
318 | - } |
|
314 | + $resp->setETag((string)crc32($image->data() ?? '')); |
|
315 | + $resp->cacheFor(0); |
|
316 | + $resp->setLastModified(new \DateTime('now', new \DateTimeZone('GMT'))); |
|
317 | + return $resp; |
|
318 | + } |
|
319 | 319 | |
320 | - #[NoAdminRequired] |
|
321 | - #[FrontpageRoute(verb: 'POST', url: '/avatar/cropped')] |
|
322 | - public function postCroppedAvatar(?array $crop = null): JSONResponse { |
|
323 | - if (is_null($crop)) { |
|
324 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('No crop data provided')]], |
|
325 | - Http::STATUS_BAD_REQUEST); |
|
326 | - } |
|
320 | + #[NoAdminRequired] |
|
321 | + #[FrontpageRoute(verb: 'POST', url: '/avatar/cropped')] |
|
322 | + public function postCroppedAvatar(?array $crop = null): JSONResponse { |
|
323 | + if (is_null($crop)) { |
|
324 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('No crop data provided')]], |
|
325 | + Http::STATUS_BAD_REQUEST); |
|
326 | + } |
|
327 | 327 | |
328 | - if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) { |
|
329 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('No valid crop data provided')]], |
|
330 | - Http::STATUS_BAD_REQUEST); |
|
331 | - } |
|
328 | + if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) { |
|
329 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('No valid crop data provided')]], |
|
330 | + Http::STATUS_BAD_REQUEST); |
|
331 | + } |
|
332 | 332 | |
333 | - $tmpAvatar = $this->cache->get('tmpAvatar'); |
|
334 | - if (is_null($tmpAvatar)) { |
|
335 | - return new JSONResponse(['data' => [ |
|
336 | - 'message' => $this->l10n->t('No temporary profile picture available, try again') |
|
337 | - ]], |
|
338 | - Http::STATUS_BAD_REQUEST); |
|
339 | - } |
|
333 | + $tmpAvatar = $this->cache->get('tmpAvatar'); |
|
334 | + if (is_null($tmpAvatar)) { |
|
335 | + return new JSONResponse(['data' => [ |
|
336 | + 'message' => $this->l10n->t('No temporary profile picture available, try again') |
|
337 | + ]], |
|
338 | + Http::STATUS_BAD_REQUEST); |
|
339 | + } |
|
340 | 340 | |
341 | - $image = new Image(); |
|
342 | - $image->loadFromData($tmpAvatar); |
|
343 | - $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h'])); |
|
344 | - try { |
|
345 | - $avatar = $this->avatarManager->getAvatar($this->userId); |
|
346 | - $avatar->set($image); |
|
347 | - // Clean up |
|
348 | - $this->cache->remove('tmpAvatar'); |
|
349 | - return new JSONResponse(['status' => 'success']); |
|
350 | - } catch (NotSquareException $e) { |
|
351 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('Crop is not square')]], |
|
352 | - Http::STATUS_BAD_REQUEST); |
|
353 | - } catch (\Exception $e) { |
|
354 | - $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
355 | - return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST); |
|
356 | - } |
|
357 | - } |
|
341 | + $image = new Image(); |
|
342 | + $image->loadFromData($tmpAvatar); |
|
343 | + $image->crop($crop['x'], $crop['y'], (int)round($crop['w']), (int)round($crop['h'])); |
|
344 | + try { |
|
345 | + $avatar = $this->avatarManager->getAvatar($this->userId); |
|
346 | + $avatar->set($image); |
|
347 | + // Clean up |
|
348 | + $this->cache->remove('tmpAvatar'); |
|
349 | + return new JSONResponse(['status' => 'success']); |
|
350 | + } catch (NotSquareException $e) { |
|
351 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('Crop is not square')]], |
|
352 | + Http::STATUS_BAD_REQUEST); |
|
353 | + } catch (\Exception $e) { |
|
354 | + $this->logger->error($e->getMessage(), ['exception' => $e, 'app' => 'core']); |
|
355 | + return new JSONResponse(['data' => ['message' => $this->l10n->t('An error occurred. Please contact your admin.')]], Http::STATUS_BAD_REQUEST); |
|
356 | + } |
|
357 | + } |
|
358 | 358 | } |
@@ -15,50 +15,50 @@ |
||
15 | 15 | * @package Test\Cache |
16 | 16 | */ |
17 | 17 | class CappedMemoryCacheTest extends TestCache { |
18 | - protected function setUp(): void { |
|
19 | - parent::setUp(); |
|
20 | - $this->instance = new CappedMemoryCache(); |
|
21 | - } |
|
18 | + protected function setUp(): void { |
|
19 | + parent::setUp(); |
|
20 | + $this->instance = new CappedMemoryCache(); |
|
21 | + } |
|
22 | 22 | |
23 | - public function testSetOverCap(): void { |
|
24 | - $instance = new CappedMemoryCache(3); |
|
23 | + public function testSetOverCap(): void { |
|
24 | + $instance = new CappedMemoryCache(3); |
|
25 | 25 | |
26 | - $instance->set('1', 'a'); |
|
27 | - $instance->set('2', 'b'); |
|
28 | - $instance->set('3', 'c'); |
|
29 | - $instance->set('4', 'd'); |
|
30 | - $instance->set('5', 'e'); |
|
26 | + $instance->set('1', 'a'); |
|
27 | + $instance->set('2', 'b'); |
|
28 | + $instance->set('3', 'c'); |
|
29 | + $instance->set('4', 'd'); |
|
30 | + $instance->set('5', 'e'); |
|
31 | 31 | |
32 | - $this->assertFalse($instance->hasKey('1')); |
|
33 | - $this->assertFalse($instance->hasKey('2')); |
|
34 | - $this->assertTrue($instance->hasKey('3')); |
|
35 | - $this->assertTrue($instance->hasKey('4')); |
|
36 | - $this->assertTrue($instance->hasKey('5')); |
|
37 | - } |
|
32 | + $this->assertFalse($instance->hasKey('1')); |
|
33 | + $this->assertFalse($instance->hasKey('2')); |
|
34 | + $this->assertTrue($instance->hasKey('3')); |
|
35 | + $this->assertTrue($instance->hasKey('4')); |
|
36 | + $this->assertTrue($instance->hasKey('5')); |
|
37 | + } |
|
38 | 38 | |
39 | - public function testClear(): void { |
|
40 | - $value = 'ipsum lorum'; |
|
41 | - $this->instance->set('1_value1', $value); |
|
42 | - $this->instance->set('1_value2', $value); |
|
43 | - $this->instance->set('2_value1', $value); |
|
44 | - $this->instance->set('3_value1', $value); |
|
39 | + public function testClear(): void { |
|
40 | + $value = 'ipsum lorum'; |
|
41 | + $this->instance->set('1_value1', $value); |
|
42 | + $this->instance->set('1_value2', $value); |
|
43 | + $this->instance->set('2_value1', $value); |
|
44 | + $this->instance->set('3_value1', $value); |
|
45 | 45 | |
46 | - $this->assertTrue($this->instance->clear()); |
|
47 | - $this->assertFalse($this->instance->hasKey('1_value1')); |
|
48 | - $this->assertFalse($this->instance->hasKey('1_value2')); |
|
49 | - $this->assertFalse($this->instance->hasKey('2_value1')); |
|
50 | - $this->assertFalse($this->instance->hasKey('3_value1')); |
|
51 | - } |
|
46 | + $this->assertTrue($this->instance->clear()); |
|
47 | + $this->assertFalse($this->instance->hasKey('1_value1')); |
|
48 | + $this->assertFalse($this->instance->hasKey('1_value2')); |
|
49 | + $this->assertFalse($this->instance->hasKey('2_value1')); |
|
50 | + $this->assertFalse($this->instance->hasKey('3_value1')); |
|
51 | + } |
|
52 | 52 | |
53 | - public function testIndirectSet(): void { |
|
54 | - $this->instance->set('array', []); |
|
53 | + public function testIndirectSet(): void { |
|
54 | + $this->instance->set('array', []); |
|
55 | 55 | |
56 | - $this->instance['array'][] = 'foo'; |
|
56 | + $this->instance['array'][] = 'foo'; |
|
57 | 57 | |
58 | - $this->assertEquals(['foo'], $this->instance->get('array')); |
|
58 | + $this->assertEquals(['foo'], $this->instance->get('array')); |
|
59 | 59 | |
60 | - $this->instance['array']['bar'] = 'qwerty'; |
|
60 | + $this->instance['array']['bar'] = 'qwerty'; |
|
61 | 61 | |
62 | - $this->assertEquals(['foo', 'bar' => 'qwerty'], $this->instance->get('array')); |
|
63 | - } |
|
62 | + $this->assertEquals(['foo', 'bar' => 'qwerty'], $this->instance->get('array')); |
|
63 | + } |
|
64 | 64 | } |
@@ -12,7 +12,7 @@ discard block |
||
12 | 12 | * proper unit testing of the postAvatar call. |
13 | 13 | */ |
14 | 14 | function is_uploaded_file($filename) { |
15 | - return file_exists($filename); |
|
15 | + return file_exists($filename); |
|
16 | 16 | } |
17 | 17 | |
18 | 18 | namespace Tests\Core\Controller; |
@@ -41,526 +41,526 @@ discard block |
||
41 | 41 | * @package OC\Core\Controller |
42 | 42 | */ |
43 | 43 | class AvatarControllerTest extends \Test\TestCase { |
44 | - /** @var AvatarController */ |
|
45 | - private $avatarController; |
|
46 | - /** @var GuestAvatarController */ |
|
47 | - private $guestAvatarController; |
|
48 | - |
|
49 | - /** @var IAvatar|\PHPUnit\Framework\MockObject\MockObject */ |
|
50 | - private $avatarMock; |
|
51 | - /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ |
|
52 | - private $userMock; |
|
53 | - /** @var ISimpleFile|\PHPUnit\Framework\MockObject\MockObject */ |
|
54 | - private $avatarFile; |
|
55 | - /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */ |
|
56 | - private $avatarManager; |
|
57 | - /** @var ICache|\PHPUnit\Framework\MockObject\MockObject */ |
|
58 | - private $cache; |
|
59 | - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ |
|
60 | - private $l; |
|
61 | - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ |
|
62 | - private $userManager; |
|
63 | - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ |
|
64 | - private $rootFolder; |
|
65 | - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ |
|
66 | - private $logger; |
|
67 | - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ |
|
68 | - private $request; |
|
69 | - /** @var TimeFactory|\PHPUnit\Framework\MockObject\MockObject */ |
|
70 | - private $timeFactory; |
|
71 | - |
|
72 | - protected function setUp(): void { |
|
73 | - parent::setUp(); |
|
74 | - |
|
75 | - $this->avatarManager = $this->getMockBuilder('OCP\IAvatarManager')->getMock(); |
|
76 | - $this->cache = $this->getMockBuilder('OCP\ICache') |
|
77 | - ->disableOriginalConstructor()->getMock(); |
|
78 | - $this->l = $this->getMockBuilder(IL10N::class)->getMock(); |
|
79 | - $this->l->method('t')->willReturnArgument(0); |
|
80 | - $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); |
|
81 | - $this->request = $this->getMockBuilder(IRequest::class)->getMock(); |
|
82 | - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->getMock(); |
|
83 | - $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); |
|
84 | - $this->timeFactory = $this->getMockBuilder('OC\AppFramework\Utility\TimeFactory')->getMock(); |
|
85 | - |
|
86 | - $this->avatarMock = $this->getMockBuilder('OCP\IAvatar')->getMock(); |
|
87 | - $this->userMock = $this->getMockBuilder(IUser::class)->getMock(); |
|
88 | - |
|
89 | - $this->guestAvatarController = new GuestAvatarController( |
|
90 | - 'core', |
|
91 | - $this->request, |
|
92 | - $this->avatarManager, |
|
93 | - $this->logger |
|
94 | - ); |
|
95 | - |
|
96 | - $this->avatarController = new AvatarController( |
|
97 | - 'core', |
|
98 | - $this->request, |
|
99 | - $this->avatarManager, |
|
100 | - $this->cache, |
|
101 | - $this->l, |
|
102 | - $this->userManager, |
|
103 | - $this->rootFolder, |
|
104 | - $this->logger, |
|
105 | - 'userid', |
|
106 | - $this->timeFactory, |
|
107 | - $this->guestAvatarController, |
|
108 | - ); |
|
109 | - |
|
110 | - // Configure userMock |
|
111 | - $this->userMock->method('getDisplayName')->willReturn('displayName'); |
|
112 | - $this->userMock->method('getUID')->willReturn('userId'); |
|
113 | - $this->userManager->method('get') |
|
114 | - ->willReturnMap([['userId', $this->userMock]]); |
|
115 | - |
|
116 | - $this->avatarFile = $this->getMockBuilder(ISimpleFile::class)->getMock(); |
|
117 | - $this->avatarFile->method('getContent')->willReturn('image data'); |
|
118 | - $this->avatarFile->method('getMimeType')->willReturn('image type'); |
|
119 | - $this->avatarFile->method('getEtag')->willReturn('my etag'); |
|
120 | - $this->avatarFile->method('getName')->willReturn('my name'); |
|
121 | - $this->avatarFile->method('getMTime')->willReturn(42); |
|
122 | - } |
|
123 | - |
|
124 | - protected function tearDown(): void { |
|
125 | - parent::tearDown(); |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * Fetch an avatar if a user has no avatar |
|
130 | - */ |
|
131 | - public function testGetAvatarNoAvatar(): void { |
|
132 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
133 | - $this->avatarMock->method('getFile')->willThrowException(new NotFoundException()); |
|
134 | - $response = $this->avatarController->getAvatar('userId', 32); |
|
135 | - |
|
136 | - //Comment out until JS is fixed |
|
137 | - $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); |
|
138 | - } |
|
139 | - |
|
140 | - /** |
|
141 | - * Fetch the user's avatar |
|
142 | - */ |
|
143 | - public function testGetAvatar(): void { |
|
144 | - $this->avatarMock->method('getFile')->willReturn($this->avatarFile); |
|
145 | - $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock); |
|
146 | - $this->avatarMock->expects($this->once()) |
|
147 | - ->method('isCustomAvatar') |
|
148 | - ->willReturn(true); |
|
149 | - |
|
150 | - $response = $this->avatarController->getAvatar('userId', 32); |
|
151 | - |
|
152 | - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
153 | - $this->assertArrayHasKey('Content-Type', $response->getHeaders()); |
|
154 | - $this->assertEquals('image type', $response->getHeaders()['Content-Type']); |
|
155 | - $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders()); |
|
156 | - $this->assertEquals('1', $response->getHeaders()['X-NC-IsCustomAvatar']); |
|
157 | - |
|
158 | - $this->assertEquals('my etag', $response->getETag()); |
|
159 | - } |
|
160 | - |
|
161 | - /** |
|
162 | - * Fetch the user's avatar |
|
163 | - */ |
|
164 | - public function testGetGeneratedAvatar(): void { |
|
165 | - $this->avatarMock->method('getFile')->willReturn($this->avatarFile); |
|
166 | - $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock); |
|
167 | - |
|
168 | - $response = $this->avatarController->getAvatar('userId', 32); |
|
169 | - |
|
170 | - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
171 | - $this->assertArrayHasKey('Content-Type', $response->getHeaders()); |
|
172 | - $this->assertEquals('image type', $response->getHeaders()['Content-Type']); |
|
173 | - $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders()); |
|
174 | - $this->assertEquals('0', $response->getHeaders()['X-NC-IsCustomAvatar']); |
|
175 | - |
|
176 | - $this->assertEquals('my etag', $response->getETag()); |
|
177 | - } |
|
178 | - |
|
179 | - /** |
|
180 | - * Fetch the avatar of a non-existing user |
|
181 | - */ |
|
182 | - public function testGetAvatarNoUser(): void { |
|
183 | - $this->avatarManager |
|
184 | - ->method('getAvatar') |
|
185 | - ->with('userDoesNotExist') |
|
186 | - ->willThrowException(new \Exception('user does not exist')); |
|
187 | - |
|
188 | - $response = $this->avatarController->getAvatar('userDoesNotExist', 32); |
|
189 | - |
|
190 | - //Comment out until JS is fixed |
|
191 | - $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); |
|
192 | - } |
|
193 | - |
|
194 | - public function testGetAvatarSize64(): void { |
|
195 | - $this->avatarMock->expects($this->once()) |
|
196 | - ->method('getFile') |
|
197 | - ->with($this->equalTo(64)) |
|
198 | - ->willReturn($this->avatarFile); |
|
199 | - |
|
200 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
201 | - |
|
202 | - $this->logger->expects($this->never()) |
|
203 | - ->method('debug'); |
|
204 | - |
|
205 | - $this->avatarController->getAvatar('userId', 64); |
|
206 | - } |
|
207 | - |
|
208 | - public function testGetAvatarSize512(): void { |
|
209 | - $this->avatarMock->expects($this->once()) |
|
210 | - ->method('getFile') |
|
211 | - ->with($this->equalTo(512)) |
|
212 | - ->willReturn($this->avatarFile); |
|
213 | - |
|
214 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
215 | - |
|
216 | - $this->logger->expects($this->never()) |
|
217 | - ->method('debug'); |
|
218 | - |
|
219 | - $this->avatarController->getAvatar('userId', 512); |
|
220 | - } |
|
221 | - |
|
222 | - /** |
|
223 | - * Small sizes return 64 and generate a log |
|
224 | - */ |
|
225 | - public function testGetAvatarSizeTooSmall(): void { |
|
226 | - $this->avatarMock->expects($this->once()) |
|
227 | - ->method('getFile') |
|
228 | - ->with($this->equalTo(64)) |
|
229 | - ->willReturn($this->avatarFile); |
|
230 | - |
|
231 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
232 | - |
|
233 | - $this->logger->expects($this->once()) |
|
234 | - ->method('debug') |
|
235 | - ->with('Avatar requested in deprecated size 32'); |
|
236 | - |
|
237 | - $this->avatarController->getAvatar('userId', 32); |
|
238 | - } |
|
239 | - |
|
240 | - /** |
|
241 | - * Avatars between 64 and 512 are upgraded to 512 |
|
242 | - */ |
|
243 | - public function testGetAvatarSizeBetween(): void { |
|
244 | - $this->avatarMock->expects($this->once()) |
|
245 | - ->method('getFile') |
|
246 | - ->with($this->equalTo(512)) |
|
247 | - ->willReturn($this->avatarFile); |
|
248 | - |
|
249 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
250 | - |
|
251 | - $this->logger->expects($this->once()) |
|
252 | - ->method('debug') |
|
253 | - ->with('Avatar requested in deprecated size 65'); |
|
254 | - |
|
255 | - $this->avatarController->getAvatar('userId', 65); |
|
256 | - } |
|
257 | - |
|
258 | - /** |
|
259 | - * We do not support avatars larger than 512 |
|
260 | - */ |
|
261 | - public function testGetAvatarSizeTooBig(): void { |
|
262 | - $this->avatarMock->expects($this->once()) |
|
263 | - ->method('getFile') |
|
264 | - ->with($this->equalTo(512)) |
|
265 | - ->willReturn($this->avatarFile); |
|
266 | - |
|
267 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
268 | - |
|
269 | - $this->logger->expects($this->once()) |
|
270 | - ->method('debug') |
|
271 | - ->with('Avatar requested in deprecated size 513'); |
|
272 | - |
|
273 | - $this->avatarController->getAvatar('userId', 513); |
|
274 | - } |
|
275 | - |
|
276 | - /** |
|
277 | - * Remove an avatar |
|
278 | - */ |
|
279 | - public function testDeleteAvatar(): void { |
|
280 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
281 | - |
|
282 | - $response = $this->avatarController->deleteAvatar(); |
|
283 | - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
284 | - } |
|
285 | - |
|
286 | - /** |
|
287 | - * Test what happens if the removing of the avatar fails |
|
288 | - */ |
|
289 | - public function testDeleteAvatarException(): void { |
|
290 | - $this->avatarMock->method('remove')->willThrowException(new \Exception('foo')); |
|
291 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
292 | - |
|
293 | - $this->logger->expects($this->once()) |
|
294 | - ->method('error') |
|
295 | - ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']); |
|
296 | - $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); |
|
297 | - $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar()); |
|
298 | - } |
|
299 | - |
|
300 | - /** |
|
301 | - * Trying to get a tmp avatar when it is not available. 404 |
|
302 | - */ |
|
303 | - public function testTmpAvatarNoTmp(): void { |
|
304 | - $response = $this->avatarController->getTmpAvatar(); |
|
305 | - $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); |
|
306 | - } |
|
307 | - |
|
308 | - /** |
|
309 | - * Fetch tmp avatar |
|
310 | - */ |
|
311 | - public function testTmpAvatarValid(): void { |
|
312 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
313 | - |
|
314 | - $response = $this->avatarController->getTmpAvatar(); |
|
315 | - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
316 | - } |
|
317 | - |
|
318 | - |
|
319 | - /** |
|
320 | - * When trying to post a new avatar a path or image should be posted. |
|
321 | - */ |
|
322 | - public function testPostAvatarNoPathOrImage(): void { |
|
323 | - $response = $this->avatarController->postAvatar(null); |
|
324 | - |
|
325 | - $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
326 | - } |
|
327 | - |
|
328 | - /** |
|
329 | - * Test a correct post of an avatar using POST |
|
330 | - */ |
|
331 | - public function testPostAvatarFile(): void { |
|
332 | - //Create temp file |
|
333 | - $fileName = tempnam('', 'avatarTest'); |
|
334 | - $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.jpg', $fileName); |
|
335 | - $this->assertTrue($copyRes); |
|
336 | - |
|
337 | - //Create file in cache |
|
338 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
339 | - |
|
340 | - //Create request return |
|
341 | - $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.jpg')]]; |
|
342 | - $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
343 | - |
|
344 | - $response = $this->avatarController->postAvatar(null); |
|
345 | - |
|
346 | - //On correct upload always respond with the notsquare message |
|
347 | - $this->assertEquals('notsquare', $response->getData()['data']); |
|
348 | - |
|
349 | - //File should be deleted |
|
350 | - $this->assertFalse(file_exists($fileName)); |
|
351 | - } |
|
352 | - |
|
353 | - /** |
|
354 | - * Test invalid post os an avatar using POST |
|
355 | - */ |
|
356 | - public function testPostAvatarInvalidFile(): void { |
|
357 | - //Create request return |
|
358 | - $reqRet = ['error' => [1], 'tmp_name' => ['foo']]; |
|
359 | - $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
360 | - |
|
361 | - $response = $this->avatarController->postAvatar(null); |
|
362 | - |
|
363 | - $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
364 | - } |
|
365 | - |
|
366 | - /** |
|
367 | - * Check what happens when we upload a GIF |
|
368 | - */ |
|
369 | - public function testPostAvatarFileGif(): void { |
|
370 | - //Create temp file |
|
371 | - $fileName = tempnam('', 'avatarTest'); |
|
372 | - $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.gif', $fileName); |
|
373 | - $this->assertTrue($copyRes); |
|
374 | - |
|
375 | - //Create file in cache |
|
376 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.gif')); |
|
377 | - |
|
378 | - //Create request return |
|
379 | - $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.gif')]]; |
|
380 | - $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
381 | - |
|
382 | - $response = $this->avatarController->postAvatar(null); |
|
383 | - |
|
384 | - $this->assertEquals('Unknown filetype', $response->getData()['data']['message']); |
|
385 | - |
|
386 | - //File should be deleted |
|
387 | - $this->assertFalse(file_exists($fileName)); |
|
388 | - } |
|
389 | - |
|
390 | - /** |
|
391 | - * Test posting avatar from existing file |
|
392 | - */ |
|
393 | - public function testPostAvatarFromFile(): void { |
|
394 | - //Mock node API call |
|
395 | - $file = $this->getMockBuilder('OCP\Files\File') |
|
396 | - ->disableOriginalConstructor()->getMock(); |
|
397 | - $file->expects($this->once()) |
|
398 | - ->method('getContent') |
|
399 | - ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
400 | - $file->expects($this->once()) |
|
401 | - ->method('getMimeType') |
|
402 | - ->willReturn('image/jpeg'); |
|
403 | - $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
404 | - $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
405 | - $userFolder->method('get')->willReturn($file); |
|
406 | - |
|
407 | - //Create request return |
|
408 | - $response = $this->avatarController->postAvatar('avatar.jpg'); |
|
409 | - |
|
410 | - //On correct upload always respond with the notsquare message |
|
411 | - $this->assertEquals('notsquare', $response->getData()['data']); |
|
412 | - } |
|
413 | - |
|
414 | - /** |
|
415 | - * Test posting avatar from existing folder |
|
416 | - */ |
|
417 | - public function testPostAvatarFromNoFile(): void { |
|
418 | - $file = $this->getMockBuilder('OCP\Files\Node')->getMock(); |
|
419 | - $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
420 | - $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
421 | - $userFolder |
|
422 | - ->method('get') |
|
423 | - ->with('folder') |
|
424 | - ->willReturn($file); |
|
425 | - |
|
426 | - //Create request return |
|
427 | - $response = $this->avatarController->postAvatar('folder'); |
|
428 | - |
|
429 | - //On correct upload always respond with the notsquare message |
|
430 | - $this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData()); |
|
431 | - } |
|
432 | - |
|
433 | - public function testPostAvatarInvalidType(): void { |
|
434 | - $file = $this->getMockBuilder('OCP\Files\File') |
|
435 | - ->disableOriginalConstructor()->getMock(); |
|
436 | - $file->expects($this->never()) |
|
437 | - ->method('getContent'); |
|
438 | - $file->expects($this->exactly(2)) |
|
439 | - ->method('getMimeType') |
|
440 | - ->willReturn('text/plain'); |
|
441 | - $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
442 | - $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
443 | - $userFolder->method('get')->willReturn($file); |
|
444 | - |
|
445 | - $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file is not an image.']], Http::STATUS_BAD_REQUEST); |
|
446 | - $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); |
|
447 | - } |
|
448 | - |
|
449 | - public function testPostAvatarNotPermittedException(): void { |
|
450 | - $file = $this->getMockBuilder('OCP\Files\File') |
|
451 | - ->disableOriginalConstructor()->getMock(); |
|
452 | - $file->expects($this->once()) |
|
453 | - ->method('getContent') |
|
454 | - ->willThrowException(new NotPermittedException()); |
|
455 | - $file->expects($this->once()) |
|
456 | - ->method('getMimeType') |
|
457 | - ->willReturn('image/jpeg'); |
|
458 | - $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
459 | - $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
460 | - $userFolder->method('get')->willReturn($file); |
|
461 | - |
|
462 | - $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file cannot be read.']], Http::STATUS_BAD_REQUEST); |
|
463 | - $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); |
|
464 | - } |
|
465 | - |
|
466 | - /** |
|
467 | - * Test what happens if the upload of the avatar fails |
|
468 | - */ |
|
469 | - public function testPostAvatarException(): void { |
|
470 | - $this->cache->expects($this->once()) |
|
471 | - ->method('set') |
|
472 | - ->willThrowException(new \Exception('foo')); |
|
473 | - $file = $this->getMockBuilder('OCP\Files\File') |
|
474 | - ->disableOriginalConstructor()->getMock(); |
|
475 | - $file->expects($this->once()) |
|
476 | - ->method('getContent') |
|
477 | - ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
478 | - $file->expects($this->once()) |
|
479 | - ->method('getMimeType') |
|
480 | - ->willReturn('image/jpeg'); |
|
481 | - $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
482 | - $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
483 | - $userFolder->method('get')->willReturn($file); |
|
484 | - |
|
485 | - $this->logger->expects($this->once()) |
|
486 | - ->method('error') |
|
487 | - ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']); |
|
488 | - $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK); |
|
489 | - $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); |
|
490 | - } |
|
491 | - |
|
492 | - |
|
493 | - /** |
|
494 | - * Test invalid crop argument |
|
495 | - */ |
|
496 | - public function testPostCroppedAvatarInvalidCrop(): void { |
|
497 | - $response = $this->avatarController->postCroppedAvatar([]); |
|
498 | - |
|
499 | - $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
500 | - } |
|
501 | - |
|
502 | - /** |
|
503 | - * Test no tmp avatar to crop |
|
504 | - */ |
|
505 | - public function testPostCroppedAvatarNoTmpAvatar(): void { |
|
506 | - $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]); |
|
507 | - |
|
508 | - $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
509 | - } |
|
510 | - |
|
511 | - /** |
|
512 | - * Test with non square crop |
|
513 | - */ |
|
514 | - public function testPostCroppedAvatarNoSquareCrop(): void { |
|
515 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
516 | - |
|
517 | - $this->avatarMock->method('set')->willThrowException(new \OC\NotSquareException); |
|
518 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
519 | - $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]); |
|
520 | - |
|
521 | - $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
522 | - } |
|
523 | - |
|
524 | - /** |
|
525 | - * Check for proper reply on proper crop argument |
|
526 | - */ |
|
527 | - public function testPostCroppedAvatarValidCrop(): void { |
|
528 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
529 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
530 | - $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]); |
|
531 | - |
|
532 | - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
533 | - $this->assertEquals('success', $response->getData()['status']); |
|
534 | - } |
|
535 | - |
|
536 | - /** |
|
537 | - * Test what happens if the cropping of the avatar fails |
|
538 | - */ |
|
539 | - public function testPostCroppedAvatarException(): void { |
|
540 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
541 | - |
|
542 | - $this->avatarMock->method('set')->willThrowException(new \Exception('foo')); |
|
543 | - $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
544 | - |
|
545 | - $this->logger->expects($this->once()) |
|
546 | - ->method('error') |
|
547 | - ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']); |
|
548 | - $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); |
|
549 | - $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11])); |
|
550 | - } |
|
551 | - |
|
552 | - |
|
553 | - /** |
|
554 | - * Check for proper reply on proper crop argument |
|
555 | - */ |
|
556 | - public function testFileTooBig(): void { |
|
557 | - $fileName = \OC::$SERVERROOT . '/tests/data/testimage.jpg'; |
|
558 | - //Create request return |
|
559 | - $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]]; |
|
560 | - $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
561 | - |
|
562 | - $response = $this->avatarController->postAvatar(null); |
|
563 | - |
|
564 | - $this->assertEquals('File is too big', $response->getData()['data']['message']); |
|
565 | - } |
|
44 | + /** @var AvatarController */ |
|
45 | + private $avatarController; |
|
46 | + /** @var GuestAvatarController */ |
|
47 | + private $guestAvatarController; |
|
48 | + |
|
49 | + /** @var IAvatar|\PHPUnit\Framework\MockObject\MockObject */ |
|
50 | + private $avatarMock; |
|
51 | + /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ |
|
52 | + private $userMock; |
|
53 | + /** @var ISimpleFile|\PHPUnit\Framework\MockObject\MockObject */ |
|
54 | + private $avatarFile; |
|
55 | + /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */ |
|
56 | + private $avatarManager; |
|
57 | + /** @var ICache|\PHPUnit\Framework\MockObject\MockObject */ |
|
58 | + private $cache; |
|
59 | + /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ |
|
60 | + private $l; |
|
61 | + /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ |
|
62 | + private $userManager; |
|
63 | + /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ |
|
64 | + private $rootFolder; |
|
65 | + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ |
|
66 | + private $logger; |
|
67 | + /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ |
|
68 | + private $request; |
|
69 | + /** @var TimeFactory|\PHPUnit\Framework\MockObject\MockObject */ |
|
70 | + private $timeFactory; |
|
71 | + |
|
72 | + protected function setUp(): void { |
|
73 | + parent::setUp(); |
|
74 | + |
|
75 | + $this->avatarManager = $this->getMockBuilder('OCP\IAvatarManager')->getMock(); |
|
76 | + $this->cache = $this->getMockBuilder('OCP\ICache') |
|
77 | + ->disableOriginalConstructor()->getMock(); |
|
78 | + $this->l = $this->getMockBuilder(IL10N::class)->getMock(); |
|
79 | + $this->l->method('t')->willReturnArgument(0); |
|
80 | + $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); |
|
81 | + $this->request = $this->getMockBuilder(IRequest::class)->getMock(); |
|
82 | + $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->getMock(); |
|
83 | + $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); |
|
84 | + $this->timeFactory = $this->getMockBuilder('OC\AppFramework\Utility\TimeFactory')->getMock(); |
|
85 | + |
|
86 | + $this->avatarMock = $this->getMockBuilder('OCP\IAvatar')->getMock(); |
|
87 | + $this->userMock = $this->getMockBuilder(IUser::class)->getMock(); |
|
88 | + |
|
89 | + $this->guestAvatarController = new GuestAvatarController( |
|
90 | + 'core', |
|
91 | + $this->request, |
|
92 | + $this->avatarManager, |
|
93 | + $this->logger |
|
94 | + ); |
|
95 | + |
|
96 | + $this->avatarController = new AvatarController( |
|
97 | + 'core', |
|
98 | + $this->request, |
|
99 | + $this->avatarManager, |
|
100 | + $this->cache, |
|
101 | + $this->l, |
|
102 | + $this->userManager, |
|
103 | + $this->rootFolder, |
|
104 | + $this->logger, |
|
105 | + 'userid', |
|
106 | + $this->timeFactory, |
|
107 | + $this->guestAvatarController, |
|
108 | + ); |
|
109 | + |
|
110 | + // Configure userMock |
|
111 | + $this->userMock->method('getDisplayName')->willReturn('displayName'); |
|
112 | + $this->userMock->method('getUID')->willReturn('userId'); |
|
113 | + $this->userManager->method('get') |
|
114 | + ->willReturnMap([['userId', $this->userMock]]); |
|
115 | + |
|
116 | + $this->avatarFile = $this->getMockBuilder(ISimpleFile::class)->getMock(); |
|
117 | + $this->avatarFile->method('getContent')->willReturn('image data'); |
|
118 | + $this->avatarFile->method('getMimeType')->willReturn('image type'); |
|
119 | + $this->avatarFile->method('getEtag')->willReturn('my etag'); |
|
120 | + $this->avatarFile->method('getName')->willReturn('my name'); |
|
121 | + $this->avatarFile->method('getMTime')->willReturn(42); |
|
122 | + } |
|
123 | + |
|
124 | + protected function tearDown(): void { |
|
125 | + parent::tearDown(); |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * Fetch an avatar if a user has no avatar |
|
130 | + */ |
|
131 | + public function testGetAvatarNoAvatar(): void { |
|
132 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
133 | + $this->avatarMock->method('getFile')->willThrowException(new NotFoundException()); |
|
134 | + $response = $this->avatarController->getAvatar('userId', 32); |
|
135 | + |
|
136 | + //Comment out until JS is fixed |
|
137 | + $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); |
|
138 | + } |
|
139 | + |
|
140 | + /** |
|
141 | + * Fetch the user's avatar |
|
142 | + */ |
|
143 | + public function testGetAvatar(): void { |
|
144 | + $this->avatarMock->method('getFile')->willReturn($this->avatarFile); |
|
145 | + $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock); |
|
146 | + $this->avatarMock->expects($this->once()) |
|
147 | + ->method('isCustomAvatar') |
|
148 | + ->willReturn(true); |
|
149 | + |
|
150 | + $response = $this->avatarController->getAvatar('userId', 32); |
|
151 | + |
|
152 | + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
153 | + $this->assertArrayHasKey('Content-Type', $response->getHeaders()); |
|
154 | + $this->assertEquals('image type', $response->getHeaders()['Content-Type']); |
|
155 | + $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders()); |
|
156 | + $this->assertEquals('1', $response->getHeaders()['X-NC-IsCustomAvatar']); |
|
157 | + |
|
158 | + $this->assertEquals('my etag', $response->getETag()); |
|
159 | + } |
|
160 | + |
|
161 | + /** |
|
162 | + * Fetch the user's avatar |
|
163 | + */ |
|
164 | + public function testGetGeneratedAvatar(): void { |
|
165 | + $this->avatarMock->method('getFile')->willReturn($this->avatarFile); |
|
166 | + $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock); |
|
167 | + |
|
168 | + $response = $this->avatarController->getAvatar('userId', 32); |
|
169 | + |
|
170 | + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
171 | + $this->assertArrayHasKey('Content-Type', $response->getHeaders()); |
|
172 | + $this->assertEquals('image type', $response->getHeaders()['Content-Type']); |
|
173 | + $this->assertArrayHasKey('X-NC-IsCustomAvatar', $response->getHeaders()); |
|
174 | + $this->assertEquals('0', $response->getHeaders()['X-NC-IsCustomAvatar']); |
|
175 | + |
|
176 | + $this->assertEquals('my etag', $response->getETag()); |
|
177 | + } |
|
178 | + |
|
179 | + /** |
|
180 | + * Fetch the avatar of a non-existing user |
|
181 | + */ |
|
182 | + public function testGetAvatarNoUser(): void { |
|
183 | + $this->avatarManager |
|
184 | + ->method('getAvatar') |
|
185 | + ->with('userDoesNotExist') |
|
186 | + ->willThrowException(new \Exception('user does not exist')); |
|
187 | + |
|
188 | + $response = $this->avatarController->getAvatar('userDoesNotExist', 32); |
|
189 | + |
|
190 | + //Comment out until JS is fixed |
|
191 | + $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); |
|
192 | + } |
|
193 | + |
|
194 | + public function testGetAvatarSize64(): void { |
|
195 | + $this->avatarMock->expects($this->once()) |
|
196 | + ->method('getFile') |
|
197 | + ->with($this->equalTo(64)) |
|
198 | + ->willReturn($this->avatarFile); |
|
199 | + |
|
200 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
201 | + |
|
202 | + $this->logger->expects($this->never()) |
|
203 | + ->method('debug'); |
|
204 | + |
|
205 | + $this->avatarController->getAvatar('userId', 64); |
|
206 | + } |
|
207 | + |
|
208 | + public function testGetAvatarSize512(): void { |
|
209 | + $this->avatarMock->expects($this->once()) |
|
210 | + ->method('getFile') |
|
211 | + ->with($this->equalTo(512)) |
|
212 | + ->willReturn($this->avatarFile); |
|
213 | + |
|
214 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
215 | + |
|
216 | + $this->logger->expects($this->never()) |
|
217 | + ->method('debug'); |
|
218 | + |
|
219 | + $this->avatarController->getAvatar('userId', 512); |
|
220 | + } |
|
221 | + |
|
222 | + /** |
|
223 | + * Small sizes return 64 and generate a log |
|
224 | + */ |
|
225 | + public function testGetAvatarSizeTooSmall(): void { |
|
226 | + $this->avatarMock->expects($this->once()) |
|
227 | + ->method('getFile') |
|
228 | + ->with($this->equalTo(64)) |
|
229 | + ->willReturn($this->avatarFile); |
|
230 | + |
|
231 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
232 | + |
|
233 | + $this->logger->expects($this->once()) |
|
234 | + ->method('debug') |
|
235 | + ->with('Avatar requested in deprecated size 32'); |
|
236 | + |
|
237 | + $this->avatarController->getAvatar('userId', 32); |
|
238 | + } |
|
239 | + |
|
240 | + /** |
|
241 | + * Avatars between 64 and 512 are upgraded to 512 |
|
242 | + */ |
|
243 | + public function testGetAvatarSizeBetween(): void { |
|
244 | + $this->avatarMock->expects($this->once()) |
|
245 | + ->method('getFile') |
|
246 | + ->with($this->equalTo(512)) |
|
247 | + ->willReturn($this->avatarFile); |
|
248 | + |
|
249 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
250 | + |
|
251 | + $this->logger->expects($this->once()) |
|
252 | + ->method('debug') |
|
253 | + ->with('Avatar requested in deprecated size 65'); |
|
254 | + |
|
255 | + $this->avatarController->getAvatar('userId', 65); |
|
256 | + } |
|
257 | + |
|
258 | + /** |
|
259 | + * We do not support avatars larger than 512 |
|
260 | + */ |
|
261 | + public function testGetAvatarSizeTooBig(): void { |
|
262 | + $this->avatarMock->expects($this->once()) |
|
263 | + ->method('getFile') |
|
264 | + ->with($this->equalTo(512)) |
|
265 | + ->willReturn($this->avatarFile); |
|
266 | + |
|
267 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
268 | + |
|
269 | + $this->logger->expects($this->once()) |
|
270 | + ->method('debug') |
|
271 | + ->with('Avatar requested in deprecated size 513'); |
|
272 | + |
|
273 | + $this->avatarController->getAvatar('userId', 513); |
|
274 | + } |
|
275 | + |
|
276 | + /** |
|
277 | + * Remove an avatar |
|
278 | + */ |
|
279 | + public function testDeleteAvatar(): void { |
|
280 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
281 | + |
|
282 | + $response = $this->avatarController->deleteAvatar(); |
|
283 | + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
284 | + } |
|
285 | + |
|
286 | + /** |
|
287 | + * Test what happens if the removing of the avatar fails |
|
288 | + */ |
|
289 | + public function testDeleteAvatarException(): void { |
|
290 | + $this->avatarMock->method('remove')->willThrowException(new \Exception('foo')); |
|
291 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
292 | + |
|
293 | + $this->logger->expects($this->once()) |
|
294 | + ->method('error') |
|
295 | + ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']); |
|
296 | + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); |
|
297 | + $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar()); |
|
298 | + } |
|
299 | + |
|
300 | + /** |
|
301 | + * Trying to get a tmp avatar when it is not available. 404 |
|
302 | + */ |
|
303 | + public function testTmpAvatarNoTmp(): void { |
|
304 | + $response = $this->avatarController->getTmpAvatar(); |
|
305 | + $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); |
|
306 | + } |
|
307 | + |
|
308 | + /** |
|
309 | + * Fetch tmp avatar |
|
310 | + */ |
|
311 | + public function testTmpAvatarValid(): void { |
|
312 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
313 | + |
|
314 | + $response = $this->avatarController->getTmpAvatar(); |
|
315 | + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
316 | + } |
|
317 | + |
|
318 | + |
|
319 | + /** |
|
320 | + * When trying to post a new avatar a path or image should be posted. |
|
321 | + */ |
|
322 | + public function testPostAvatarNoPathOrImage(): void { |
|
323 | + $response = $this->avatarController->postAvatar(null); |
|
324 | + |
|
325 | + $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
326 | + } |
|
327 | + |
|
328 | + /** |
|
329 | + * Test a correct post of an avatar using POST |
|
330 | + */ |
|
331 | + public function testPostAvatarFile(): void { |
|
332 | + //Create temp file |
|
333 | + $fileName = tempnam('', 'avatarTest'); |
|
334 | + $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.jpg', $fileName); |
|
335 | + $this->assertTrue($copyRes); |
|
336 | + |
|
337 | + //Create file in cache |
|
338 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
339 | + |
|
340 | + //Create request return |
|
341 | + $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.jpg')]]; |
|
342 | + $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
343 | + |
|
344 | + $response = $this->avatarController->postAvatar(null); |
|
345 | + |
|
346 | + //On correct upload always respond with the notsquare message |
|
347 | + $this->assertEquals('notsquare', $response->getData()['data']); |
|
348 | + |
|
349 | + //File should be deleted |
|
350 | + $this->assertFalse(file_exists($fileName)); |
|
351 | + } |
|
352 | + |
|
353 | + /** |
|
354 | + * Test invalid post os an avatar using POST |
|
355 | + */ |
|
356 | + public function testPostAvatarInvalidFile(): void { |
|
357 | + //Create request return |
|
358 | + $reqRet = ['error' => [1], 'tmp_name' => ['foo']]; |
|
359 | + $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
360 | + |
|
361 | + $response = $this->avatarController->postAvatar(null); |
|
362 | + |
|
363 | + $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
364 | + } |
|
365 | + |
|
366 | + /** |
|
367 | + * Check what happens when we upload a GIF |
|
368 | + */ |
|
369 | + public function testPostAvatarFileGif(): void { |
|
370 | + //Create temp file |
|
371 | + $fileName = tempnam('', 'avatarTest'); |
|
372 | + $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.gif', $fileName); |
|
373 | + $this->assertTrue($copyRes); |
|
374 | + |
|
375 | + //Create file in cache |
|
376 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.gif')); |
|
377 | + |
|
378 | + //Create request return |
|
379 | + $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.gif')]]; |
|
380 | + $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
381 | + |
|
382 | + $response = $this->avatarController->postAvatar(null); |
|
383 | + |
|
384 | + $this->assertEquals('Unknown filetype', $response->getData()['data']['message']); |
|
385 | + |
|
386 | + //File should be deleted |
|
387 | + $this->assertFalse(file_exists($fileName)); |
|
388 | + } |
|
389 | + |
|
390 | + /** |
|
391 | + * Test posting avatar from existing file |
|
392 | + */ |
|
393 | + public function testPostAvatarFromFile(): void { |
|
394 | + //Mock node API call |
|
395 | + $file = $this->getMockBuilder('OCP\Files\File') |
|
396 | + ->disableOriginalConstructor()->getMock(); |
|
397 | + $file->expects($this->once()) |
|
398 | + ->method('getContent') |
|
399 | + ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
400 | + $file->expects($this->once()) |
|
401 | + ->method('getMimeType') |
|
402 | + ->willReturn('image/jpeg'); |
|
403 | + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
404 | + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
405 | + $userFolder->method('get')->willReturn($file); |
|
406 | + |
|
407 | + //Create request return |
|
408 | + $response = $this->avatarController->postAvatar('avatar.jpg'); |
|
409 | + |
|
410 | + //On correct upload always respond with the notsquare message |
|
411 | + $this->assertEquals('notsquare', $response->getData()['data']); |
|
412 | + } |
|
413 | + |
|
414 | + /** |
|
415 | + * Test posting avatar from existing folder |
|
416 | + */ |
|
417 | + public function testPostAvatarFromNoFile(): void { |
|
418 | + $file = $this->getMockBuilder('OCP\Files\Node')->getMock(); |
|
419 | + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
420 | + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
421 | + $userFolder |
|
422 | + ->method('get') |
|
423 | + ->with('folder') |
|
424 | + ->willReturn($file); |
|
425 | + |
|
426 | + //Create request return |
|
427 | + $response = $this->avatarController->postAvatar('folder'); |
|
428 | + |
|
429 | + //On correct upload always respond with the notsquare message |
|
430 | + $this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData()); |
|
431 | + } |
|
432 | + |
|
433 | + public function testPostAvatarInvalidType(): void { |
|
434 | + $file = $this->getMockBuilder('OCP\Files\File') |
|
435 | + ->disableOriginalConstructor()->getMock(); |
|
436 | + $file->expects($this->never()) |
|
437 | + ->method('getContent'); |
|
438 | + $file->expects($this->exactly(2)) |
|
439 | + ->method('getMimeType') |
|
440 | + ->willReturn('text/plain'); |
|
441 | + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
442 | + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
443 | + $userFolder->method('get')->willReturn($file); |
|
444 | + |
|
445 | + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file is not an image.']], Http::STATUS_BAD_REQUEST); |
|
446 | + $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); |
|
447 | + } |
|
448 | + |
|
449 | + public function testPostAvatarNotPermittedException(): void { |
|
450 | + $file = $this->getMockBuilder('OCP\Files\File') |
|
451 | + ->disableOriginalConstructor()->getMock(); |
|
452 | + $file->expects($this->once()) |
|
453 | + ->method('getContent') |
|
454 | + ->willThrowException(new NotPermittedException()); |
|
455 | + $file->expects($this->once()) |
|
456 | + ->method('getMimeType') |
|
457 | + ->willReturn('image/jpeg'); |
|
458 | + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
459 | + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
460 | + $userFolder->method('get')->willReturn($file); |
|
461 | + |
|
462 | + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'The selected file cannot be read.']], Http::STATUS_BAD_REQUEST); |
|
463 | + $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); |
|
464 | + } |
|
465 | + |
|
466 | + /** |
|
467 | + * Test what happens if the upload of the avatar fails |
|
468 | + */ |
|
469 | + public function testPostAvatarException(): void { |
|
470 | + $this->cache->expects($this->once()) |
|
471 | + ->method('set') |
|
472 | + ->willThrowException(new \Exception('foo')); |
|
473 | + $file = $this->getMockBuilder('OCP\Files\File') |
|
474 | + ->disableOriginalConstructor()->getMock(); |
|
475 | + $file->expects($this->once()) |
|
476 | + ->method('getContent') |
|
477 | + ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
478 | + $file->expects($this->once()) |
|
479 | + ->method('getMimeType') |
|
480 | + ->willReturn('image/jpeg'); |
|
481 | + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); |
|
482 | + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); |
|
483 | + $userFolder->method('get')->willReturn($file); |
|
484 | + |
|
485 | + $this->logger->expects($this->once()) |
|
486 | + ->method('error') |
|
487 | + ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']); |
|
488 | + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK); |
|
489 | + $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); |
|
490 | + } |
|
491 | + |
|
492 | + |
|
493 | + /** |
|
494 | + * Test invalid crop argument |
|
495 | + */ |
|
496 | + public function testPostCroppedAvatarInvalidCrop(): void { |
|
497 | + $response = $this->avatarController->postCroppedAvatar([]); |
|
498 | + |
|
499 | + $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
500 | + } |
|
501 | + |
|
502 | + /** |
|
503 | + * Test no tmp avatar to crop |
|
504 | + */ |
|
505 | + public function testPostCroppedAvatarNoTmpAvatar(): void { |
|
506 | + $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]); |
|
507 | + |
|
508 | + $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
509 | + } |
|
510 | + |
|
511 | + /** |
|
512 | + * Test with non square crop |
|
513 | + */ |
|
514 | + public function testPostCroppedAvatarNoSquareCrop(): void { |
|
515 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
516 | + |
|
517 | + $this->avatarMock->method('set')->willThrowException(new \OC\NotSquareException); |
|
518 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
519 | + $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]); |
|
520 | + |
|
521 | + $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); |
|
522 | + } |
|
523 | + |
|
524 | + /** |
|
525 | + * Check for proper reply on proper crop argument |
|
526 | + */ |
|
527 | + public function testPostCroppedAvatarValidCrop(): void { |
|
528 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
529 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
530 | + $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]); |
|
531 | + |
|
532 | + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
|
533 | + $this->assertEquals('success', $response->getData()['status']); |
|
534 | + } |
|
535 | + |
|
536 | + /** |
|
537 | + * Test what happens if the cropping of the avatar fails |
|
538 | + */ |
|
539 | + public function testPostCroppedAvatarException(): void { |
|
540 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
541 | + |
|
542 | + $this->avatarMock->method('set')->willThrowException(new \Exception('foo')); |
|
543 | + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
|
544 | + |
|
545 | + $this->logger->expects($this->once()) |
|
546 | + ->method('error') |
|
547 | + ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']); |
|
548 | + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); |
|
549 | + $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11])); |
|
550 | + } |
|
551 | + |
|
552 | + |
|
553 | + /** |
|
554 | + * Check for proper reply on proper crop argument |
|
555 | + */ |
|
556 | + public function testFileTooBig(): void { |
|
557 | + $fileName = \OC::$SERVERROOT . '/tests/data/testimage.jpg'; |
|
558 | + //Create request return |
|
559 | + $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]]; |
|
560 | + $this->request->method('getUploadedFile')->willReturn($reqRet); |
|
561 | + |
|
562 | + $response = $this->avatarController->postAvatar(null); |
|
563 | + |
|
564 | + $this->assertEquals('File is too big', $response->getData()['data']['message']); |
|
565 | + } |
|
566 | 566 | } |
@@ -309,7 +309,7 @@ discard block |
||
309 | 309 | * Fetch tmp avatar |
310 | 310 | */ |
311 | 311 | public function testTmpAvatarValid(): void { |
312 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
312 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
313 | 313 | |
314 | 314 | $response = $this->avatarController->getTmpAvatar(); |
315 | 315 | $this->assertEquals(Http::STATUS_OK, $response->getStatus()); |
@@ -331,14 +331,14 @@ discard block |
||
331 | 331 | public function testPostAvatarFile(): void { |
332 | 332 | //Create temp file |
333 | 333 | $fileName = tempnam('', 'avatarTest'); |
334 | - $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.jpg', $fileName); |
|
334 | + $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.jpg', $fileName); |
|
335 | 335 | $this->assertTrue($copyRes); |
336 | 336 | |
337 | 337 | //Create file in cache |
338 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
338 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
339 | 339 | |
340 | 340 | //Create request return |
341 | - $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.jpg')]]; |
|
341 | + $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]]; |
|
342 | 342 | $this->request->method('getUploadedFile')->willReturn($reqRet); |
343 | 343 | |
344 | 344 | $response = $this->avatarController->postAvatar(null); |
@@ -369,14 +369,14 @@ discard block |
||
369 | 369 | public function testPostAvatarFileGif(): void { |
370 | 370 | //Create temp file |
371 | 371 | $fileName = tempnam('', 'avatarTest'); |
372 | - $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.gif', $fileName); |
|
372 | + $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.gif', $fileName); |
|
373 | 373 | $this->assertTrue($copyRes); |
374 | 374 | |
375 | 375 | //Create file in cache |
376 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.gif')); |
|
376 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif')); |
|
377 | 377 | |
378 | 378 | //Create request return |
379 | - $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.gif')]]; |
|
379 | + $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')]]; |
|
380 | 380 | $this->request->method('getUploadedFile')->willReturn($reqRet); |
381 | 381 | |
382 | 382 | $response = $this->avatarController->postAvatar(null); |
@@ -396,7 +396,7 @@ discard block |
||
396 | 396 | ->disableOriginalConstructor()->getMock(); |
397 | 397 | $file->expects($this->once()) |
398 | 398 | ->method('getContent') |
399 | - ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
399 | + ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
400 | 400 | $file->expects($this->once()) |
401 | 401 | ->method('getMimeType') |
402 | 402 | ->willReturn('image/jpeg'); |
@@ -474,7 +474,7 @@ discard block |
||
474 | 474 | ->disableOriginalConstructor()->getMock(); |
475 | 475 | $file->expects($this->once()) |
476 | 476 | ->method('getContent') |
477 | - ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
477 | + ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
478 | 478 | $file->expects($this->once()) |
479 | 479 | ->method('getMimeType') |
480 | 480 | ->willReturn('image/jpeg'); |
@@ -512,7 +512,7 @@ discard block |
||
512 | 512 | * Test with non square crop |
513 | 513 | */ |
514 | 514 | public function testPostCroppedAvatarNoSquareCrop(): void { |
515 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
515 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
516 | 516 | |
517 | 517 | $this->avatarMock->method('set')->willThrowException(new \OC\NotSquareException); |
518 | 518 | $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
@@ -525,7 +525,7 @@ discard block |
||
525 | 525 | * Check for proper reply on proper crop argument |
526 | 526 | */ |
527 | 527 | public function testPostCroppedAvatarValidCrop(): void { |
528 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
528 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
529 | 529 | $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
530 | 530 | $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]); |
531 | 531 | |
@@ -537,7 +537,7 @@ discard block |
||
537 | 537 | * Test what happens if the cropping of the avatar fails |
538 | 538 | */ |
539 | 539 | public function testPostCroppedAvatarException(): void { |
540 | - $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg')); |
|
540 | + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); |
|
541 | 541 | |
542 | 542 | $this->avatarMock->method('set')->willThrowException(new \Exception('foo')); |
543 | 543 | $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); |
@@ -554,7 +554,7 @@ discard block |
||
554 | 554 | * Check for proper reply on proper crop argument |
555 | 555 | */ |
556 | 556 | public function testFileTooBig(): void { |
557 | - $fileName = \OC::$SERVERROOT . '/tests/data/testimage.jpg'; |
|
557 | + $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg'; |
|
558 | 558 | //Create request return |
559 | 559 | $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]]; |
560 | 560 | $this->request->method('getUploadedFile')->willReturn($reqRet); |
@@ -29,132 +29,132 @@ |
||
29 | 29 | * @package Test\Cache |
30 | 30 | */ |
31 | 31 | class FileCacheTest extends TestCache { |
32 | - use UserTrait; |
|
33 | - |
|
34 | - /** |
|
35 | - * @var string |
|
36 | - * */ |
|
37 | - private $user; |
|
38 | - /** |
|
39 | - * @var string |
|
40 | - * */ |
|
41 | - private $datadir; |
|
42 | - /** |
|
43 | - * @var Storage |
|
44 | - * */ |
|
45 | - private $storage; |
|
46 | - /** |
|
47 | - * @var View |
|
48 | - * */ |
|
49 | - private $rootView; |
|
50 | - |
|
51 | - public function skip() { |
|
52 | - //$this->skipUnless(OC_User::isLoggedIn()); |
|
53 | - } |
|
54 | - |
|
55 | - protected function setUp(): void { |
|
56 | - parent::setUp(); |
|
57 | - |
|
58 | - //login |
|
59 | - $this->createUser('test', 'test'); |
|
60 | - |
|
61 | - $this->user = \OC_User::getUser(); |
|
62 | - \OC_User::setUserId('test'); |
|
63 | - |
|
64 | - //clear all proxies and hooks so we can do clean testing |
|
65 | - \OC_Hook::clear('OC_Filesystem'); |
|
66 | - |
|
67 | - /** @var IMountManager $manager */ |
|
68 | - $manager = Server::get(IMountManager::class); |
|
69 | - $manager->removeMount('/test'); |
|
70 | - |
|
71 | - $storage = new Temporary([]); |
|
72 | - Filesystem::mount($storage, [], '/test/cache'); |
|
73 | - |
|
74 | - //set up the users dir |
|
75 | - $this->rootView = new View(''); |
|
76 | - $this->rootView->mkdir('/test'); |
|
77 | - |
|
78 | - $this->instance = new File(); |
|
79 | - |
|
80 | - // forces creation of cache folder for subsequent tests |
|
81 | - $this->instance->set('hack', 'hack'); |
|
82 | - } |
|
83 | - |
|
84 | - protected function tearDown(): void { |
|
85 | - if ($this->instance) { |
|
86 | - $this->instance->remove('hack', 'hack'); |
|
87 | - } |
|
88 | - |
|
89 | - \OC_User::setUserId($this->user); |
|
90 | - |
|
91 | - if ($this->instance) { |
|
92 | - $this->instance->clear(); |
|
93 | - $this->instance = null; |
|
94 | - } |
|
95 | - |
|
96 | - parent::tearDown(); |
|
97 | - } |
|
98 | - |
|
99 | - private function setupMockStorage() { |
|
100 | - $mockStorage = $this->getMockBuilder(Local::class) |
|
101 | - ->onlyMethods(['filemtime', 'unlink']) |
|
102 | - ->setConstructorArgs([['datadir' => Server::get(ITempManager::class)->getTemporaryFolder()]]) |
|
103 | - ->getMock(); |
|
104 | - |
|
105 | - Filesystem::mount($mockStorage, [], '/test/cache'); |
|
106 | - |
|
107 | - return $mockStorage; |
|
108 | - } |
|
109 | - |
|
110 | - public function testGarbageCollectOldKeys(): void { |
|
111 | - $mockStorage = $this->setupMockStorage(); |
|
112 | - |
|
113 | - $mockStorage->expects($this->atLeastOnce()) |
|
114 | - ->method('filemtime') |
|
115 | - ->willReturn(100); |
|
116 | - $mockStorage->expects($this->once()) |
|
117 | - ->method('unlink') |
|
118 | - ->with('key1') |
|
119 | - ->willReturn(true); |
|
120 | - |
|
121 | - $this->instance->set('key1', 'value1'); |
|
122 | - $this->instance->gc(); |
|
123 | - } |
|
124 | - |
|
125 | - public function testGarbageCollectLeaveRecentKeys(): void { |
|
126 | - $mockStorage = $this->setupMockStorage(); |
|
127 | - |
|
128 | - $mockStorage->expects($this->atLeastOnce()) |
|
129 | - ->method('filemtime') |
|
130 | - ->willReturn(time() + 3600); |
|
131 | - $mockStorage->expects($this->never()) |
|
132 | - ->method('unlink') |
|
133 | - ->with('key1'); |
|
134 | - $this->instance->set('key1', 'value1'); |
|
135 | - $this->instance->gc(); |
|
136 | - } |
|
137 | - |
|
138 | - public static function lockExceptionProvider(): array { |
|
139 | - return [ |
|
140 | - [new LockedException('key1')], |
|
141 | - [new LockNotAcquiredException('key1', 1)], |
|
142 | - ]; |
|
143 | - } |
|
144 | - |
|
145 | - #[\PHPUnit\Framework\Attributes\DataProvider('lockExceptionProvider')] |
|
146 | - public function testGarbageCollectIgnoreLockedKeys($testException): void { |
|
147 | - $mockStorage = $this->setupMockStorage(); |
|
148 | - |
|
149 | - $mockStorage->expects($this->atLeastOnce()) |
|
150 | - ->method('filemtime') |
|
151 | - ->willReturn(100); |
|
152 | - $mockStorage->expects($this->atLeastOnce()) |
|
153 | - ->method('unlink')->willReturnOnConsecutiveCalls($this->throwException($testException), $this->returnValue(true)); |
|
32 | + use UserTrait; |
|
33 | + |
|
34 | + /** |
|
35 | + * @var string |
|
36 | + * */ |
|
37 | + private $user; |
|
38 | + /** |
|
39 | + * @var string |
|
40 | + * */ |
|
41 | + private $datadir; |
|
42 | + /** |
|
43 | + * @var Storage |
|
44 | + * */ |
|
45 | + private $storage; |
|
46 | + /** |
|
47 | + * @var View |
|
48 | + * */ |
|
49 | + private $rootView; |
|
50 | + |
|
51 | + public function skip() { |
|
52 | + //$this->skipUnless(OC_User::isLoggedIn()); |
|
53 | + } |
|
54 | + |
|
55 | + protected function setUp(): void { |
|
56 | + parent::setUp(); |
|
57 | + |
|
58 | + //login |
|
59 | + $this->createUser('test', 'test'); |
|
60 | + |
|
61 | + $this->user = \OC_User::getUser(); |
|
62 | + \OC_User::setUserId('test'); |
|
63 | + |
|
64 | + //clear all proxies and hooks so we can do clean testing |
|
65 | + \OC_Hook::clear('OC_Filesystem'); |
|
66 | + |
|
67 | + /** @var IMountManager $manager */ |
|
68 | + $manager = Server::get(IMountManager::class); |
|
69 | + $manager->removeMount('/test'); |
|
70 | + |
|
71 | + $storage = new Temporary([]); |
|
72 | + Filesystem::mount($storage, [], '/test/cache'); |
|
73 | + |
|
74 | + //set up the users dir |
|
75 | + $this->rootView = new View(''); |
|
76 | + $this->rootView->mkdir('/test'); |
|
77 | + |
|
78 | + $this->instance = new File(); |
|
79 | + |
|
80 | + // forces creation of cache folder for subsequent tests |
|
81 | + $this->instance->set('hack', 'hack'); |
|
82 | + } |
|
83 | + |
|
84 | + protected function tearDown(): void { |
|
85 | + if ($this->instance) { |
|
86 | + $this->instance->remove('hack', 'hack'); |
|
87 | + } |
|
88 | + |
|
89 | + \OC_User::setUserId($this->user); |
|
90 | + |
|
91 | + if ($this->instance) { |
|
92 | + $this->instance->clear(); |
|
93 | + $this->instance = null; |
|
94 | + } |
|
95 | + |
|
96 | + parent::tearDown(); |
|
97 | + } |
|
98 | + |
|
99 | + private function setupMockStorage() { |
|
100 | + $mockStorage = $this->getMockBuilder(Local::class) |
|
101 | + ->onlyMethods(['filemtime', 'unlink']) |
|
102 | + ->setConstructorArgs([['datadir' => Server::get(ITempManager::class)->getTemporaryFolder()]]) |
|
103 | + ->getMock(); |
|
104 | + |
|
105 | + Filesystem::mount($mockStorage, [], '/test/cache'); |
|
106 | + |
|
107 | + return $mockStorage; |
|
108 | + } |
|
109 | + |
|
110 | + public function testGarbageCollectOldKeys(): void { |
|
111 | + $mockStorage = $this->setupMockStorage(); |
|
112 | + |
|
113 | + $mockStorage->expects($this->atLeastOnce()) |
|
114 | + ->method('filemtime') |
|
115 | + ->willReturn(100); |
|
116 | + $mockStorage->expects($this->once()) |
|
117 | + ->method('unlink') |
|
118 | + ->with('key1') |
|
119 | + ->willReturn(true); |
|
120 | + |
|
121 | + $this->instance->set('key1', 'value1'); |
|
122 | + $this->instance->gc(); |
|
123 | + } |
|
124 | + |
|
125 | + public function testGarbageCollectLeaveRecentKeys(): void { |
|
126 | + $mockStorage = $this->setupMockStorage(); |
|
127 | + |
|
128 | + $mockStorage->expects($this->atLeastOnce()) |
|
129 | + ->method('filemtime') |
|
130 | + ->willReturn(time() + 3600); |
|
131 | + $mockStorage->expects($this->never()) |
|
132 | + ->method('unlink') |
|
133 | + ->with('key1'); |
|
134 | + $this->instance->set('key1', 'value1'); |
|
135 | + $this->instance->gc(); |
|
136 | + } |
|
137 | + |
|
138 | + public static function lockExceptionProvider(): array { |
|
139 | + return [ |
|
140 | + [new LockedException('key1')], |
|
141 | + [new LockNotAcquiredException('key1', 1)], |
|
142 | + ]; |
|
143 | + } |
|
144 | + |
|
145 | + #[\PHPUnit\Framework\Attributes\DataProvider('lockExceptionProvider')] |
|
146 | + public function testGarbageCollectIgnoreLockedKeys($testException): void { |
|
147 | + $mockStorage = $this->setupMockStorage(); |
|
148 | + |
|
149 | + $mockStorage->expects($this->atLeastOnce()) |
|
150 | + ->method('filemtime') |
|
151 | + ->willReturn(100); |
|
152 | + $mockStorage->expects($this->atLeastOnce()) |
|
153 | + ->method('unlink')->willReturnOnConsecutiveCalls($this->throwException($testException), $this->returnValue(true)); |
|
154 | 154 | |
155 | - $this->instance->set('key1', 'value1'); |
|
156 | - $this->instance->set('key2', 'value2'); |
|
155 | + $this->instance->set('key1', 'value1'); |
|
156 | + $this->instance->set('key2', 'value2'); |
|
157 | 157 | |
158 | - $this->instance->gc(); |
|
159 | - } |
|
158 | + $this->instance->gc(); |
|
159 | + } |
|
160 | 160 | } |
@@ -40,1152 +40,1152 @@ |
||
40 | 40 | * OC_autoload! |
41 | 41 | */ |
42 | 42 | class OC { |
43 | - /** |
|
44 | - * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
45 | - */ |
|
46 | - public static string $SERVERROOT = ''; |
|
47 | - /** |
|
48 | - * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
49 | - */ |
|
50 | - private static string $SUBURI = ''; |
|
51 | - /** |
|
52 | - * the Nextcloud root path for http requests (e.g. /nextcloud) |
|
53 | - */ |
|
54 | - public static string $WEBROOT = ''; |
|
55 | - /** |
|
56 | - * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
57 | - * web path in 'url' |
|
58 | - */ |
|
59 | - public static array $APPSROOTS = []; |
|
60 | - |
|
61 | - public static string $configDir; |
|
62 | - |
|
63 | - /** |
|
64 | - * requested app |
|
65 | - */ |
|
66 | - public static string $REQUESTEDAPP = ''; |
|
67 | - |
|
68 | - /** |
|
69 | - * check if Nextcloud runs in cli mode |
|
70 | - */ |
|
71 | - public static bool $CLI = false; |
|
72 | - |
|
73 | - public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
74 | - |
|
75 | - public static \OC\Server $server; |
|
76 | - |
|
77 | - private static \OC\Config $config; |
|
78 | - |
|
79 | - /** |
|
80 | - * @throws \RuntimeException when the 3rdparty directory is missing or |
|
81 | - * the app path list is empty or contains an invalid path |
|
82 | - */ |
|
83 | - public static function initPaths(): void { |
|
84 | - if (defined('PHPUNIT_CONFIG_DIR')) { |
|
85 | - self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
86 | - } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
87 | - self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
88 | - } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
89 | - self::$configDir = rtrim($dir, '/') . '/'; |
|
90 | - } else { |
|
91 | - self::$configDir = OC::$SERVERROOT . '/config/'; |
|
92 | - } |
|
93 | - self::$config = new \OC\Config(self::$configDir); |
|
94 | - |
|
95 | - OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT))); |
|
96 | - /** |
|
97 | - * FIXME: The following lines are required because we can't yet instantiate |
|
98 | - * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
99 | - */ |
|
100 | - $params = [ |
|
101 | - 'server' => [ |
|
102 | - 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
103 | - 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
104 | - ], |
|
105 | - ]; |
|
106 | - if (isset($_SERVER['REMOTE_ADDR'])) { |
|
107 | - $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; |
|
108 | - } |
|
109 | - $fakeRequest = new \OC\AppFramework\Http\Request( |
|
110 | - $params, |
|
111 | - new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
112 | - new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
113 | - ); |
|
114 | - $scriptName = $fakeRequest->getScriptName(); |
|
115 | - if (substr($scriptName, -1) == '/') { |
|
116 | - $scriptName .= 'index.php'; |
|
117 | - //make sure suburi follows the same rules as scriptName |
|
118 | - if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
119 | - if (substr(OC::$SUBURI, -1) != '/') { |
|
120 | - OC::$SUBURI = OC::$SUBURI . '/'; |
|
121 | - } |
|
122 | - OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
123 | - } |
|
124 | - } |
|
125 | - |
|
126 | - if (OC::$CLI) { |
|
127 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
128 | - } else { |
|
129 | - if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
130 | - OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
131 | - |
|
132 | - if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
133 | - OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
134 | - } |
|
135 | - } else { |
|
136 | - // The scriptName is not ending with OC::$SUBURI |
|
137 | - // This most likely means that we are calling from CLI. |
|
138 | - // However some cron jobs still need to generate |
|
139 | - // a web URL, so we use overwritewebroot as a fallback. |
|
140 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
141 | - } |
|
142 | - |
|
143 | - // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
144 | - // slash which is required by URL generation. |
|
145 | - if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT |
|
146 | - && substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
147 | - header('Location: ' . \OC::$WEBROOT . '/'); |
|
148 | - exit(); |
|
149 | - } |
|
150 | - } |
|
151 | - |
|
152 | - // search the apps folder |
|
153 | - $config_paths = self::$config->getValue('apps_paths', []); |
|
154 | - if (!empty($config_paths)) { |
|
155 | - foreach ($config_paths as $paths) { |
|
156 | - if (isset($paths['url']) && isset($paths['path'])) { |
|
157 | - $paths['url'] = rtrim($paths['url'], '/'); |
|
158 | - $paths['path'] = rtrim($paths['path'], '/'); |
|
159 | - OC::$APPSROOTS[] = $paths; |
|
160 | - } |
|
161 | - } |
|
162 | - } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
163 | - OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
164 | - } |
|
165 | - |
|
166 | - if (empty(OC::$APPSROOTS)) { |
|
167 | - throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
168 | - . '. You can also configure the location in the config.php file.'); |
|
169 | - } |
|
170 | - $paths = []; |
|
171 | - foreach (OC::$APPSROOTS as $path) { |
|
172 | - $paths[] = $path['path']; |
|
173 | - if (!is_dir($path['path'])) { |
|
174 | - throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
175 | - . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
176 | - } |
|
177 | - } |
|
178 | - |
|
179 | - // set the right include path |
|
180 | - set_include_path( |
|
181 | - implode(PATH_SEPARATOR, $paths) |
|
182 | - ); |
|
183 | - } |
|
184 | - |
|
185 | - public static function checkConfig(): void { |
|
186 | - // Create config if it does not already exist |
|
187 | - $configFilePath = self::$configDir . '/config.php'; |
|
188 | - if (!file_exists($configFilePath)) { |
|
189 | - @touch($configFilePath); |
|
190 | - } |
|
191 | - |
|
192 | - // Check if config is writable |
|
193 | - $configFileWritable = is_writable($configFilePath); |
|
194 | - $configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only'); |
|
195 | - if (!$configFileWritable && !$configReadOnly |
|
196 | - || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
197 | - $urlGenerator = Server::get(IURLGenerator::class); |
|
198 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
199 | - |
|
200 | - if (self::$CLI) { |
|
201 | - echo $l->t('Cannot write into "config" directory!') . "\n"; |
|
202 | - echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n"; |
|
203 | - echo "\n"; |
|
204 | - echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n"; |
|
205 | - echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n"; |
|
206 | - exit; |
|
207 | - } else { |
|
208 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
209 | - $l->t('Cannot write into "config" directory!'), |
|
210 | - $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
211 | - . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
212 | - . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
213 | - 503 |
|
214 | - ); |
|
215 | - } |
|
216 | - } |
|
217 | - } |
|
218 | - |
|
219 | - public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
220 | - if (defined('OC_CONSOLE')) { |
|
221 | - return; |
|
222 | - } |
|
223 | - // Redirect to installer if not installed |
|
224 | - if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
225 | - if (OC::$CLI) { |
|
226 | - throw new Exception('Not installed'); |
|
227 | - } else { |
|
228 | - $url = OC::$WEBROOT . '/index.php'; |
|
229 | - header('Location: ' . $url); |
|
230 | - } |
|
231 | - exit(); |
|
232 | - } |
|
233 | - } |
|
234 | - |
|
235 | - public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
236 | - // Allow ajax update script to execute without being stopped |
|
237 | - if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
238 | - // send http status 503 |
|
239 | - http_response_code(503); |
|
240 | - header('X-Nextcloud-Maintenance-Mode: 1'); |
|
241 | - header('Retry-After: 120'); |
|
242 | - |
|
243 | - // render error page |
|
244 | - $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest'); |
|
245 | - \OCP\Util::addScript('core', 'maintenance'); |
|
246 | - \OCP\Util::addScript('core', 'common'); |
|
247 | - \OCP\Util::addStyle('core', 'guest'); |
|
248 | - $template->printPage(); |
|
249 | - die(); |
|
250 | - } |
|
251 | - } |
|
252 | - |
|
253 | - /** |
|
254 | - * Prints the upgrade page |
|
255 | - */ |
|
256 | - private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
257 | - $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', ''); |
|
258 | - $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
259 | - $tooBig = false; |
|
260 | - if (!$disableWebUpdater) { |
|
261 | - $apps = Server::get(\OCP\App\IAppManager::class); |
|
262 | - if ($apps->isEnabledForAnyone('user_ldap')) { |
|
263 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
264 | - |
|
265 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
266 | - ->from('ldap_user_mapping') |
|
267 | - ->executeQuery(); |
|
268 | - $row = $result->fetch(); |
|
269 | - $result->closeCursor(); |
|
270 | - |
|
271 | - $tooBig = ($row['user_count'] > 50); |
|
272 | - } |
|
273 | - if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) { |
|
274 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
275 | - |
|
276 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
277 | - ->from('user_saml_users') |
|
278 | - ->executeQuery(); |
|
279 | - $row = $result->fetch(); |
|
280 | - $result->closeCursor(); |
|
281 | - |
|
282 | - $tooBig = ($row['user_count'] > 50); |
|
283 | - } |
|
284 | - if (!$tooBig) { |
|
285 | - // count users |
|
286 | - $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51); |
|
287 | - $tooBig = ($totalUsers > 50); |
|
288 | - } |
|
289 | - } |
|
290 | - $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) |
|
291 | - && $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
292 | - |
|
293 | - if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
294 | - // send http status 503 |
|
295 | - http_response_code(503); |
|
296 | - header('Retry-After: 120'); |
|
297 | - |
|
298 | - $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class); |
|
299 | - |
|
300 | - // render error page |
|
301 | - $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest'); |
|
302 | - $template->assign('productName', 'nextcloud'); // for now |
|
303 | - $template->assign('version', $serverVersion->getVersionString()); |
|
304 | - $template->assign('tooBig', $tooBig); |
|
305 | - $template->assign('cliUpgradeLink', $cliUpgradeLink); |
|
306 | - |
|
307 | - $template->printPage(); |
|
308 | - die(); |
|
309 | - } |
|
310 | - |
|
311 | - // check whether this is a core update or apps update |
|
312 | - $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
313 | - $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
314 | - |
|
315 | - // if not a core upgrade, then it's apps upgrade |
|
316 | - $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
317 | - |
|
318 | - $oldTheme = $systemConfig->getValue('theme'); |
|
319 | - $systemConfig->setValue('theme', ''); |
|
320 | - \OCP\Util::addScript('core', 'common'); |
|
321 | - \OCP\Util::addScript('core', 'main'); |
|
322 | - \OCP\Util::addTranslations('core'); |
|
323 | - \OCP\Util::addScript('core', 'update'); |
|
324 | - |
|
325 | - /** @var \OC\App\AppManager $appManager */ |
|
326 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
327 | - |
|
328 | - $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest'); |
|
329 | - $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString()); |
|
330 | - $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
331 | - |
|
332 | - // get third party apps |
|
333 | - $ocVersion = \OCP\Util::getVersion(); |
|
334 | - $ocVersion = implode('.', $ocVersion); |
|
335 | - $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
336 | - $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []); |
|
337 | - $incompatibleShippedApps = []; |
|
338 | - $incompatibleDisabledApps = []; |
|
339 | - foreach ($incompatibleApps as $appInfo) { |
|
340 | - if ($appManager->isShipped($appInfo['id'])) { |
|
341 | - $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
342 | - } |
|
343 | - if (!in_array($appInfo['id'], $incompatibleOverwrites)) { |
|
344 | - $incompatibleDisabledApps[] = $appInfo; |
|
345 | - } |
|
346 | - } |
|
347 | - |
|
348 | - if (!empty($incompatibleShippedApps)) { |
|
349 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
350 | - $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]); |
|
351 | - throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint); |
|
352 | - } |
|
353 | - |
|
354 | - $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
355 | - $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps); |
|
356 | - try { |
|
357 | - $defaults = new \OC_Defaults(); |
|
358 | - $tmpl->assign('productName', $defaults->getName()); |
|
359 | - } catch (Throwable $error) { |
|
360 | - $tmpl->assign('productName', 'Nextcloud'); |
|
361 | - } |
|
362 | - $tmpl->assign('oldTheme', $oldTheme); |
|
363 | - $tmpl->printPage(); |
|
364 | - } |
|
365 | - |
|
366 | - public static function initSession(): void { |
|
367 | - $request = Server::get(IRequest::class); |
|
368 | - |
|
369 | - // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies |
|
370 | - // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments |
|
371 | - // TODO: for further information. |
|
372 | - // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
373 | - // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
374 | - // setcookie('cookie_test', 'test', time() + 3600); |
|
375 | - // // Do not initialize the session if a request is authenticated directly |
|
376 | - // // unless there is a session cookie already sent along |
|
377 | - // return; |
|
378 | - // } |
|
379 | - |
|
380 | - if ($request->getServerProtocol() === 'https') { |
|
381 | - ini_set('session.cookie_secure', 'true'); |
|
382 | - } |
|
383 | - |
|
384 | - // prevents javascript from accessing php session cookies |
|
385 | - ini_set('session.cookie_httponly', 'true'); |
|
386 | - |
|
387 | - // Do not initialize sessions for 'status.php' requests |
|
388 | - // Monitoring endpoints can quickly flood session handlers |
|
389 | - // and 'status.php' doesn't require sessions anyway |
|
390 | - if (str_ends_with($request->getScriptName(), '/status.php')) { |
|
391 | - return; |
|
392 | - } |
|
393 | - |
|
394 | - // set the cookie path to the Nextcloud directory |
|
395 | - $cookie_path = OC::$WEBROOT ? : '/'; |
|
396 | - ini_set('session.cookie_path', $cookie_path); |
|
397 | - |
|
398 | - // set the cookie domain to the Nextcloud domain |
|
399 | - $cookie_domain = self::$config->getValue('cookie_domain', ''); |
|
400 | - if ($cookie_domain) { |
|
401 | - ini_set('session.cookie_domain', $cookie_domain); |
|
402 | - } |
|
403 | - |
|
404 | - // Let the session name be changed in the initSession Hook |
|
405 | - $sessionName = OC_Util::getInstanceId(); |
|
406 | - |
|
407 | - try { |
|
408 | - $logger = null; |
|
409 | - if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) { |
|
410 | - $logger = logger('core'); |
|
411 | - } |
|
412 | - |
|
413 | - // set the session name to the instance id - which is unique |
|
414 | - $session = new \OC\Session\Internal( |
|
415 | - $sessionName, |
|
416 | - $logger, |
|
417 | - ); |
|
418 | - |
|
419 | - $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
420 | - $session = $cryptoWrapper->wrapSession($session); |
|
421 | - self::$server->setSession($session); |
|
422 | - |
|
423 | - // if session can't be started break with http 500 error |
|
424 | - } catch (Exception $e) { |
|
425 | - Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
426 | - //show the user a detailed error page |
|
427 | - Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500); |
|
428 | - die(); |
|
429 | - } |
|
430 | - |
|
431 | - //try to set the session lifetime |
|
432 | - $sessionLifeTime = self::getSessionLifeTime(); |
|
433 | - |
|
434 | - // session timeout |
|
435 | - if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
436 | - if (isset($_COOKIE[session_name()])) { |
|
437 | - setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
438 | - } |
|
439 | - Server::get(IUserSession::class)->logout(); |
|
440 | - } |
|
441 | - |
|
442 | - if (!self::hasSessionRelaxedExpiry()) { |
|
443 | - $session->set('LAST_ACTIVITY', time()); |
|
444 | - } |
|
445 | - $session->close(); |
|
446 | - } |
|
447 | - |
|
448 | - private static function getSessionLifeTime(): int { |
|
449 | - return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
450 | - } |
|
451 | - |
|
452 | - /** |
|
453 | - * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
454 | - */ |
|
455 | - public static function hasSessionRelaxedExpiry(): bool { |
|
456 | - return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
457 | - } |
|
458 | - |
|
459 | - /** |
|
460 | - * Try to set some values to the required Nextcloud default |
|
461 | - */ |
|
462 | - public static function setRequiredIniValues(): void { |
|
463 | - // Don't display errors and log them |
|
464 | - @ini_set('display_errors', '0'); |
|
465 | - @ini_set('log_errors', '1'); |
|
466 | - |
|
467 | - // Try to configure php to enable big file uploads. |
|
468 | - // This doesn't work always depending on the webserver and php configuration. |
|
469 | - // Let's try to overwrite some defaults if they are smaller than 1 hour |
|
470 | - |
|
471 | - if (intval(@ini_get('max_execution_time') ?: 0) < 3600) { |
|
472 | - @ini_set('max_execution_time', strval(3600)); |
|
473 | - } |
|
474 | - |
|
475 | - if (intval(@ini_get('max_input_time') ?: 0) < 3600) { |
|
476 | - @ini_set('max_input_time', strval(3600)); |
|
477 | - } |
|
478 | - |
|
479 | - // Try to set the maximum execution time to the largest time limit we have |
|
480 | - if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
481 | - @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
482 | - } |
|
483 | - |
|
484 | - @ini_set('default_charset', 'UTF-8'); |
|
485 | - @ini_set('gd.jpeg_ignore_warning', '1'); |
|
486 | - } |
|
487 | - |
|
488 | - /** |
|
489 | - * Send the same site cookies |
|
490 | - */ |
|
491 | - private static function sendSameSiteCookies(): void { |
|
492 | - $cookieParams = session_get_cookie_params(); |
|
493 | - $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
494 | - $policies = [ |
|
495 | - 'lax', |
|
496 | - 'strict', |
|
497 | - ]; |
|
498 | - |
|
499 | - // Append __Host to the cookie if it meets the requirements |
|
500 | - $cookiePrefix = ''; |
|
501 | - if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
502 | - $cookiePrefix = '__Host-'; |
|
503 | - } |
|
504 | - |
|
505 | - foreach ($policies as $policy) { |
|
506 | - header( |
|
507 | - sprintf( |
|
508 | - 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
509 | - $cookiePrefix, |
|
510 | - $policy, |
|
511 | - $cookieParams['path'], |
|
512 | - $policy |
|
513 | - ), |
|
514 | - false |
|
515 | - ); |
|
516 | - } |
|
517 | - } |
|
518 | - |
|
519 | - /** |
|
520 | - * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
521 | - * be set in every request if cookies are sent to add a second level of |
|
522 | - * defense against CSRF. |
|
523 | - * |
|
524 | - * If the cookie is not sent this will set the cookie and reload the page. |
|
525 | - * We use an additional cookie since we want to protect logout CSRF and |
|
526 | - * also we can't directly interfere with PHP's session mechanism. |
|
527 | - */ |
|
528 | - private static function performSameSiteCookieProtection(IConfig $config): void { |
|
529 | - $request = Server::get(IRequest::class); |
|
530 | - |
|
531 | - // Some user agents are notorious and don't really properly follow HTTP |
|
532 | - // specifications. For those, have an automated opt-out. Since the protection |
|
533 | - // for remote.php is applied in base.php as starting point we need to opt out |
|
534 | - // here. |
|
535 | - $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
536 | - |
|
537 | - // Fallback, if csrf.optout is unset |
|
538 | - if (!is_array($incompatibleUserAgents)) { |
|
539 | - $incompatibleUserAgents = [ |
|
540 | - // OS X Finder |
|
541 | - '/^WebDAVFS/', |
|
542 | - // Windows webdav drive |
|
543 | - '/^Microsoft-WebDAV-MiniRedir/', |
|
544 | - ]; |
|
545 | - } |
|
546 | - |
|
547 | - if ($request->isUserAgent($incompatibleUserAgents)) { |
|
548 | - return; |
|
549 | - } |
|
550 | - |
|
551 | - if (count($_COOKIE) > 0) { |
|
552 | - $requestUri = $request->getScriptName(); |
|
553 | - $processingScript = explode('/', $requestUri); |
|
554 | - $processingScript = $processingScript[count($processingScript) - 1]; |
|
555 | - |
|
556 | - if ($processingScript === 'index.php' // index.php routes are handled in the middleware |
|
557 | - || $processingScript === 'cron.php' // and cron.php does not need any authentication at all |
|
558 | - || $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin |
|
559 | - ) { |
|
560 | - return; |
|
561 | - } |
|
562 | - |
|
563 | - // All other endpoints require the lax and the strict cookie |
|
564 | - if (!$request->passesStrictCookieCheck()) { |
|
565 | - logger('core')->warning('Request does not pass strict cookie check'); |
|
566 | - self::sendSameSiteCookies(); |
|
567 | - // Debug mode gets access to the resources without strict cookie |
|
568 | - // due to the fact that the SabreDAV browser also lives there. |
|
569 | - if (!$config->getSystemValueBool('debug', false)) { |
|
570 | - http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED); |
|
571 | - header('Content-Type: application/json'); |
|
572 | - echo json_encode(['error' => 'Strict Cookie has not been found in request']); |
|
573 | - exit(); |
|
574 | - } |
|
575 | - } |
|
576 | - } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
577 | - self::sendSameSiteCookies(); |
|
578 | - } |
|
579 | - } |
|
580 | - |
|
581 | - public static function init(): void { |
|
582 | - // First handle PHP configuration and copy auth headers to the expected |
|
583 | - // $_SERVER variable before doing anything Server object related |
|
584 | - self::setRequiredIniValues(); |
|
585 | - self::handleAuthHeaders(); |
|
586 | - |
|
587 | - // prevent any XML processing from loading external entities |
|
588 | - libxml_set_external_entity_loader(static function () { |
|
589 | - return null; |
|
590 | - }); |
|
591 | - |
|
592 | - // Set default timezone before the Server object is booted |
|
593 | - if (!date_default_timezone_set('UTC')) { |
|
594 | - throw new \RuntimeException('Could not set timezone to UTC'); |
|
595 | - } |
|
596 | - |
|
597 | - // calculate the root directories |
|
598 | - OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4)); |
|
599 | - |
|
600 | - // register autoloader |
|
601 | - $loaderStart = microtime(true); |
|
602 | - |
|
603 | - self::$CLI = (php_sapi_name() == 'cli'); |
|
604 | - |
|
605 | - // Add default composer PSR-4 autoloader, ensure apcu to be disabled |
|
606 | - self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
607 | - self::$composerAutoloader->setApcuPrefix(null); |
|
608 | - |
|
609 | - |
|
610 | - try { |
|
611 | - self::initPaths(); |
|
612 | - // setup 3rdparty autoloader |
|
613 | - $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php'; |
|
614 | - if (!file_exists($vendorAutoLoad)) { |
|
615 | - throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
|
616 | - } |
|
617 | - require_once $vendorAutoLoad; |
|
618 | - } catch (\RuntimeException $e) { |
|
619 | - if (!self::$CLI) { |
|
620 | - http_response_code(503); |
|
621 | - } |
|
622 | - // we can't use the template error page here, because this needs the |
|
623 | - // DI container which isn't available yet |
|
624 | - print($e->getMessage()); |
|
625 | - exit(); |
|
626 | - } |
|
627 | - $loaderEnd = microtime(true); |
|
628 | - |
|
629 | - // Enable lazy loading if activated |
|
630 | - \OC\AppFramework\Utility\SimpleContainer::$useLazyObjects = (bool)self::$config->getValue('enable_lazy_objects', true); |
|
631 | - |
|
632 | - // setup the basic server |
|
633 | - self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
634 | - self::$server->boot(); |
|
635 | - |
|
636 | - try { |
|
637 | - $profiler = new BuiltInProfiler( |
|
638 | - Server::get(IConfig::class), |
|
639 | - Server::get(IRequest::class), |
|
640 | - ); |
|
641 | - $profiler->start(); |
|
642 | - } catch (\Throwable $e) { |
|
643 | - logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']); |
|
644 | - } |
|
645 | - |
|
646 | - if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) { |
|
647 | - \OC\Core\Listener\BeforeMessageLoggedEventListener::setup(); |
|
648 | - } |
|
649 | - |
|
650 | - $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
651 | - $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
652 | - $eventLogger->start('boot', 'Initialize'); |
|
653 | - |
|
654 | - // Override php.ini and log everything if we're troubleshooting |
|
655 | - if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
656 | - error_reporting(E_ALL); |
|
657 | - } |
|
658 | - |
|
659 | - // initialize intl fallback if necessary |
|
660 | - OC_Util::isSetLocaleWorking(); |
|
661 | - |
|
662 | - $config = Server::get(IConfig::class); |
|
663 | - if (!defined('PHPUNIT_RUN')) { |
|
664 | - $errorHandler = new OC\Log\ErrorHandler( |
|
665 | - \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
666 | - ); |
|
667 | - $exceptionHandler = [$errorHandler, 'onException']; |
|
668 | - if ($config->getSystemValueBool('debug', false)) { |
|
669 | - set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
670 | - if (\OC::$CLI) { |
|
671 | - $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage']; |
|
672 | - } |
|
673 | - } else { |
|
674 | - set_error_handler([$errorHandler, 'onError']); |
|
675 | - } |
|
676 | - register_shutdown_function([$errorHandler, 'onShutdown']); |
|
677 | - set_exception_handler($exceptionHandler); |
|
678 | - } |
|
679 | - |
|
680 | - /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
681 | - $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
682 | - $bootstrapCoordinator->runInitialRegistration(); |
|
683 | - |
|
684 | - $eventLogger->start('init_session', 'Initialize session'); |
|
685 | - |
|
686 | - // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users |
|
687 | - // see https://github.com/nextcloud/server/pull/2619 |
|
688 | - if (!function_exists('simplexml_load_file')) { |
|
689 | - throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.'); |
|
690 | - } |
|
691 | - |
|
692 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
693 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
694 | - if ($systemConfig->getValue('installed', false)) { |
|
695 | - $appManager->loadApps(['session']); |
|
696 | - } |
|
697 | - if (!self::$CLI) { |
|
698 | - self::initSession(); |
|
699 | - } |
|
700 | - $eventLogger->end('init_session'); |
|
701 | - self::checkConfig(); |
|
702 | - self::checkInstalled($systemConfig); |
|
703 | - |
|
704 | - OC_Response::addSecurityHeaders(); |
|
705 | - |
|
706 | - self::performSameSiteCookieProtection($config); |
|
707 | - |
|
708 | - if (!defined('OC_CONSOLE')) { |
|
709 | - $eventLogger->start('check_server', 'Run a few configuration checks'); |
|
710 | - $errors = OC_Util::checkServer($systemConfig); |
|
711 | - if (count($errors) > 0) { |
|
712 | - if (!self::$CLI) { |
|
713 | - http_response_code(503); |
|
714 | - Util::addStyle('guest'); |
|
715 | - try { |
|
716 | - Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]); |
|
717 | - exit; |
|
718 | - } catch (\Exception $e) { |
|
719 | - // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
720 | - // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
721 | - } |
|
722 | - } |
|
723 | - |
|
724 | - // Convert l10n string into regular string for usage in database |
|
725 | - $staticErrors = []; |
|
726 | - foreach ($errors as $error) { |
|
727 | - echo $error['error'] . "\n"; |
|
728 | - echo $error['hint'] . "\n\n"; |
|
729 | - $staticErrors[] = [ |
|
730 | - 'error' => (string)$error['error'], |
|
731 | - 'hint' => (string)$error['hint'], |
|
732 | - ]; |
|
733 | - } |
|
734 | - |
|
735 | - try { |
|
736 | - $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
737 | - } catch (\Exception $e) { |
|
738 | - echo('Writing to database failed'); |
|
739 | - } |
|
740 | - exit(1); |
|
741 | - } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) { |
|
742 | - $config->deleteAppValue('core', 'cronErrors'); |
|
743 | - } |
|
744 | - $eventLogger->end('check_server'); |
|
745 | - } |
|
746 | - |
|
747 | - // User and Groups |
|
748 | - if (!$systemConfig->getValue('installed', false)) { |
|
749 | - self::$server->getSession()->set('user_id', ''); |
|
750 | - } |
|
751 | - |
|
752 | - $eventLogger->start('setup_backends', 'Setup group and user backends'); |
|
753 | - Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
754 | - Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
755 | - |
|
756 | - // Subscribe to the hook |
|
757 | - \OCP\Util::connectHook( |
|
758 | - '\OCA\Files_Sharing\API\Server2Server', |
|
759 | - 'preLoginNameUsedAsUserName', |
|
760 | - '\OC\User\Database', |
|
761 | - 'preLoginNameUsedAsUserName' |
|
762 | - ); |
|
763 | - |
|
764 | - //setup extra user backends |
|
765 | - if (!\OCP\Util::needUpgrade()) { |
|
766 | - OC_User::setupBackends(); |
|
767 | - } else { |
|
768 | - // Run upgrades in incognito mode |
|
769 | - OC_User::setIncognitoMode(true); |
|
770 | - } |
|
771 | - $eventLogger->end('setup_backends'); |
|
772 | - |
|
773 | - self::registerCleanupHooks($systemConfig); |
|
774 | - self::registerShareHooks($systemConfig); |
|
775 | - self::registerEncryptionWrapperAndHooks(); |
|
776 | - self::registerAccountHooks(); |
|
777 | - self::registerResourceCollectionHooks(); |
|
778 | - self::registerFileReferenceEventListener(); |
|
779 | - self::registerRenderReferenceEventListener(); |
|
780 | - self::registerAppRestrictionsHooks(); |
|
781 | - |
|
782 | - // Make sure that the application class is not loaded before the database is setup |
|
783 | - if ($systemConfig->getValue('installed', false)) { |
|
784 | - $appManager->loadApp('settings'); |
|
785 | - } |
|
786 | - |
|
787 | - //make sure temporary files are cleaned up |
|
788 | - $tmpManager = Server::get(\OCP\ITempManager::class); |
|
789 | - register_shutdown_function([$tmpManager, 'clean']); |
|
790 | - $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
791 | - register_shutdown_function([$lockProvider, 'releaseAll']); |
|
792 | - |
|
793 | - // Check whether the sample configuration has been copied |
|
794 | - if ($systemConfig->getValue('copied_sample_config', false)) { |
|
795 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
796 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
797 | - $l->t('Sample configuration detected'), |
|
798 | - $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'), |
|
799 | - 503 |
|
800 | - ); |
|
801 | - return; |
|
802 | - } |
|
803 | - |
|
804 | - $request = Server::get(IRequest::class); |
|
805 | - $host = $request->getInsecureServerHost(); |
|
806 | - /** |
|
807 | - * if the host passed in headers isn't trusted |
|
808 | - * FIXME: Should not be in here at all :see_no_evil: |
|
809 | - */ |
|
810 | - if (!OC::$CLI |
|
811 | - && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
812 | - && $config->getSystemValueBool('installed', false) |
|
813 | - ) { |
|
814 | - // Allow access to CSS resources |
|
815 | - $isScssRequest = false; |
|
816 | - if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
817 | - $isScssRequest = true; |
|
818 | - } |
|
819 | - |
|
820 | - if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
821 | - http_response_code(400); |
|
822 | - header('Content-Type: application/json'); |
|
823 | - echo '{"error": "Trusted domain error.", "code": 15}'; |
|
824 | - exit(); |
|
825 | - } |
|
826 | - |
|
827 | - if (!$isScssRequest) { |
|
828 | - http_response_code(400); |
|
829 | - Server::get(LoggerInterface::class)->info( |
|
830 | - 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
831 | - [ |
|
832 | - 'app' => 'core', |
|
833 | - 'remoteAddress' => $request->getRemoteAddress(), |
|
834 | - 'host' => $host, |
|
835 | - ] |
|
836 | - ); |
|
837 | - |
|
838 | - $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest'); |
|
839 | - $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
840 | - $tmpl->printPage(); |
|
841 | - |
|
842 | - exit(); |
|
843 | - } |
|
844 | - } |
|
845 | - $eventLogger->end('boot'); |
|
846 | - $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
847 | - $eventLogger->start('runtime', 'Runtime'); |
|
848 | - $eventLogger->start('request', 'Full request after boot'); |
|
849 | - register_shutdown_function(function () use ($eventLogger) { |
|
850 | - $eventLogger->end('request'); |
|
851 | - }); |
|
852 | - |
|
853 | - register_shutdown_function(function () { |
|
854 | - $memoryPeak = memory_get_peak_usage(); |
|
855 | - $logLevel = match (true) { |
|
856 | - $memoryPeak > 500_000_000 => ILogger::FATAL, |
|
857 | - $memoryPeak > 400_000_000 => ILogger::ERROR, |
|
858 | - $memoryPeak > 300_000_000 => ILogger::WARN, |
|
859 | - default => null, |
|
860 | - }; |
|
861 | - if ($logLevel !== null) { |
|
862 | - $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak); |
|
863 | - $logger = Server::get(LoggerInterface::class); |
|
864 | - $logger->log($logLevel, $message, ['app' => 'core']); |
|
865 | - } |
|
866 | - }); |
|
867 | - } |
|
868 | - |
|
869 | - /** |
|
870 | - * register hooks for the cleanup of cache and bruteforce protection |
|
871 | - */ |
|
872 | - public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
873 | - //don't try to do this before we are properly setup |
|
874 | - if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
875 | - // NOTE: This will be replaced to use OCP |
|
876 | - $userSession = Server::get(\OC\User\Session::class); |
|
877 | - $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
878 | - if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
879 | - // reset brute force delay for this IP address and username |
|
880 | - $uid = $userSession->getUser()->getUID(); |
|
881 | - $request = Server::get(IRequest::class); |
|
882 | - $throttler = Server::get(IThrottler::class); |
|
883 | - $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
884 | - } |
|
885 | - |
|
886 | - try { |
|
887 | - $cache = new \OC\Cache\File(); |
|
888 | - $cache->gc(); |
|
889 | - } catch (\OC\ServerNotAvailableException $e) { |
|
890 | - // not a GC exception, pass it on |
|
891 | - throw $e; |
|
892 | - } catch (\OC\ForbiddenException $e) { |
|
893 | - // filesystem blocked for this request, ignore |
|
894 | - } catch (\Exception $e) { |
|
895 | - // a GC exception should not prevent users from using OC, |
|
896 | - // so log the exception |
|
897 | - Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
898 | - 'app' => 'core', |
|
899 | - 'exception' => $e, |
|
900 | - ]); |
|
901 | - } |
|
902 | - }); |
|
903 | - } |
|
904 | - } |
|
905 | - |
|
906 | - private static function registerEncryptionWrapperAndHooks(): void { |
|
907 | - /** @var \OC\Encryption\Manager */ |
|
908 | - $manager = Server::get(\OCP\Encryption\IManager::class); |
|
909 | - Server::get(IEventDispatcher::class)->addListener( |
|
910 | - BeforeFileSystemSetupEvent::class, |
|
911 | - $manager->setupStorage(...), |
|
912 | - ); |
|
913 | - |
|
914 | - $enabled = $manager->isEnabled(); |
|
915 | - if ($enabled) { |
|
916 | - \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class)); |
|
917 | - } |
|
918 | - } |
|
919 | - |
|
920 | - private static function registerAccountHooks(): void { |
|
921 | - /** @var IEventDispatcher $dispatcher */ |
|
922 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
923 | - $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
924 | - } |
|
925 | - |
|
926 | - private static function registerAppRestrictionsHooks(): void { |
|
927 | - /** @var \OC\Group\Manager $groupManager */ |
|
928 | - $groupManager = Server::get(\OCP\IGroupManager::class); |
|
929 | - $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
930 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
931 | - $apps = $appManager->getEnabledAppsForGroup($group); |
|
932 | - foreach ($apps as $appId) { |
|
933 | - $restrictions = $appManager->getAppRestriction($appId); |
|
934 | - if (empty($restrictions)) { |
|
935 | - continue; |
|
936 | - } |
|
937 | - $key = array_search($group->getGID(), $restrictions); |
|
938 | - unset($restrictions[$key]); |
|
939 | - $restrictions = array_values($restrictions); |
|
940 | - if (empty($restrictions)) { |
|
941 | - $appManager->disableApp($appId); |
|
942 | - } else { |
|
943 | - $appManager->enableAppForGroups($appId, $restrictions); |
|
944 | - } |
|
945 | - } |
|
946 | - }); |
|
947 | - } |
|
948 | - |
|
949 | - private static function registerResourceCollectionHooks(): void { |
|
950 | - \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class)); |
|
951 | - } |
|
952 | - |
|
953 | - private static function registerFileReferenceEventListener(): void { |
|
954 | - \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
955 | - } |
|
956 | - |
|
957 | - private static function registerRenderReferenceEventListener() { |
|
958 | - \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
959 | - } |
|
960 | - |
|
961 | - /** |
|
962 | - * register hooks for sharing |
|
963 | - */ |
|
964 | - public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
965 | - if ($systemConfig->getValue('installed')) { |
|
966 | - |
|
967 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
968 | - $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class); |
|
969 | - $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class); |
|
970 | - $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class); |
|
971 | - } |
|
972 | - } |
|
973 | - |
|
974 | - /** |
|
975 | - * Handle the request |
|
976 | - */ |
|
977 | - public static function handleRequest(): void { |
|
978 | - Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
979 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
980 | - |
|
981 | - // Check if Nextcloud is installed or in maintenance (update) mode |
|
982 | - if (!$systemConfig->getValue('installed', false)) { |
|
983 | - \OC::$server->getSession()->clear(); |
|
984 | - $controller = Server::get(\OC\Core\Controller\SetupController::class); |
|
985 | - $controller->run($_POST); |
|
986 | - exit(); |
|
987 | - } |
|
988 | - |
|
989 | - $request = Server::get(IRequest::class); |
|
990 | - $request->throwDecodingExceptionIfAny(); |
|
991 | - $requestPath = $request->getRawPathInfo(); |
|
992 | - if ($requestPath === '/heartbeat') { |
|
993 | - return; |
|
994 | - } |
|
995 | - if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
996 | - self::checkMaintenanceMode($systemConfig); |
|
997 | - |
|
998 | - if (\OCP\Util::needUpgrade()) { |
|
999 | - if (function_exists('opcache_reset')) { |
|
1000 | - opcache_reset(); |
|
1001 | - } |
|
1002 | - if (!((bool)$systemConfig->getValue('maintenance', false))) { |
|
1003 | - self::printUpgradePage($systemConfig); |
|
1004 | - exit(); |
|
1005 | - } |
|
1006 | - } |
|
1007 | - } |
|
1008 | - |
|
1009 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
1010 | - |
|
1011 | - // Always load authentication apps |
|
1012 | - $appManager->loadApps(['authentication']); |
|
1013 | - $appManager->loadApps(['extended_authentication']); |
|
1014 | - |
|
1015 | - // Load minimum set of apps |
|
1016 | - if (!\OCP\Util::needUpgrade() |
|
1017 | - && !((bool)$systemConfig->getValue('maintenance', false))) { |
|
1018 | - // For logged-in users: Load everything |
|
1019 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1020 | - $appManager->loadApps(); |
|
1021 | - } else { |
|
1022 | - // For guests: Load only filesystem and logging |
|
1023 | - $appManager->loadApps(['filesystem', 'logging']); |
|
1024 | - |
|
1025 | - // Don't try to login when a client is trying to get a OAuth token. |
|
1026 | - // OAuth needs to support basic auth too, so the login is not valid |
|
1027 | - // inside Nextcloud and the Login exception would ruin it. |
|
1028 | - if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
1029 | - try { |
|
1030 | - self::handleLogin($request); |
|
1031 | - } catch (DisabledUserException $e) { |
|
1032 | - // Disabled users would not be seen as logged in and |
|
1033 | - // trying to log them in would fail, so the login |
|
1034 | - // exception is ignored for the themed stylesheets and |
|
1035 | - // images. |
|
1036 | - if ($request->getRawPathInfo() !== '/apps/theming/theme/default.css' |
|
1037 | - && $request->getRawPathInfo() !== '/apps/theming/theme/light.css' |
|
1038 | - && $request->getRawPathInfo() !== '/apps/theming/theme/dark.css' |
|
1039 | - && $request->getRawPathInfo() !== '/apps/theming/theme/light-highcontrast.css' |
|
1040 | - && $request->getRawPathInfo() !== '/apps/theming/theme/dark-highcontrast.css' |
|
1041 | - && $request->getRawPathInfo() !== '/apps/theming/theme/opendyslexic.css' |
|
1042 | - && $request->getRawPathInfo() !== '/apps/theming/image/background' |
|
1043 | - && $request->getRawPathInfo() !== '/apps/theming/image/logo' |
|
1044 | - && $request->getRawPathInfo() !== '/apps/theming/image/logoheader' |
|
1045 | - && !str_starts_with($request->getRawPathInfo(), '/apps/theming/favicon') |
|
1046 | - && !str_starts_with($request->getRawPathInfo(), '/apps/theming/icon')) { |
|
1047 | - throw $e; |
|
1048 | - } |
|
1049 | - } |
|
1050 | - } |
|
1051 | - } |
|
1052 | - } |
|
1053 | - |
|
1054 | - if (!self::$CLI) { |
|
1055 | - try { |
|
1056 | - if (!\OCP\Util::needUpgrade()) { |
|
1057 | - $appManager->loadApps(['filesystem', 'logging']); |
|
1058 | - $appManager->loadApps(); |
|
1059 | - } |
|
1060 | - Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1061 | - return; |
|
1062 | - } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1063 | - //header('HTTP/1.0 404 Not Found'); |
|
1064 | - } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1065 | - http_response_code(405); |
|
1066 | - return; |
|
1067 | - } |
|
1068 | - } |
|
1069 | - |
|
1070 | - // Handle WebDAV |
|
1071 | - if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1072 | - // not allowed any more to prevent people |
|
1073 | - // mounting this root directly. |
|
1074 | - // Users need to mount remote.php/webdav instead. |
|
1075 | - http_response_code(405); |
|
1076 | - return; |
|
1077 | - } |
|
1078 | - |
|
1079 | - // Handle requests for JSON or XML |
|
1080 | - $acceptHeader = $request->getHeader('Accept'); |
|
1081 | - if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
1082 | - http_response_code(404); |
|
1083 | - return; |
|
1084 | - } |
|
1085 | - |
|
1086 | - // Handle resources that can't be found |
|
1087 | - // This prevents browsers from redirecting to the default page and then |
|
1088 | - // attempting to parse HTML as CSS and similar. |
|
1089 | - $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
1090 | - if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
1091 | - http_response_code(404); |
|
1092 | - return; |
|
1093 | - } |
|
1094 | - |
|
1095 | - // Redirect to the default app or login only as an entry point |
|
1096 | - if ($requestPath === '') { |
|
1097 | - // Someone is logged in |
|
1098 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1099 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
1100 | - } else { |
|
1101 | - // Not handled and not logged in |
|
1102 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1103 | - } |
|
1104 | - return; |
|
1105 | - } |
|
1106 | - |
|
1107 | - try { |
|
1108 | - Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
1109 | - } catch (\Exception $e) { |
|
1110 | - if (!$e instanceof MethodNotAllowedException) { |
|
1111 | - logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
1112 | - } |
|
1113 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
1114 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
1115 | - '404', |
|
1116 | - $l->t('The page could not be found on the server.'), |
|
1117 | - 404 |
|
1118 | - ); |
|
1119 | - } |
|
1120 | - } |
|
1121 | - |
|
1122 | - /** |
|
1123 | - * Check login: apache auth, auth token, basic auth |
|
1124 | - */ |
|
1125 | - public static function handleLogin(OCP\IRequest $request): bool { |
|
1126 | - if ($request->getHeader('X-Nextcloud-Federation')) { |
|
1127 | - return false; |
|
1128 | - } |
|
1129 | - $userSession = Server::get(\OC\User\Session::class); |
|
1130 | - if (OC_User::handleApacheAuth()) { |
|
1131 | - return true; |
|
1132 | - } |
|
1133 | - if (self::tryAppAPILogin($request)) { |
|
1134 | - return true; |
|
1135 | - } |
|
1136 | - if ($userSession->tryTokenLogin($request)) { |
|
1137 | - return true; |
|
1138 | - } |
|
1139 | - if (isset($_COOKIE['nc_username']) |
|
1140 | - && isset($_COOKIE['nc_token']) |
|
1141 | - && isset($_COOKIE['nc_session_id']) |
|
1142 | - && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1143 | - return true; |
|
1144 | - } |
|
1145 | - if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) { |
|
1146 | - return true; |
|
1147 | - } |
|
1148 | - return false; |
|
1149 | - } |
|
1150 | - |
|
1151 | - protected static function handleAuthHeaders(): void { |
|
1152 | - //copy http auth headers for apache+php-fcgid work around |
|
1153 | - if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1154 | - $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1155 | - } |
|
1156 | - |
|
1157 | - // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1158 | - $vars = [ |
|
1159 | - 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1160 | - 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1161 | - ]; |
|
1162 | - foreach ($vars as $var) { |
|
1163 | - if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1164 | - $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1165 | - if (count($credentials) === 2) { |
|
1166 | - $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1167 | - $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1168 | - break; |
|
1169 | - } |
|
1170 | - } |
|
1171 | - } |
|
1172 | - } |
|
1173 | - |
|
1174 | - protected static function tryAppAPILogin(OCP\IRequest $request): bool { |
|
1175 | - if (!$request->getHeader('AUTHORIZATION-APP-API')) { |
|
1176 | - return false; |
|
1177 | - } |
|
1178 | - $appManager = Server::get(OCP\App\IAppManager::class); |
|
1179 | - if (!$appManager->isEnabledForAnyone('app_api')) { |
|
1180 | - return false; |
|
1181 | - } |
|
1182 | - try { |
|
1183 | - $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class); |
|
1184 | - return $appAPIService->validateExAppRequestToNC($request); |
|
1185 | - } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { |
|
1186 | - return false; |
|
1187 | - } |
|
1188 | - } |
|
43 | + /** |
|
44 | + * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
45 | + */ |
|
46 | + public static string $SERVERROOT = ''; |
|
47 | + /** |
|
48 | + * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
49 | + */ |
|
50 | + private static string $SUBURI = ''; |
|
51 | + /** |
|
52 | + * the Nextcloud root path for http requests (e.g. /nextcloud) |
|
53 | + */ |
|
54 | + public static string $WEBROOT = ''; |
|
55 | + /** |
|
56 | + * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
57 | + * web path in 'url' |
|
58 | + */ |
|
59 | + public static array $APPSROOTS = []; |
|
60 | + |
|
61 | + public static string $configDir; |
|
62 | + |
|
63 | + /** |
|
64 | + * requested app |
|
65 | + */ |
|
66 | + public static string $REQUESTEDAPP = ''; |
|
67 | + |
|
68 | + /** |
|
69 | + * check if Nextcloud runs in cli mode |
|
70 | + */ |
|
71 | + public static bool $CLI = false; |
|
72 | + |
|
73 | + public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
74 | + |
|
75 | + public static \OC\Server $server; |
|
76 | + |
|
77 | + private static \OC\Config $config; |
|
78 | + |
|
79 | + /** |
|
80 | + * @throws \RuntimeException when the 3rdparty directory is missing or |
|
81 | + * the app path list is empty or contains an invalid path |
|
82 | + */ |
|
83 | + public static function initPaths(): void { |
|
84 | + if (defined('PHPUNIT_CONFIG_DIR')) { |
|
85 | + self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
86 | + } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
87 | + self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
88 | + } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
89 | + self::$configDir = rtrim($dir, '/') . '/'; |
|
90 | + } else { |
|
91 | + self::$configDir = OC::$SERVERROOT . '/config/'; |
|
92 | + } |
|
93 | + self::$config = new \OC\Config(self::$configDir); |
|
94 | + |
|
95 | + OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT))); |
|
96 | + /** |
|
97 | + * FIXME: The following lines are required because we can't yet instantiate |
|
98 | + * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
99 | + */ |
|
100 | + $params = [ |
|
101 | + 'server' => [ |
|
102 | + 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
103 | + 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
104 | + ], |
|
105 | + ]; |
|
106 | + if (isset($_SERVER['REMOTE_ADDR'])) { |
|
107 | + $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; |
|
108 | + } |
|
109 | + $fakeRequest = new \OC\AppFramework\Http\Request( |
|
110 | + $params, |
|
111 | + new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
112 | + new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
113 | + ); |
|
114 | + $scriptName = $fakeRequest->getScriptName(); |
|
115 | + if (substr($scriptName, -1) == '/') { |
|
116 | + $scriptName .= 'index.php'; |
|
117 | + //make sure suburi follows the same rules as scriptName |
|
118 | + if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
119 | + if (substr(OC::$SUBURI, -1) != '/') { |
|
120 | + OC::$SUBURI = OC::$SUBURI . '/'; |
|
121 | + } |
|
122 | + OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
123 | + } |
|
124 | + } |
|
125 | + |
|
126 | + if (OC::$CLI) { |
|
127 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
128 | + } else { |
|
129 | + if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
130 | + OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
131 | + |
|
132 | + if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
133 | + OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
134 | + } |
|
135 | + } else { |
|
136 | + // The scriptName is not ending with OC::$SUBURI |
|
137 | + // This most likely means that we are calling from CLI. |
|
138 | + // However some cron jobs still need to generate |
|
139 | + // a web URL, so we use overwritewebroot as a fallback. |
|
140 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
141 | + } |
|
142 | + |
|
143 | + // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
144 | + // slash which is required by URL generation. |
|
145 | + if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT |
|
146 | + && substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
147 | + header('Location: ' . \OC::$WEBROOT . '/'); |
|
148 | + exit(); |
|
149 | + } |
|
150 | + } |
|
151 | + |
|
152 | + // search the apps folder |
|
153 | + $config_paths = self::$config->getValue('apps_paths', []); |
|
154 | + if (!empty($config_paths)) { |
|
155 | + foreach ($config_paths as $paths) { |
|
156 | + if (isset($paths['url']) && isset($paths['path'])) { |
|
157 | + $paths['url'] = rtrim($paths['url'], '/'); |
|
158 | + $paths['path'] = rtrim($paths['path'], '/'); |
|
159 | + OC::$APPSROOTS[] = $paths; |
|
160 | + } |
|
161 | + } |
|
162 | + } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
163 | + OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
164 | + } |
|
165 | + |
|
166 | + if (empty(OC::$APPSROOTS)) { |
|
167 | + throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
168 | + . '. You can also configure the location in the config.php file.'); |
|
169 | + } |
|
170 | + $paths = []; |
|
171 | + foreach (OC::$APPSROOTS as $path) { |
|
172 | + $paths[] = $path['path']; |
|
173 | + if (!is_dir($path['path'])) { |
|
174 | + throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
175 | + . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
176 | + } |
|
177 | + } |
|
178 | + |
|
179 | + // set the right include path |
|
180 | + set_include_path( |
|
181 | + implode(PATH_SEPARATOR, $paths) |
|
182 | + ); |
|
183 | + } |
|
184 | + |
|
185 | + public static function checkConfig(): void { |
|
186 | + // Create config if it does not already exist |
|
187 | + $configFilePath = self::$configDir . '/config.php'; |
|
188 | + if (!file_exists($configFilePath)) { |
|
189 | + @touch($configFilePath); |
|
190 | + } |
|
191 | + |
|
192 | + // Check if config is writable |
|
193 | + $configFileWritable = is_writable($configFilePath); |
|
194 | + $configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only'); |
|
195 | + if (!$configFileWritable && !$configReadOnly |
|
196 | + || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
197 | + $urlGenerator = Server::get(IURLGenerator::class); |
|
198 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
199 | + |
|
200 | + if (self::$CLI) { |
|
201 | + echo $l->t('Cannot write into "config" directory!') . "\n"; |
|
202 | + echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n"; |
|
203 | + echo "\n"; |
|
204 | + echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n"; |
|
205 | + echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n"; |
|
206 | + exit; |
|
207 | + } else { |
|
208 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
209 | + $l->t('Cannot write into "config" directory!'), |
|
210 | + $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
211 | + . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
212 | + . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
213 | + 503 |
|
214 | + ); |
|
215 | + } |
|
216 | + } |
|
217 | + } |
|
218 | + |
|
219 | + public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
220 | + if (defined('OC_CONSOLE')) { |
|
221 | + return; |
|
222 | + } |
|
223 | + // Redirect to installer if not installed |
|
224 | + if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
225 | + if (OC::$CLI) { |
|
226 | + throw new Exception('Not installed'); |
|
227 | + } else { |
|
228 | + $url = OC::$WEBROOT . '/index.php'; |
|
229 | + header('Location: ' . $url); |
|
230 | + } |
|
231 | + exit(); |
|
232 | + } |
|
233 | + } |
|
234 | + |
|
235 | + public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
236 | + // Allow ajax update script to execute without being stopped |
|
237 | + if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
238 | + // send http status 503 |
|
239 | + http_response_code(503); |
|
240 | + header('X-Nextcloud-Maintenance-Mode: 1'); |
|
241 | + header('Retry-After: 120'); |
|
242 | + |
|
243 | + // render error page |
|
244 | + $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest'); |
|
245 | + \OCP\Util::addScript('core', 'maintenance'); |
|
246 | + \OCP\Util::addScript('core', 'common'); |
|
247 | + \OCP\Util::addStyle('core', 'guest'); |
|
248 | + $template->printPage(); |
|
249 | + die(); |
|
250 | + } |
|
251 | + } |
|
252 | + |
|
253 | + /** |
|
254 | + * Prints the upgrade page |
|
255 | + */ |
|
256 | + private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
257 | + $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', ''); |
|
258 | + $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
259 | + $tooBig = false; |
|
260 | + if (!$disableWebUpdater) { |
|
261 | + $apps = Server::get(\OCP\App\IAppManager::class); |
|
262 | + if ($apps->isEnabledForAnyone('user_ldap')) { |
|
263 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
264 | + |
|
265 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
266 | + ->from('ldap_user_mapping') |
|
267 | + ->executeQuery(); |
|
268 | + $row = $result->fetch(); |
|
269 | + $result->closeCursor(); |
|
270 | + |
|
271 | + $tooBig = ($row['user_count'] > 50); |
|
272 | + } |
|
273 | + if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) { |
|
274 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
275 | + |
|
276 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
277 | + ->from('user_saml_users') |
|
278 | + ->executeQuery(); |
|
279 | + $row = $result->fetch(); |
|
280 | + $result->closeCursor(); |
|
281 | + |
|
282 | + $tooBig = ($row['user_count'] > 50); |
|
283 | + } |
|
284 | + if (!$tooBig) { |
|
285 | + // count users |
|
286 | + $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51); |
|
287 | + $tooBig = ($totalUsers > 50); |
|
288 | + } |
|
289 | + } |
|
290 | + $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) |
|
291 | + && $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
292 | + |
|
293 | + if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
294 | + // send http status 503 |
|
295 | + http_response_code(503); |
|
296 | + header('Retry-After: 120'); |
|
297 | + |
|
298 | + $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class); |
|
299 | + |
|
300 | + // render error page |
|
301 | + $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest'); |
|
302 | + $template->assign('productName', 'nextcloud'); // for now |
|
303 | + $template->assign('version', $serverVersion->getVersionString()); |
|
304 | + $template->assign('tooBig', $tooBig); |
|
305 | + $template->assign('cliUpgradeLink', $cliUpgradeLink); |
|
306 | + |
|
307 | + $template->printPage(); |
|
308 | + die(); |
|
309 | + } |
|
310 | + |
|
311 | + // check whether this is a core update or apps update |
|
312 | + $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
313 | + $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
314 | + |
|
315 | + // if not a core upgrade, then it's apps upgrade |
|
316 | + $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
317 | + |
|
318 | + $oldTheme = $systemConfig->getValue('theme'); |
|
319 | + $systemConfig->setValue('theme', ''); |
|
320 | + \OCP\Util::addScript('core', 'common'); |
|
321 | + \OCP\Util::addScript('core', 'main'); |
|
322 | + \OCP\Util::addTranslations('core'); |
|
323 | + \OCP\Util::addScript('core', 'update'); |
|
324 | + |
|
325 | + /** @var \OC\App\AppManager $appManager */ |
|
326 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
327 | + |
|
328 | + $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest'); |
|
329 | + $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString()); |
|
330 | + $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
331 | + |
|
332 | + // get third party apps |
|
333 | + $ocVersion = \OCP\Util::getVersion(); |
|
334 | + $ocVersion = implode('.', $ocVersion); |
|
335 | + $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
336 | + $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []); |
|
337 | + $incompatibleShippedApps = []; |
|
338 | + $incompatibleDisabledApps = []; |
|
339 | + foreach ($incompatibleApps as $appInfo) { |
|
340 | + if ($appManager->isShipped($appInfo['id'])) { |
|
341 | + $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
342 | + } |
|
343 | + if (!in_array($appInfo['id'], $incompatibleOverwrites)) { |
|
344 | + $incompatibleDisabledApps[] = $appInfo; |
|
345 | + } |
|
346 | + } |
|
347 | + |
|
348 | + if (!empty($incompatibleShippedApps)) { |
|
349 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
350 | + $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]); |
|
351 | + throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint); |
|
352 | + } |
|
353 | + |
|
354 | + $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
355 | + $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps); |
|
356 | + try { |
|
357 | + $defaults = new \OC_Defaults(); |
|
358 | + $tmpl->assign('productName', $defaults->getName()); |
|
359 | + } catch (Throwable $error) { |
|
360 | + $tmpl->assign('productName', 'Nextcloud'); |
|
361 | + } |
|
362 | + $tmpl->assign('oldTheme', $oldTheme); |
|
363 | + $tmpl->printPage(); |
|
364 | + } |
|
365 | + |
|
366 | + public static function initSession(): void { |
|
367 | + $request = Server::get(IRequest::class); |
|
368 | + |
|
369 | + // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies |
|
370 | + // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments |
|
371 | + // TODO: for further information. |
|
372 | + // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
373 | + // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
374 | + // setcookie('cookie_test', 'test', time() + 3600); |
|
375 | + // // Do not initialize the session if a request is authenticated directly |
|
376 | + // // unless there is a session cookie already sent along |
|
377 | + // return; |
|
378 | + // } |
|
379 | + |
|
380 | + if ($request->getServerProtocol() === 'https') { |
|
381 | + ini_set('session.cookie_secure', 'true'); |
|
382 | + } |
|
383 | + |
|
384 | + // prevents javascript from accessing php session cookies |
|
385 | + ini_set('session.cookie_httponly', 'true'); |
|
386 | + |
|
387 | + // Do not initialize sessions for 'status.php' requests |
|
388 | + // Monitoring endpoints can quickly flood session handlers |
|
389 | + // and 'status.php' doesn't require sessions anyway |
|
390 | + if (str_ends_with($request->getScriptName(), '/status.php')) { |
|
391 | + return; |
|
392 | + } |
|
393 | + |
|
394 | + // set the cookie path to the Nextcloud directory |
|
395 | + $cookie_path = OC::$WEBROOT ? : '/'; |
|
396 | + ini_set('session.cookie_path', $cookie_path); |
|
397 | + |
|
398 | + // set the cookie domain to the Nextcloud domain |
|
399 | + $cookie_domain = self::$config->getValue('cookie_domain', ''); |
|
400 | + if ($cookie_domain) { |
|
401 | + ini_set('session.cookie_domain', $cookie_domain); |
|
402 | + } |
|
403 | + |
|
404 | + // Let the session name be changed in the initSession Hook |
|
405 | + $sessionName = OC_Util::getInstanceId(); |
|
406 | + |
|
407 | + try { |
|
408 | + $logger = null; |
|
409 | + if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) { |
|
410 | + $logger = logger('core'); |
|
411 | + } |
|
412 | + |
|
413 | + // set the session name to the instance id - which is unique |
|
414 | + $session = new \OC\Session\Internal( |
|
415 | + $sessionName, |
|
416 | + $logger, |
|
417 | + ); |
|
418 | + |
|
419 | + $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
420 | + $session = $cryptoWrapper->wrapSession($session); |
|
421 | + self::$server->setSession($session); |
|
422 | + |
|
423 | + // if session can't be started break with http 500 error |
|
424 | + } catch (Exception $e) { |
|
425 | + Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
426 | + //show the user a detailed error page |
|
427 | + Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500); |
|
428 | + die(); |
|
429 | + } |
|
430 | + |
|
431 | + //try to set the session lifetime |
|
432 | + $sessionLifeTime = self::getSessionLifeTime(); |
|
433 | + |
|
434 | + // session timeout |
|
435 | + if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
436 | + if (isset($_COOKIE[session_name()])) { |
|
437 | + setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
438 | + } |
|
439 | + Server::get(IUserSession::class)->logout(); |
|
440 | + } |
|
441 | + |
|
442 | + if (!self::hasSessionRelaxedExpiry()) { |
|
443 | + $session->set('LAST_ACTIVITY', time()); |
|
444 | + } |
|
445 | + $session->close(); |
|
446 | + } |
|
447 | + |
|
448 | + private static function getSessionLifeTime(): int { |
|
449 | + return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
450 | + } |
|
451 | + |
|
452 | + /** |
|
453 | + * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
454 | + */ |
|
455 | + public static function hasSessionRelaxedExpiry(): bool { |
|
456 | + return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
457 | + } |
|
458 | + |
|
459 | + /** |
|
460 | + * Try to set some values to the required Nextcloud default |
|
461 | + */ |
|
462 | + public static function setRequiredIniValues(): void { |
|
463 | + // Don't display errors and log them |
|
464 | + @ini_set('display_errors', '0'); |
|
465 | + @ini_set('log_errors', '1'); |
|
466 | + |
|
467 | + // Try to configure php to enable big file uploads. |
|
468 | + // This doesn't work always depending on the webserver and php configuration. |
|
469 | + // Let's try to overwrite some defaults if they are smaller than 1 hour |
|
470 | + |
|
471 | + if (intval(@ini_get('max_execution_time') ?: 0) < 3600) { |
|
472 | + @ini_set('max_execution_time', strval(3600)); |
|
473 | + } |
|
474 | + |
|
475 | + if (intval(@ini_get('max_input_time') ?: 0) < 3600) { |
|
476 | + @ini_set('max_input_time', strval(3600)); |
|
477 | + } |
|
478 | + |
|
479 | + // Try to set the maximum execution time to the largest time limit we have |
|
480 | + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
481 | + @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
482 | + } |
|
483 | + |
|
484 | + @ini_set('default_charset', 'UTF-8'); |
|
485 | + @ini_set('gd.jpeg_ignore_warning', '1'); |
|
486 | + } |
|
487 | + |
|
488 | + /** |
|
489 | + * Send the same site cookies |
|
490 | + */ |
|
491 | + private static function sendSameSiteCookies(): void { |
|
492 | + $cookieParams = session_get_cookie_params(); |
|
493 | + $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
494 | + $policies = [ |
|
495 | + 'lax', |
|
496 | + 'strict', |
|
497 | + ]; |
|
498 | + |
|
499 | + // Append __Host to the cookie if it meets the requirements |
|
500 | + $cookiePrefix = ''; |
|
501 | + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
502 | + $cookiePrefix = '__Host-'; |
|
503 | + } |
|
504 | + |
|
505 | + foreach ($policies as $policy) { |
|
506 | + header( |
|
507 | + sprintf( |
|
508 | + 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
509 | + $cookiePrefix, |
|
510 | + $policy, |
|
511 | + $cookieParams['path'], |
|
512 | + $policy |
|
513 | + ), |
|
514 | + false |
|
515 | + ); |
|
516 | + } |
|
517 | + } |
|
518 | + |
|
519 | + /** |
|
520 | + * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
521 | + * be set in every request if cookies are sent to add a second level of |
|
522 | + * defense against CSRF. |
|
523 | + * |
|
524 | + * If the cookie is not sent this will set the cookie and reload the page. |
|
525 | + * We use an additional cookie since we want to protect logout CSRF and |
|
526 | + * also we can't directly interfere with PHP's session mechanism. |
|
527 | + */ |
|
528 | + private static function performSameSiteCookieProtection(IConfig $config): void { |
|
529 | + $request = Server::get(IRequest::class); |
|
530 | + |
|
531 | + // Some user agents are notorious and don't really properly follow HTTP |
|
532 | + // specifications. For those, have an automated opt-out. Since the protection |
|
533 | + // for remote.php is applied in base.php as starting point we need to opt out |
|
534 | + // here. |
|
535 | + $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
536 | + |
|
537 | + // Fallback, if csrf.optout is unset |
|
538 | + if (!is_array($incompatibleUserAgents)) { |
|
539 | + $incompatibleUserAgents = [ |
|
540 | + // OS X Finder |
|
541 | + '/^WebDAVFS/', |
|
542 | + // Windows webdav drive |
|
543 | + '/^Microsoft-WebDAV-MiniRedir/', |
|
544 | + ]; |
|
545 | + } |
|
546 | + |
|
547 | + if ($request->isUserAgent($incompatibleUserAgents)) { |
|
548 | + return; |
|
549 | + } |
|
550 | + |
|
551 | + if (count($_COOKIE) > 0) { |
|
552 | + $requestUri = $request->getScriptName(); |
|
553 | + $processingScript = explode('/', $requestUri); |
|
554 | + $processingScript = $processingScript[count($processingScript) - 1]; |
|
555 | + |
|
556 | + if ($processingScript === 'index.php' // index.php routes are handled in the middleware |
|
557 | + || $processingScript === 'cron.php' // and cron.php does not need any authentication at all |
|
558 | + || $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin |
|
559 | + ) { |
|
560 | + return; |
|
561 | + } |
|
562 | + |
|
563 | + // All other endpoints require the lax and the strict cookie |
|
564 | + if (!$request->passesStrictCookieCheck()) { |
|
565 | + logger('core')->warning('Request does not pass strict cookie check'); |
|
566 | + self::sendSameSiteCookies(); |
|
567 | + // Debug mode gets access to the resources without strict cookie |
|
568 | + // due to the fact that the SabreDAV browser also lives there. |
|
569 | + if (!$config->getSystemValueBool('debug', false)) { |
|
570 | + http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED); |
|
571 | + header('Content-Type: application/json'); |
|
572 | + echo json_encode(['error' => 'Strict Cookie has not been found in request']); |
|
573 | + exit(); |
|
574 | + } |
|
575 | + } |
|
576 | + } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
577 | + self::sendSameSiteCookies(); |
|
578 | + } |
|
579 | + } |
|
580 | + |
|
581 | + public static function init(): void { |
|
582 | + // First handle PHP configuration and copy auth headers to the expected |
|
583 | + // $_SERVER variable before doing anything Server object related |
|
584 | + self::setRequiredIniValues(); |
|
585 | + self::handleAuthHeaders(); |
|
586 | + |
|
587 | + // prevent any XML processing from loading external entities |
|
588 | + libxml_set_external_entity_loader(static function () { |
|
589 | + return null; |
|
590 | + }); |
|
591 | + |
|
592 | + // Set default timezone before the Server object is booted |
|
593 | + if (!date_default_timezone_set('UTC')) { |
|
594 | + throw new \RuntimeException('Could not set timezone to UTC'); |
|
595 | + } |
|
596 | + |
|
597 | + // calculate the root directories |
|
598 | + OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4)); |
|
599 | + |
|
600 | + // register autoloader |
|
601 | + $loaderStart = microtime(true); |
|
602 | + |
|
603 | + self::$CLI = (php_sapi_name() == 'cli'); |
|
604 | + |
|
605 | + // Add default composer PSR-4 autoloader, ensure apcu to be disabled |
|
606 | + self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
607 | + self::$composerAutoloader->setApcuPrefix(null); |
|
608 | + |
|
609 | + |
|
610 | + try { |
|
611 | + self::initPaths(); |
|
612 | + // setup 3rdparty autoloader |
|
613 | + $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php'; |
|
614 | + if (!file_exists($vendorAutoLoad)) { |
|
615 | + throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
|
616 | + } |
|
617 | + require_once $vendorAutoLoad; |
|
618 | + } catch (\RuntimeException $e) { |
|
619 | + if (!self::$CLI) { |
|
620 | + http_response_code(503); |
|
621 | + } |
|
622 | + // we can't use the template error page here, because this needs the |
|
623 | + // DI container which isn't available yet |
|
624 | + print($e->getMessage()); |
|
625 | + exit(); |
|
626 | + } |
|
627 | + $loaderEnd = microtime(true); |
|
628 | + |
|
629 | + // Enable lazy loading if activated |
|
630 | + \OC\AppFramework\Utility\SimpleContainer::$useLazyObjects = (bool)self::$config->getValue('enable_lazy_objects', true); |
|
631 | + |
|
632 | + // setup the basic server |
|
633 | + self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
634 | + self::$server->boot(); |
|
635 | + |
|
636 | + try { |
|
637 | + $profiler = new BuiltInProfiler( |
|
638 | + Server::get(IConfig::class), |
|
639 | + Server::get(IRequest::class), |
|
640 | + ); |
|
641 | + $profiler->start(); |
|
642 | + } catch (\Throwable $e) { |
|
643 | + logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']); |
|
644 | + } |
|
645 | + |
|
646 | + if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) { |
|
647 | + \OC\Core\Listener\BeforeMessageLoggedEventListener::setup(); |
|
648 | + } |
|
649 | + |
|
650 | + $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
651 | + $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
652 | + $eventLogger->start('boot', 'Initialize'); |
|
653 | + |
|
654 | + // Override php.ini and log everything if we're troubleshooting |
|
655 | + if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
656 | + error_reporting(E_ALL); |
|
657 | + } |
|
658 | + |
|
659 | + // initialize intl fallback if necessary |
|
660 | + OC_Util::isSetLocaleWorking(); |
|
661 | + |
|
662 | + $config = Server::get(IConfig::class); |
|
663 | + if (!defined('PHPUNIT_RUN')) { |
|
664 | + $errorHandler = new OC\Log\ErrorHandler( |
|
665 | + \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
666 | + ); |
|
667 | + $exceptionHandler = [$errorHandler, 'onException']; |
|
668 | + if ($config->getSystemValueBool('debug', false)) { |
|
669 | + set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
670 | + if (\OC::$CLI) { |
|
671 | + $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage']; |
|
672 | + } |
|
673 | + } else { |
|
674 | + set_error_handler([$errorHandler, 'onError']); |
|
675 | + } |
|
676 | + register_shutdown_function([$errorHandler, 'onShutdown']); |
|
677 | + set_exception_handler($exceptionHandler); |
|
678 | + } |
|
679 | + |
|
680 | + /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
681 | + $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
682 | + $bootstrapCoordinator->runInitialRegistration(); |
|
683 | + |
|
684 | + $eventLogger->start('init_session', 'Initialize session'); |
|
685 | + |
|
686 | + // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users |
|
687 | + // see https://github.com/nextcloud/server/pull/2619 |
|
688 | + if (!function_exists('simplexml_load_file')) { |
|
689 | + throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.'); |
|
690 | + } |
|
691 | + |
|
692 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
693 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
694 | + if ($systemConfig->getValue('installed', false)) { |
|
695 | + $appManager->loadApps(['session']); |
|
696 | + } |
|
697 | + if (!self::$CLI) { |
|
698 | + self::initSession(); |
|
699 | + } |
|
700 | + $eventLogger->end('init_session'); |
|
701 | + self::checkConfig(); |
|
702 | + self::checkInstalled($systemConfig); |
|
703 | + |
|
704 | + OC_Response::addSecurityHeaders(); |
|
705 | + |
|
706 | + self::performSameSiteCookieProtection($config); |
|
707 | + |
|
708 | + if (!defined('OC_CONSOLE')) { |
|
709 | + $eventLogger->start('check_server', 'Run a few configuration checks'); |
|
710 | + $errors = OC_Util::checkServer($systemConfig); |
|
711 | + if (count($errors) > 0) { |
|
712 | + if (!self::$CLI) { |
|
713 | + http_response_code(503); |
|
714 | + Util::addStyle('guest'); |
|
715 | + try { |
|
716 | + Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]); |
|
717 | + exit; |
|
718 | + } catch (\Exception $e) { |
|
719 | + // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
720 | + // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
721 | + } |
|
722 | + } |
|
723 | + |
|
724 | + // Convert l10n string into regular string for usage in database |
|
725 | + $staticErrors = []; |
|
726 | + foreach ($errors as $error) { |
|
727 | + echo $error['error'] . "\n"; |
|
728 | + echo $error['hint'] . "\n\n"; |
|
729 | + $staticErrors[] = [ |
|
730 | + 'error' => (string)$error['error'], |
|
731 | + 'hint' => (string)$error['hint'], |
|
732 | + ]; |
|
733 | + } |
|
734 | + |
|
735 | + try { |
|
736 | + $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
737 | + } catch (\Exception $e) { |
|
738 | + echo('Writing to database failed'); |
|
739 | + } |
|
740 | + exit(1); |
|
741 | + } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) { |
|
742 | + $config->deleteAppValue('core', 'cronErrors'); |
|
743 | + } |
|
744 | + $eventLogger->end('check_server'); |
|
745 | + } |
|
746 | + |
|
747 | + // User and Groups |
|
748 | + if (!$systemConfig->getValue('installed', false)) { |
|
749 | + self::$server->getSession()->set('user_id', ''); |
|
750 | + } |
|
751 | + |
|
752 | + $eventLogger->start('setup_backends', 'Setup group and user backends'); |
|
753 | + Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
754 | + Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
755 | + |
|
756 | + // Subscribe to the hook |
|
757 | + \OCP\Util::connectHook( |
|
758 | + '\OCA\Files_Sharing\API\Server2Server', |
|
759 | + 'preLoginNameUsedAsUserName', |
|
760 | + '\OC\User\Database', |
|
761 | + 'preLoginNameUsedAsUserName' |
|
762 | + ); |
|
763 | + |
|
764 | + //setup extra user backends |
|
765 | + if (!\OCP\Util::needUpgrade()) { |
|
766 | + OC_User::setupBackends(); |
|
767 | + } else { |
|
768 | + // Run upgrades in incognito mode |
|
769 | + OC_User::setIncognitoMode(true); |
|
770 | + } |
|
771 | + $eventLogger->end('setup_backends'); |
|
772 | + |
|
773 | + self::registerCleanupHooks($systemConfig); |
|
774 | + self::registerShareHooks($systemConfig); |
|
775 | + self::registerEncryptionWrapperAndHooks(); |
|
776 | + self::registerAccountHooks(); |
|
777 | + self::registerResourceCollectionHooks(); |
|
778 | + self::registerFileReferenceEventListener(); |
|
779 | + self::registerRenderReferenceEventListener(); |
|
780 | + self::registerAppRestrictionsHooks(); |
|
781 | + |
|
782 | + // Make sure that the application class is not loaded before the database is setup |
|
783 | + if ($systemConfig->getValue('installed', false)) { |
|
784 | + $appManager->loadApp('settings'); |
|
785 | + } |
|
786 | + |
|
787 | + //make sure temporary files are cleaned up |
|
788 | + $tmpManager = Server::get(\OCP\ITempManager::class); |
|
789 | + register_shutdown_function([$tmpManager, 'clean']); |
|
790 | + $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
791 | + register_shutdown_function([$lockProvider, 'releaseAll']); |
|
792 | + |
|
793 | + // Check whether the sample configuration has been copied |
|
794 | + if ($systemConfig->getValue('copied_sample_config', false)) { |
|
795 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
796 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
797 | + $l->t('Sample configuration detected'), |
|
798 | + $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'), |
|
799 | + 503 |
|
800 | + ); |
|
801 | + return; |
|
802 | + } |
|
803 | + |
|
804 | + $request = Server::get(IRequest::class); |
|
805 | + $host = $request->getInsecureServerHost(); |
|
806 | + /** |
|
807 | + * if the host passed in headers isn't trusted |
|
808 | + * FIXME: Should not be in here at all :see_no_evil: |
|
809 | + */ |
|
810 | + if (!OC::$CLI |
|
811 | + && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
812 | + && $config->getSystemValueBool('installed', false) |
|
813 | + ) { |
|
814 | + // Allow access to CSS resources |
|
815 | + $isScssRequest = false; |
|
816 | + if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
817 | + $isScssRequest = true; |
|
818 | + } |
|
819 | + |
|
820 | + if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
821 | + http_response_code(400); |
|
822 | + header('Content-Type: application/json'); |
|
823 | + echo '{"error": "Trusted domain error.", "code": 15}'; |
|
824 | + exit(); |
|
825 | + } |
|
826 | + |
|
827 | + if (!$isScssRequest) { |
|
828 | + http_response_code(400); |
|
829 | + Server::get(LoggerInterface::class)->info( |
|
830 | + 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
831 | + [ |
|
832 | + 'app' => 'core', |
|
833 | + 'remoteAddress' => $request->getRemoteAddress(), |
|
834 | + 'host' => $host, |
|
835 | + ] |
|
836 | + ); |
|
837 | + |
|
838 | + $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest'); |
|
839 | + $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
840 | + $tmpl->printPage(); |
|
841 | + |
|
842 | + exit(); |
|
843 | + } |
|
844 | + } |
|
845 | + $eventLogger->end('boot'); |
|
846 | + $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
847 | + $eventLogger->start('runtime', 'Runtime'); |
|
848 | + $eventLogger->start('request', 'Full request after boot'); |
|
849 | + register_shutdown_function(function () use ($eventLogger) { |
|
850 | + $eventLogger->end('request'); |
|
851 | + }); |
|
852 | + |
|
853 | + register_shutdown_function(function () { |
|
854 | + $memoryPeak = memory_get_peak_usage(); |
|
855 | + $logLevel = match (true) { |
|
856 | + $memoryPeak > 500_000_000 => ILogger::FATAL, |
|
857 | + $memoryPeak > 400_000_000 => ILogger::ERROR, |
|
858 | + $memoryPeak > 300_000_000 => ILogger::WARN, |
|
859 | + default => null, |
|
860 | + }; |
|
861 | + if ($logLevel !== null) { |
|
862 | + $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak); |
|
863 | + $logger = Server::get(LoggerInterface::class); |
|
864 | + $logger->log($logLevel, $message, ['app' => 'core']); |
|
865 | + } |
|
866 | + }); |
|
867 | + } |
|
868 | + |
|
869 | + /** |
|
870 | + * register hooks for the cleanup of cache and bruteforce protection |
|
871 | + */ |
|
872 | + public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
873 | + //don't try to do this before we are properly setup |
|
874 | + if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
875 | + // NOTE: This will be replaced to use OCP |
|
876 | + $userSession = Server::get(\OC\User\Session::class); |
|
877 | + $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
878 | + if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
879 | + // reset brute force delay for this IP address and username |
|
880 | + $uid = $userSession->getUser()->getUID(); |
|
881 | + $request = Server::get(IRequest::class); |
|
882 | + $throttler = Server::get(IThrottler::class); |
|
883 | + $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
884 | + } |
|
885 | + |
|
886 | + try { |
|
887 | + $cache = new \OC\Cache\File(); |
|
888 | + $cache->gc(); |
|
889 | + } catch (\OC\ServerNotAvailableException $e) { |
|
890 | + // not a GC exception, pass it on |
|
891 | + throw $e; |
|
892 | + } catch (\OC\ForbiddenException $e) { |
|
893 | + // filesystem blocked for this request, ignore |
|
894 | + } catch (\Exception $e) { |
|
895 | + // a GC exception should not prevent users from using OC, |
|
896 | + // so log the exception |
|
897 | + Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
898 | + 'app' => 'core', |
|
899 | + 'exception' => $e, |
|
900 | + ]); |
|
901 | + } |
|
902 | + }); |
|
903 | + } |
|
904 | + } |
|
905 | + |
|
906 | + private static function registerEncryptionWrapperAndHooks(): void { |
|
907 | + /** @var \OC\Encryption\Manager */ |
|
908 | + $manager = Server::get(\OCP\Encryption\IManager::class); |
|
909 | + Server::get(IEventDispatcher::class)->addListener( |
|
910 | + BeforeFileSystemSetupEvent::class, |
|
911 | + $manager->setupStorage(...), |
|
912 | + ); |
|
913 | + |
|
914 | + $enabled = $manager->isEnabled(); |
|
915 | + if ($enabled) { |
|
916 | + \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class)); |
|
917 | + } |
|
918 | + } |
|
919 | + |
|
920 | + private static function registerAccountHooks(): void { |
|
921 | + /** @var IEventDispatcher $dispatcher */ |
|
922 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
923 | + $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
924 | + } |
|
925 | + |
|
926 | + private static function registerAppRestrictionsHooks(): void { |
|
927 | + /** @var \OC\Group\Manager $groupManager */ |
|
928 | + $groupManager = Server::get(\OCP\IGroupManager::class); |
|
929 | + $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
930 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
931 | + $apps = $appManager->getEnabledAppsForGroup($group); |
|
932 | + foreach ($apps as $appId) { |
|
933 | + $restrictions = $appManager->getAppRestriction($appId); |
|
934 | + if (empty($restrictions)) { |
|
935 | + continue; |
|
936 | + } |
|
937 | + $key = array_search($group->getGID(), $restrictions); |
|
938 | + unset($restrictions[$key]); |
|
939 | + $restrictions = array_values($restrictions); |
|
940 | + if (empty($restrictions)) { |
|
941 | + $appManager->disableApp($appId); |
|
942 | + } else { |
|
943 | + $appManager->enableAppForGroups($appId, $restrictions); |
|
944 | + } |
|
945 | + } |
|
946 | + }); |
|
947 | + } |
|
948 | + |
|
949 | + private static function registerResourceCollectionHooks(): void { |
|
950 | + \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class)); |
|
951 | + } |
|
952 | + |
|
953 | + private static function registerFileReferenceEventListener(): void { |
|
954 | + \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
955 | + } |
|
956 | + |
|
957 | + private static function registerRenderReferenceEventListener() { |
|
958 | + \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
959 | + } |
|
960 | + |
|
961 | + /** |
|
962 | + * register hooks for sharing |
|
963 | + */ |
|
964 | + public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
965 | + if ($systemConfig->getValue('installed')) { |
|
966 | + |
|
967 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
968 | + $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class); |
|
969 | + $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class); |
|
970 | + $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class); |
|
971 | + } |
|
972 | + } |
|
973 | + |
|
974 | + /** |
|
975 | + * Handle the request |
|
976 | + */ |
|
977 | + public static function handleRequest(): void { |
|
978 | + Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
979 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
980 | + |
|
981 | + // Check if Nextcloud is installed or in maintenance (update) mode |
|
982 | + if (!$systemConfig->getValue('installed', false)) { |
|
983 | + \OC::$server->getSession()->clear(); |
|
984 | + $controller = Server::get(\OC\Core\Controller\SetupController::class); |
|
985 | + $controller->run($_POST); |
|
986 | + exit(); |
|
987 | + } |
|
988 | + |
|
989 | + $request = Server::get(IRequest::class); |
|
990 | + $request->throwDecodingExceptionIfAny(); |
|
991 | + $requestPath = $request->getRawPathInfo(); |
|
992 | + if ($requestPath === '/heartbeat') { |
|
993 | + return; |
|
994 | + } |
|
995 | + if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
996 | + self::checkMaintenanceMode($systemConfig); |
|
997 | + |
|
998 | + if (\OCP\Util::needUpgrade()) { |
|
999 | + if (function_exists('opcache_reset')) { |
|
1000 | + opcache_reset(); |
|
1001 | + } |
|
1002 | + if (!((bool)$systemConfig->getValue('maintenance', false))) { |
|
1003 | + self::printUpgradePage($systemConfig); |
|
1004 | + exit(); |
|
1005 | + } |
|
1006 | + } |
|
1007 | + } |
|
1008 | + |
|
1009 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
1010 | + |
|
1011 | + // Always load authentication apps |
|
1012 | + $appManager->loadApps(['authentication']); |
|
1013 | + $appManager->loadApps(['extended_authentication']); |
|
1014 | + |
|
1015 | + // Load minimum set of apps |
|
1016 | + if (!\OCP\Util::needUpgrade() |
|
1017 | + && !((bool)$systemConfig->getValue('maintenance', false))) { |
|
1018 | + // For logged-in users: Load everything |
|
1019 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1020 | + $appManager->loadApps(); |
|
1021 | + } else { |
|
1022 | + // For guests: Load only filesystem and logging |
|
1023 | + $appManager->loadApps(['filesystem', 'logging']); |
|
1024 | + |
|
1025 | + // Don't try to login when a client is trying to get a OAuth token. |
|
1026 | + // OAuth needs to support basic auth too, so the login is not valid |
|
1027 | + // inside Nextcloud and the Login exception would ruin it. |
|
1028 | + if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
1029 | + try { |
|
1030 | + self::handleLogin($request); |
|
1031 | + } catch (DisabledUserException $e) { |
|
1032 | + // Disabled users would not be seen as logged in and |
|
1033 | + // trying to log them in would fail, so the login |
|
1034 | + // exception is ignored for the themed stylesheets and |
|
1035 | + // images. |
|
1036 | + if ($request->getRawPathInfo() !== '/apps/theming/theme/default.css' |
|
1037 | + && $request->getRawPathInfo() !== '/apps/theming/theme/light.css' |
|
1038 | + && $request->getRawPathInfo() !== '/apps/theming/theme/dark.css' |
|
1039 | + && $request->getRawPathInfo() !== '/apps/theming/theme/light-highcontrast.css' |
|
1040 | + && $request->getRawPathInfo() !== '/apps/theming/theme/dark-highcontrast.css' |
|
1041 | + && $request->getRawPathInfo() !== '/apps/theming/theme/opendyslexic.css' |
|
1042 | + && $request->getRawPathInfo() !== '/apps/theming/image/background' |
|
1043 | + && $request->getRawPathInfo() !== '/apps/theming/image/logo' |
|
1044 | + && $request->getRawPathInfo() !== '/apps/theming/image/logoheader' |
|
1045 | + && !str_starts_with($request->getRawPathInfo(), '/apps/theming/favicon') |
|
1046 | + && !str_starts_with($request->getRawPathInfo(), '/apps/theming/icon')) { |
|
1047 | + throw $e; |
|
1048 | + } |
|
1049 | + } |
|
1050 | + } |
|
1051 | + } |
|
1052 | + } |
|
1053 | + |
|
1054 | + if (!self::$CLI) { |
|
1055 | + try { |
|
1056 | + if (!\OCP\Util::needUpgrade()) { |
|
1057 | + $appManager->loadApps(['filesystem', 'logging']); |
|
1058 | + $appManager->loadApps(); |
|
1059 | + } |
|
1060 | + Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1061 | + return; |
|
1062 | + } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1063 | + //header('HTTP/1.0 404 Not Found'); |
|
1064 | + } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1065 | + http_response_code(405); |
|
1066 | + return; |
|
1067 | + } |
|
1068 | + } |
|
1069 | + |
|
1070 | + // Handle WebDAV |
|
1071 | + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1072 | + // not allowed any more to prevent people |
|
1073 | + // mounting this root directly. |
|
1074 | + // Users need to mount remote.php/webdav instead. |
|
1075 | + http_response_code(405); |
|
1076 | + return; |
|
1077 | + } |
|
1078 | + |
|
1079 | + // Handle requests for JSON or XML |
|
1080 | + $acceptHeader = $request->getHeader('Accept'); |
|
1081 | + if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
1082 | + http_response_code(404); |
|
1083 | + return; |
|
1084 | + } |
|
1085 | + |
|
1086 | + // Handle resources that can't be found |
|
1087 | + // This prevents browsers from redirecting to the default page and then |
|
1088 | + // attempting to parse HTML as CSS and similar. |
|
1089 | + $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
1090 | + if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
1091 | + http_response_code(404); |
|
1092 | + return; |
|
1093 | + } |
|
1094 | + |
|
1095 | + // Redirect to the default app or login only as an entry point |
|
1096 | + if ($requestPath === '') { |
|
1097 | + // Someone is logged in |
|
1098 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1099 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
1100 | + } else { |
|
1101 | + // Not handled and not logged in |
|
1102 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1103 | + } |
|
1104 | + return; |
|
1105 | + } |
|
1106 | + |
|
1107 | + try { |
|
1108 | + Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
1109 | + } catch (\Exception $e) { |
|
1110 | + if (!$e instanceof MethodNotAllowedException) { |
|
1111 | + logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
1112 | + } |
|
1113 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
1114 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
1115 | + '404', |
|
1116 | + $l->t('The page could not be found on the server.'), |
|
1117 | + 404 |
|
1118 | + ); |
|
1119 | + } |
|
1120 | + } |
|
1121 | + |
|
1122 | + /** |
|
1123 | + * Check login: apache auth, auth token, basic auth |
|
1124 | + */ |
|
1125 | + public static function handleLogin(OCP\IRequest $request): bool { |
|
1126 | + if ($request->getHeader('X-Nextcloud-Federation')) { |
|
1127 | + return false; |
|
1128 | + } |
|
1129 | + $userSession = Server::get(\OC\User\Session::class); |
|
1130 | + if (OC_User::handleApacheAuth()) { |
|
1131 | + return true; |
|
1132 | + } |
|
1133 | + if (self::tryAppAPILogin($request)) { |
|
1134 | + return true; |
|
1135 | + } |
|
1136 | + if ($userSession->tryTokenLogin($request)) { |
|
1137 | + return true; |
|
1138 | + } |
|
1139 | + if (isset($_COOKIE['nc_username']) |
|
1140 | + && isset($_COOKIE['nc_token']) |
|
1141 | + && isset($_COOKIE['nc_session_id']) |
|
1142 | + && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1143 | + return true; |
|
1144 | + } |
|
1145 | + if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) { |
|
1146 | + return true; |
|
1147 | + } |
|
1148 | + return false; |
|
1149 | + } |
|
1150 | + |
|
1151 | + protected static function handleAuthHeaders(): void { |
|
1152 | + //copy http auth headers for apache+php-fcgid work around |
|
1153 | + if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1154 | + $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1155 | + } |
|
1156 | + |
|
1157 | + // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1158 | + $vars = [ |
|
1159 | + 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1160 | + 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1161 | + ]; |
|
1162 | + foreach ($vars as $var) { |
|
1163 | + if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1164 | + $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1165 | + if (count($credentials) === 2) { |
|
1166 | + $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1167 | + $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1168 | + break; |
|
1169 | + } |
|
1170 | + } |
|
1171 | + } |
|
1172 | + } |
|
1173 | + |
|
1174 | + protected static function tryAppAPILogin(OCP\IRequest $request): bool { |
|
1175 | + if (!$request->getHeader('AUTHORIZATION-APP-API')) { |
|
1176 | + return false; |
|
1177 | + } |
|
1178 | + $appManager = Server::get(OCP\App\IAppManager::class); |
|
1179 | + if (!$appManager->isEnabledForAnyone('app_api')) { |
|
1180 | + return false; |
|
1181 | + } |
|
1182 | + try { |
|
1183 | + $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class); |
|
1184 | + return $appAPIService->validateExAppRequestToNC($request); |
|
1185 | + } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { |
|
1186 | + return false; |
|
1187 | + } |
|
1188 | + } |
|
1189 | 1189 | } |
1190 | 1190 | |
1191 | 1191 | OC::init(); |