@@ -24,223 +24,223 @@ |
||
| 24 | 24 | * @since 8.0.0 |
| 25 | 25 | */ |
| 26 | 26 | interface IUserManager { |
| 27 | - /** |
|
| 28 | - * @since 26.0.0 |
|
| 29 | - */ |
|
| 30 | - public const MAX_PASSWORD_LENGTH = 469; |
|
| 31 | - |
|
| 32 | - /** |
|
| 33 | - * register a user backend |
|
| 34 | - * |
|
| 35 | - * @since 8.0.0 |
|
| 36 | - * @return void |
|
| 37 | - */ |
|
| 38 | - public function registerBackend(UserInterface $backend); |
|
| 39 | - |
|
| 40 | - /** |
|
| 41 | - * Get the active backends |
|
| 42 | - * @return UserInterface[] |
|
| 43 | - * @since 8.0.0 |
|
| 44 | - */ |
|
| 45 | - public function getBackends(); |
|
| 46 | - |
|
| 47 | - /** |
|
| 48 | - * remove a user backend |
|
| 49 | - * |
|
| 50 | - * @since 8.0.0 |
|
| 51 | - * @return void |
|
| 52 | - */ |
|
| 53 | - public function removeBackend(UserInterface $backend); |
|
| 54 | - |
|
| 55 | - /** |
|
| 56 | - * remove all user backends |
|
| 57 | - * @since 8.0.0 |
|
| 58 | - * @return void |
|
| 59 | - */ |
|
| 60 | - public function clearBackends(); |
|
| 61 | - |
|
| 62 | - /** |
|
| 63 | - * get a user by user id |
|
| 64 | - * |
|
| 65 | - * @param string $uid |
|
| 66 | - * @return \OCP\IUser|null Either the user or null if the specified user does not exist |
|
| 67 | - * @since 8.0.0 |
|
| 68 | - */ |
|
| 69 | - public function get($uid); |
|
| 70 | - |
|
| 71 | - /** |
|
| 72 | - * Get the display name of a user |
|
| 73 | - * |
|
| 74 | - * @param string $uid |
|
| 75 | - * @return string|null |
|
| 76 | - * @since 25.0.0 |
|
| 77 | - */ |
|
| 78 | - public function getDisplayName(string $uid): ?string; |
|
| 79 | - |
|
| 80 | - /** |
|
| 81 | - * check if a user exists |
|
| 82 | - * |
|
| 83 | - * @param string $uid |
|
| 84 | - * @return bool |
|
| 85 | - * @since 8.0.0 |
|
| 86 | - */ |
|
| 87 | - public function userExists($uid); |
|
| 88 | - |
|
| 89 | - /** |
|
| 90 | - * Check if the password is valid for the user |
|
| 91 | - * |
|
| 92 | - * @param string $loginName |
|
| 93 | - * @param string $password |
|
| 94 | - * @return IUser|false the User object on success, false otherwise |
|
| 95 | - * @since 8.0.0 |
|
| 96 | - */ |
|
| 97 | - public function checkPassword($loginName, $password); |
|
| 98 | - |
|
| 99 | - /** |
|
| 100 | - * search by user id |
|
| 101 | - * |
|
| 102 | - * @param string $pattern |
|
| 103 | - * @param int $limit |
|
| 104 | - * @param int $offset |
|
| 105 | - * @return \OCP\IUser[] |
|
| 106 | - * @since 8.0.0 |
|
| 107 | - */ |
|
| 108 | - public function search($pattern, $limit = null, $offset = null); |
|
| 109 | - |
|
| 110 | - /** |
|
| 111 | - * search by displayName |
|
| 112 | - * |
|
| 113 | - * @param string $pattern |
|
| 114 | - * @param int $limit |
|
| 115 | - * @param int $offset |
|
| 116 | - * @return \OCP\IUser[] |
|
| 117 | - * @since 8.0.0 |
|
| 118 | - */ |
|
| 119 | - public function searchDisplayName($pattern, $limit = null, $offset = null); |
|
| 120 | - |
|
| 121 | - /** |
|
| 122 | - * @return IUser[] |
|
| 123 | - * @since 28.0.0 |
|
| 124 | - * @since 30.0.0 $search parameter added |
|
| 125 | - */ |
|
| 126 | - public function getDisabledUsers(?int $limit = null, int $offset = 0, string $search = ''): array; |
|
| 127 | - |
|
| 128 | - /** |
|
| 129 | - * Search known users (from phonebook sync) by displayName |
|
| 130 | - * |
|
| 131 | - * @param string $searcher |
|
| 132 | - * @param string $pattern |
|
| 133 | - * @param int|null $limit |
|
| 134 | - * @param int|null $offset |
|
| 135 | - * @return IUser[] |
|
| 136 | - * @since 21.0.1 |
|
| 137 | - */ |
|
| 138 | - public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array; |
|
| 139 | - |
|
| 140 | - /** |
|
| 141 | - * @param string $uid |
|
| 142 | - * @param string $password |
|
| 143 | - * @throws \InvalidArgumentException |
|
| 144 | - * @return false|\OCP\IUser the created user or false |
|
| 145 | - * @since 8.0.0 |
|
| 146 | - */ |
|
| 147 | - public function createUser($uid, $password); |
|
| 148 | - |
|
| 149 | - /** |
|
| 150 | - * @param string $uid |
|
| 151 | - * @param string $password |
|
| 152 | - * @param UserInterface $backend |
|
| 153 | - * @return IUser|null |
|
| 154 | - * @throws \InvalidArgumentException |
|
| 155 | - * @since 12.0.0 |
|
| 156 | - */ |
|
| 157 | - public function createUserFromBackend($uid, $password, UserInterface $backend); |
|
| 158 | - |
|
| 159 | - /** |
|
| 160 | - * Get how many users per backend exist (if supported by backend) |
|
| 161 | - * |
|
| 162 | - * @return array<string, int> an array of backend class name as key and count number as value |
|
| 163 | - * @since 8.0.0 |
|
| 164 | - */ |
|
| 165 | - public function countUsers(); |
|
| 166 | - |
|
| 167 | - /** |
|
| 168 | - * Get how many users exists in total, whithin limit |
|
| 169 | - * |
|
| 170 | - * @param int $limit Limit the count to avoid resource waste. 0 to disable |
|
| 171 | - * @param bool $onlyMappedUsers Count mapped users instead of all users for compatible backends |
|
| 172 | - * |
|
| 173 | - * @since 31.0.0 |
|
| 174 | - */ |
|
| 175 | - public function countUsersTotal(int $limit = 0, bool $onlyMappedUsers = false): int|false; |
|
| 176 | - |
|
| 177 | - /** |
|
| 178 | - * @param \Closure $callback |
|
| 179 | - * @psalm-param \Closure(\OCP\IUser):void $callback |
|
| 180 | - * @param string $search |
|
| 181 | - * @since 9.0.0 |
|
| 182 | - */ |
|
| 183 | - public function callForAllUsers(\Closure $callback, $search = ''); |
|
| 184 | - |
|
| 185 | - /** |
|
| 186 | - * returns how many users have logged in once |
|
| 187 | - * |
|
| 188 | - * @return int |
|
| 189 | - * @since 11.0.0 |
|
| 190 | - */ |
|
| 191 | - public function countDisabledUsers(); |
|
| 192 | - |
|
| 193 | - /** |
|
| 194 | - * returns how many users have logged in once |
|
| 195 | - * |
|
| 196 | - * @return int |
|
| 197 | - * @since 11.0.0 |
|
| 198 | - */ |
|
| 199 | - public function countSeenUsers(); |
|
| 200 | - |
|
| 201 | - /** |
|
| 202 | - * @param \Closure $callback |
|
| 203 | - * @psalm-param \Closure(\OCP\IUser):?bool $callback |
|
| 204 | - * @since 11.0.0 |
|
| 205 | - */ |
|
| 206 | - public function callForSeenUsers(\Closure $callback); |
|
| 207 | - |
|
| 208 | - /** |
|
| 209 | - * returns all users having the provided email set as system email address |
|
| 210 | - * |
|
| 211 | - * @param string $email |
|
| 212 | - * @return IUser[] |
|
| 213 | - * @since 9.1.0 |
|
| 214 | - */ |
|
| 215 | - public function getByEmail($email); |
|
| 216 | - |
|
| 217 | - /** |
|
| 218 | - * @param string $uid The user ID to validate |
|
| 219 | - * @param bool $checkDataDirectory Whether it should be checked if files for the ID exist inside the data directory |
|
| 220 | - * @throws \InvalidArgumentException Message is an already translated string with a reason why the ID is not valid |
|
| 221 | - * @since 26.0.0 |
|
| 222 | - */ |
|
| 223 | - public function validateUserId(string $uid, bool $checkDataDirectory = false): void; |
|
| 224 | - |
|
| 225 | - /** |
|
| 226 | - * Gets the list of users sorted by lastLogin, from most recent to least recent |
|
| 227 | - * |
|
| 228 | - * @param int|null $limit how many records to fetch |
|
| 229 | - * @param int $offset from which offset to fetch |
|
| 230 | - * @param string $search search users based on search params |
|
| 231 | - * @return list<string> list of user IDs |
|
| 232 | - * @since 30.0.0 |
|
| 233 | - */ |
|
| 234 | - public function getLastLoggedInUsers(?int $limit = null, int $offset = 0, string $search = ''): array; |
|
| 235 | - |
|
| 236 | - /** |
|
| 237 | - * Gets the list of users. |
|
| 238 | - * An iterator is returned allowing the caller to stop the iteration at any time. |
|
| 239 | - * The offset argument allows the caller to continue the iteration at a specific offset. |
|
| 240 | - * |
|
| 241 | - * @param int $offset from which offset to fetch |
|
| 242 | - * @return \Iterator<IUser> list of IUser object |
|
| 243 | - * @since 32.0.0 |
|
| 244 | - */ |
|
| 245 | - public function getSeenUsers(int $offset = 0): \Iterator; |
|
| 27 | + /** |
|
| 28 | + * @since 26.0.0 |
|
| 29 | + */ |
|
| 30 | + public const MAX_PASSWORD_LENGTH = 469; |
|
| 31 | + |
|
| 32 | + /** |
|
| 33 | + * register a user backend |
|
| 34 | + * |
|
| 35 | + * @since 8.0.0 |
|
| 36 | + * @return void |
|
| 37 | + */ |
|
| 38 | + public function registerBackend(UserInterface $backend); |
|
| 39 | + |
|
| 40 | + /** |
|
| 41 | + * Get the active backends |
|
| 42 | + * @return UserInterface[] |
|
| 43 | + * @since 8.0.0 |
|
| 44 | + */ |
|
| 45 | + public function getBackends(); |
|
| 46 | + |
|
| 47 | + /** |
|
| 48 | + * remove a user backend |
|
| 49 | + * |
|
| 50 | + * @since 8.0.0 |
|
| 51 | + * @return void |
|
| 52 | + */ |
|
| 53 | + public function removeBackend(UserInterface $backend); |
|
| 54 | + |
|
| 55 | + /** |
|
| 56 | + * remove all user backends |
|
| 57 | + * @since 8.0.0 |
|
| 58 | + * @return void |
|
| 59 | + */ |
|
| 60 | + public function clearBackends(); |
|
| 61 | + |
|
| 62 | + /** |
|
| 63 | + * get a user by user id |
|
| 64 | + * |
|
| 65 | + * @param string $uid |
|
| 66 | + * @return \OCP\IUser|null Either the user or null if the specified user does not exist |
|
| 67 | + * @since 8.0.0 |
|
| 68 | + */ |
|
| 69 | + public function get($uid); |
|
| 70 | + |
|
| 71 | + /** |
|
| 72 | + * Get the display name of a user |
|
| 73 | + * |
|
| 74 | + * @param string $uid |
|
| 75 | + * @return string|null |
|
| 76 | + * @since 25.0.0 |
|
| 77 | + */ |
|
| 78 | + public function getDisplayName(string $uid): ?string; |
|
| 79 | + |
|
| 80 | + /** |
|
| 81 | + * check if a user exists |
|
| 82 | + * |
|
| 83 | + * @param string $uid |
|
| 84 | + * @return bool |
|
| 85 | + * @since 8.0.0 |
|
| 86 | + */ |
|
| 87 | + public function userExists($uid); |
|
| 88 | + |
|
| 89 | + /** |
|
| 90 | + * Check if the password is valid for the user |
|
| 91 | + * |
|
| 92 | + * @param string $loginName |
|
| 93 | + * @param string $password |
|
| 94 | + * @return IUser|false the User object on success, false otherwise |
|
| 95 | + * @since 8.0.0 |
|
| 96 | + */ |
|
| 97 | + public function checkPassword($loginName, $password); |
|
| 98 | + |
|
| 99 | + /** |
|
| 100 | + * search by user id |
|
| 101 | + * |
|
| 102 | + * @param string $pattern |
|
| 103 | + * @param int $limit |
|
| 104 | + * @param int $offset |
|
| 105 | + * @return \OCP\IUser[] |
|
| 106 | + * @since 8.0.0 |
|
| 107 | + */ |
|
| 108 | + public function search($pattern, $limit = null, $offset = null); |
|
| 109 | + |
|
| 110 | + /** |
|
| 111 | + * search by displayName |
|
| 112 | + * |
|
| 113 | + * @param string $pattern |
|
| 114 | + * @param int $limit |
|
| 115 | + * @param int $offset |
|
| 116 | + * @return \OCP\IUser[] |
|
| 117 | + * @since 8.0.0 |
|
| 118 | + */ |
|
| 119 | + public function searchDisplayName($pattern, $limit = null, $offset = null); |
|
| 120 | + |
|
| 121 | + /** |
|
| 122 | + * @return IUser[] |
|
| 123 | + * @since 28.0.0 |
|
| 124 | + * @since 30.0.0 $search parameter added |
|
| 125 | + */ |
|
| 126 | + public function getDisabledUsers(?int $limit = null, int $offset = 0, string $search = ''): array; |
|
| 127 | + |
|
| 128 | + /** |
|
| 129 | + * Search known users (from phonebook sync) by displayName |
|
| 130 | + * |
|
| 131 | + * @param string $searcher |
|
| 132 | + * @param string $pattern |
|
| 133 | + * @param int|null $limit |
|
| 134 | + * @param int|null $offset |
|
| 135 | + * @return IUser[] |
|
| 136 | + * @since 21.0.1 |
|
| 137 | + */ |
|
| 138 | + public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array; |
|
| 139 | + |
|
| 140 | + /** |
|
| 141 | + * @param string $uid |
|
| 142 | + * @param string $password |
|
| 143 | + * @throws \InvalidArgumentException |
|
| 144 | + * @return false|\OCP\IUser the created user or false |
|
| 145 | + * @since 8.0.0 |
|
| 146 | + */ |
|
| 147 | + public function createUser($uid, $password); |
|
| 148 | + |
|
| 149 | + /** |
|
| 150 | + * @param string $uid |
|
| 151 | + * @param string $password |
|
| 152 | + * @param UserInterface $backend |
|
| 153 | + * @return IUser|null |
|
| 154 | + * @throws \InvalidArgumentException |
|
| 155 | + * @since 12.0.0 |
|
| 156 | + */ |
|
| 157 | + public function createUserFromBackend($uid, $password, UserInterface $backend); |
|
| 158 | + |
|
| 159 | + /** |
|
| 160 | + * Get how many users per backend exist (if supported by backend) |
|
| 161 | + * |
|
| 162 | + * @return array<string, int> an array of backend class name as key and count number as value |
|
| 163 | + * @since 8.0.0 |
|
| 164 | + */ |
|
| 165 | + public function countUsers(); |
|
| 166 | + |
|
| 167 | + /** |
|
| 168 | + * Get how many users exists in total, whithin limit |
|
| 169 | + * |
|
| 170 | + * @param int $limit Limit the count to avoid resource waste. 0 to disable |
|
| 171 | + * @param bool $onlyMappedUsers Count mapped users instead of all users for compatible backends |
|
| 172 | + * |
|
| 173 | + * @since 31.0.0 |
|
| 174 | + */ |
|
| 175 | + public function countUsersTotal(int $limit = 0, bool $onlyMappedUsers = false): int|false; |
|
| 176 | + |
|
| 177 | + /** |
|
| 178 | + * @param \Closure $callback |
|
| 179 | + * @psalm-param \Closure(\OCP\IUser):void $callback |
|
| 180 | + * @param string $search |
|
| 181 | + * @since 9.0.0 |
|
| 182 | + */ |
|
| 183 | + public function callForAllUsers(\Closure $callback, $search = ''); |
|
| 184 | + |
|
| 185 | + /** |
|
| 186 | + * returns how many users have logged in once |
|
| 187 | + * |
|
| 188 | + * @return int |
|
| 189 | + * @since 11.0.0 |
|
| 190 | + */ |
|
| 191 | + public function countDisabledUsers(); |
|
| 192 | + |
|
| 193 | + /** |
|
| 194 | + * returns how many users have logged in once |
|
| 195 | + * |
|
| 196 | + * @return int |
|
| 197 | + * @since 11.0.0 |
|
| 198 | + */ |
|
| 199 | + public function countSeenUsers(); |
|
| 200 | + |
|
| 201 | + /** |
|
| 202 | + * @param \Closure $callback |
|
| 203 | + * @psalm-param \Closure(\OCP\IUser):?bool $callback |
|
| 204 | + * @since 11.0.0 |
|
| 205 | + */ |
|
| 206 | + public function callForSeenUsers(\Closure $callback); |
|
| 207 | + |
|
| 208 | + /** |
|
| 209 | + * returns all users having the provided email set as system email address |
|
| 210 | + * |
|
| 211 | + * @param string $email |
|
| 212 | + * @return IUser[] |
|
| 213 | + * @since 9.1.0 |
|
| 214 | + */ |
|
| 215 | + public function getByEmail($email); |
|
| 216 | + |
|
| 217 | + /** |
|
| 218 | + * @param string $uid The user ID to validate |
|
| 219 | + * @param bool $checkDataDirectory Whether it should be checked if files for the ID exist inside the data directory |
|
| 220 | + * @throws \InvalidArgumentException Message is an already translated string with a reason why the ID is not valid |
|
| 221 | + * @since 26.0.0 |
|
| 222 | + */ |
|
| 223 | + public function validateUserId(string $uid, bool $checkDataDirectory = false): void; |
|
| 224 | + |
|
| 225 | + /** |
|
| 226 | + * Gets the list of users sorted by lastLogin, from most recent to least recent |
|
| 227 | + * |
|
| 228 | + * @param int|null $limit how many records to fetch |
|
| 229 | + * @param int $offset from which offset to fetch |
|
| 230 | + * @param string $search search users based on search params |
|
| 231 | + * @return list<string> list of user IDs |
|
| 232 | + * @since 30.0.0 |
|
| 233 | + */ |
|
| 234 | + public function getLastLoggedInUsers(?int $limit = null, int $offset = 0, string $search = ''): array; |
|
| 235 | + |
|
| 236 | + /** |
|
| 237 | + * Gets the list of users. |
|
| 238 | + * An iterator is returned allowing the caller to stop the iteration at any time. |
|
| 239 | + * The offset argument allows the caller to continue the iteration at a specific offset. |
|
| 240 | + * |
|
| 241 | + * @param int $offset from which offset to fetch |
|
| 242 | + * @return \Iterator<IUser> list of IUser object |
|
| 243 | + * @since 32.0.0 |
|
| 244 | + */ |
|
| 245 | + public function getSeenUsers(int $offset = 0): \Iterator; |
|
| 246 | 246 | } |
@@ -172,7 +172,7 @@ |
||
| 172 | 172 | * |
| 173 | 173 | * @since 31.0.0 |
| 174 | 174 | */ |
| 175 | - public function countUsersTotal(int $limit = 0, bool $onlyMappedUsers = false): int|false; |
|
| 175 | + public function countUsersTotal(int $limit = 0, bool $onlyMappedUsers = false): int | false; |
|
| 176 | 176 | |
| 177 | 177 | /** |
| 178 | 178 | * @param \Closure $callback |
@@ -40,366 +40,366 @@ |
||
| 40 | 40 | * logout() |
| 41 | 41 | */ |
| 42 | 42 | class OC_User { |
| 43 | - private static $_setupedBackends = []; |
|
| 44 | - |
|
| 45 | - // bool, stores if a user want to access a resource anonymously, e.g if they open a public link |
|
| 46 | - private static $incognitoMode = false; |
|
| 47 | - |
|
| 48 | - /** |
|
| 49 | - * Adds the backend to the list of used backends |
|
| 50 | - * |
|
| 51 | - * @param string|\OCP\UserInterface $backend default: database The backend to use for user management |
|
| 52 | - * @return bool |
|
| 53 | - * @deprecated 32.0.0 Use IUserManager::registerBackend instead |
|
| 54 | - * |
|
| 55 | - * Set the User Authentication Module |
|
| 56 | - */ |
|
| 57 | - public static function useBackend($backend = 'database') { |
|
| 58 | - if ($backend instanceof \OCP\UserInterface) { |
|
| 59 | - Server::get(IUserManager::class)->registerBackend($backend); |
|
| 60 | - } else { |
|
| 61 | - // You'll never know what happens |
|
| 62 | - if ($backend === null or !is_string($backend)) { |
|
| 63 | - $backend = 'database'; |
|
| 64 | - } |
|
| 65 | - |
|
| 66 | - // Load backend |
|
| 67 | - switch ($backend) { |
|
| 68 | - case 'database': |
|
| 69 | - case 'mysql': |
|
| 70 | - case 'sqlite': |
|
| 71 | - Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); |
|
| 72 | - Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 73 | - break; |
|
| 74 | - case 'dummy': |
|
| 75 | - Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); |
|
| 76 | - break; |
|
| 77 | - default: |
|
| 78 | - Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); |
|
| 79 | - $className = 'OC_USER_' . strtoupper($backend); |
|
| 80 | - Server::get(IUserManager::class)->registerBackend(new $className()); |
|
| 81 | - break; |
|
| 82 | - } |
|
| 83 | - } |
|
| 84 | - return true; |
|
| 85 | - } |
|
| 86 | - |
|
| 87 | - /** |
|
| 88 | - * remove all used backends |
|
| 89 | - * @deprecated 32.0.0 Use IUserManager::clearBackends instead |
|
| 90 | - */ |
|
| 91 | - public static function clearBackends() { |
|
| 92 | - Server::get(IUserManager::class)->clearBackends(); |
|
| 93 | - } |
|
| 94 | - |
|
| 95 | - /** |
|
| 96 | - * setup the configured backends in config.php |
|
| 97 | - * @suppress PhanDeprecatedFunction |
|
| 98 | - */ |
|
| 99 | - public static function setupBackends() { |
|
| 100 | - OC_App::loadApps(['prelogin']); |
|
| 101 | - $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []); |
|
| 102 | - if (isset($backends['default']) && !$backends['default']) { |
|
| 103 | - // clear default backends |
|
| 104 | - self::clearBackends(); |
|
| 105 | - } |
|
| 106 | - foreach ($backends as $i => $config) { |
|
| 107 | - if (!is_array($config)) { |
|
| 108 | - continue; |
|
| 109 | - } |
|
| 110 | - $class = $config['class']; |
|
| 111 | - $arguments = $config['arguments']; |
|
| 112 | - if (class_exists($class)) { |
|
| 113 | - if (!in_array($i, self::$_setupedBackends)) { |
|
| 114 | - // make a reflection object |
|
| 115 | - $reflectionObj = new ReflectionClass($class); |
|
| 116 | - |
|
| 117 | - // use Reflection to create a new instance, using the $args |
|
| 118 | - $backend = $reflectionObj->newInstanceArgs($arguments); |
|
| 119 | - self::useBackend($backend); |
|
| 120 | - self::$_setupedBackends[] = $i; |
|
| 121 | - } else { |
|
| 122 | - Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); |
|
| 123 | - } |
|
| 124 | - } else { |
|
| 125 | - Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']); |
|
| 126 | - } |
|
| 127 | - } |
|
| 128 | - } |
|
| 129 | - |
|
| 130 | - /** |
|
| 131 | - * Try to login a user, assuming authentication |
|
| 132 | - * has already happened (e.g. via Single Sign On). |
|
| 133 | - * |
|
| 134 | - * Log in a user and regenerate a new session. |
|
| 135 | - * |
|
| 136 | - * @param \OCP\Authentication\IApacheBackend $backend |
|
| 137 | - * @return bool |
|
| 138 | - */ |
|
| 139 | - public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { |
|
| 140 | - $uid = $backend->getCurrentUserId(); |
|
| 141 | - $run = true; |
|
| 142 | - OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); |
|
| 143 | - |
|
| 144 | - if ($uid) { |
|
| 145 | - if (self::getUser() !== $uid) { |
|
| 146 | - self::setUserId($uid); |
|
| 147 | - $userSession = \OC::$server->getUserSession(); |
|
| 148 | - |
|
| 149 | - /** @var IEventDispatcher $dispatcher */ |
|
| 150 | - $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
| 151 | - |
|
| 152 | - if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { |
|
| 153 | - $message = \OC::$server->getL10N('lib')->t('Account disabled'); |
|
| 154 | - throw new LoginException($message); |
|
| 155 | - } |
|
| 156 | - $userSession->setLoginName($uid); |
|
| 157 | - $request = OC::$server->getRequest(); |
|
| 158 | - $password = null; |
|
| 159 | - if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) { |
|
| 160 | - $password = $backend->getCurrentUserSecret(); |
|
| 161 | - } |
|
| 162 | - |
|
| 163 | - /** @var IEventDispatcher $dispatcher */ |
|
| 164 | - $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend)); |
|
| 165 | - |
|
| 166 | - $userSession->createSessionToken($request, $uid, $uid, $password); |
|
| 167 | - $userSession->createRememberMeToken($userSession->getUser()); |
|
| 168 | - |
|
| 169 | - if (empty($password)) { |
|
| 170 | - $tokenProvider = \OC::$server->get(IProvider::class); |
|
| 171 | - try { |
|
| 172 | - $token = $tokenProvider->getToken($userSession->getSession()->getId()); |
|
| 173 | - $token->setScope([ |
|
| 174 | - IToken::SCOPE_SKIP_PASSWORD_VALIDATION => true, |
|
| 175 | - IToken::SCOPE_FILESYSTEM => true, |
|
| 176 | - ]); |
|
| 177 | - $tokenProvider->updateToken($token); |
|
| 178 | - } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { |
|
| 179 | - // swallow the exceptions as we do not deal with them here |
|
| 180 | - // simply skip updating the token when is it missing |
|
| 181 | - } |
|
| 182 | - } |
|
| 183 | - |
|
| 184 | - // setup the filesystem |
|
| 185 | - OC_Util::setupFS($uid); |
|
| 186 | - // first call the post_login hooks, the login-process needs to be |
|
| 187 | - // completed before we can safely create the users folder. |
|
| 188 | - // For example encryption needs to initialize the users keys first |
|
| 189 | - // before we can create the user folder with the skeleton files |
|
| 190 | - OC_Hook::emit( |
|
| 191 | - 'OC_User', |
|
| 192 | - 'post_login', |
|
| 193 | - [ |
|
| 194 | - 'uid' => $uid, |
|
| 195 | - 'password' => $password, |
|
| 196 | - 'isTokenLogin' => false, |
|
| 197 | - ] |
|
| 198 | - ); |
|
| 199 | - $dispatcher->dispatchTyped(new UserLoggedInEvent( |
|
| 200 | - \OC::$server->get(IUserManager::class)->get($uid), |
|
| 201 | - $uid, |
|
| 202 | - null, |
|
| 203 | - false) |
|
| 204 | - ); |
|
| 205 | - |
|
| 206 | - //trigger creation of user home and /files folder |
|
| 207 | - \OC::$server->getUserFolder($uid); |
|
| 208 | - } |
|
| 209 | - return true; |
|
| 210 | - } |
|
| 211 | - return false; |
|
| 212 | - } |
|
| 213 | - |
|
| 214 | - /** |
|
| 215 | - * Verify with Apache whether user is authenticated. |
|
| 216 | - * |
|
| 217 | - * @return boolean|null |
|
| 218 | - * true: authenticated |
|
| 219 | - * false: not authenticated |
|
| 220 | - * null: not handled / no backend available |
|
| 221 | - */ |
|
| 222 | - public static function handleApacheAuth() { |
|
| 223 | - $backend = self::findFirstActiveUsedBackend(); |
|
| 224 | - if ($backend) { |
|
| 225 | - OC_App::loadApps(); |
|
| 226 | - |
|
| 227 | - //setup extra user backends |
|
| 228 | - self::setupBackends(); |
|
| 229 | - \OC::$server->getUserSession()->unsetMagicInCookie(); |
|
| 230 | - |
|
| 231 | - return self::loginWithApache($backend); |
|
| 232 | - } |
|
| 233 | - |
|
| 234 | - return null; |
|
| 235 | - } |
|
| 236 | - |
|
| 237 | - |
|
| 238 | - /** |
|
| 239 | - * Sets user id for session and triggers emit |
|
| 240 | - * |
|
| 241 | - * @param string $uid |
|
| 242 | - */ |
|
| 243 | - public static function setUserId($uid) { |
|
| 244 | - $userSession = \OC::$server->getUserSession(); |
|
| 245 | - $userManager = Server::get(IUserManager::class); |
|
| 246 | - if ($user = $userManager->get($uid)) { |
|
| 247 | - $userSession->setUser($user); |
|
| 248 | - } else { |
|
| 249 | - \OC::$server->getSession()->set('user_id', $uid); |
|
| 250 | - } |
|
| 251 | - } |
|
| 252 | - |
|
| 253 | - /** |
|
| 254 | - * Check if the user is logged in, considers also the HTTP basic credentials |
|
| 255 | - * |
|
| 256 | - * @deprecated 12.0.0 use \OC::$server->getUserSession()->isLoggedIn() |
|
| 257 | - * @return bool |
|
| 258 | - */ |
|
| 259 | - public static function isLoggedIn() { |
|
| 260 | - return \OC::$server->getUserSession()->isLoggedIn(); |
|
| 261 | - } |
|
| 262 | - |
|
| 263 | - /** |
|
| 264 | - * set incognito mode, e.g. if a user wants to open a public link |
|
| 265 | - * |
|
| 266 | - * @param bool $status |
|
| 267 | - */ |
|
| 268 | - public static function setIncognitoMode($status) { |
|
| 269 | - self::$incognitoMode = $status; |
|
| 270 | - } |
|
| 271 | - |
|
| 272 | - /** |
|
| 273 | - * get incognito mode status |
|
| 274 | - * |
|
| 275 | - * @return bool |
|
| 276 | - */ |
|
| 277 | - public static function isIncognitoMode() { |
|
| 278 | - return self::$incognitoMode; |
|
| 279 | - } |
|
| 280 | - |
|
| 281 | - /** |
|
| 282 | - * Returns the current logout URL valid for the currently logged-in user |
|
| 283 | - * |
|
| 284 | - * @param \OCP\IURLGenerator $urlGenerator |
|
| 285 | - * @return string |
|
| 286 | - */ |
|
| 287 | - public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { |
|
| 288 | - $backend = self::findFirstActiveUsedBackend(); |
|
| 289 | - if ($backend) { |
|
| 290 | - return $backend->getLogoutUrl(); |
|
| 291 | - } |
|
| 292 | - |
|
| 293 | - $user = \OC::$server->getUserSession()->getUser(); |
|
| 294 | - if ($user instanceof IUser) { |
|
| 295 | - $backend = $user->getBackend(); |
|
| 296 | - if ($backend instanceof \OCP\User\Backend\ICustomLogout) { |
|
| 297 | - return $backend->getLogoutUrl(); |
|
| 298 | - } |
|
| 299 | - } |
|
| 300 | - |
|
| 301 | - $logoutUrl = $urlGenerator->linkToRoute('core.login.logout'); |
|
| 302 | - $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister()); |
|
| 303 | - |
|
| 304 | - return $logoutUrl; |
|
| 305 | - } |
|
| 306 | - |
|
| 307 | - /** |
|
| 308 | - * Check if the user is an admin user |
|
| 309 | - * |
|
| 310 | - * @param string $uid uid of the admin |
|
| 311 | - * @return bool |
|
| 312 | - */ |
|
| 313 | - public static function isAdminUser($uid) { |
|
| 314 | - $user = Server::get(IUserManager::class)->get($uid); |
|
| 315 | - $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); |
|
| 316 | - return $isAdmin && self::$incognitoMode === false; |
|
| 317 | - } |
|
| 318 | - |
|
| 319 | - |
|
| 320 | - /** |
|
| 321 | - * get the user id of the user currently logged in. |
|
| 322 | - * |
|
| 323 | - * @return string|false uid or false |
|
| 324 | - */ |
|
| 325 | - public static function getUser() { |
|
| 326 | - $uid = Server::get(ISession::class)?->get('user_id'); |
|
| 327 | - if (!is_null($uid) && self::$incognitoMode === false) { |
|
| 328 | - return $uid; |
|
| 329 | - } else { |
|
| 330 | - return false; |
|
| 331 | - } |
|
| 332 | - } |
|
| 333 | - |
|
| 334 | - /** |
|
| 335 | - * Set password |
|
| 336 | - * |
|
| 337 | - * @param string $uid The username |
|
| 338 | - * @param string $password The new password |
|
| 339 | - * @param string $recoveryPassword for the encryption app to reset encryption keys |
|
| 340 | - * @return bool |
|
| 341 | - * |
|
| 342 | - * Change the password of a user |
|
| 343 | - */ |
|
| 344 | - public static function setPassword($uid, $password, $recoveryPassword = null) { |
|
| 345 | - $user = Server::get(IUserManager::class)->get($uid); |
|
| 346 | - if ($user) { |
|
| 347 | - return $user->setPassword($password, $recoveryPassword); |
|
| 348 | - } else { |
|
| 349 | - return false; |
|
| 350 | - } |
|
| 351 | - } |
|
| 352 | - |
|
| 353 | - /** |
|
| 354 | - * @param string $uid The username |
|
| 355 | - * @return string |
|
| 356 | - * |
|
| 357 | - * returns the path to the users home directory |
|
| 358 | - * @deprecated 12.0.0 Use \OC::$server->getUserManager->getHome() |
|
| 359 | - */ |
|
| 360 | - public static function getHome($uid) { |
|
| 361 | - $user = Server::get(IUserManager::class)->get($uid); |
|
| 362 | - if ($user) { |
|
| 363 | - return $user->getHome(); |
|
| 364 | - } else { |
|
| 365 | - return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid; |
|
| 366 | - } |
|
| 367 | - } |
|
| 368 | - |
|
| 369 | - /** |
|
| 370 | - * Get a list of all users display name |
|
| 371 | - * |
|
| 372 | - * @param string $search |
|
| 373 | - * @param int $limit |
|
| 374 | - * @param int $offset |
|
| 375 | - * @return array associative array with all display names (value) and corresponding uids (key) |
|
| 376 | - * |
|
| 377 | - * Get a list of all display names and user ids. |
|
| 378 | - * @deprecated 12.0.0 Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead. |
|
| 379 | - */ |
|
| 380 | - public static function getDisplayNames($search = '', $limit = null, $offset = null) { |
|
| 381 | - $displayNames = []; |
|
| 382 | - $users = Server::get(IUserManager::class)->searchDisplayName($search, $limit, $offset); |
|
| 383 | - foreach ($users as $user) { |
|
| 384 | - $displayNames[$user->getUID()] = $user->getDisplayName(); |
|
| 385 | - } |
|
| 386 | - return $displayNames; |
|
| 387 | - } |
|
| 388 | - |
|
| 389 | - /** |
|
| 390 | - * Returns the first active backend from self::$_usedBackends. |
|
| 391 | - * |
|
| 392 | - * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend |
|
| 393 | - */ |
|
| 394 | - private static function findFirstActiveUsedBackend() { |
|
| 395 | - foreach (Server::get(IUserManager::class)->getBackends() as $backend) { |
|
| 396 | - if ($backend instanceof OCP\Authentication\IApacheBackend) { |
|
| 397 | - if ($backend->isSessionActive()) { |
|
| 398 | - return $backend; |
|
| 399 | - } |
|
| 400 | - } |
|
| 401 | - } |
|
| 402 | - |
|
| 403 | - return null; |
|
| 404 | - } |
|
| 43 | + private static $_setupedBackends = []; |
|
| 44 | + |
|
| 45 | + // bool, stores if a user want to access a resource anonymously, e.g if they open a public link |
|
| 46 | + private static $incognitoMode = false; |
|
| 47 | + |
|
| 48 | + /** |
|
| 49 | + * Adds the backend to the list of used backends |
|
| 50 | + * |
|
| 51 | + * @param string|\OCP\UserInterface $backend default: database The backend to use for user management |
|
| 52 | + * @return bool |
|
| 53 | + * @deprecated 32.0.0 Use IUserManager::registerBackend instead |
|
| 54 | + * |
|
| 55 | + * Set the User Authentication Module |
|
| 56 | + */ |
|
| 57 | + public static function useBackend($backend = 'database') { |
|
| 58 | + if ($backend instanceof \OCP\UserInterface) { |
|
| 59 | + Server::get(IUserManager::class)->registerBackend($backend); |
|
| 60 | + } else { |
|
| 61 | + // You'll never know what happens |
|
| 62 | + if ($backend === null or !is_string($backend)) { |
|
| 63 | + $backend = 'database'; |
|
| 64 | + } |
|
| 65 | + |
|
| 66 | + // Load backend |
|
| 67 | + switch ($backend) { |
|
| 68 | + case 'database': |
|
| 69 | + case 'mysql': |
|
| 70 | + case 'sqlite': |
|
| 71 | + Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); |
|
| 72 | + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 73 | + break; |
|
| 74 | + case 'dummy': |
|
| 75 | + Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); |
|
| 76 | + break; |
|
| 77 | + default: |
|
| 78 | + Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); |
|
| 79 | + $className = 'OC_USER_' . strtoupper($backend); |
|
| 80 | + Server::get(IUserManager::class)->registerBackend(new $className()); |
|
| 81 | + break; |
|
| 82 | + } |
|
| 83 | + } |
|
| 84 | + return true; |
|
| 85 | + } |
|
| 86 | + |
|
| 87 | + /** |
|
| 88 | + * remove all used backends |
|
| 89 | + * @deprecated 32.0.0 Use IUserManager::clearBackends instead |
|
| 90 | + */ |
|
| 91 | + public static function clearBackends() { |
|
| 92 | + Server::get(IUserManager::class)->clearBackends(); |
|
| 93 | + } |
|
| 94 | + |
|
| 95 | + /** |
|
| 96 | + * setup the configured backends in config.php |
|
| 97 | + * @suppress PhanDeprecatedFunction |
|
| 98 | + */ |
|
| 99 | + public static function setupBackends() { |
|
| 100 | + OC_App::loadApps(['prelogin']); |
|
| 101 | + $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []); |
|
| 102 | + if (isset($backends['default']) && !$backends['default']) { |
|
| 103 | + // clear default backends |
|
| 104 | + self::clearBackends(); |
|
| 105 | + } |
|
| 106 | + foreach ($backends as $i => $config) { |
|
| 107 | + if (!is_array($config)) { |
|
| 108 | + continue; |
|
| 109 | + } |
|
| 110 | + $class = $config['class']; |
|
| 111 | + $arguments = $config['arguments']; |
|
| 112 | + if (class_exists($class)) { |
|
| 113 | + if (!in_array($i, self::$_setupedBackends)) { |
|
| 114 | + // make a reflection object |
|
| 115 | + $reflectionObj = new ReflectionClass($class); |
|
| 116 | + |
|
| 117 | + // use Reflection to create a new instance, using the $args |
|
| 118 | + $backend = $reflectionObj->newInstanceArgs($arguments); |
|
| 119 | + self::useBackend($backend); |
|
| 120 | + self::$_setupedBackends[] = $i; |
|
| 121 | + } else { |
|
| 122 | + Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); |
|
| 123 | + } |
|
| 124 | + } else { |
|
| 125 | + Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']); |
|
| 126 | + } |
|
| 127 | + } |
|
| 128 | + } |
|
| 129 | + |
|
| 130 | + /** |
|
| 131 | + * Try to login a user, assuming authentication |
|
| 132 | + * has already happened (e.g. via Single Sign On). |
|
| 133 | + * |
|
| 134 | + * Log in a user and regenerate a new session. |
|
| 135 | + * |
|
| 136 | + * @param \OCP\Authentication\IApacheBackend $backend |
|
| 137 | + * @return bool |
|
| 138 | + */ |
|
| 139 | + public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { |
|
| 140 | + $uid = $backend->getCurrentUserId(); |
|
| 141 | + $run = true; |
|
| 142 | + OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); |
|
| 143 | + |
|
| 144 | + if ($uid) { |
|
| 145 | + if (self::getUser() !== $uid) { |
|
| 146 | + self::setUserId($uid); |
|
| 147 | + $userSession = \OC::$server->getUserSession(); |
|
| 148 | + |
|
| 149 | + /** @var IEventDispatcher $dispatcher */ |
|
| 150 | + $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
| 151 | + |
|
| 152 | + if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { |
|
| 153 | + $message = \OC::$server->getL10N('lib')->t('Account disabled'); |
|
| 154 | + throw new LoginException($message); |
|
| 155 | + } |
|
| 156 | + $userSession->setLoginName($uid); |
|
| 157 | + $request = OC::$server->getRequest(); |
|
| 158 | + $password = null; |
|
| 159 | + if ($backend instanceof \OCP\Authentication\IProvideUserSecretBackend) { |
|
| 160 | + $password = $backend->getCurrentUserSecret(); |
|
| 161 | + } |
|
| 162 | + |
|
| 163 | + /** @var IEventDispatcher $dispatcher */ |
|
| 164 | + $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password, $backend)); |
|
| 165 | + |
|
| 166 | + $userSession->createSessionToken($request, $uid, $uid, $password); |
|
| 167 | + $userSession->createRememberMeToken($userSession->getUser()); |
|
| 168 | + |
|
| 169 | + if (empty($password)) { |
|
| 170 | + $tokenProvider = \OC::$server->get(IProvider::class); |
|
| 171 | + try { |
|
| 172 | + $token = $tokenProvider->getToken($userSession->getSession()->getId()); |
|
| 173 | + $token->setScope([ |
|
| 174 | + IToken::SCOPE_SKIP_PASSWORD_VALIDATION => true, |
|
| 175 | + IToken::SCOPE_FILESYSTEM => true, |
|
| 176 | + ]); |
|
| 177 | + $tokenProvider->updateToken($token); |
|
| 178 | + } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { |
|
| 179 | + // swallow the exceptions as we do not deal with them here |
|
| 180 | + // simply skip updating the token when is it missing |
|
| 181 | + } |
|
| 182 | + } |
|
| 183 | + |
|
| 184 | + // setup the filesystem |
|
| 185 | + OC_Util::setupFS($uid); |
|
| 186 | + // first call the post_login hooks, the login-process needs to be |
|
| 187 | + // completed before we can safely create the users folder. |
|
| 188 | + // For example encryption needs to initialize the users keys first |
|
| 189 | + // before we can create the user folder with the skeleton files |
|
| 190 | + OC_Hook::emit( |
|
| 191 | + 'OC_User', |
|
| 192 | + 'post_login', |
|
| 193 | + [ |
|
| 194 | + 'uid' => $uid, |
|
| 195 | + 'password' => $password, |
|
| 196 | + 'isTokenLogin' => false, |
|
| 197 | + ] |
|
| 198 | + ); |
|
| 199 | + $dispatcher->dispatchTyped(new UserLoggedInEvent( |
|
| 200 | + \OC::$server->get(IUserManager::class)->get($uid), |
|
| 201 | + $uid, |
|
| 202 | + null, |
|
| 203 | + false) |
|
| 204 | + ); |
|
| 205 | + |
|
| 206 | + //trigger creation of user home and /files folder |
|
| 207 | + \OC::$server->getUserFolder($uid); |
|
| 208 | + } |
|
| 209 | + return true; |
|
| 210 | + } |
|
| 211 | + return false; |
|
| 212 | + } |
|
| 213 | + |
|
| 214 | + /** |
|
| 215 | + * Verify with Apache whether user is authenticated. |
|
| 216 | + * |
|
| 217 | + * @return boolean|null |
|
| 218 | + * true: authenticated |
|
| 219 | + * false: not authenticated |
|
| 220 | + * null: not handled / no backend available |
|
| 221 | + */ |
|
| 222 | + public static function handleApacheAuth() { |
|
| 223 | + $backend = self::findFirstActiveUsedBackend(); |
|
| 224 | + if ($backend) { |
|
| 225 | + OC_App::loadApps(); |
|
| 226 | + |
|
| 227 | + //setup extra user backends |
|
| 228 | + self::setupBackends(); |
|
| 229 | + \OC::$server->getUserSession()->unsetMagicInCookie(); |
|
| 230 | + |
|
| 231 | + return self::loginWithApache($backend); |
|
| 232 | + } |
|
| 233 | + |
|
| 234 | + return null; |
|
| 235 | + } |
|
| 236 | + |
|
| 237 | + |
|
| 238 | + /** |
|
| 239 | + * Sets user id for session and triggers emit |
|
| 240 | + * |
|
| 241 | + * @param string $uid |
|
| 242 | + */ |
|
| 243 | + public static function setUserId($uid) { |
|
| 244 | + $userSession = \OC::$server->getUserSession(); |
|
| 245 | + $userManager = Server::get(IUserManager::class); |
|
| 246 | + if ($user = $userManager->get($uid)) { |
|
| 247 | + $userSession->setUser($user); |
|
| 248 | + } else { |
|
| 249 | + \OC::$server->getSession()->set('user_id', $uid); |
|
| 250 | + } |
|
| 251 | + } |
|
| 252 | + |
|
| 253 | + /** |
|
| 254 | + * Check if the user is logged in, considers also the HTTP basic credentials |
|
| 255 | + * |
|
| 256 | + * @deprecated 12.0.0 use \OC::$server->getUserSession()->isLoggedIn() |
|
| 257 | + * @return bool |
|
| 258 | + */ |
|
| 259 | + public static function isLoggedIn() { |
|
| 260 | + return \OC::$server->getUserSession()->isLoggedIn(); |
|
| 261 | + } |
|
| 262 | + |
|
| 263 | + /** |
|
| 264 | + * set incognito mode, e.g. if a user wants to open a public link |
|
| 265 | + * |
|
| 266 | + * @param bool $status |
|
| 267 | + */ |
|
| 268 | + public static function setIncognitoMode($status) { |
|
| 269 | + self::$incognitoMode = $status; |
|
| 270 | + } |
|
| 271 | + |
|
| 272 | + /** |
|
| 273 | + * get incognito mode status |
|
| 274 | + * |
|
| 275 | + * @return bool |
|
| 276 | + */ |
|
| 277 | + public static function isIncognitoMode() { |
|
| 278 | + return self::$incognitoMode; |
|
| 279 | + } |
|
| 280 | + |
|
| 281 | + /** |
|
| 282 | + * Returns the current logout URL valid for the currently logged-in user |
|
| 283 | + * |
|
| 284 | + * @param \OCP\IURLGenerator $urlGenerator |
|
| 285 | + * @return string |
|
| 286 | + */ |
|
| 287 | + public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) { |
|
| 288 | + $backend = self::findFirstActiveUsedBackend(); |
|
| 289 | + if ($backend) { |
|
| 290 | + return $backend->getLogoutUrl(); |
|
| 291 | + } |
|
| 292 | + |
|
| 293 | + $user = \OC::$server->getUserSession()->getUser(); |
|
| 294 | + if ($user instanceof IUser) { |
|
| 295 | + $backend = $user->getBackend(); |
|
| 296 | + if ($backend instanceof \OCP\User\Backend\ICustomLogout) { |
|
| 297 | + return $backend->getLogoutUrl(); |
|
| 298 | + } |
|
| 299 | + } |
|
| 300 | + |
|
| 301 | + $logoutUrl = $urlGenerator->linkToRoute('core.login.logout'); |
|
| 302 | + $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister()); |
|
| 303 | + |
|
| 304 | + return $logoutUrl; |
|
| 305 | + } |
|
| 306 | + |
|
| 307 | + /** |
|
| 308 | + * Check if the user is an admin user |
|
| 309 | + * |
|
| 310 | + * @param string $uid uid of the admin |
|
| 311 | + * @return bool |
|
| 312 | + */ |
|
| 313 | + public static function isAdminUser($uid) { |
|
| 314 | + $user = Server::get(IUserManager::class)->get($uid); |
|
| 315 | + $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); |
|
| 316 | + return $isAdmin && self::$incognitoMode === false; |
|
| 317 | + } |
|
| 318 | + |
|
| 319 | + |
|
| 320 | + /** |
|
| 321 | + * get the user id of the user currently logged in. |
|
| 322 | + * |
|
| 323 | + * @return string|false uid or false |
|
| 324 | + */ |
|
| 325 | + public static function getUser() { |
|
| 326 | + $uid = Server::get(ISession::class)?->get('user_id'); |
|
| 327 | + if (!is_null($uid) && self::$incognitoMode === false) { |
|
| 328 | + return $uid; |
|
| 329 | + } else { |
|
| 330 | + return false; |
|
| 331 | + } |
|
| 332 | + } |
|
| 333 | + |
|
| 334 | + /** |
|
| 335 | + * Set password |
|
| 336 | + * |
|
| 337 | + * @param string $uid The username |
|
| 338 | + * @param string $password The new password |
|
| 339 | + * @param string $recoveryPassword for the encryption app to reset encryption keys |
|
| 340 | + * @return bool |
|
| 341 | + * |
|
| 342 | + * Change the password of a user |
|
| 343 | + */ |
|
| 344 | + public static function setPassword($uid, $password, $recoveryPassword = null) { |
|
| 345 | + $user = Server::get(IUserManager::class)->get($uid); |
|
| 346 | + if ($user) { |
|
| 347 | + return $user->setPassword($password, $recoveryPassword); |
|
| 348 | + } else { |
|
| 349 | + return false; |
|
| 350 | + } |
|
| 351 | + } |
|
| 352 | + |
|
| 353 | + /** |
|
| 354 | + * @param string $uid The username |
|
| 355 | + * @return string |
|
| 356 | + * |
|
| 357 | + * returns the path to the users home directory |
|
| 358 | + * @deprecated 12.0.0 Use \OC::$server->getUserManager->getHome() |
|
| 359 | + */ |
|
| 360 | + public static function getHome($uid) { |
|
| 361 | + $user = Server::get(IUserManager::class)->get($uid); |
|
| 362 | + if ($user) { |
|
| 363 | + return $user->getHome(); |
|
| 364 | + } else { |
|
| 365 | + return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid; |
|
| 366 | + } |
|
| 367 | + } |
|
| 368 | + |
|
| 369 | + /** |
|
| 370 | + * Get a list of all users display name |
|
| 371 | + * |
|
| 372 | + * @param string $search |
|
| 373 | + * @param int $limit |
|
| 374 | + * @param int $offset |
|
| 375 | + * @return array associative array with all display names (value) and corresponding uids (key) |
|
| 376 | + * |
|
| 377 | + * Get a list of all display names and user ids. |
|
| 378 | + * @deprecated 12.0.0 Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead. |
|
| 379 | + */ |
|
| 380 | + public static function getDisplayNames($search = '', $limit = null, $offset = null) { |
|
| 381 | + $displayNames = []; |
|
| 382 | + $users = Server::get(IUserManager::class)->searchDisplayName($search, $limit, $offset); |
|
| 383 | + foreach ($users as $user) { |
|
| 384 | + $displayNames[$user->getUID()] = $user->getDisplayName(); |
|
| 385 | + } |
|
| 386 | + return $displayNames; |
|
| 387 | + } |
|
| 388 | + |
|
| 389 | + /** |
|
| 390 | + * Returns the first active backend from self::$_usedBackends. |
|
| 391 | + * |
|
| 392 | + * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend |
|
| 393 | + */ |
|
| 394 | + private static function findFirstActiveUsedBackend() { |
|
| 395 | + foreach (Server::get(IUserManager::class)->getBackends() as $backend) { |
|
| 396 | + if ($backend instanceof OCP\Authentication\IApacheBackend) { |
|
| 397 | + if ($backend->isSessionActive()) { |
|
| 398 | + return $backend; |
|
| 399 | + } |
|
| 400 | + } |
|
| 401 | + } |
|
| 402 | + |
|
| 403 | + return null; |
|
| 404 | + } |
|
| 405 | 405 | } |
@@ -68,15 +68,15 @@ discard block |
||
| 68 | 68 | case 'database': |
| 69 | 69 | case 'mysql': |
| 70 | 70 | case 'sqlite': |
| 71 | - Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); |
|
| 71 | + Server::get(LoggerInterface::class)->debug('Adding user backend '.$backend.'.', ['app' => 'core']); |
|
| 72 | 72 | Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
| 73 | 73 | break; |
| 74 | 74 | case 'dummy': |
| 75 | 75 | Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); |
| 76 | 76 | break; |
| 77 | 77 | default: |
| 78 | - Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); |
|
| 79 | - $className = 'OC_USER_' . strtoupper($backend); |
|
| 78 | + Server::get(LoggerInterface::class)->debug('Adding default user backend '.$backend.'.', ['app' => 'core']); |
|
| 79 | + $className = 'OC_USER_'.strtoupper($backend); |
|
| 80 | 80 | Server::get(IUserManager::class)->registerBackend(new $className()); |
| 81 | 81 | break; |
| 82 | 82 | } |
@@ -119,10 +119,10 @@ discard block |
||
| 119 | 119 | self::useBackend($backend); |
| 120 | 120 | self::$_setupedBackends[] = $i; |
| 121 | 121 | } else { |
| 122 | - Server::get(LoggerInterface::class)->debug('User backend ' . $class . ' already initialized.', ['app' => 'core']); |
|
| 122 | + Server::get(LoggerInterface::class)->debug('User backend '.$class.' already initialized.', ['app' => 'core']); |
|
| 123 | 123 | } |
| 124 | 124 | } else { |
| 125 | - Server::get(LoggerInterface::class)->error('User backend ' . $class . ' not found.', ['app' => 'core']); |
|
| 125 | + Server::get(LoggerInterface::class)->error('User backend '.$class.' not found.', ['app' => 'core']); |
|
| 126 | 126 | } |
| 127 | 127 | } |
| 128 | 128 | } |
@@ -175,7 +175,7 @@ discard block |
||
| 175 | 175 | IToken::SCOPE_FILESYSTEM => true, |
| 176 | 176 | ]); |
| 177 | 177 | $tokenProvider->updateToken($token); |
| 178 | - } catch (InvalidTokenException|WipeTokenException|SessionNotAvailableException) { |
|
| 178 | + } catch (InvalidTokenException | WipeTokenException | SessionNotAvailableException) { |
|
| 179 | 179 | // swallow the exceptions as we do not deal with them here |
| 180 | 180 | // simply skip updating the token when is it missing |
| 181 | 181 | } |
@@ -299,7 +299,7 @@ discard block |
||
| 299 | 299 | } |
| 300 | 300 | |
| 301 | 301 | $logoutUrl = $urlGenerator->linkToRoute('core.login.logout'); |
| 302 | - $logoutUrl .= '?requesttoken=' . urlencode(\OCP\Util::callRegister()); |
|
| 302 | + $logoutUrl .= '?requesttoken='.urlencode(\OCP\Util::callRegister()); |
|
| 303 | 303 | |
| 304 | 304 | return $logoutUrl; |
| 305 | 305 | } |
@@ -362,7 +362,7 @@ discard block |
||
| 362 | 362 | if ($user) { |
| 363 | 363 | return $user->getHome(); |
| 364 | 364 | } else { |
| 365 | - return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid; |
|
| 365 | + return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$uid; |
|
| 366 | 366 | } |
| 367 | 367 | } |
| 368 | 368 | |
@@ -53,775 +53,775 @@ |
||
| 53 | 53 | * @package OC\User |
| 54 | 54 | */ |
| 55 | 55 | class Manager extends PublicEmitter implements IUserManager { |
| 56 | - /** |
|
| 57 | - * @var UserInterface[] $backends |
|
| 58 | - */ |
|
| 59 | - private array $backends = []; |
|
| 60 | - |
|
| 61 | - /** |
|
| 62 | - * @var array<string,\OC\User\User> $cachedUsers |
|
| 63 | - */ |
|
| 64 | - private array $cachedUsers = []; |
|
| 65 | - |
|
| 66 | - private ICache $cache; |
|
| 67 | - |
|
| 68 | - private DisplayNameCache $displayNameCache; |
|
| 69 | - |
|
| 70 | - public function __construct( |
|
| 71 | - private IConfig $config, |
|
| 72 | - ICacheFactory $cacheFactory, |
|
| 73 | - private IEventDispatcher $eventDispatcher, |
|
| 74 | - private LoggerInterface $logger, |
|
| 75 | - ) { |
|
| 76 | - $this->cache = new WithLocalCache($cacheFactory->createDistributed('user_backend_map')); |
|
| 77 | - $this->listen('\OC\User', 'postDelete', function (IUser $user): void { |
|
| 78 | - unset($this->cachedUsers[$user->getUID()]); |
|
| 79 | - }); |
|
| 80 | - $this->displayNameCache = new DisplayNameCache($cacheFactory, $this); |
|
| 81 | - } |
|
| 82 | - |
|
| 83 | - /** |
|
| 84 | - * Get the active backends |
|
| 85 | - * @return UserInterface[] |
|
| 86 | - */ |
|
| 87 | - public function getBackends(): array { |
|
| 88 | - return $this->backends; |
|
| 89 | - } |
|
| 90 | - |
|
| 91 | - public function registerBackend(UserInterface $backend): void { |
|
| 92 | - $this->backends[] = $backend; |
|
| 93 | - } |
|
| 94 | - |
|
| 95 | - public function removeBackend(UserInterface $backend): void { |
|
| 96 | - $this->cachedUsers = []; |
|
| 97 | - if (($i = array_search($backend, $this->backends)) !== false) { |
|
| 98 | - unset($this->backends[$i]); |
|
| 99 | - } |
|
| 100 | - } |
|
| 101 | - |
|
| 102 | - public function clearBackends(): void { |
|
| 103 | - $this->cachedUsers = []; |
|
| 104 | - $this->backends = []; |
|
| 105 | - } |
|
| 106 | - |
|
| 107 | - /** |
|
| 108 | - * get a user by user id |
|
| 109 | - * |
|
| 110 | - * @param string $uid |
|
| 111 | - * @return \OC\User\User|null Either the user or null if the specified user does not exist |
|
| 112 | - */ |
|
| 113 | - public function get($uid) { |
|
| 114 | - if (is_null($uid) || $uid === '' || $uid === false) { |
|
| 115 | - return null; |
|
| 116 | - } |
|
| 117 | - if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends |
|
| 118 | - return $this->cachedUsers[$uid]; |
|
| 119 | - } |
|
| 120 | - |
|
| 121 | - $cachedBackend = $this->cache->get(sha1($uid)); |
|
| 122 | - if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) { |
|
| 123 | - // Cache has the info of the user backend already, so ask that one directly |
|
| 124 | - $backend = $this->backends[$cachedBackend]; |
|
| 125 | - if ($backend->userExists($uid)) { |
|
| 126 | - return $this->getUserObject($uid, $backend); |
|
| 127 | - } |
|
| 128 | - } |
|
| 129 | - |
|
| 130 | - foreach ($this->backends as $i => $backend) { |
|
| 131 | - if ($i === $cachedBackend) { |
|
| 132 | - // Tried that one already |
|
| 133 | - continue; |
|
| 134 | - } |
|
| 135 | - |
|
| 136 | - if ($backend->userExists($uid)) { |
|
| 137 | - // Hash $uid to ensure that only valid characters are used for the cache key |
|
| 138 | - $this->cache->set(sha1($uid), $i, 300); |
|
| 139 | - return $this->getUserObject($uid, $backend); |
|
| 140 | - } |
|
| 141 | - } |
|
| 142 | - return null; |
|
| 143 | - } |
|
| 144 | - |
|
| 145 | - public function getDisplayName(string $uid): ?string { |
|
| 146 | - return $this->displayNameCache->getDisplayName($uid); |
|
| 147 | - } |
|
| 148 | - |
|
| 149 | - /** |
|
| 150 | - * get or construct the user object |
|
| 151 | - * |
|
| 152 | - * @param string $uid |
|
| 153 | - * @param \OCP\UserInterface $backend |
|
| 154 | - * @param bool $cacheUser If false the newly created user object will not be cached |
|
| 155 | - * @return \OC\User\User |
|
| 156 | - */ |
|
| 157 | - public function getUserObject($uid, $backend, $cacheUser = true) { |
|
| 158 | - if ($backend instanceof IGetRealUIDBackend) { |
|
| 159 | - $uid = $backend->getRealUID($uid); |
|
| 160 | - } |
|
| 161 | - |
|
| 162 | - if (isset($this->cachedUsers[$uid])) { |
|
| 163 | - return $this->cachedUsers[$uid]; |
|
| 164 | - } |
|
| 165 | - |
|
| 166 | - $user = new User($uid, $backend, $this->eventDispatcher, $this, $this->config); |
|
| 167 | - if ($cacheUser) { |
|
| 168 | - $this->cachedUsers[$uid] = $user; |
|
| 169 | - } |
|
| 170 | - return $user; |
|
| 171 | - } |
|
| 172 | - |
|
| 173 | - /** |
|
| 174 | - * check if a user exists |
|
| 175 | - * |
|
| 176 | - * @param string $uid |
|
| 177 | - * @return bool |
|
| 178 | - */ |
|
| 179 | - public function userExists($uid) { |
|
| 180 | - $user = $this->get($uid); |
|
| 181 | - return ($user !== null); |
|
| 182 | - } |
|
| 183 | - |
|
| 184 | - /** |
|
| 185 | - * Check if the password is valid for the user |
|
| 186 | - * |
|
| 187 | - * @param string $loginName |
|
| 188 | - * @param string $password |
|
| 189 | - * @return IUser|false the User object on success, false otherwise |
|
| 190 | - */ |
|
| 191 | - public function checkPassword($loginName, $password) { |
|
| 192 | - $result = $this->checkPasswordNoLogging($loginName, $password); |
|
| 193 | - |
|
| 194 | - if ($result === false) { |
|
| 195 | - $this->logger->warning('Login failed: \'' . $loginName . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']); |
|
| 196 | - } |
|
| 197 | - |
|
| 198 | - return $result; |
|
| 199 | - } |
|
| 200 | - |
|
| 201 | - /** |
|
| 202 | - * Check if the password is valid for the user |
|
| 203 | - * |
|
| 204 | - * @internal |
|
| 205 | - * @param string $loginName |
|
| 206 | - * @param string $password |
|
| 207 | - * @return IUser|false the User object on success, false otherwise |
|
| 208 | - */ |
|
| 209 | - public function checkPasswordNoLogging($loginName, $password) { |
|
| 210 | - $loginName = str_replace("\0", '', $loginName); |
|
| 211 | - $password = str_replace("\0", '', $password); |
|
| 212 | - |
|
| 213 | - $cachedBackend = $this->cache->get($loginName); |
|
| 214 | - if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) { |
|
| 215 | - $backends = [$this->backends[$cachedBackend]]; |
|
| 216 | - } else { |
|
| 217 | - $backends = $this->backends; |
|
| 218 | - } |
|
| 219 | - foreach ($backends as $backend) { |
|
| 220 | - if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) { |
|
| 221 | - /** @var ICheckPasswordBackend $backend */ |
|
| 222 | - $uid = $backend->checkPassword($loginName, $password); |
|
| 223 | - if ($uid !== false) { |
|
| 224 | - return $this->getUserObject($uid, $backend); |
|
| 225 | - } |
|
| 226 | - } |
|
| 227 | - } |
|
| 228 | - |
|
| 229 | - // since http basic auth doesn't provide a standard way of handling non ascii password we allow password to be urlencoded |
|
| 230 | - // we only do this decoding after using the plain password fails to maintain compatibility with any password that happens |
|
| 231 | - // to contain urlencoded patterns by "accident". |
|
| 232 | - $password = urldecode($password); |
|
| 233 | - |
|
| 234 | - foreach ($backends as $backend) { |
|
| 235 | - if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) { |
|
| 236 | - /** @var ICheckPasswordBackend|UserInterface $backend */ |
|
| 237 | - $uid = $backend->checkPassword($loginName, $password); |
|
| 238 | - if ($uid !== false) { |
|
| 239 | - return $this->getUserObject($uid, $backend); |
|
| 240 | - } |
|
| 241 | - } |
|
| 242 | - } |
|
| 243 | - |
|
| 244 | - return false; |
|
| 245 | - } |
|
| 246 | - |
|
| 247 | - /** |
|
| 248 | - * Search by user id |
|
| 249 | - * |
|
| 250 | - * @param string $pattern |
|
| 251 | - * @param int $limit |
|
| 252 | - * @param int $offset |
|
| 253 | - * @return IUser[] |
|
| 254 | - * @deprecated 27.0.0, use searchDisplayName instead |
|
| 255 | - */ |
|
| 256 | - public function search($pattern, $limit = null, $offset = null) { |
|
| 257 | - $users = []; |
|
| 258 | - foreach ($this->backends as $backend) { |
|
| 259 | - $backendUsers = $backend->getUsers($pattern, $limit, $offset); |
|
| 260 | - if (is_array($backendUsers)) { |
|
| 261 | - foreach ($backendUsers as $uid) { |
|
| 262 | - $users[$uid] = new LazyUser($uid, $this, null, $backend); |
|
| 263 | - } |
|
| 264 | - } |
|
| 265 | - } |
|
| 266 | - |
|
| 267 | - uasort($users, function (IUser $a, IUser $b) { |
|
| 268 | - return strcasecmp($a->getUID(), $b->getUID()); |
|
| 269 | - }); |
|
| 270 | - return $users; |
|
| 271 | - } |
|
| 272 | - |
|
| 273 | - /** |
|
| 274 | - * Search by displayName |
|
| 275 | - * |
|
| 276 | - * @param string $pattern |
|
| 277 | - * @param int $limit |
|
| 278 | - * @param int $offset |
|
| 279 | - * @return IUser[] |
|
| 280 | - */ |
|
| 281 | - public function searchDisplayName($pattern, $limit = null, $offset = null) { |
|
| 282 | - $users = []; |
|
| 283 | - foreach ($this->backends as $backend) { |
|
| 284 | - $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); |
|
| 285 | - if (is_array($backendUsers)) { |
|
| 286 | - foreach ($backendUsers as $uid => $displayName) { |
|
| 287 | - $users[] = new LazyUser($uid, $this, $displayName, $backend); |
|
| 288 | - } |
|
| 289 | - } |
|
| 290 | - } |
|
| 291 | - |
|
| 292 | - usort($users, function (IUser $a, IUser $b) { |
|
| 293 | - return strcasecmp($a->getDisplayName(), $b->getDisplayName()); |
|
| 294 | - }); |
|
| 295 | - return $users; |
|
| 296 | - } |
|
| 297 | - |
|
| 298 | - /** |
|
| 299 | - * @return IUser[] |
|
| 300 | - */ |
|
| 301 | - public function getDisabledUsers(?int $limit = null, int $offset = 0, string $search = ''): array { |
|
| 302 | - $users = $this->config->getUsersForUserValue('core', 'enabled', 'false'); |
|
| 303 | - $users = array_combine( |
|
| 304 | - $users, |
|
| 305 | - array_map( |
|
| 306 | - fn (string $uid): IUser => new LazyUser($uid, $this), |
|
| 307 | - $users |
|
| 308 | - ) |
|
| 309 | - ); |
|
| 310 | - if ($search !== '') { |
|
| 311 | - $users = array_filter( |
|
| 312 | - $users, |
|
| 313 | - function (IUser $user) use ($search): bool { |
|
| 314 | - try { |
|
| 315 | - return mb_stripos($user->getUID(), $search) !== false || |
|
| 316 | - mb_stripos($user->getDisplayName(), $search) !== false || |
|
| 317 | - mb_stripos($user->getEMailAddress() ?? '', $search) !== false; |
|
| 318 | - } catch (NoUserException $ex) { |
|
| 319 | - $this->logger->error('Error while filtering disabled users', ['exception' => $ex, 'userUID' => $user->getUID()]); |
|
| 320 | - return false; |
|
| 321 | - } |
|
| 322 | - }); |
|
| 323 | - } |
|
| 324 | - |
|
| 325 | - $tempLimit = ($limit === null ? null : $limit + $offset); |
|
| 326 | - foreach ($this->backends as $backend) { |
|
| 327 | - if (($tempLimit !== null) && (count($users) >= $tempLimit)) { |
|
| 328 | - break; |
|
| 329 | - } |
|
| 330 | - if ($backend instanceof IProvideEnabledStateBackend) { |
|
| 331 | - $backendUsers = $backend->getDisabledUserList(($tempLimit === null ? null : $tempLimit - count($users)), 0, $search); |
|
| 332 | - foreach ($backendUsers as $uid) { |
|
| 333 | - $users[$uid] = new LazyUser($uid, $this, null, $backend); |
|
| 334 | - } |
|
| 335 | - } |
|
| 336 | - } |
|
| 337 | - |
|
| 338 | - return array_slice($users, $offset, $limit); |
|
| 339 | - } |
|
| 340 | - |
|
| 341 | - /** |
|
| 342 | - * Search known users (from phonebook sync) by displayName |
|
| 343 | - * |
|
| 344 | - * @param string $searcher |
|
| 345 | - * @param string $pattern |
|
| 346 | - * @param int|null $limit |
|
| 347 | - * @param int|null $offset |
|
| 348 | - * @return IUser[] |
|
| 349 | - */ |
|
| 350 | - public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array { |
|
| 351 | - $users = []; |
|
| 352 | - foreach ($this->backends as $backend) { |
|
| 353 | - if ($backend instanceof ISearchKnownUsersBackend) { |
|
| 354 | - $backendUsers = $backend->searchKnownUsersByDisplayName($searcher, $pattern, $limit, $offset); |
|
| 355 | - } else { |
|
| 356 | - // Better than nothing, but filtering after pagination can remove lots of results. |
|
| 357 | - $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); |
|
| 358 | - } |
|
| 359 | - if (is_array($backendUsers)) { |
|
| 360 | - foreach ($backendUsers as $uid => $displayName) { |
|
| 361 | - $users[] = $this->getUserObject($uid, $backend); |
|
| 362 | - } |
|
| 363 | - } |
|
| 364 | - } |
|
| 365 | - |
|
| 366 | - usort($users, function ($a, $b) { |
|
| 367 | - /** |
|
| 368 | - * @var IUser $a |
|
| 369 | - * @var IUser $b |
|
| 370 | - */ |
|
| 371 | - return strcasecmp($a->getDisplayName(), $b->getDisplayName()); |
|
| 372 | - }); |
|
| 373 | - return $users; |
|
| 374 | - } |
|
| 375 | - |
|
| 376 | - /** |
|
| 377 | - * @param string $uid |
|
| 378 | - * @param string $password |
|
| 379 | - * @return false|IUser the created user or false |
|
| 380 | - * @throws \InvalidArgumentException |
|
| 381 | - * @throws HintException |
|
| 382 | - */ |
|
| 383 | - public function createUser($uid, $password) { |
|
| 384 | - // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency |
|
| 385 | - /** @var IAssertion $assertion */ |
|
| 386 | - $assertion = \OC::$server->get(IAssertion::class); |
|
| 387 | - $assertion->createUserIsLegit(); |
|
| 388 | - |
|
| 389 | - $localBackends = []; |
|
| 390 | - foreach ($this->backends as $backend) { |
|
| 391 | - if ($backend instanceof Database) { |
|
| 392 | - // First check if there is another user backend |
|
| 393 | - $localBackends[] = $backend; |
|
| 394 | - continue; |
|
| 395 | - } |
|
| 396 | - |
|
| 397 | - if ($backend->implementsActions(Backend::CREATE_USER)) { |
|
| 398 | - return $this->createUserFromBackend($uid, $password, $backend); |
|
| 399 | - } |
|
| 400 | - } |
|
| 401 | - |
|
| 402 | - foreach ($localBackends as $backend) { |
|
| 403 | - if ($backend->implementsActions(Backend::CREATE_USER)) { |
|
| 404 | - return $this->createUserFromBackend($uid, $password, $backend); |
|
| 405 | - } |
|
| 406 | - } |
|
| 407 | - |
|
| 408 | - return false; |
|
| 409 | - } |
|
| 410 | - |
|
| 411 | - /** |
|
| 412 | - * @param string $uid |
|
| 413 | - * @param string $password |
|
| 414 | - * @param UserInterface $backend |
|
| 415 | - * @return IUser|false |
|
| 416 | - * @throws \InvalidArgumentException |
|
| 417 | - */ |
|
| 418 | - public function createUserFromBackend($uid, $password, UserInterface $backend) { |
|
| 419 | - $l = \OCP\Util::getL10N('lib'); |
|
| 420 | - |
|
| 421 | - $this->validateUserId($uid, true); |
|
| 422 | - |
|
| 423 | - // No empty password |
|
| 424 | - if (trim($password) === '') { |
|
| 425 | - throw new \InvalidArgumentException($l->t('A valid password must be provided')); |
|
| 426 | - } |
|
| 427 | - |
|
| 428 | - // Check if user already exists |
|
| 429 | - if ($this->userExists($uid)) { |
|
| 430 | - throw new \InvalidArgumentException($l->t('The Login is already being used')); |
|
| 431 | - } |
|
| 432 | - |
|
| 433 | - /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */ |
|
| 434 | - $this->emit('\OC\User', 'preCreateUser', [$uid, $password]); |
|
| 435 | - $this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password)); |
|
| 436 | - $state = $backend->createUser($uid, $password); |
|
| 437 | - if ($state === false) { |
|
| 438 | - throw new \InvalidArgumentException($l->t('Could not create account')); |
|
| 439 | - } |
|
| 440 | - $user = $this->getUserObject($uid, $backend); |
|
| 441 | - if ($user instanceof IUser) { |
|
| 442 | - /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */ |
|
| 443 | - $this->emit('\OC\User', 'postCreateUser', [$user, $password]); |
|
| 444 | - $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password)); |
|
| 445 | - return $user; |
|
| 446 | - } |
|
| 447 | - return false; |
|
| 448 | - } |
|
| 449 | - |
|
| 450 | - /** |
|
| 451 | - * returns how many users per backend exist (if supported by backend) |
|
| 452 | - * |
|
| 453 | - * @param boolean $hasLoggedIn when true only users that have a lastLogin |
|
| 454 | - * entry in the preferences table will be affected |
|
| 455 | - * @return array<string, int> an array of backend class as key and count number as value |
|
| 456 | - */ |
|
| 457 | - public function countUsers() { |
|
| 458 | - $userCountStatistics = []; |
|
| 459 | - foreach ($this->backends as $backend) { |
|
| 460 | - if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) { |
|
| 461 | - /** @var ICountUsersBackend|IUserBackend $backend */ |
|
| 462 | - $backendUsers = $backend->countUsers(); |
|
| 463 | - if ($backendUsers !== false) { |
|
| 464 | - if ($backend instanceof IUserBackend) { |
|
| 465 | - $name = $backend->getBackendName(); |
|
| 466 | - } else { |
|
| 467 | - $name = get_class($backend); |
|
| 468 | - } |
|
| 469 | - if (isset($userCountStatistics[$name])) { |
|
| 470 | - $userCountStatistics[$name] += $backendUsers; |
|
| 471 | - } else { |
|
| 472 | - $userCountStatistics[$name] = $backendUsers; |
|
| 473 | - } |
|
| 474 | - } |
|
| 475 | - } |
|
| 476 | - } |
|
| 477 | - return $userCountStatistics; |
|
| 478 | - } |
|
| 479 | - |
|
| 480 | - public function countUsersTotal(int $limit = 0, bool $onlyMappedUsers = false): int|false { |
|
| 481 | - $userCount = false; |
|
| 482 | - |
|
| 483 | - foreach ($this->backends as $backend) { |
|
| 484 | - if ($onlyMappedUsers && $backend instanceof ICountMappedUsersBackend) { |
|
| 485 | - $backendUsers = $backend->countMappedUsers(); |
|
| 486 | - } elseif ($backend instanceof ILimitAwareCountUsersBackend) { |
|
| 487 | - $backendUsers = $backend->countUsers($limit); |
|
| 488 | - } elseif ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) { |
|
| 489 | - /** @var ICountUsersBackend $backend */ |
|
| 490 | - $backendUsers = $backend->countUsers(); |
|
| 491 | - } else { |
|
| 492 | - $this->logger->debug('Skip backend for user count: ' . get_class($backend)); |
|
| 493 | - continue; |
|
| 494 | - } |
|
| 495 | - if ($backendUsers !== false) { |
|
| 496 | - $userCount = (int)$userCount + $backendUsers; |
|
| 497 | - if ($limit > 0) { |
|
| 498 | - if ($userCount >= $limit) { |
|
| 499 | - break; |
|
| 500 | - } |
|
| 501 | - $limit -= $userCount; |
|
| 502 | - } |
|
| 503 | - } else { |
|
| 504 | - $this->logger->warning('Can not determine user count for ' . get_class($backend)); |
|
| 505 | - } |
|
| 506 | - } |
|
| 507 | - return $userCount; |
|
| 508 | - } |
|
| 509 | - |
|
| 510 | - /** |
|
| 511 | - * returns how many users per backend exist in the requested groups (if supported by backend) |
|
| 512 | - * |
|
| 513 | - * @param IGroup[] $groups an array of groups to search in |
|
| 514 | - * @param int $limit limit to stop counting |
|
| 515 | - * @return array{int,int} total number of users, and number of disabled users in the given groups, below $limit. If limit is reached, -1 is returned for number of disabled users |
|
| 516 | - */ |
|
| 517 | - public function countUsersAndDisabledUsersOfGroups(array $groups, int $limit): array { |
|
| 518 | - $users = []; |
|
| 519 | - $disabled = []; |
|
| 520 | - foreach ($groups as $group) { |
|
| 521 | - foreach ($group->getUsers() as $user) { |
|
| 522 | - $users[$user->getUID()] = 1; |
|
| 523 | - if (!$user->isEnabled()) { |
|
| 524 | - $disabled[$user->getUID()] = 1; |
|
| 525 | - } |
|
| 526 | - if (count($users) >= $limit) { |
|
| 527 | - return [count($users),-1]; |
|
| 528 | - } |
|
| 529 | - } |
|
| 530 | - } |
|
| 531 | - return [count($users),count($disabled)]; |
|
| 532 | - } |
|
| 533 | - |
|
| 534 | - /** |
|
| 535 | - * The callback is executed for each user on each backend. |
|
| 536 | - * If the callback returns false no further users will be retrieved. |
|
| 537 | - * |
|
| 538 | - * @psalm-param \Closure(\OCP\IUser):?bool $callback |
|
| 539 | - * @param string $search |
|
| 540 | - * @param boolean $onlySeen when true only users that have a lastLogin entry |
|
| 541 | - * in the preferences table will be affected |
|
| 542 | - * @since 9.0.0 |
|
| 543 | - */ |
|
| 544 | - public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) { |
|
| 545 | - if ($onlySeen) { |
|
| 546 | - $this->callForSeenUsers($callback); |
|
| 547 | - } else { |
|
| 548 | - foreach ($this->getBackends() as $backend) { |
|
| 549 | - $limit = 500; |
|
| 550 | - $offset = 0; |
|
| 551 | - do { |
|
| 552 | - $users = $backend->getUsers($search, $limit, $offset); |
|
| 553 | - foreach ($users as $uid) { |
|
| 554 | - if (!$backend->userExists($uid)) { |
|
| 555 | - continue; |
|
| 556 | - } |
|
| 557 | - $user = $this->getUserObject($uid, $backend, false); |
|
| 558 | - $return = $callback($user); |
|
| 559 | - if ($return === false) { |
|
| 560 | - break; |
|
| 561 | - } |
|
| 562 | - } |
|
| 563 | - $offset += $limit; |
|
| 564 | - } while (count($users) >= $limit); |
|
| 565 | - } |
|
| 566 | - } |
|
| 567 | - } |
|
| 568 | - |
|
| 569 | - /** |
|
| 570 | - * returns how many users are disabled |
|
| 571 | - * |
|
| 572 | - * @return int |
|
| 573 | - * @since 12.0.0 |
|
| 574 | - */ |
|
| 575 | - public function countDisabledUsers(): int { |
|
| 576 | - $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
| 577 | - $queryBuilder->select($queryBuilder->func()->count('*')) |
|
| 578 | - ->from('preferences') |
|
| 579 | - ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core'))) |
|
| 580 | - ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled'))) |
|
| 581 | - ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR)); |
|
| 582 | - |
|
| 583 | - |
|
| 584 | - $result = $queryBuilder->execute(); |
|
| 585 | - $count = $result->fetchOne(); |
|
| 586 | - $result->closeCursor(); |
|
| 587 | - |
|
| 588 | - if ($count !== false) { |
|
| 589 | - $count = (int)$count; |
|
| 590 | - } else { |
|
| 591 | - $count = 0; |
|
| 592 | - } |
|
| 593 | - |
|
| 594 | - return $count; |
|
| 595 | - } |
|
| 596 | - |
|
| 597 | - /** |
|
| 598 | - * returns how many users have logged in once |
|
| 599 | - * |
|
| 600 | - * @return int |
|
| 601 | - * @since 11.0.0 |
|
| 602 | - */ |
|
| 603 | - public function countSeenUsers() { |
|
| 604 | - $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
| 605 | - $queryBuilder->select($queryBuilder->func()->count('*')) |
|
| 606 | - ->from('preferences') |
|
| 607 | - ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login'))) |
|
| 608 | - ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin'))); |
|
| 609 | - |
|
| 610 | - $query = $queryBuilder->execute(); |
|
| 611 | - |
|
| 612 | - $result = (int)$query->fetchOne(); |
|
| 613 | - $query->closeCursor(); |
|
| 614 | - |
|
| 615 | - return $result; |
|
| 616 | - } |
|
| 617 | - |
|
| 618 | - public function callForSeenUsers(\Closure $callback) { |
|
| 619 | - $users = $this->getSeenUsers(); |
|
| 620 | - foreach ($users as $user) { |
|
| 621 | - $return = $callback($user); |
|
| 622 | - if ($return === false) { |
|
| 623 | - return; |
|
| 624 | - } |
|
| 625 | - } |
|
| 626 | - } |
|
| 627 | - |
|
| 628 | - /** |
|
| 629 | - * Getting all userIds that have a listLogin value requires checking the |
|
| 630 | - * value in php because on oracle you cannot use a clob in a where clause, |
|
| 631 | - * preventing us from doing a not null or length(value) > 0 check. |
|
| 632 | - * |
|
| 633 | - * @param int $limit |
|
| 634 | - * @param int $offset |
|
| 635 | - * @return string[] with user ids |
|
| 636 | - */ |
|
| 637 | - private function getSeenUserIds($limit = null, $offset = null) { |
|
| 638 | - $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
| 639 | - $queryBuilder->select(['userid']) |
|
| 640 | - ->from('preferences') |
|
| 641 | - ->where($queryBuilder->expr()->eq( |
|
| 642 | - 'appid', $queryBuilder->createNamedParameter('login')) |
|
| 643 | - ) |
|
| 644 | - ->andWhere($queryBuilder->expr()->eq( |
|
| 645 | - 'configkey', $queryBuilder->createNamedParameter('lastLogin')) |
|
| 646 | - ) |
|
| 647 | - ->andWhere($queryBuilder->expr()->isNotNull('configvalue') |
|
| 648 | - ); |
|
| 649 | - |
|
| 650 | - if ($limit !== null) { |
|
| 651 | - $queryBuilder->setMaxResults($limit); |
|
| 652 | - } |
|
| 653 | - if ($offset !== null) { |
|
| 654 | - $queryBuilder->setFirstResult($offset); |
|
| 655 | - } |
|
| 656 | - $query = $queryBuilder->execute(); |
|
| 657 | - $result = []; |
|
| 658 | - |
|
| 659 | - while ($row = $query->fetch()) { |
|
| 660 | - $result[] = $row['userid']; |
|
| 661 | - } |
|
| 662 | - |
|
| 663 | - $query->closeCursor(); |
|
| 664 | - |
|
| 665 | - return $result; |
|
| 666 | - } |
|
| 667 | - |
|
| 668 | - /** |
|
| 669 | - * @param string $email |
|
| 670 | - * @return IUser[] |
|
| 671 | - * @since 9.1.0 |
|
| 672 | - */ |
|
| 673 | - public function getByEmail($email) { |
|
| 674 | - // looking for 'email' only (and not primary_mail) is intentional |
|
| 675 | - $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email); |
|
| 676 | - |
|
| 677 | - $users = array_map(function ($uid) { |
|
| 678 | - return $this->get($uid); |
|
| 679 | - }, $userIds); |
|
| 680 | - |
|
| 681 | - return array_values(array_filter($users, function ($u) { |
|
| 682 | - return ($u instanceof IUser); |
|
| 683 | - })); |
|
| 684 | - } |
|
| 685 | - |
|
| 686 | - /** |
|
| 687 | - * @param string $uid |
|
| 688 | - * @param bool $checkDataDirectory |
|
| 689 | - * @throws \InvalidArgumentException Message is an already translated string with a reason why the id is not valid |
|
| 690 | - * @since 26.0.0 |
|
| 691 | - */ |
|
| 692 | - public function validateUserId(string $uid, bool $checkDataDirectory = false): void { |
|
| 693 | - $l = Server::get(IFactory::class)->get('lib'); |
|
| 694 | - |
|
| 695 | - // Check the name for bad characters |
|
| 696 | - // Allowed are: "a-z", "A-Z", "0-9", spaces and "_.@-'" |
|
| 697 | - if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) { |
|
| 698 | - throw new \InvalidArgumentException($l->t('Only the following characters are allowed in an Login:' |
|
| 699 | - . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"')); |
|
| 700 | - } |
|
| 701 | - |
|
| 702 | - // No empty username |
|
| 703 | - if (trim($uid) === '') { |
|
| 704 | - throw new \InvalidArgumentException($l->t('A valid Login must be provided')); |
|
| 705 | - } |
|
| 706 | - |
|
| 707 | - // No whitespace at the beginning or at the end |
|
| 708 | - if (trim($uid) !== $uid) { |
|
| 709 | - throw new \InvalidArgumentException($l->t('Login contains whitespace at the beginning or at the end')); |
|
| 710 | - } |
|
| 711 | - |
|
| 712 | - // Username only consists of 1 or 2 dots (directory traversal) |
|
| 713 | - if ($uid === '.' || $uid === '..') { |
|
| 714 | - throw new \InvalidArgumentException($l->t('Login must not consist of dots only')); |
|
| 715 | - } |
|
| 716 | - |
|
| 717 | - if (!$this->verifyUid($uid, $checkDataDirectory)) { |
|
| 718 | - throw new \InvalidArgumentException($l->t('Login is invalid because files already exist for this user')); |
|
| 719 | - } |
|
| 720 | - } |
|
| 721 | - |
|
| 722 | - /** |
|
| 723 | - * Gets the list of user ids sorted by lastLogin, from most recent to least recent |
|
| 724 | - * |
|
| 725 | - * @param int|null $limit how many users to fetch (default: 25, max: 100) |
|
| 726 | - * @param int $offset from which offset to fetch |
|
| 727 | - * @param string $search search users based on search params |
|
| 728 | - * @return list<string> list of user IDs |
|
| 729 | - */ |
|
| 730 | - public function getLastLoggedInUsers(?int $limit = null, int $offset = 0, string $search = ''): array { |
|
| 731 | - // We can't load all users who already logged in |
|
| 732 | - $limit = min(100, $limit ?: 25); |
|
| 733 | - |
|
| 734 | - $connection = \OC::$server->getDatabaseConnection(); |
|
| 735 | - $queryBuilder = $connection->getQueryBuilder(); |
|
| 736 | - $queryBuilder->select('pref_login.userid') |
|
| 737 | - ->from('preferences', 'pref_login') |
|
| 738 | - ->where($queryBuilder->expr()->eq('pref_login.appid', $queryBuilder->expr()->literal('login'))) |
|
| 739 | - ->andWhere($queryBuilder->expr()->eq('pref_login.configkey', $queryBuilder->expr()->literal('lastLogin'))) |
|
| 740 | - ->setFirstResult($offset) |
|
| 741 | - ->setMaxResults($limit) |
|
| 742 | - ; |
|
| 743 | - |
|
| 744 | - // Oracle don't want to run ORDER BY on CLOB column |
|
| 745 | - $loginOrder = $connection->getDatabasePlatform() instanceof OraclePlatform |
|
| 746 | - ? $queryBuilder->expr()->castColumn('pref_login.configvalue', IQueryBuilder::PARAM_INT) |
|
| 747 | - : 'pref_login.configvalue'; |
|
| 748 | - $queryBuilder |
|
| 749 | - ->orderBy($loginOrder, 'DESC') |
|
| 750 | - ->addOrderBy($queryBuilder->func()->lower('pref_login.userid'), 'ASC'); |
|
| 751 | - |
|
| 752 | - if ($search !== '') { |
|
| 753 | - $displayNameMatches = $this->searchDisplayName($search); |
|
| 754 | - $matchedUids = array_map(static fn (IUser $u): string => $u->getUID(), $displayNameMatches); |
|
| 755 | - |
|
| 756 | - $queryBuilder |
|
| 757 | - ->leftJoin('pref_login', 'preferences', 'pref_email', $queryBuilder->expr()->andX( |
|
| 758 | - $queryBuilder->expr()->eq('pref_login.userid', 'pref_email.userid'), |
|
| 759 | - $queryBuilder->expr()->eq('pref_email.appid', $queryBuilder->expr()->literal('settings')), |
|
| 760 | - $queryBuilder->expr()->eq('pref_email.configkey', $queryBuilder->expr()->literal('email')), |
|
| 761 | - )) |
|
| 762 | - ->andWhere($queryBuilder->expr()->orX( |
|
| 763 | - $queryBuilder->expr()->in('pref_login.userid', $queryBuilder->createNamedParameter($matchedUids, IQueryBuilder::PARAM_STR_ARRAY)), |
|
| 764 | - )); |
|
| 765 | - } |
|
| 766 | - |
|
| 767 | - /** @var list<string> */ |
|
| 768 | - $list = $queryBuilder->executeQuery()->fetchAll(\PDO::FETCH_COLUMN); |
|
| 769 | - |
|
| 770 | - return $list; |
|
| 771 | - } |
|
| 772 | - |
|
| 773 | - private function verifyUid(string $uid, bool $checkDataDirectory = false): bool { |
|
| 774 | - $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid'); |
|
| 775 | - |
|
| 776 | - if (\in_array($uid, [ |
|
| 777 | - '.htaccess', |
|
| 778 | - 'files_external', |
|
| 779 | - '__groupfolders', |
|
| 780 | - '.ncdata', |
|
| 781 | - 'owncloud.log', |
|
| 782 | - 'nextcloud.log', |
|
| 783 | - 'updater.log', |
|
| 784 | - 'audit.log', |
|
| 785 | - $appdata], true)) { |
|
| 786 | - return false; |
|
| 787 | - } |
|
| 788 | - |
|
| 789 | - if (!$checkDataDirectory) { |
|
| 790 | - return true; |
|
| 791 | - } |
|
| 792 | - |
|
| 793 | - $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data'); |
|
| 794 | - |
|
| 795 | - return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid); |
|
| 796 | - } |
|
| 797 | - |
|
| 798 | - public function getDisplayNameCache(): DisplayNameCache { |
|
| 799 | - return $this->displayNameCache; |
|
| 800 | - } |
|
| 801 | - |
|
| 802 | - /** |
|
| 803 | - * Gets the list of users sorted by lastLogin, from most recent to least recent |
|
| 804 | - * |
|
| 805 | - * @param int $offset from which offset to fetch |
|
| 806 | - * @return \Iterator<IUser> list of user IDs |
|
| 807 | - * @since 30.0.0 |
|
| 808 | - */ |
|
| 809 | - public function getSeenUsers(int $offset = 0): \Iterator { |
|
| 810 | - $limit = 1000; |
|
| 811 | - |
|
| 812 | - do { |
|
| 813 | - $userIds = $this->getSeenUserIds($limit, $offset); |
|
| 814 | - $offset += $limit; |
|
| 815 | - |
|
| 816 | - foreach ($userIds as $userId) { |
|
| 817 | - foreach ($this->backends as $backend) { |
|
| 818 | - if ($backend->userExists($userId)) { |
|
| 819 | - $user = $this->getUserObject($userId, $backend, false); |
|
| 820 | - yield $user; |
|
| 821 | - break; |
|
| 822 | - } |
|
| 823 | - } |
|
| 824 | - } |
|
| 825 | - } while (count($userIds) === $limit); |
|
| 826 | - } |
|
| 56 | + /** |
|
| 57 | + * @var UserInterface[] $backends |
|
| 58 | + */ |
|
| 59 | + private array $backends = []; |
|
| 60 | + |
|
| 61 | + /** |
|
| 62 | + * @var array<string,\OC\User\User> $cachedUsers |
|
| 63 | + */ |
|
| 64 | + private array $cachedUsers = []; |
|
| 65 | + |
|
| 66 | + private ICache $cache; |
|
| 67 | + |
|
| 68 | + private DisplayNameCache $displayNameCache; |
|
| 69 | + |
|
| 70 | + public function __construct( |
|
| 71 | + private IConfig $config, |
|
| 72 | + ICacheFactory $cacheFactory, |
|
| 73 | + private IEventDispatcher $eventDispatcher, |
|
| 74 | + private LoggerInterface $logger, |
|
| 75 | + ) { |
|
| 76 | + $this->cache = new WithLocalCache($cacheFactory->createDistributed('user_backend_map')); |
|
| 77 | + $this->listen('\OC\User', 'postDelete', function (IUser $user): void { |
|
| 78 | + unset($this->cachedUsers[$user->getUID()]); |
|
| 79 | + }); |
|
| 80 | + $this->displayNameCache = new DisplayNameCache($cacheFactory, $this); |
|
| 81 | + } |
|
| 82 | + |
|
| 83 | + /** |
|
| 84 | + * Get the active backends |
|
| 85 | + * @return UserInterface[] |
|
| 86 | + */ |
|
| 87 | + public function getBackends(): array { |
|
| 88 | + return $this->backends; |
|
| 89 | + } |
|
| 90 | + |
|
| 91 | + public function registerBackend(UserInterface $backend): void { |
|
| 92 | + $this->backends[] = $backend; |
|
| 93 | + } |
|
| 94 | + |
|
| 95 | + public function removeBackend(UserInterface $backend): void { |
|
| 96 | + $this->cachedUsers = []; |
|
| 97 | + if (($i = array_search($backend, $this->backends)) !== false) { |
|
| 98 | + unset($this->backends[$i]); |
|
| 99 | + } |
|
| 100 | + } |
|
| 101 | + |
|
| 102 | + public function clearBackends(): void { |
|
| 103 | + $this->cachedUsers = []; |
|
| 104 | + $this->backends = []; |
|
| 105 | + } |
|
| 106 | + |
|
| 107 | + /** |
|
| 108 | + * get a user by user id |
|
| 109 | + * |
|
| 110 | + * @param string $uid |
|
| 111 | + * @return \OC\User\User|null Either the user or null if the specified user does not exist |
|
| 112 | + */ |
|
| 113 | + public function get($uid) { |
|
| 114 | + if (is_null($uid) || $uid === '' || $uid === false) { |
|
| 115 | + return null; |
|
| 116 | + } |
|
| 117 | + if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends |
|
| 118 | + return $this->cachedUsers[$uid]; |
|
| 119 | + } |
|
| 120 | + |
|
| 121 | + $cachedBackend = $this->cache->get(sha1($uid)); |
|
| 122 | + if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) { |
|
| 123 | + // Cache has the info of the user backend already, so ask that one directly |
|
| 124 | + $backend = $this->backends[$cachedBackend]; |
|
| 125 | + if ($backend->userExists($uid)) { |
|
| 126 | + return $this->getUserObject($uid, $backend); |
|
| 127 | + } |
|
| 128 | + } |
|
| 129 | + |
|
| 130 | + foreach ($this->backends as $i => $backend) { |
|
| 131 | + if ($i === $cachedBackend) { |
|
| 132 | + // Tried that one already |
|
| 133 | + continue; |
|
| 134 | + } |
|
| 135 | + |
|
| 136 | + if ($backend->userExists($uid)) { |
|
| 137 | + // Hash $uid to ensure that only valid characters are used for the cache key |
|
| 138 | + $this->cache->set(sha1($uid), $i, 300); |
|
| 139 | + return $this->getUserObject($uid, $backend); |
|
| 140 | + } |
|
| 141 | + } |
|
| 142 | + return null; |
|
| 143 | + } |
|
| 144 | + |
|
| 145 | + public function getDisplayName(string $uid): ?string { |
|
| 146 | + return $this->displayNameCache->getDisplayName($uid); |
|
| 147 | + } |
|
| 148 | + |
|
| 149 | + /** |
|
| 150 | + * get or construct the user object |
|
| 151 | + * |
|
| 152 | + * @param string $uid |
|
| 153 | + * @param \OCP\UserInterface $backend |
|
| 154 | + * @param bool $cacheUser If false the newly created user object will not be cached |
|
| 155 | + * @return \OC\User\User |
|
| 156 | + */ |
|
| 157 | + public function getUserObject($uid, $backend, $cacheUser = true) { |
|
| 158 | + if ($backend instanceof IGetRealUIDBackend) { |
|
| 159 | + $uid = $backend->getRealUID($uid); |
|
| 160 | + } |
|
| 161 | + |
|
| 162 | + if (isset($this->cachedUsers[$uid])) { |
|
| 163 | + return $this->cachedUsers[$uid]; |
|
| 164 | + } |
|
| 165 | + |
|
| 166 | + $user = new User($uid, $backend, $this->eventDispatcher, $this, $this->config); |
|
| 167 | + if ($cacheUser) { |
|
| 168 | + $this->cachedUsers[$uid] = $user; |
|
| 169 | + } |
|
| 170 | + return $user; |
|
| 171 | + } |
|
| 172 | + |
|
| 173 | + /** |
|
| 174 | + * check if a user exists |
|
| 175 | + * |
|
| 176 | + * @param string $uid |
|
| 177 | + * @return bool |
|
| 178 | + */ |
|
| 179 | + public function userExists($uid) { |
|
| 180 | + $user = $this->get($uid); |
|
| 181 | + return ($user !== null); |
|
| 182 | + } |
|
| 183 | + |
|
| 184 | + /** |
|
| 185 | + * Check if the password is valid for the user |
|
| 186 | + * |
|
| 187 | + * @param string $loginName |
|
| 188 | + * @param string $password |
|
| 189 | + * @return IUser|false the User object on success, false otherwise |
|
| 190 | + */ |
|
| 191 | + public function checkPassword($loginName, $password) { |
|
| 192 | + $result = $this->checkPasswordNoLogging($loginName, $password); |
|
| 193 | + |
|
| 194 | + if ($result === false) { |
|
| 195 | + $this->logger->warning('Login failed: \'' . $loginName . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']); |
|
| 196 | + } |
|
| 197 | + |
|
| 198 | + return $result; |
|
| 199 | + } |
|
| 200 | + |
|
| 201 | + /** |
|
| 202 | + * Check if the password is valid for the user |
|
| 203 | + * |
|
| 204 | + * @internal |
|
| 205 | + * @param string $loginName |
|
| 206 | + * @param string $password |
|
| 207 | + * @return IUser|false the User object on success, false otherwise |
|
| 208 | + */ |
|
| 209 | + public function checkPasswordNoLogging($loginName, $password) { |
|
| 210 | + $loginName = str_replace("\0", '', $loginName); |
|
| 211 | + $password = str_replace("\0", '', $password); |
|
| 212 | + |
|
| 213 | + $cachedBackend = $this->cache->get($loginName); |
|
| 214 | + if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) { |
|
| 215 | + $backends = [$this->backends[$cachedBackend]]; |
|
| 216 | + } else { |
|
| 217 | + $backends = $this->backends; |
|
| 218 | + } |
|
| 219 | + foreach ($backends as $backend) { |
|
| 220 | + if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) { |
|
| 221 | + /** @var ICheckPasswordBackend $backend */ |
|
| 222 | + $uid = $backend->checkPassword($loginName, $password); |
|
| 223 | + if ($uid !== false) { |
|
| 224 | + return $this->getUserObject($uid, $backend); |
|
| 225 | + } |
|
| 226 | + } |
|
| 227 | + } |
|
| 228 | + |
|
| 229 | + // since http basic auth doesn't provide a standard way of handling non ascii password we allow password to be urlencoded |
|
| 230 | + // we only do this decoding after using the plain password fails to maintain compatibility with any password that happens |
|
| 231 | + // to contain urlencoded patterns by "accident". |
|
| 232 | + $password = urldecode($password); |
|
| 233 | + |
|
| 234 | + foreach ($backends as $backend) { |
|
| 235 | + if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) { |
|
| 236 | + /** @var ICheckPasswordBackend|UserInterface $backend */ |
|
| 237 | + $uid = $backend->checkPassword($loginName, $password); |
|
| 238 | + if ($uid !== false) { |
|
| 239 | + return $this->getUserObject($uid, $backend); |
|
| 240 | + } |
|
| 241 | + } |
|
| 242 | + } |
|
| 243 | + |
|
| 244 | + return false; |
|
| 245 | + } |
|
| 246 | + |
|
| 247 | + /** |
|
| 248 | + * Search by user id |
|
| 249 | + * |
|
| 250 | + * @param string $pattern |
|
| 251 | + * @param int $limit |
|
| 252 | + * @param int $offset |
|
| 253 | + * @return IUser[] |
|
| 254 | + * @deprecated 27.0.0, use searchDisplayName instead |
|
| 255 | + */ |
|
| 256 | + public function search($pattern, $limit = null, $offset = null) { |
|
| 257 | + $users = []; |
|
| 258 | + foreach ($this->backends as $backend) { |
|
| 259 | + $backendUsers = $backend->getUsers($pattern, $limit, $offset); |
|
| 260 | + if (is_array($backendUsers)) { |
|
| 261 | + foreach ($backendUsers as $uid) { |
|
| 262 | + $users[$uid] = new LazyUser($uid, $this, null, $backend); |
|
| 263 | + } |
|
| 264 | + } |
|
| 265 | + } |
|
| 266 | + |
|
| 267 | + uasort($users, function (IUser $a, IUser $b) { |
|
| 268 | + return strcasecmp($a->getUID(), $b->getUID()); |
|
| 269 | + }); |
|
| 270 | + return $users; |
|
| 271 | + } |
|
| 272 | + |
|
| 273 | + /** |
|
| 274 | + * Search by displayName |
|
| 275 | + * |
|
| 276 | + * @param string $pattern |
|
| 277 | + * @param int $limit |
|
| 278 | + * @param int $offset |
|
| 279 | + * @return IUser[] |
|
| 280 | + */ |
|
| 281 | + public function searchDisplayName($pattern, $limit = null, $offset = null) { |
|
| 282 | + $users = []; |
|
| 283 | + foreach ($this->backends as $backend) { |
|
| 284 | + $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); |
|
| 285 | + if (is_array($backendUsers)) { |
|
| 286 | + foreach ($backendUsers as $uid => $displayName) { |
|
| 287 | + $users[] = new LazyUser($uid, $this, $displayName, $backend); |
|
| 288 | + } |
|
| 289 | + } |
|
| 290 | + } |
|
| 291 | + |
|
| 292 | + usort($users, function (IUser $a, IUser $b) { |
|
| 293 | + return strcasecmp($a->getDisplayName(), $b->getDisplayName()); |
|
| 294 | + }); |
|
| 295 | + return $users; |
|
| 296 | + } |
|
| 297 | + |
|
| 298 | + /** |
|
| 299 | + * @return IUser[] |
|
| 300 | + */ |
|
| 301 | + public function getDisabledUsers(?int $limit = null, int $offset = 0, string $search = ''): array { |
|
| 302 | + $users = $this->config->getUsersForUserValue('core', 'enabled', 'false'); |
|
| 303 | + $users = array_combine( |
|
| 304 | + $users, |
|
| 305 | + array_map( |
|
| 306 | + fn (string $uid): IUser => new LazyUser($uid, $this), |
|
| 307 | + $users |
|
| 308 | + ) |
|
| 309 | + ); |
|
| 310 | + if ($search !== '') { |
|
| 311 | + $users = array_filter( |
|
| 312 | + $users, |
|
| 313 | + function (IUser $user) use ($search): bool { |
|
| 314 | + try { |
|
| 315 | + return mb_stripos($user->getUID(), $search) !== false || |
|
| 316 | + mb_stripos($user->getDisplayName(), $search) !== false || |
|
| 317 | + mb_stripos($user->getEMailAddress() ?? '', $search) !== false; |
|
| 318 | + } catch (NoUserException $ex) { |
|
| 319 | + $this->logger->error('Error while filtering disabled users', ['exception' => $ex, 'userUID' => $user->getUID()]); |
|
| 320 | + return false; |
|
| 321 | + } |
|
| 322 | + }); |
|
| 323 | + } |
|
| 324 | + |
|
| 325 | + $tempLimit = ($limit === null ? null : $limit + $offset); |
|
| 326 | + foreach ($this->backends as $backend) { |
|
| 327 | + if (($tempLimit !== null) && (count($users) >= $tempLimit)) { |
|
| 328 | + break; |
|
| 329 | + } |
|
| 330 | + if ($backend instanceof IProvideEnabledStateBackend) { |
|
| 331 | + $backendUsers = $backend->getDisabledUserList(($tempLimit === null ? null : $tempLimit - count($users)), 0, $search); |
|
| 332 | + foreach ($backendUsers as $uid) { |
|
| 333 | + $users[$uid] = new LazyUser($uid, $this, null, $backend); |
|
| 334 | + } |
|
| 335 | + } |
|
| 336 | + } |
|
| 337 | + |
|
| 338 | + return array_slice($users, $offset, $limit); |
|
| 339 | + } |
|
| 340 | + |
|
| 341 | + /** |
|
| 342 | + * Search known users (from phonebook sync) by displayName |
|
| 343 | + * |
|
| 344 | + * @param string $searcher |
|
| 345 | + * @param string $pattern |
|
| 346 | + * @param int|null $limit |
|
| 347 | + * @param int|null $offset |
|
| 348 | + * @return IUser[] |
|
| 349 | + */ |
|
| 350 | + public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array { |
|
| 351 | + $users = []; |
|
| 352 | + foreach ($this->backends as $backend) { |
|
| 353 | + if ($backend instanceof ISearchKnownUsersBackend) { |
|
| 354 | + $backendUsers = $backend->searchKnownUsersByDisplayName($searcher, $pattern, $limit, $offset); |
|
| 355 | + } else { |
|
| 356 | + // Better than nothing, but filtering after pagination can remove lots of results. |
|
| 357 | + $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); |
|
| 358 | + } |
|
| 359 | + if (is_array($backendUsers)) { |
|
| 360 | + foreach ($backendUsers as $uid => $displayName) { |
|
| 361 | + $users[] = $this->getUserObject($uid, $backend); |
|
| 362 | + } |
|
| 363 | + } |
|
| 364 | + } |
|
| 365 | + |
|
| 366 | + usort($users, function ($a, $b) { |
|
| 367 | + /** |
|
| 368 | + * @var IUser $a |
|
| 369 | + * @var IUser $b |
|
| 370 | + */ |
|
| 371 | + return strcasecmp($a->getDisplayName(), $b->getDisplayName()); |
|
| 372 | + }); |
|
| 373 | + return $users; |
|
| 374 | + } |
|
| 375 | + |
|
| 376 | + /** |
|
| 377 | + * @param string $uid |
|
| 378 | + * @param string $password |
|
| 379 | + * @return false|IUser the created user or false |
|
| 380 | + * @throws \InvalidArgumentException |
|
| 381 | + * @throws HintException |
|
| 382 | + */ |
|
| 383 | + public function createUser($uid, $password) { |
|
| 384 | + // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency |
|
| 385 | + /** @var IAssertion $assertion */ |
|
| 386 | + $assertion = \OC::$server->get(IAssertion::class); |
|
| 387 | + $assertion->createUserIsLegit(); |
|
| 388 | + |
|
| 389 | + $localBackends = []; |
|
| 390 | + foreach ($this->backends as $backend) { |
|
| 391 | + if ($backend instanceof Database) { |
|
| 392 | + // First check if there is another user backend |
|
| 393 | + $localBackends[] = $backend; |
|
| 394 | + continue; |
|
| 395 | + } |
|
| 396 | + |
|
| 397 | + if ($backend->implementsActions(Backend::CREATE_USER)) { |
|
| 398 | + return $this->createUserFromBackend($uid, $password, $backend); |
|
| 399 | + } |
|
| 400 | + } |
|
| 401 | + |
|
| 402 | + foreach ($localBackends as $backend) { |
|
| 403 | + if ($backend->implementsActions(Backend::CREATE_USER)) { |
|
| 404 | + return $this->createUserFromBackend($uid, $password, $backend); |
|
| 405 | + } |
|
| 406 | + } |
|
| 407 | + |
|
| 408 | + return false; |
|
| 409 | + } |
|
| 410 | + |
|
| 411 | + /** |
|
| 412 | + * @param string $uid |
|
| 413 | + * @param string $password |
|
| 414 | + * @param UserInterface $backend |
|
| 415 | + * @return IUser|false |
|
| 416 | + * @throws \InvalidArgumentException |
|
| 417 | + */ |
|
| 418 | + public function createUserFromBackend($uid, $password, UserInterface $backend) { |
|
| 419 | + $l = \OCP\Util::getL10N('lib'); |
|
| 420 | + |
|
| 421 | + $this->validateUserId($uid, true); |
|
| 422 | + |
|
| 423 | + // No empty password |
|
| 424 | + if (trim($password) === '') { |
|
| 425 | + throw new \InvalidArgumentException($l->t('A valid password must be provided')); |
|
| 426 | + } |
|
| 427 | + |
|
| 428 | + // Check if user already exists |
|
| 429 | + if ($this->userExists($uid)) { |
|
| 430 | + throw new \InvalidArgumentException($l->t('The Login is already being used')); |
|
| 431 | + } |
|
| 432 | + |
|
| 433 | + /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */ |
|
| 434 | + $this->emit('\OC\User', 'preCreateUser', [$uid, $password]); |
|
| 435 | + $this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password)); |
|
| 436 | + $state = $backend->createUser($uid, $password); |
|
| 437 | + if ($state === false) { |
|
| 438 | + throw new \InvalidArgumentException($l->t('Could not create account')); |
|
| 439 | + } |
|
| 440 | + $user = $this->getUserObject($uid, $backend); |
|
| 441 | + if ($user instanceof IUser) { |
|
| 442 | + /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */ |
|
| 443 | + $this->emit('\OC\User', 'postCreateUser', [$user, $password]); |
|
| 444 | + $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password)); |
|
| 445 | + return $user; |
|
| 446 | + } |
|
| 447 | + return false; |
|
| 448 | + } |
|
| 449 | + |
|
| 450 | + /** |
|
| 451 | + * returns how many users per backend exist (if supported by backend) |
|
| 452 | + * |
|
| 453 | + * @param boolean $hasLoggedIn when true only users that have a lastLogin |
|
| 454 | + * entry in the preferences table will be affected |
|
| 455 | + * @return array<string, int> an array of backend class as key and count number as value |
|
| 456 | + */ |
|
| 457 | + public function countUsers() { |
|
| 458 | + $userCountStatistics = []; |
|
| 459 | + foreach ($this->backends as $backend) { |
|
| 460 | + if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) { |
|
| 461 | + /** @var ICountUsersBackend|IUserBackend $backend */ |
|
| 462 | + $backendUsers = $backend->countUsers(); |
|
| 463 | + if ($backendUsers !== false) { |
|
| 464 | + if ($backend instanceof IUserBackend) { |
|
| 465 | + $name = $backend->getBackendName(); |
|
| 466 | + } else { |
|
| 467 | + $name = get_class($backend); |
|
| 468 | + } |
|
| 469 | + if (isset($userCountStatistics[$name])) { |
|
| 470 | + $userCountStatistics[$name] += $backendUsers; |
|
| 471 | + } else { |
|
| 472 | + $userCountStatistics[$name] = $backendUsers; |
|
| 473 | + } |
|
| 474 | + } |
|
| 475 | + } |
|
| 476 | + } |
|
| 477 | + return $userCountStatistics; |
|
| 478 | + } |
|
| 479 | + |
|
| 480 | + public function countUsersTotal(int $limit = 0, bool $onlyMappedUsers = false): int|false { |
|
| 481 | + $userCount = false; |
|
| 482 | + |
|
| 483 | + foreach ($this->backends as $backend) { |
|
| 484 | + if ($onlyMappedUsers && $backend instanceof ICountMappedUsersBackend) { |
|
| 485 | + $backendUsers = $backend->countMappedUsers(); |
|
| 486 | + } elseif ($backend instanceof ILimitAwareCountUsersBackend) { |
|
| 487 | + $backendUsers = $backend->countUsers($limit); |
|
| 488 | + } elseif ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) { |
|
| 489 | + /** @var ICountUsersBackend $backend */ |
|
| 490 | + $backendUsers = $backend->countUsers(); |
|
| 491 | + } else { |
|
| 492 | + $this->logger->debug('Skip backend for user count: ' . get_class($backend)); |
|
| 493 | + continue; |
|
| 494 | + } |
|
| 495 | + if ($backendUsers !== false) { |
|
| 496 | + $userCount = (int)$userCount + $backendUsers; |
|
| 497 | + if ($limit > 0) { |
|
| 498 | + if ($userCount >= $limit) { |
|
| 499 | + break; |
|
| 500 | + } |
|
| 501 | + $limit -= $userCount; |
|
| 502 | + } |
|
| 503 | + } else { |
|
| 504 | + $this->logger->warning('Can not determine user count for ' . get_class($backend)); |
|
| 505 | + } |
|
| 506 | + } |
|
| 507 | + return $userCount; |
|
| 508 | + } |
|
| 509 | + |
|
| 510 | + /** |
|
| 511 | + * returns how many users per backend exist in the requested groups (if supported by backend) |
|
| 512 | + * |
|
| 513 | + * @param IGroup[] $groups an array of groups to search in |
|
| 514 | + * @param int $limit limit to stop counting |
|
| 515 | + * @return array{int,int} total number of users, and number of disabled users in the given groups, below $limit. If limit is reached, -1 is returned for number of disabled users |
|
| 516 | + */ |
|
| 517 | + public function countUsersAndDisabledUsersOfGroups(array $groups, int $limit): array { |
|
| 518 | + $users = []; |
|
| 519 | + $disabled = []; |
|
| 520 | + foreach ($groups as $group) { |
|
| 521 | + foreach ($group->getUsers() as $user) { |
|
| 522 | + $users[$user->getUID()] = 1; |
|
| 523 | + if (!$user->isEnabled()) { |
|
| 524 | + $disabled[$user->getUID()] = 1; |
|
| 525 | + } |
|
| 526 | + if (count($users) >= $limit) { |
|
| 527 | + return [count($users),-1]; |
|
| 528 | + } |
|
| 529 | + } |
|
| 530 | + } |
|
| 531 | + return [count($users),count($disabled)]; |
|
| 532 | + } |
|
| 533 | + |
|
| 534 | + /** |
|
| 535 | + * The callback is executed for each user on each backend. |
|
| 536 | + * If the callback returns false no further users will be retrieved. |
|
| 537 | + * |
|
| 538 | + * @psalm-param \Closure(\OCP\IUser):?bool $callback |
|
| 539 | + * @param string $search |
|
| 540 | + * @param boolean $onlySeen when true only users that have a lastLogin entry |
|
| 541 | + * in the preferences table will be affected |
|
| 542 | + * @since 9.0.0 |
|
| 543 | + */ |
|
| 544 | + public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) { |
|
| 545 | + if ($onlySeen) { |
|
| 546 | + $this->callForSeenUsers($callback); |
|
| 547 | + } else { |
|
| 548 | + foreach ($this->getBackends() as $backend) { |
|
| 549 | + $limit = 500; |
|
| 550 | + $offset = 0; |
|
| 551 | + do { |
|
| 552 | + $users = $backend->getUsers($search, $limit, $offset); |
|
| 553 | + foreach ($users as $uid) { |
|
| 554 | + if (!$backend->userExists($uid)) { |
|
| 555 | + continue; |
|
| 556 | + } |
|
| 557 | + $user = $this->getUserObject($uid, $backend, false); |
|
| 558 | + $return = $callback($user); |
|
| 559 | + if ($return === false) { |
|
| 560 | + break; |
|
| 561 | + } |
|
| 562 | + } |
|
| 563 | + $offset += $limit; |
|
| 564 | + } while (count($users) >= $limit); |
|
| 565 | + } |
|
| 566 | + } |
|
| 567 | + } |
|
| 568 | + |
|
| 569 | + /** |
|
| 570 | + * returns how many users are disabled |
|
| 571 | + * |
|
| 572 | + * @return int |
|
| 573 | + * @since 12.0.0 |
|
| 574 | + */ |
|
| 575 | + public function countDisabledUsers(): int { |
|
| 576 | + $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
| 577 | + $queryBuilder->select($queryBuilder->func()->count('*')) |
|
| 578 | + ->from('preferences') |
|
| 579 | + ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core'))) |
|
| 580 | + ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled'))) |
|
| 581 | + ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR)); |
|
| 582 | + |
|
| 583 | + |
|
| 584 | + $result = $queryBuilder->execute(); |
|
| 585 | + $count = $result->fetchOne(); |
|
| 586 | + $result->closeCursor(); |
|
| 587 | + |
|
| 588 | + if ($count !== false) { |
|
| 589 | + $count = (int)$count; |
|
| 590 | + } else { |
|
| 591 | + $count = 0; |
|
| 592 | + } |
|
| 593 | + |
|
| 594 | + return $count; |
|
| 595 | + } |
|
| 596 | + |
|
| 597 | + /** |
|
| 598 | + * returns how many users have logged in once |
|
| 599 | + * |
|
| 600 | + * @return int |
|
| 601 | + * @since 11.0.0 |
|
| 602 | + */ |
|
| 603 | + public function countSeenUsers() { |
|
| 604 | + $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
| 605 | + $queryBuilder->select($queryBuilder->func()->count('*')) |
|
| 606 | + ->from('preferences') |
|
| 607 | + ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login'))) |
|
| 608 | + ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin'))); |
|
| 609 | + |
|
| 610 | + $query = $queryBuilder->execute(); |
|
| 611 | + |
|
| 612 | + $result = (int)$query->fetchOne(); |
|
| 613 | + $query->closeCursor(); |
|
| 614 | + |
|
| 615 | + return $result; |
|
| 616 | + } |
|
| 617 | + |
|
| 618 | + public function callForSeenUsers(\Closure $callback) { |
|
| 619 | + $users = $this->getSeenUsers(); |
|
| 620 | + foreach ($users as $user) { |
|
| 621 | + $return = $callback($user); |
|
| 622 | + if ($return === false) { |
|
| 623 | + return; |
|
| 624 | + } |
|
| 625 | + } |
|
| 626 | + } |
|
| 627 | + |
|
| 628 | + /** |
|
| 629 | + * Getting all userIds that have a listLogin value requires checking the |
|
| 630 | + * value in php because on oracle you cannot use a clob in a where clause, |
|
| 631 | + * preventing us from doing a not null or length(value) > 0 check. |
|
| 632 | + * |
|
| 633 | + * @param int $limit |
|
| 634 | + * @param int $offset |
|
| 635 | + * @return string[] with user ids |
|
| 636 | + */ |
|
| 637 | + private function getSeenUserIds($limit = null, $offset = null) { |
|
| 638 | + $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
| 639 | + $queryBuilder->select(['userid']) |
|
| 640 | + ->from('preferences') |
|
| 641 | + ->where($queryBuilder->expr()->eq( |
|
| 642 | + 'appid', $queryBuilder->createNamedParameter('login')) |
|
| 643 | + ) |
|
| 644 | + ->andWhere($queryBuilder->expr()->eq( |
|
| 645 | + 'configkey', $queryBuilder->createNamedParameter('lastLogin')) |
|
| 646 | + ) |
|
| 647 | + ->andWhere($queryBuilder->expr()->isNotNull('configvalue') |
|
| 648 | + ); |
|
| 649 | + |
|
| 650 | + if ($limit !== null) { |
|
| 651 | + $queryBuilder->setMaxResults($limit); |
|
| 652 | + } |
|
| 653 | + if ($offset !== null) { |
|
| 654 | + $queryBuilder->setFirstResult($offset); |
|
| 655 | + } |
|
| 656 | + $query = $queryBuilder->execute(); |
|
| 657 | + $result = []; |
|
| 658 | + |
|
| 659 | + while ($row = $query->fetch()) { |
|
| 660 | + $result[] = $row['userid']; |
|
| 661 | + } |
|
| 662 | + |
|
| 663 | + $query->closeCursor(); |
|
| 664 | + |
|
| 665 | + return $result; |
|
| 666 | + } |
|
| 667 | + |
|
| 668 | + /** |
|
| 669 | + * @param string $email |
|
| 670 | + * @return IUser[] |
|
| 671 | + * @since 9.1.0 |
|
| 672 | + */ |
|
| 673 | + public function getByEmail($email) { |
|
| 674 | + // looking for 'email' only (and not primary_mail) is intentional |
|
| 675 | + $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email); |
|
| 676 | + |
|
| 677 | + $users = array_map(function ($uid) { |
|
| 678 | + return $this->get($uid); |
|
| 679 | + }, $userIds); |
|
| 680 | + |
|
| 681 | + return array_values(array_filter($users, function ($u) { |
|
| 682 | + return ($u instanceof IUser); |
|
| 683 | + })); |
|
| 684 | + } |
|
| 685 | + |
|
| 686 | + /** |
|
| 687 | + * @param string $uid |
|
| 688 | + * @param bool $checkDataDirectory |
|
| 689 | + * @throws \InvalidArgumentException Message is an already translated string with a reason why the id is not valid |
|
| 690 | + * @since 26.0.0 |
|
| 691 | + */ |
|
| 692 | + public function validateUserId(string $uid, bool $checkDataDirectory = false): void { |
|
| 693 | + $l = Server::get(IFactory::class)->get('lib'); |
|
| 694 | + |
|
| 695 | + // Check the name for bad characters |
|
| 696 | + // Allowed are: "a-z", "A-Z", "0-9", spaces and "_.@-'" |
|
| 697 | + if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) { |
|
| 698 | + throw new \InvalidArgumentException($l->t('Only the following characters are allowed in an Login:' |
|
| 699 | + . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"')); |
|
| 700 | + } |
|
| 701 | + |
|
| 702 | + // No empty username |
|
| 703 | + if (trim($uid) === '') { |
|
| 704 | + throw new \InvalidArgumentException($l->t('A valid Login must be provided')); |
|
| 705 | + } |
|
| 706 | + |
|
| 707 | + // No whitespace at the beginning or at the end |
|
| 708 | + if (trim($uid) !== $uid) { |
|
| 709 | + throw new \InvalidArgumentException($l->t('Login contains whitespace at the beginning or at the end')); |
|
| 710 | + } |
|
| 711 | + |
|
| 712 | + // Username only consists of 1 or 2 dots (directory traversal) |
|
| 713 | + if ($uid === '.' || $uid === '..') { |
|
| 714 | + throw new \InvalidArgumentException($l->t('Login must not consist of dots only')); |
|
| 715 | + } |
|
| 716 | + |
|
| 717 | + if (!$this->verifyUid($uid, $checkDataDirectory)) { |
|
| 718 | + throw new \InvalidArgumentException($l->t('Login is invalid because files already exist for this user')); |
|
| 719 | + } |
|
| 720 | + } |
|
| 721 | + |
|
| 722 | + /** |
|
| 723 | + * Gets the list of user ids sorted by lastLogin, from most recent to least recent |
|
| 724 | + * |
|
| 725 | + * @param int|null $limit how many users to fetch (default: 25, max: 100) |
|
| 726 | + * @param int $offset from which offset to fetch |
|
| 727 | + * @param string $search search users based on search params |
|
| 728 | + * @return list<string> list of user IDs |
|
| 729 | + */ |
|
| 730 | + public function getLastLoggedInUsers(?int $limit = null, int $offset = 0, string $search = ''): array { |
|
| 731 | + // We can't load all users who already logged in |
|
| 732 | + $limit = min(100, $limit ?: 25); |
|
| 733 | + |
|
| 734 | + $connection = \OC::$server->getDatabaseConnection(); |
|
| 735 | + $queryBuilder = $connection->getQueryBuilder(); |
|
| 736 | + $queryBuilder->select('pref_login.userid') |
|
| 737 | + ->from('preferences', 'pref_login') |
|
| 738 | + ->where($queryBuilder->expr()->eq('pref_login.appid', $queryBuilder->expr()->literal('login'))) |
|
| 739 | + ->andWhere($queryBuilder->expr()->eq('pref_login.configkey', $queryBuilder->expr()->literal('lastLogin'))) |
|
| 740 | + ->setFirstResult($offset) |
|
| 741 | + ->setMaxResults($limit) |
|
| 742 | + ; |
|
| 743 | + |
|
| 744 | + // Oracle don't want to run ORDER BY on CLOB column |
|
| 745 | + $loginOrder = $connection->getDatabasePlatform() instanceof OraclePlatform |
|
| 746 | + ? $queryBuilder->expr()->castColumn('pref_login.configvalue', IQueryBuilder::PARAM_INT) |
|
| 747 | + : 'pref_login.configvalue'; |
|
| 748 | + $queryBuilder |
|
| 749 | + ->orderBy($loginOrder, 'DESC') |
|
| 750 | + ->addOrderBy($queryBuilder->func()->lower('pref_login.userid'), 'ASC'); |
|
| 751 | + |
|
| 752 | + if ($search !== '') { |
|
| 753 | + $displayNameMatches = $this->searchDisplayName($search); |
|
| 754 | + $matchedUids = array_map(static fn (IUser $u): string => $u->getUID(), $displayNameMatches); |
|
| 755 | + |
|
| 756 | + $queryBuilder |
|
| 757 | + ->leftJoin('pref_login', 'preferences', 'pref_email', $queryBuilder->expr()->andX( |
|
| 758 | + $queryBuilder->expr()->eq('pref_login.userid', 'pref_email.userid'), |
|
| 759 | + $queryBuilder->expr()->eq('pref_email.appid', $queryBuilder->expr()->literal('settings')), |
|
| 760 | + $queryBuilder->expr()->eq('pref_email.configkey', $queryBuilder->expr()->literal('email')), |
|
| 761 | + )) |
|
| 762 | + ->andWhere($queryBuilder->expr()->orX( |
|
| 763 | + $queryBuilder->expr()->in('pref_login.userid', $queryBuilder->createNamedParameter($matchedUids, IQueryBuilder::PARAM_STR_ARRAY)), |
|
| 764 | + )); |
|
| 765 | + } |
|
| 766 | + |
|
| 767 | + /** @var list<string> */ |
|
| 768 | + $list = $queryBuilder->executeQuery()->fetchAll(\PDO::FETCH_COLUMN); |
|
| 769 | + |
|
| 770 | + return $list; |
|
| 771 | + } |
|
| 772 | + |
|
| 773 | + private function verifyUid(string $uid, bool $checkDataDirectory = false): bool { |
|
| 774 | + $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid'); |
|
| 775 | + |
|
| 776 | + if (\in_array($uid, [ |
|
| 777 | + '.htaccess', |
|
| 778 | + 'files_external', |
|
| 779 | + '__groupfolders', |
|
| 780 | + '.ncdata', |
|
| 781 | + 'owncloud.log', |
|
| 782 | + 'nextcloud.log', |
|
| 783 | + 'updater.log', |
|
| 784 | + 'audit.log', |
|
| 785 | + $appdata], true)) { |
|
| 786 | + return false; |
|
| 787 | + } |
|
| 788 | + |
|
| 789 | + if (!$checkDataDirectory) { |
|
| 790 | + return true; |
|
| 791 | + } |
|
| 792 | + |
|
| 793 | + $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data'); |
|
| 794 | + |
|
| 795 | + return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid); |
|
| 796 | + } |
|
| 797 | + |
|
| 798 | + public function getDisplayNameCache(): DisplayNameCache { |
|
| 799 | + return $this->displayNameCache; |
|
| 800 | + } |
|
| 801 | + |
|
| 802 | + /** |
|
| 803 | + * Gets the list of users sorted by lastLogin, from most recent to least recent |
|
| 804 | + * |
|
| 805 | + * @param int $offset from which offset to fetch |
|
| 806 | + * @return \Iterator<IUser> list of user IDs |
|
| 807 | + * @since 30.0.0 |
|
| 808 | + */ |
|
| 809 | + public function getSeenUsers(int $offset = 0): \Iterator { |
|
| 810 | + $limit = 1000; |
|
| 811 | + |
|
| 812 | + do { |
|
| 813 | + $userIds = $this->getSeenUserIds($limit, $offset); |
|
| 814 | + $offset += $limit; |
|
| 815 | + |
|
| 816 | + foreach ($userIds as $userId) { |
|
| 817 | + foreach ($this->backends as $backend) { |
|
| 818 | + if ($backend->userExists($userId)) { |
|
| 819 | + $user = $this->getUserObject($userId, $backend, false); |
|
| 820 | + yield $user; |
|
| 821 | + break; |
|
| 822 | + } |
|
| 823 | + } |
|
| 824 | + } |
|
| 825 | + } while (count($userIds) === $limit); |
|
| 826 | + } |
|
| 827 | 827 | } |
@@ -37,1142 +37,1142 @@ |
||
| 37 | 37 | * OC_autoload! |
| 38 | 38 | */ |
| 39 | 39 | class OC { |
| 40 | - /** |
|
| 41 | - * Associative array for autoloading. classname => filename |
|
| 42 | - */ |
|
| 43 | - public static array $CLASSPATH = []; |
|
| 44 | - /** |
|
| 45 | - * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
| 46 | - */ |
|
| 47 | - public static string $SERVERROOT = ''; |
|
| 48 | - /** |
|
| 49 | - * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
| 50 | - */ |
|
| 51 | - private static string $SUBURI = ''; |
|
| 52 | - /** |
|
| 53 | - * the Nextcloud root path for http requests (e.g. /nextcloud) |
|
| 54 | - */ |
|
| 55 | - public static string $WEBROOT = ''; |
|
| 56 | - /** |
|
| 57 | - * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
| 58 | - * web path in 'url' |
|
| 59 | - */ |
|
| 60 | - public static array $APPSROOTS = []; |
|
| 61 | - |
|
| 62 | - public static string $configDir; |
|
| 63 | - |
|
| 64 | - /** |
|
| 65 | - * requested app |
|
| 66 | - */ |
|
| 67 | - public static string $REQUESTEDAPP = ''; |
|
| 68 | - |
|
| 69 | - /** |
|
| 70 | - * check if Nextcloud runs in cli mode |
|
| 71 | - */ |
|
| 72 | - public static bool $CLI = false; |
|
| 73 | - |
|
| 74 | - public static \OC\Autoloader $loader; |
|
| 75 | - |
|
| 76 | - public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
| 77 | - |
|
| 78 | - public static \OC\Server $server; |
|
| 79 | - |
|
| 80 | - private static \OC\Config $config; |
|
| 81 | - |
|
| 82 | - /** |
|
| 83 | - * @throws \RuntimeException when the 3rdparty directory is missing or |
|
| 84 | - * the app path list is empty or contains an invalid path |
|
| 85 | - */ |
|
| 86 | - public static function initPaths(): void { |
|
| 87 | - if (defined('PHPUNIT_CONFIG_DIR')) { |
|
| 88 | - self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
| 89 | - } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
| 90 | - self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
| 91 | - } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
| 92 | - self::$configDir = rtrim($dir, '/') . '/'; |
|
| 93 | - } else { |
|
| 94 | - self::$configDir = OC::$SERVERROOT . '/config/'; |
|
| 95 | - } |
|
| 96 | - self::$config = new \OC\Config(self::$configDir); |
|
| 97 | - |
|
| 98 | - OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT))); |
|
| 99 | - /** |
|
| 100 | - * FIXME: The following lines are required because we can't yet instantiate |
|
| 101 | - * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
| 102 | - */ |
|
| 103 | - $params = [ |
|
| 104 | - 'server' => [ |
|
| 105 | - 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
| 106 | - 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
| 107 | - ], |
|
| 108 | - ]; |
|
| 109 | - if (isset($_SERVER['REMOTE_ADDR'])) { |
|
| 110 | - $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; |
|
| 111 | - } |
|
| 112 | - $fakeRequest = new \OC\AppFramework\Http\Request( |
|
| 113 | - $params, |
|
| 114 | - new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
| 115 | - new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
| 116 | - ); |
|
| 117 | - $scriptName = $fakeRequest->getScriptName(); |
|
| 118 | - if (substr($scriptName, -1) == '/') { |
|
| 119 | - $scriptName .= 'index.php'; |
|
| 120 | - //make sure suburi follows the same rules as scriptName |
|
| 121 | - if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
| 122 | - if (substr(OC::$SUBURI, -1) != '/') { |
|
| 123 | - OC::$SUBURI = OC::$SUBURI . '/'; |
|
| 124 | - } |
|
| 125 | - OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
| 126 | - } |
|
| 127 | - } |
|
| 128 | - |
|
| 129 | - |
|
| 130 | - if (OC::$CLI) { |
|
| 131 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
| 132 | - } else { |
|
| 133 | - if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
| 134 | - OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
| 135 | - |
|
| 136 | - if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
| 137 | - OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
| 138 | - } |
|
| 139 | - } else { |
|
| 140 | - // The scriptName is not ending with OC::$SUBURI |
|
| 141 | - // This most likely means that we are calling from CLI. |
|
| 142 | - // However some cron jobs still need to generate |
|
| 143 | - // a web URL, so we use overwritewebroot as a fallback. |
|
| 144 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
| 145 | - } |
|
| 146 | - |
|
| 147 | - // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
| 148 | - // slash which is required by URL generation. |
|
| 149 | - if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
|
| 150 | - substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
| 151 | - header('Location: ' . \OC::$WEBROOT . '/'); |
|
| 152 | - exit(); |
|
| 153 | - } |
|
| 154 | - } |
|
| 155 | - |
|
| 156 | - // search the apps folder |
|
| 157 | - $config_paths = self::$config->getValue('apps_paths', []); |
|
| 158 | - if (!empty($config_paths)) { |
|
| 159 | - foreach ($config_paths as $paths) { |
|
| 160 | - if (isset($paths['url']) && isset($paths['path'])) { |
|
| 161 | - $paths['url'] = rtrim($paths['url'], '/'); |
|
| 162 | - $paths['path'] = rtrim($paths['path'], '/'); |
|
| 163 | - OC::$APPSROOTS[] = $paths; |
|
| 164 | - } |
|
| 165 | - } |
|
| 166 | - } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
| 167 | - OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
| 168 | - } |
|
| 169 | - |
|
| 170 | - if (empty(OC::$APPSROOTS)) { |
|
| 171 | - throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
| 172 | - . '. You can also configure the location in the config.php file.'); |
|
| 173 | - } |
|
| 174 | - $paths = []; |
|
| 175 | - foreach (OC::$APPSROOTS as $path) { |
|
| 176 | - $paths[] = $path['path']; |
|
| 177 | - if (!is_dir($path['path'])) { |
|
| 178 | - throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
| 179 | - . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
| 180 | - } |
|
| 181 | - } |
|
| 182 | - |
|
| 183 | - // set the right include path |
|
| 184 | - set_include_path( |
|
| 185 | - implode(PATH_SEPARATOR, $paths) |
|
| 186 | - ); |
|
| 187 | - } |
|
| 188 | - |
|
| 189 | - public static function checkConfig(): void { |
|
| 190 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
| 191 | - |
|
| 192 | - // Create config if it does not already exist |
|
| 193 | - $configFilePath = self::$configDir . '/config.php'; |
|
| 194 | - if (!file_exists($configFilePath)) { |
|
| 195 | - @touch($configFilePath); |
|
| 196 | - } |
|
| 197 | - |
|
| 198 | - // Check if config is writable |
|
| 199 | - $configFileWritable = is_writable($configFilePath); |
|
| 200 | - if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
|
| 201 | - || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
| 202 | - $urlGenerator = Server::get(IURLGenerator::class); |
|
| 203 | - |
|
| 204 | - if (self::$CLI) { |
|
| 205 | - echo $l->t('Cannot write into "config" directory!') . "\n"; |
|
| 206 | - echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n"; |
|
| 207 | - echo "\n"; |
|
| 208 | - 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"; |
|
| 209 | - echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n"; |
|
| 210 | - exit; |
|
| 211 | - } else { |
|
| 212 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
| 213 | - $l->t('Cannot write into "config" directory!'), |
|
| 214 | - $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
| 215 | - . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
| 216 | - . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
| 217 | - 503 |
|
| 218 | - ); |
|
| 219 | - } |
|
| 220 | - } |
|
| 221 | - } |
|
| 222 | - |
|
| 223 | - public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
| 224 | - if (defined('OC_CONSOLE')) { |
|
| 225 | - return; |
|
| 226 | - } |
|
| 227 | - // Redirect to installer if not installed |
|
| 228 | - if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
| 229 | - if (OC::$CLI) { |
|
| 230 | - throw new Exception('Not installed'); |
|
| 231 | - } else { |
|
| 232 | - $url = OC::$WEBROOT . '/index.php'; |
|
| 233 | - header('Location: ' . $url); |
|
| 234 | - } |
|
| 235 | - exit(); |
|
| 236 | - } |
|
| 237 | - } |
|
| 238 | - |
|
| 239 | - public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
| 240 | - // Allow ajax update script to execute without being stopped |
|
| 241 | - if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
| 242 | - // send http status 503 |
|
| 243 | - http_response_code(503); |
|
| 244 | - header('X-Nextcloud-Maintenance-Mode: 1'); |
|
| 245 | - header('Retry-After: 120'); |
|
| 246 | - |
|
| 247 | - // render error page |
|
| 248 | - $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest'); |
|
| 249 | - \OCP\Util::addScript('core', 'maintenance'); |
|
| 250 | - \OCP\Util::addStyle('core', 'guest'); |
|
| 251 | - $template->printPage(); |
|
| 252 | - die(); |
|
| 253 | - } |
|
| 254 | - } |
|
| 255 | - |
|
| 256 | - /** |
|
| 257 | - * Prints the upgrade page |
|
| 258 | - */ |
|
| 259 | - private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
| 260 | - $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', ''); |
|
| 261 | - $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
| 262 | - $tooBig = false; |
|
| 263 | - if (!$disableWebUpdater) { |
|
| 264 | - $apps = Server::get(\OCP\App\IAppManager::class); |
|
| 265 | - if ($apps->isEnabledForAnyone('user_ldap')) { |
|
| 266 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
| 267 | - |
|
| 268 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
| 269 | - ->from('ldap_user_mapping') |
|
| 270 | - ->executeQuery(); |
|
| 271 | - $row = $result->fetch(); |
|
| 272 | - $result->closeCursor(); |
|
| 273 | - |
|
| 274 | - $tooBig = ($row['user_count'] > 50); |
|
| 275 | - } |
|
| 276 | - if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) { |
|
| 277 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
| 278 | - |
|
| 279 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
| 280 | - ->from('user_saml_users') |
|
| 281 | - ->executeQuery(); |
|
| 282 | - $row = $result->fetch(); |
|
| 283 | - $result->closeCursor(); |
|
| 284 | - |
|
| 285 | - $tooBig = ($row['user_count'] > 50); |
|
| 286 | - } |
|
| 287 | - if (!$tooBig) { |
|
| 288 | - // count users |
|
| 289 | - $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51); |
|
| 290 | - $tooBig = ($totalUsers > 50); |
|
| 291 | - } |
|
| 292 | - } |
|
| 293 | - $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) && |
|
| 294 | - $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
| 295 | - |
|
| 296 | - if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
| 297 | - // send http status 503 |
|
| 298 | - http_response_code(503); |
|
| 299 | - header('Retry-After: 120'); |
|
| 300 | - |
|
| 301 | - $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class); |
|
| 302 | - |
|
| 303 | - // render error page |
|
| 304 | - $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest'); |
|
| 305 | - $template->assign('productName', 'nextcloud'); // for now |
|
| 306 | - $template->assign('version', $serverVersion->getVersionString()); |
|
| 307 | - $template->assign('tooBig', $tooBig); |
|
| 308 | - $template->assign('cliUpgradeLink', $cliUpgradeLink); |
|
| 309 | - |
|
| 310 | - $template->printPage(); |
|
| 311 | - die(); |
|
| 312 | - } |
|
| 313 | - |
|
| 314 | - // check whether this is a core update or apps update |
|
| 315 | - $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
| 316 | - $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
| 317 | - |
|
| 318 | - // if not a core upgrade, then it's apps upgrade |
|
| 319 | - $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
| 320 | - |
|
| 321 | - $oldTheme = $systemConfig->getValue('theme'); |
|
| 322 | - $systemConfig->setValue('theme', ''); |
|
| 323 | - \OCP\Util::addScript('core', 'common'); |
|
| 324 | - \OCP\Util::addScript('core', 'main'); |
|
| 325 | - \OCP\Util::addTranslations('core'); |
|
| 326 | - \OCP\Util::addScript('core', 'update'); |
|
| 327 | - |
|
| 328 | - /** @var \OC\App\AppManager $appManager */ |
|
| 329 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 330 | - |
|
| 331 | - $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest'); |
|
| 332 | - $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString()); |
|
| 333 | - $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
| 334 | - |
|
| 335 | - // get third party apps |
|
| 336 | - $ocVersion = \OCP\Util::getVersion(); |
|
| 337 | - $ocVersion = implode('.', $ocVersion); |
|
| 338 | - $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
| 339 | - $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []); |
|
| 340 | - $incompatibleShippedApps = []; |
|
| 341 | - $incompatibleDisabledApps = []; |
|
| 342 | - foreach ($incompatibleApps as $appInfo) { |
|
| 343 | - if ($appManager->isShipped($appInfo['id'])) { |
|
| 344 | - $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
| 345 | - } |
|
| 346 | - if (!in_array($appInfo['id'], $incompatibleOverwrites)) { |
|
| 347 | - $incompatibleDisabledApps[] = $appInfo; |
|
| 348 | - } |
|
| 349 | - } |
|
| 350 | - |
|
| 351 | - if (!empty($incompatibleShippedApps)) { |
|
| 352 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
| 353 | - $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)]); |
|
| 354 | - 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); |
|
| 355 | - } |
|
| 356 | - |
|
| 357 | - $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
| 358 | - $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps); |
|
| 359 | - try { |
|
| 360 | - $defaults = new \OC_Defaults(); |
|
| 361 | - $tmpl->assign('productName', $defaults->getName()); |
|
| 362 | - } catch (Throwable $error) { |
|
| 363 | - $tmpl->assign('productName', 'Nextcloud'); |
|
| 364 | - } |
|
| 365 | - $tmpl->assign('oldTheme', $oldTheme); |
|
| 366 | - $tmpl->printPage(); |
|
| 367 | - } |
|
| 368 | - |
|
| 369 | - public static function initSession(): void { |
|
| 370 | - $request = Server::get(IRequest::class); |
|
| 371 | - |
|
| 372 | - // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies |
|
| 373 | - // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments |
|
| 374 | - // TODO: for further information. |
|
| 375 | - // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
| 376 | - // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
| 377 | - // setcookie('cookie_test', 'test', time() + 3600); |
|
| 378 | - // // Do not initialize the session if a request is authenticated directly |
|
| 379 | - // // unless there is a session cookie already sent along |
|
| 380 | - // return; |
|
| 381 | - // } |
|
| 382 | - |
|
| 383 | - if ($request->getServerProtocol() === 'https') { |
|
| 384 | - ini_set('session.cookie_secure', 'true'); |
|
| 385 | - } |
|
| 386 | - |
|
| 387 | - // prevents javascript from accessing php session cookies |
|
| 388 | - ini_set('session.cookie_httponly', 'true'); |
|
| 389 | - |
|
| 390 | - // Do not initialize sessions for 'status.php' requests |
|
| 391 | - // Monitoring endpoints can quickly flood session handlers |
|
| 392 | - // and 'status.php' doesn't require sessions anyway |
|
| 393 | - if (str_ends_with($request->getScriptName(), '/status.php')) { |
|
| 394 | - return; |
|
| 395 | - } |
|
| 396 | - |
|
| 397 | - // set the cookie path to the Nextcloud directory |
|
| 398 | - $cookie_path = OC::$WEBROOT ? : '/'; |
|
| 399 | - ini_set('session.cookie_path', $cookie_path); |
|
| 400 | - |
|
| 401 | - // Let the session name be changed in the initSession Hook |
|
| 402 | - $sessionName = OC_Util::getInstanceId(); |
|
| 403 | - |
|
| 404 | - try { |
|
| 405 | - $logger = null; |
|
| 406 | - if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) { |
|
| 407 | - $logger = logger('core'); |
|
| 408 | - } |
|
| 409 | - |
|
| 410 | - // set the session name to the instance id - which is unique |
|
| 411 | - $session = new \OC\Session\Internal( |
|
| 412 | - $sessionName, |
|
| 413 | - $logger, |
|
| 414 | - ); |
|
| 415 | - |
|
| 416 | - $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
| 417 | - $session = $cryptoWrapper->wrapSession($session); |
|
| 418 | - self::$server->setSession($session); |
|
| 419 | - |
|
| 420 | - // if session can't be started break with http 500 error |
|
| 421 | - } catch (Exception $e) { |
|
| 422 | - Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
| 423 | - //show the user a detailed error page |
|
| 424 | - Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500); |
|
| 425 | - die(); |
|
| 426 | - } |
|
| 427 | - |
|
| 428 | - //try to set the session lifetime |
|
| 429 | - $sessionLifeTime = self::getSessionLifeTime(); |
|
| 430 | - |
|
| 431 | - // session timeout |
|
| 432 | - if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
| 433 | - if (isset($_COOKIE[session_name()])) { |
|
| 434 | - setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
| 435 | - } |
|
| 436 | - Server::get(IUserSession::class)->logout(); |
|
| 437 | - } |
|
| 438 | - |
|
| 439 | - if (!self::hasSessionRelaxedExpiry()) { |
|
| 440 | - $session->set('LAST_ACTIVITY', time()); |
|
| 441 | - } |
|
| 442 | - $session->close(); |
|
| 443 | - } |
|
| 444 | - |
|
| 445 | - private static function getSessionLifeTime(): int { |
|
| 446 | - return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
| 447 | - } |
|
| 448 | - |
|
| 449 | - /** |
|
| 450 | - * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
| 451 | - */ |
|
| 452 | - public static function hasSessionRelaxedExpiry(): bool { |
|
| 453 | - return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
| 454 | - } |
|
| 455 | - |
|
| 456 | - /** |
|
| 457 | - * Try to set some values to the required Nextcloud default |
|
| 458 | - */ |
|
| 459 | - public static function setRequiredIniValues(): void { |
|
| 460 | - // Don't display errors and log them |
|
| 461 | - @ini_set('display_errors', '0'); |
|
| 462 | - @ini_set('log_errors', '1'); |
|
| 463 | - |
|
| 464 | - // Try to configure php to enable big file uploads. |
|
| 465 | - // This doesn't work always depending on the webserver and php configuration. |
|
| 466 | - // Let's try to overwrite some defaults if they are smaller than 1 hour |
|
| 467 | - |
|
| 468 | - if (intval(@ini_get('max_execution_time') ?: 0) < 3600) { |
|
| 469 | - @ini_set('max_execution_time', strval(3600)); |
|
| 470 | - } |
|
| 471 | - |
|
| 472 | - if (intval(@ini_get('max_input_time') ?: 0) < 3600) { |
|
| 473 | - @ini_set('max_input_time', strval(3600)); |
|
| 474 | - } |
|
| 475 | - |
|
| 476 | - // Try to set the maximum execution time to the largest time limit we have |
|
| 477 | - if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
| 478 | - @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
| 479 | - } |
|
| 480 | - |
|
| 481 | - @ini_set('default_charset', 'UTF-8'); |
|
| 482 | - @ini_set('gd.jpeg_ignore_warning', '1'); |
|
| 483 | - } |
|
| 484 | - |
|
| 485 | - /** |
|
| 486 | - * Send the same site cookies |
|
| 487 | - */ |
|
| 488 | - private static function sendSameSiteCookies(): void { |
|
| 489 | - $cookieParams = session_get_cookie_params(); |
|
| 490 | - $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
| 491 | - $policies = [ |
|
| 492 | - 'lax', |
|
| 493 | - 'strict', |
|
| 494 | - ]; |
|
| 495 | - |
|
| 496 | - // Append __Host to the cookie if it meets the requirements |
|
| 497 | - $cookiePrefix = ''; |
|
| 498 | - if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
| 499 | - $cookiePrefix = '__Host-'; |
|
| 500 | - } |
|
| 501 | - |
|
| 502 | - foreach ($policies as $policy) { |
|
| 503 | - header( |
|
| 504 | - sprintf( |
|
| 505 | - 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
| 506 | - $cookiePrefix, |
|
| 507 | - $policy, |
|
| 508 | - $cookieParams['path'], |
|
| 509 | - $policy |
|
| 510 | - ), |
|
| 511 | - false |
|
| 512 | - ); |
|
| 513 | - } |
|
| 514 | - } |
|
| 515 | - |
|
| 516 | - /** |
|
| 517 | - * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
| 518 | - * be set in every request if cookies are sent to add a second level of |
|
| 519 | - * defense against CSRF. |
|
| 520 | - * |
|
| 521 | - * If the cookie is not sent this will set the cookie and reload the page. |
|
| 522 | - * We use an additional cookie since we want to protect logout CSRF and |
|
| 523 | - * also we can't directly interfere with PHP's session mechanism. |
|
| 524 | - */ |
|
| 525 | - private static function performSameSiteCookieProtection(\OCP\IConfig $config): void { |
|
| 526 | - $request = Server::get(IRequest::class); |
|
| 527 | - |
|
| 528 | - // Some user agents are notorious and don't really properly follow HTTP |
|
| 529 | - // specifications. For those, have an automated opt-out. Since the protection |
|
| 530 | - // for remote.php is applied in base.php as starting point we need to opt out |
|
| 531 | - // here. |
|
| 532 | - $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
| 533 | - |
|
| 534 | - // Fallback, if csrf.optout is unset |
|
| 535 | - if (!is_array($incompatibleUserAgents)) { |
|
| 536 | - $incompatibleUserAgents = [ |
|
| 537 | - // OS X Finder |
|
| 538 | - '/^WebDAVFS/', |
|
| 539 | - // Windows webdav drive |
|
| 540 | - '/^Microsoft-WebDAV-MiniRedir/', |
|
| 541 | - ]; |
|
| 542 | - } |
|
| 543 | - |
|
| 544 | - if ($request->isUserAgent($incompatibleUserAgents)) { |
|
| 545 | - return; |
|
| 546 | - } |
|
| 547 | - |
|
| 548 | - if (count($_COOKIE) > 0) { |
|
| 549 | - $requestUri = $request->getScriptName(); |
|
| 550 | - $processingScript = explode('/', $requestUri); |
|
| 551 | - $processingScript = $processingScript[count($processingScript) - 1]; |
|
| 552 | - |
|
| 553 | - // index.php routes are handled in the middleware |
|
| 554 | - // and cron.php does not need any authentication at all |
|
| 555 | - if ($processingScript === 'index.php' |
|
| 556 | - || $processingScript === 'cron.php') { |
|
| 557 | - return; |
|
| 558 | - } |
|
| 559 | - |
|
| 560 | - // All other endpoints require the lax and the strict cookie |
|
| 561 | - if (!$request->passesStrictCookieCheck()) { |
|
| 562 | - logger('core')->warning('Request does not pass strict cookie check'); |
|
| 563 | - self::sendSameSiteCookies(); |
|
| 564 | - // Debug mode gets access to the resources without strict cookie |
|
| 565 | - // due to the fact that the SabreDAV browser also lives there. |
|
| 566 | - if (!$config->getSystemValueBool('debug', false)) { |
|
| 567 | - http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED); |
|
| 568 | - header('Content-Type: application/json'); |
|
| 569 | - echo json_encode(['error' => 'Strict Cookie has not been found in request']); |
|
| 570 | - exit(); |
|
| 571 | - } |
|
| 572 | - } |
|
| 573 | - } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
| 574 | - self::sendSameSiteCookies(); |
|
| 575 | - } |
|
| 576 | - } |
|
| 577 | - |
|
| 578 | - public static function init(): void { |
|
| 579 | - // First handle PHP configuration and copy auth headers to the expected |
|
| 580 | - // $_SERVER variable before doing anything Server object related |
|
| 581 | - self::setRequiredIniValues(); |
|
| 582 | - self::handleAuthHeaders(); |
|
| 583 | - |
|
| 584 | - // prevent any XML processing from loading external entities |
|
| 585 | - libxml_set_external_entity_loader(static function () { |
|
| 586 | - return null; |
|
| 587 | - }); |
|
| 588 | - |
|
| 589 | - // Set default timezone before the Server object is booted |
|
| 590 | - if (!date_default_timezone_set('UTC')) { |
|
| 591 | - throw new \RuntimeException('Could not set timezone to UTC'); |
|
| 592 | - } |
|
| 593 | - |
|
| 594 | - // calculate the root directories |
|
| 595 | - OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4)); |
|
| 596 | - |
|
| 597 | - // register autoloader |
|
| 598 | - $loaderStart = microtime(true); |
|
| 599 | - require_once __DIR__ . '/autoloader.php'; |
|
| 600 | - self::$loader = new \OC\Autoloader([ |
|
| 601 | - OC::$SERVERROOT . '/lib/private/legacy', |
|
| 602 | - ]); |
|
| 603 | - if (defined('PHPUNIT_RUN')) { |
|
| 604 | - self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
|
| 605 | - } |
|
| 606 | - spl_autoload_register([self::$loader, 'load']); |
|
| 607 | - $loaderEnd = microtime(true); |
|
| 608 | - |
|
| 609 | - self::$CLI = (php_sapi_name() == 'cli'); |
|
| 610 | - |
|
| 611 | - // Add default composer PSR-4 autoloader, ensure apcu to be disabled |
|
| 612 | - self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
| 613 | - self::$composerAutoloader->setApcuPrefix(null); |
|
| 614 | - |
|
| 615 | - |
|
| 616 | - try { |
|
| 617 | - self::initPaths(); |
|
| 618 | - // setup 3rdparty autoloader |
|
| 619 | - $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php'; |
|
| 620 | - if (!file_exists($vendorAutoLoad)) { |
|
| 621 | - 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".'); |
|
| 622 | - } |
|
| 623 | - require_once $vendorAutoLoad; |
|
| 624 | - } catch (\RuntimeException $e) { |
|
| 625 | - if (!self::$CLI) { |
|
| 626 | - http_response_code(503); |
|
| 627 | - } |
|
| 628 | - // we can't use the template error page here, because this needs the |
|
| 629 | - // DI container which isn't available yet |
|
| 630 | - print($e->getMessage()); |
|
| 631 | - exit(); |
|
| 632 | - } |
|
| 633 | - |
|
| 634 | - // setup the basic server |
|
| 635 | - self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
| 636 | - self::$server->boot(); |
|
| 637 | - |
|
| 638 | - if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) { |
|
| 639 | - \OC\Core\Listener\BeforeMessageLoggedEventListener::setup(); |
|
| 640 | - } |
|
| 641 | - |
|
| 642 | - $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
| 643 | - $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
| 644 | - $eventLogger->start('boot', 'Initialize'); |
|
| 645 | - |
|
| 646 | - // Override php.ini and log everything if we're troubleshooting |
|
| 647 | - if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
| 648 | - error_reporting(E_ALL); |
|
| 649 | - } |
|
| 650 | - |
|
| 651 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
| 652 | - self::registerAutoloaderCache($systemConfig); |
|
| 653 | - |
|
| 654 | - // initialize intl fallback if necessary |
|
| 655 | - OC_Util::isSetLocaleWorking(); |
|
| 656 | - |
|
| 657 | - $config = Server::get(\OCP\IConfig::class); |
|
| 658 | - if (!defined('PHPUNIT_RUN')) { |
|
| 659 | - $errorHandler = new OC\Log\ErrorHandler( |
|
| 660 | - \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
| 661 | - ); |
|
| 662 | - $exceptionHandler = [$errorHandler, 'onException']; |
|
| 663 | - if ($config->getSystemValueBool('debug', false)) { |
|
| 664 | - set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
| 665 | - if (\OC::$CLI) { |
|
| 666 | - $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage']; |
|
| 667 | - } |
|
| 668 | - } else { |
|
| 669 | - set_error_handler([$errorHandler, 'onError']); |
|
| 670 | - } |
|
| 671 | - register_shutdown_function([$errorHandler, 'onShutdown']); |
|
| 672 | - set_exception_handler($exceptionHandler); |
|
| 673 | - } |
|
| 674 | - |
|
| 675 | - /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
| 676 | - $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
| 677 | - $bootstrapCoordinator->runInitialRegistration(); |
|
| 678 | - |
|
| 679 | - $eventLogger->start('init_session', 'Initialize session'); |
|
| 680 | - |
|
| 681 | - // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users |
|
| 682 | - // see https://github.com/nextcloud/server/pull/2619 |
|
| 683 | - if (!function_exists('simplexml_load_file')) { |
|
| 684 | - throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.'); |
|
| 685 | - } |
|
| 686 | - |
|
| 687 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 688 | - if ($systemConfig->getValue('installed', false)) { |
|
| 689 | - $appManager->loadApps(['session']); |
|
| 690 | - } |
|
| 691 | - if (!self::$CLI) { |
|
| 692 | - self::initSession(); |
|
| 693 | - } |
|
| 694 | - $eventLogger->end('init_session'); |
|
| 695 | - self::checkConfig(); |
|
| 696 | - self::checkInstalled($systemConfig); |
|
| 697 | - |
|
| 698 | - OC_Response::addSecurityHeaders(); |
|
| 699 | - |
|
| 700 | - self::performSameSiteCookieProtection($config); |
|
| 701 | - |
|
| 702 | - if (!defined('OC_CONSOLE')) { |
|
| 703 | - $errors = OC_Util::checkServer($systemConfig); |
|
| 704 | - if (count($errors) > 0) { |
|
| 705 | - if (!self::$CLI) { |
|
| 706 | - http_response_code(503); |
|
| 707 | - Util::addStyle('guest'); |
|
| 708 | - try { |
|
| 709 | - Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]); |
|
| 710 | - exit; |
|
| 711 | - } catch (\Exception $e) { |
|
| 712 | - // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
| 713 | - // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
| 714 | - } |
|
| 715 | - } |
|
| 716 | - |
|
| 717 | - // Convert l10n string into regular string for usage in database |
|
| 718 | - $staticErrors = []; |
|
| 719 | - foreach ($errors as $error) { |
|
| 720 | - echo $error['error'] . "\n"; |
|
| 721 | - echo $error['hint'] . "\n\n"; |
|
| 722 | - $staticErrors[] = [ |
|
| 723 | - 'error' => (string)$error['error'], |
|
| 724 | - 'hint' => (string)$error['hint'], |
|
| 725 | - ]; |
|
| 726 | - } |
|
| 727 | - |
|
| 728 | - try { |
|
| 729 | - $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
| 730 | - } catch (\Exception $e) { |
|
| 731 | - echo('Writing to database failed'); |
|
| 732 | - } |
|
| 733 | - exit(1); |
|
| 734 | - } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) { |
|
| 735 | - $config->deleteAppValue('core', 'cronErrors'); |
|
| 736 | - } |
|
| 737 | - } |
|
| 738 | - |
|
| 739 | - // User and Groups |
|
| 740 | - if (!$systemConfig->getValue('installed', false)) { |
|
| 741 | - self::$server->getSession()->set('user_id', ''); |
|
| 742 | - } |
|
| 743 | - |
|
| 744 | - Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 745 | - Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
| 746 | - |
|
| 747 | - // Subscribe to the hook |
|
| 748 | - \OCP\Util::connectHook( |
|
| 749 | - '\OCA\Files_Sharing\API\Server2Server', |
|
| 750 | - 'preLoginNameUsedAsUserName', |
|
| 751 | - '\OC\User\Database', |
|
| 752 | - 'preLoginNameUsedAsUserName' |
|
| 753 | - ); |
|
| 754 | - |
|
| 755 | - //setup extra user backends |
|
| 756 | - if (!\OCP\Util::needUpgrade()) { |
|
| 757 | - OC_User::setupBackends(); |
|
| 758 | - } else { |
|
| 759 | - // Run upgrades in incognito mode |
|
| 760 | - OC_User::setIncognitoMode(true); |
|
| 761 | - } |
|
| 762 | - |
|
| 763 | - self::registerCleanupHooks($systemConfig); |
|
| 764 | - self::registerShareHooks($systemConfig); |
|
| 765 | - self::registerEncryptionWrapperAndHooks(); |
|
| 766 | - self::registerAccountHooks(); |
|
| 767 | - self::registerResourceCollectionHooks(); |
|
| 768 | - self::registerFileReferenceEventListener(); |
|
| 769 | - self::registerRenderReferenceEventListener(); |
|
| 770 | - self::registerAppRestrictionsHooks(); |
|
| 771 | - |
|
| 772 | - // Make sure that the application class is not loaded before the database is setup |
|
| 773 | - if ($systemConfig->getValue('installed', false)) { |
|
| 774 | - $appManager->loadApp('settings'); |
|
| 775 | - /* Build core application to make sure that listeners are registered */ |
|
| 776 | - Server::get(\OC\Core\Application::class); |
|
| 777 | - } |
|
| 778 | - |
|
| 779 | - //make sure temporary files are cleaned up |
|
| 780 | - $tmpManager = Server::get(\OCP\ITempManager::class); |
|
| 781 | - register_shutdown_function([$tmpManager, 'clean']); |
|
| 782 | - $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
| 783 | - register_shutdown_function([$lockProvider, 'releaseAll']); |
|
| 784 | - |
|
| 785 | - // Check whether the sample configuration has been copied |
|
| 786 | - if ($systemConfig->getValue('copied_sample_config', false)) { |
|
| 787 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
| 788 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
| 789 | - $l->t('Sample configuration detected'), |
|
| 790 | - $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'), |
|
| 791 | - 503 |
|
| 792 | - ); |
|
| 793 | - return; |
|
| 794 | - } |
|
| 795 | - |
|
| 796 | - $request = Server::get(IRequest::class); |
|
| 797 | - $host = $request->getInsecureServerHost(); |
|
| 798 | - /** |
|
| 799 | - * if the host passed in headers isn't trusted |
|
| 800 | - * FIXME: Should not be in here at all :see_no_evil: |
|
| 801 | - */ |
|
| 802 | - if (!OC::$CLI |
|
| 803 | - && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
| 804 | - && $config->getSystemValueBool('installed', false) |
|
| 805 | - ) { |
|
| 806 | - // Allow access to CSS resources |
|
| 807 | - $isScssRequest = false; |
|
| 808 | - if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
| 809 | - $isScssRequest = true; |
|
| 810 | - } |
|
| 811 | - |
|
| 812 | - if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
| 813 | - http_response_code(400); |
|
| 814 | - header('Content-Type: application/json'); |
|
| 815 | - echo '{"error": "Trusted domain error.", "code": 15}'; |
|
| 816 | - exit(); |
|
| 817 | - } |
|
| 818 | - |
|
| 819 | - if (!$isScssRequest) { |
|
| 820 | - http_response_code(400); |
|
| 821 | - Server::get(LoggerInterface::class)->info( |
|
| 822 | - 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
| 823 | - [ |
|
| 824 | - 'app' => 'core', |
|
| 825 | - 'remoteAddress' => $request->getRemoteAddress(), |
|
| 826 | - 'host' => $host, |
|
| 827 | - ] |
|
| 828 | - ); |
|
| 829 | - |
|
| 830 | - $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest'); |
|
| 831 | - $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
| 832 | - $tmpl->printPage(); |
|
| 833 | - |
|
| 834 | - exit(); |
|
| 835 | - } |
|
| 836 | - } |
|
| 837 | - $eventLogger->end('boot'); |
|
| 838 | - $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
| 839 | - $eventLogger->start('runtime', 'Runtime'); |
|
| 840 | - $eventLogger->start('request', 'Full request after boot'); |
|
| 841 | - register_shutdown_function(function () use ($eventLogger) { |
|
| 842 | - $eventLogger->end('request'); |
|
| 843 | - }); |
|
| 844 | - |
|
| 845 | - register_shutdown_function(function () { |
|
| 846 | - $memoryPeak = memory_get_peak_usage(); |
|
| 847 | - $logLevel = match (true) { |
|
| 848 | - $memoryPeak > 500_000_000 => ILogger::FATAL, |
|
| 849 | - $memoryPeak > 400_000_000 => ILogger::ERROR, |
|
| 850 | - $memoryPeak > 300_000_000 => ILogger::WARN, |
|
| 851 | - default => null, |
|
| 852 | - }; |
|
| 853 | - if ($logLevel !== null) { |
|
| 854 | - $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak); |
|
| 855 | - $logger = Server::get(LoggerInterface::class); |
|
| 856 | - $logger->log($logLevel, $message, ['app' => 'core']); |
|
| 857 | - } |
|
| 858 | - }); |
|
| 859 | - } |
|
| 860 | - |
|
| 861 | - /** |
|
| 862 | - * register hooks for the cleanup of cache and bruteforce protection |
|
| 863 | - */ |
|
| 864 | - public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
| 865 | - //don't try to do this before we are properly setup |
|
| 866 | - if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
| 867 | - // NOTE: This will be replaced to use OCP |
|
| 868 | - $userSession = Server::get(\OC\User\Session::class); |
|
| 869 | - $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
| 870 | - if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
| 871 | - // reset brute force delay for this IP address and username |
|
| 872 | - $uid = $userSession->getUser()->getUID(); |
|
| 873 | - $request = Server::get(IRequest::class); |
|
| 874 | - $throttler = Server::get(IThrottler::class); |
|
| 875 | - $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
| 876 | - } |
|
| 877 | - |
|
| 878 | - try { |
|
| 879 | - $cache = new \OC\Cache\File(); |
|
| 880 | - $cache->gc(); |
|
| 881 | - } catch (\OC\ServerNotAvailableException $e) { |
|
| 882 | - // not a GC exception, pass it on |
|
| 883 | - throw $e; |
|
| 884 | - } catch (\OC\ForbiddenException $e) { |
|
| 885 | - // filesystem blocked for this request, ignore |
|
| 886 | - } catch (\Exception $e) { |
|
| 887 | - // a GC exception should not prevent users from using OC, |
|
| 888 | - // so log the exception |
|
| 889 | - Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
| 890 | - 'app' => 'core', |
|
| 891 | - 'exception' => $e, |
|
| 892 | - ]); |
|
| 893 | - } |
|
| 894 | - }); |
|
| 895 | - } |
|
| 896 | - } |
|
| 897 | - |
|
| 898 | - private static function registerEncryptionWrapperAndHooks(): void { |
|
| 899 | - $manager = Server::get(\OCP\Encryption\IManager::class); |
|
| 900 | - \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); |
|
| 901 | - |
|
| 902 | - $enabled = $manager->isEnabled(); |
|
| 903 | - if ($enabled) { |
|
| 904 | - \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared'); |
|
| 905 | - \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared'); |
|
| 906 | - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename'); |
|
| 907 | - \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore'); |
|
| 908 | - } |
|
| 909 | - } |
|
| 910 | - |
|
| 911 | - private static function registerAccountHooks(): void { |
|
| 912 | - /** @var IEventDispatcher $dispatcher */ |
|
| 913 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
| 914 | - $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
| 915 | - } |
|
| 916 | - |
|
| 917 | - private static function registerAppRestrictionsHooks(): void { |
|
| 918 | - /** @var \OC\Group\Manager $groupManager */ |
|
| 919 | - $groupManager = Server::get(\OCP\IGroupManager::class); |
|
| 920 | - $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
| 921 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 922 | - $apps = $appManager->getEnabledAppsForGroup($group); |
|
| 923 | - foreach ($apps as $appId) { |
|
| 924 | - $restrictions = $appManager->getAppRestriction($appId); |
|
| 925 | - if (empty($restrictions)) { |
|
| 926 | - continue; |
|
| 927 | - } |
|
| 928 | - $key = array_search($group->getGID(), $restrictions); |
|
| 929 | - unset($restrictions[$key]); |
|
| 930 | - $restrictions = array_values($restrictions); |
|
| 931 | - if (empty($restrictions)) { |
|
| 932 | - $appManager->disableApp($appId); |
|
| 933 | - } else { |
|
| 934 | - $appManager->enableAppForGroups($appId, $restrictions); |
|
| 935 | - } |
|
| 936 | - } |
|
| 937 | - }); |
|
| 938 | - } |
|
| 939 | - |
|
| 940 | - private static function registerResourceCollectionHooks(): void { |
|
| 941 | - \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class)); |
|
| 942 | - } |
|
| 943 | - |
|
| 944 | - private static function registerFileReferenceEventListener(): void { |
|
| 945 | - \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
| 946 | - } |
|
| 947 | - |
|
| 948 | - private static function registerRenderReferenceEventListener() { |
|
| 949 | - \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
| 950 | - } |
|
| 951 | - |
|
| 952 | - /** |
|
| 953 | - * register hooks for sharing |
|
| 954 | - */ |
|
| 955 | - public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
| 956 | - if ($systemConfig->getValue('installed')) { |
|
| 957 | - |
|
| 958 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
| 959 | - $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class); |
|
| 960 | - $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class); |
|
| 961 | - $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class); |
|
| 962 | - } |
|
| 963 | - } |
|
| 964 | - |
|
| 965 | - protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void { |
|
| 966 | - // The class loader takes an optional low-latency cache, which MUST be |
|
| 967 | - // namespaced. The instanceid is used for namespacing, but might be |
|
| 968 | - // unavailable at this point. Furthermore, it might not be possible to |
|
| 969 | - // generate an instanceid via \OC_Util::getInstanceId() because the |
|
| 970 | - // config file may not be writable. As such, we only register a class |
|
| 971 | - // loader cache if instanceid is available without trying to create one. |
|
| 972 | - $instanceId = $systemConfig->getValue('instanceid', null); |
|
| 973 | - if ($instanceId) { |
|
| 974 | - try { |
|
| 975 | - $memcacheFactory = Server::get(\OCP\ICacheFactory::class); |
|
| 976 | - self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); |
|
| 977 | - } catch (\Exception $ex) { |
|
| 978 | - } |
|
| 979 | - } |
|
| 980 | - } |
|
| 981 | - |
|
| 982 | - /** |
|
| 983 | - * Handle the request |
|
| 984 | - */ |
|
| 985 | - public static function handleRequest(): void { |
|
| 986 | - Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
| 987 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
| 988 | - |
|
| 989 | - // Check if Nextcloud is installed or in maintenance (update) mode |
|
| 990 | - if (!$systemConfig->getValue('installed', false)) { |
|
| 991 | - \OC::$server->getSession()->clear(); |
|
| 992 | - $controller = Server::get(\OC\Core\Controller\SetupController::class); |
|
| 993 | - $controller->run($_POST); |
|
| 994 | - exit(); |
|
| 995 | - } |
|
| 996 | - |
|
| 997 | - $request = Server::get(IRequest::class); |
|
| 998 | - $requestPath = $request->getRawPathInfo(); |
|
| 999 | - if ($requestPath === '/heartbeat') { |
|
| 1000 | - return; |
|
| 1001 | - } |
|
| 1002 | - if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
| 1003 | - self::checkMaintenanceMode($systemConfig); |
|
| 1004 | - |
|
| 1005 | - if (\OCP\Util::needUpgrade()) { |
|
| 1006 | - if (function_exists('opcache_reset')) { |
|
| 1007 | - opcache_reset(); |
|
| 1008 | - } |
|
| 1009 | - if (!((bool)$systemConfig->getValue('maintenance', false))) { |
|
| 1010 | - self::printUpgradePage($systemConfig); |
|
| 1011 | - exit(); |
|
| 1012 | - } |
|
| 1013 | - } |
|
| 1014 | - } |
|
| 1015 | - |
|
| 1016 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 1017 | - |
|
| 1018 | - // Always load authentication apps |
|
| 1019 | - $appManager->loadApps(['authentication']); |
|
| 1020 | - $appManager->loadApps(['extended_authentication']); |
|
| 1021 | - |
|
| 1022 | - // Load minimum set of apps |
|
| 1023 | - if (!\OCP\Util::needUpgrade() |
|
| 1024 | - && !((bool)$systemConfig->getValue('maintenance', false))) { |
|
| 1025 | - // For logged-in users: Load everything |
|
| 1026 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
| 1027 | - $appManager->loadApps(); |
|
| 1028 | - } else { |
|
| 1029 | - // For guests: Load only filesystem and logging |
|
| 1030 | - $appManager->loadApps(['filesystem', 'logging']); |
|
| 1031 | - |
|
| 1032 | - // Don't try to login when a client is trying to get a OAuth token. |
|
| 1033 | - // OAuth needs to support basic auth too, so the login is not valid |
|
| 1034 | - // inside Nextcloud and the Login exception would ruin it. |
|
| 1035 | - if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
| 1036 | - self::handleLogin($request); |
|
| 1037 | - } |
|
| 1038 | - } |
|
| 1039 | - } |
|
| 1040 | - |
|
| 1041 | - if (!self::$CLI) { |
|
| 1042 | - try { |
|
| 1043 | - if (!\OCP\Util::needUpgrade()) { |
|
| 1044 | - $appManager->loadApps(['filesystem', 'logging']); |
|
| 1045 | - $appManager->loadApps(); |
|
| 1046 | - } |
|
| 1047 | - Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
| 1048 | - return; |
|
| 1049 | - } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
| 1050 | - //header('HTTP/1.0 404 Not Found'); |
|
| 1051 | - } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
| 1052 | - http_response_code(405); |
|
| 1053 | - return; |
|
| 1054 | - } |
|
| 1055 | - } |
|
| 1056 | - |
|
| 1057 | - // Handle WebDAV |
|
| 1058 | - if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
| 1059 | - // not allowed any more to prevent people |
|
| 1060 | - // mounting this root directly. |
|
| 1061 | - // Users need to mount remote.php/webdav instead. |
|
| 1062 | - http_response_code(405); |
|
| 1063 | - return; |
|
| 1064 | - } |
|
| 1065 | - |
|
| 1066 | - // Handle requests for JSON or XML |
|
| 1067 | - $acceptHeader = $request->getHeader('Accept'); |
|
| 1068 | - if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
| 1069 | - http_response_code(404); |
|
| 1070 | - return; |
|
| 1071 | - } |
|
| 1072 | - |
|
| 1073 | - // Handle resources that can't be found |
|
| 1074 | - // This prevents browsers from redirecting to the default page and then |
|
| 1075 | - // attempting to parse HTML as CSS and similar. |
|
| 1076 | - $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
| 1077 | - if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
| 1078 | - http_response_code(404); |
|
| 1079 | - return; |
|
| 1080 | - } |
|
| 1081 | - |
|
| 1082 | - // Redirect to the default app or login only as an entry point |
|
| 1083 | - if ($requestPath === '') { |
|
| 1084 | - // Someone is logged in |
|
| 1085 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
| 1086 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
| 1087 | - } else { |
|
| 1088 | - // Not handled and not logged in |
|
| 1089 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
| 1090 | - } |
|
| 1091 | - return; |
|
| 1092 | - } |
|
| 1093 | - |
|
| 1094 | - try { |
|
| 1095 | - Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
| 1096 | - } catch (\Exception $e) { |
|
| 1097 | - if (!$e instanceof MethodNotAllowedException) { |
|
| 1098 | - logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
| 1099 | - } |
|
| 1100 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
| 1101 | - Server::get(ITemplateManager::class)->printErrorPage( |
|
| 1102 | - '404', |
|
| 1103 | - $l->t('The page could not be found on the server.'), |
|
| 1104 | - 404 |
|
| 1105 | - ); |
|
| 1106 | - } |
|
| 1107 | - } |
|
| 1108 | - |
|
| 1109 | - /** |
|
| 1110 | - * Check login: apache auth, auth token, basic auth |
|
| 1111 | - */ |
|
| 1112 | - public static function handleLogin(OCP\IRequest $request): bool { |
|
| 1113 | - if ($request->getHeader('X-Nextcloud-Federation')) { |
|
| 1114 | - return false; |
|
| 1115 | - } |
|
| 1116 | - $userSession = Server::get(\OC\User\Session::class); |
|
| 1117 | - if (OC_User::handleApacheAuth()) { |
|
| 1118 | - return true; |
|
| 1119 | - } |
|
| 1120 | - if (self::tryAppAPILogin($request)) { |
|
| 1121 | - return true; |
|
| 1122 | - } |
|
| 1123 | - if ($userSession->tryTokenLogin($request)) { |
|
| 1124 | - return true; |
|
| 1125 | - } |
|
| 1126 | - if (isset($_COOKIE['nc_username']) |
|
| 1127 | - && isset($_COOKIE['nc_token']) |
|
| 1128 | - && isset($_COOKIE['nc_session_id']) |
|
| 1129 | - && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
| 1130 | - return true; |
|
| 1131 | - } |
|
| 1132 | - if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) { |
|
| 1133 | - return true; |
|
| 1134 | - } |
|
| 1135 | - return false; |
|
| 1136 | - } |
|
| 1137 | - |
|
| 1138 | - protected static function handleAuthHeaders(): void { |
|
| 1139 | - //copy http auth headers for apache+php-fcgid work around |
|
| 1140 | - if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
| 1141 | - $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
| 1142 | - } |
|
| 1143 | - |
|
| 1144 | - // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
| 1145 | - $vars = [ |
|
| 1146 | - 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
| 1147 | - 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
| 1148 | - ]; |
|
| 1149 | - foreach ($vars as $var) { |
|
| 1150 | - if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
| 1151 | - $credentials = explode(':', base64_decode($matches[1]), 2); |
|
| 1152 | - if (count($credentials) === 2) { |
|
| 1153 | - $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
| 1154 | - $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
| 1155 | - break; |
|
| 1156 | - } |
|
| 1157 | - } |
|
| 1158 | - } |
|
| 1159 | - } |
|
| 1160 | - |
|
| 1161 | - protected static function tryAppAPILogin(OCP\IRequest $request): bool { |
|
| 1162 | - if (!$request->getHeader('AUTHORIZATION-APP-API')) { |
|
| 1163 | - return false; |
|
| 1164 | - } |
|
| 1165 | - $appManager = Server::get(OCP\App\IAppManager::class); |
|
| 1166 | - if (!$appManager->isEnabledForAnyone('app_api')) { |
|
| 1167 | - return false; |
|
| 1168 | - } |
|
| 1169 | - try { |
|
| 1170 | - $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class); |
|
| 1171 | - return $appAPIService->validateExAppRequestToNC($request); |
|
| 1172 | - } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { |
|
| 1173 | - return false; |
|
| 1174 | - } |
|
| 1175 | - } |
|
| 40 | + /** |
|
| 41 | + * Associative array for autoloading. classname => filename |
|
| 42 | + */ |
|
| 43 | + public static array $CLASSPATH = []; |
|
| 44 | + /** |
|
| 45 | + * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
| 46 | + */ |
|
| 47 | + public static string $SERVERROOT = ''; |
|
| 48 | + /** |
|
| 49 | + * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
| 50 | + */ |
|
| 51 | + private static string $SUBURI = ''; |
|
| 52 | + /** |
|
| 53 | + * the Nextcloud root path for http requests (e.g. /nextcloud) |
|
| 54 | + */ |
|
| 55 | + public static string $WEBROOT = ''; |
|
| 56 | + /** |
|
| 57 | + * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
| 58 | + * web path in 'url' |
|
| 59 | + */ |
|
| 60 | + public static array $APPSROOTS = []; |
|
| 61 | + |
|
| 62 | + public static string $configDir; |
|
| 63 | + |
|
| 64 | + /** |
|
| 65 | + * requested app |
|
| 66 | + */ |
|
| 67 | + public static string $REQUESTEDAPP = ''; |
|
| 68 | + |
|
| 69 | + /** |
|
| 70 | + * check if Nextcloud runs in cli mode |
|
| 71 | + */ |
|
| 72 | + public static bool $CLI = false; |
|
| 73 | + |
|
| 74 | + public static \OC\Autoloader $loader; |
|
| 75 | + |
|
| 76 | + public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
| 77 | + |
|
| 78 | + public static \OC\Server $server; |
|
| 79 | + |
|
| 80 | + private static \OC\Config $config; |
|
| 81 | + |
|
| 82 | + /** |
|
| 83 | + * @throws \RuntimeException when the 3rdparty directory is missing or |
|
| 84 | + * the app path list is empty or contains an invalid path |
|
| 85 | + */ |
|
| 86 | + public static function initPaths(): void { |
|
| 87 | + if (defined('PHPUNIT_CONFIG_DIR')) { |
|
| 88 | + self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
| 89 | + } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
| 90 | + self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
| 91 | + } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
| 92 | + self::$configDir = rtrim($dir, '/') . '/'; |
|
| 93 | + } else { |
|
| 94 | + self::$configDir = OC::$SERVERROOT . '/config/'; |
|
| 95 | + } |
|
| 96 | + self::$config = new \OC\Config(self::$configDir); |
|
| 97 | + |
|
| 98 | + OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT))); |
|
| 99 | + /** |
|
| 100 | + * FIXME: The following lines are required because we can't yet instantiate |
|
| 101 | + * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
| 102 | + */ |
|
| 103 | + $params = [ |
|
| 104 | + 'server' => [ |
|
| 105 | + 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
| 106 | + 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
| 107 | + ], |
|
| 108 | + ]; |
|
| 109 | + if (isset($_SERVER['REMOTE_ADDR'])) { |
|
| 110 | + $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; |
|
| 111 | + } |
|
| 112 | + $fakeRequest = new \OC\AppFramework\Http\Request( |
|
| 113 | + $params, |
|
| 114 | + new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
| 115 | + new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
| 116 | + ); |
|
| 117 | + $scriptName = $fakeRequest->getScriptName(); |
|
| 118 | + if (substr($scriptName, -1) == '/') { |
|
| 119 | + $scriptName .= 'index.php'; |
|
| 120 | + //make sure suburi follows the same rules as scriptName |
|
| 121 | + if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
| 122 | + if (substr(OC::$SUBURI, -1) != '/') { |
|
| 123 | + OC::$SUBURI = OC::$SUBURI . '/'; |
|
| 124 | + } |
|
| 125 | + OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
| 126 | + } |
|
| 127 | + } |
|
| 128 | + |
|
| 129 | + |
|
| 130 | + if (OC::$CLI) { |
|
| 131 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
| 132 | + } else { |
|
| 133 | + if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
| 134 | + OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
| 135 | + |
|
| 136 | + if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
| 137 | + OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
| 138 | + } |
|
| 139 | + } else { |
|
| 140 | + // The scriptName is not ending with OC::$SUBURI |
|
| 141 | + // This most likely means that we are calling from CLI. |
|
| 142 | + // However some cron jobs still need to generate |
|
| 143 | + // a web URL, so we use overwritewebroot as a fallback. |
|
| 144 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
| 145 | + } |
|
| 146 | + |
|
| 147 | + // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
| 148 | + // slash which is required by URL generation. |
|
| 149 | + if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
|
| 150 | + substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
| 151 | + header('Location: ' . \OC::$WEBROOT . '/'); |
|
| 152 | + exit(); |
|
| 153 | + } |
|
| 154 | + } |
|
| 155 | + |
|
| 156 | + // search the apps folder |
|
| 157 | + $config_paths = self::$config->getValue('apps_paths', []); |
|
| 158 | + if (!empty($config_paths)) { |
|
| 159 | + foreach ($config_paths as $paths) { |
|
| 160 | + if (isset($paths['url']) && isset($paths['path'])) { |
|
| 161 | + $paths['url'] = rtrim($paths['url'], '/'); |
|
| 162 | + $paths['path'] = rtrim($paths['path'], '/'); |
|
| 163 | + OC::$APPSROOTS[] = $paths; |
|
| 164 | + } |
|
| 165 | + } |
|
| 166 | + } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
| 167 | + OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
| 168 | + } |
|
| 169 | + |
|
| 170 | + if (empty(OC::$APPSROOTS)) { |
|
| 171 | + throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
| 172 | + . '. You can also configure the location in the config.php file.'); |
|
| 173 | + } |
|
| 174 | + $paths = []; |
|
| 175 | + foreach (OC::$APPSROOTS as $path) { |
|
| 176 | + $paths[] = $path['path']; |
|
| 177 | + if (!is_dir($path['path'])) { |
|
| 178 | + throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
| 179 | + . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
| 180 | + } |
|
| 181 | + } |
|
| 182 | + |
|
| 183 | + // set the right include path |
|
| 184 | + set_include_path( |
|
| 185 | + implode(PATH_SEPARATOR, $paths) |
|
| 186 | + ); |
|
| 187 | + } |
|
| 188 | + |
|
| 189 | + public static function checkConfig(): void { |
|
| 190 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
| 191 | + |
|
| 192 | + // Create config if it does not already exist |
|
| 193 | + $configFilePath = self::$configDir . '/config.php'; |
|
| 194 | + if (!file_exists($configFilePath)) { |
|
| 195 | + @touch($configFilePath); |
|
| 196 | + } |
|
| 197 | + |
|
| 198 | + // Check if config is writable |
|
| 199 | + $configFileWritable = is_writable($configFilePath); |
|
| 200 | + if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
|
| 201 | + || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
| 202 | + $urlGenerator = Server::get(IURLGenerator::class); |
|
| 203 | + |
|
| 204 | + if (self::$CLI) { |
|
| 205 | + echo $l->t('Cannot write into "config" directory!') . "\n"; |
|
| 206 | + echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n"; |
|
| 207 | + echo "\n"; |
|
| 208 | + 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"; |
|
| 209 | + echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n"; |
|
| 210 | + exit; |
|
| 211 | + } else { |
|
| 212 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
| 213 | + $l->t('Cannot write into "config" directory!'), |
|
| 214 | + $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
| 215 | + . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
| 216 | + . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
| 217 | + 503 |
|
| 218 | + ); |
|
| 219 | + } |
|
| 220 | + } |
|
| 221 | + } |
|
| 222 | + |
|
| 223 | + public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
| 224 | + if (defined('OC_CONSOLE')) { |
|
| 225 | + return; |
|
| 226 | + } |
|
| 227 | + // Redirect to installer if not installed |
|
| 228 | + if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
| 229 | + if (OC::$CLI) { |
|
| 230 | + throw new Exception('Not installed'); |
|
| 231 | + } else { |
|
| 232 | + $url = OC::$WEBROOT . '/index.php'; |
|
| 233 | + header('Location: ' . $url); |
|
| 234 | + } |
|
| 235 | + exit(); |
|
| 236 | + } |
|
| 237 | + } |
|
| 238 | + |
|
| 239 | + public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
| 240 | + // Allow ajax update script to execute without being stopped |
|
| 241 | + if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
| 242 | + // send http status 503 |
|
| 243 | + http_response_code(503); |
|
| 244 | + header('X-Nextcloud-Maintenance-Mode: 1'); |
|
| 245 | + header('Retry-After: 120'); |
|
| 246 | + |
|
| 247 | + // render error page |
|
| 248 | + $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest'); |
|
| 249 | + \OCP\Util::addScript('core', 'maintenance'); |
|
| 250 | + \OCP\Util::addStyle('core', 'guest'); |
|
| 251 | + $template->printPage(); |
|
| 252 | + die(); |
|
| 253 | + } |
|
| 254 | + } |
|
| 255 | + |
|
| 256 | + /** |
|
| 257 | + * Prints the upgrade page |
|
| 258 | + */ |
|
| 259 | + private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
| 260 | + $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', ''); |
|
| 261 | + $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
| 262 | + $tooBig = false; |
|
| 263 | + if (!$disableWebUpdater) { |
|
| 264 | + $apps = Server::get(\OCP\App\IAppManager::class); |
|
| 265 | + if ($apps->isEnabledForAnyone('user_ldap')) { |
|
| 266 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
| 267 | + |
|
| 268 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
| 269 | + ->from('ldap_user_mapping') |
|
| 270 | + ->executeQuery(); |
|
| 271 | + $row = $result->fetch(); |
|
| 272 | + $result->closeCursor(); |
|
| 273 | + |
|
| 274 | + $tooBig = ($row['user_count'] > 50); |
|
| 275 | + } |
|
| 276 | + if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) { |
|
| 277 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
| 278 | + |
|
| 279 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
| 280 | + ->from('user_saml_users') |
|
| 281 | + ->executeQuery(); |
|
| 282 | + $row = $result->fetch(); |
|
| 283 | + $result->closeCursor(); |
|
| 284 | + |
|
| 285 | + $tooBig = ($row['user_count'] > 50); |
|
| 286 | + } |
|
| 287 | + if (!$tooBig) { |
|
| 288 | + // count users |
|
| 289 | + $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51); |
|
| 290 | + $tooBig = ($totalUsers > 50); |
|
| 291 | + } |
|
| 292 | + } |
|
| 293 | + $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) && |
|
| 294 | + $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
| 295 | + |
|
| 296 | + if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
| 297 | + // send http status 503 |
|
| 298 | + http_response_code(503); |
|
| 299 | + header('Retry-After: 120'); |
|
| 300 | + |
|
| 301 | + $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class); |
|
| 302 | + |
|
| 303 | + // render error page |
|
| 304 | + $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest'); |
|
| 305 | + $template->assign('productName', 'nextcloud'); // for now |
|
| 306 | + $template->assign('version', $serverVersion->getVersionString()); |
|
| 307 | + $template->assign('tooBig', $tooBig); |
|
| 308 | + $template->assign('cliUpgradeLink', $cliUpgradeLink); |
|
| 309 | + |
|
| 310 | + $template->printPage(); |
|
| 311 | + die(); |
|
| 312 | + } |
|
| 313 | + |
|
| 314 | + // check whether this is a core update or apps update |
|
| 315 | + $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
| 316 | + $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
| 317 | + |
|
| 318 | + // if not a core upgrade, then it's apps upgrade |
|
| 319 | + $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
| 320 | + |
|
| 321 | + $oldTheme = $systemConfig->getValue('theme'); |
|
| 322 | + $systemConfig->setValue('theme', ''); |
|
| 323 | + \OCP\Util::addScript('core', 'common'); |
|
| 324 | + \OCP\Util::addScript('core', 'main'); |
|
| 325 | + \OCP\Util::addTranslations('core'); |
|
| 326 | + \OCP\Util::addScript('core', 'update'); |
|
| 327 | + |
|
| 328 | + /** @var \OC\App\AppManager $appManager */ |
|
| 329 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 330 | + |
|
| 331 | + $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest'); |
|
| 332 | + $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString()); |
|
| 333 | + $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
| 334 | + |
|
| 335 | + // get third party apps |
|
| 336 | + $ocVersion = \OCP\Util::getVersion(); |
|
| 337 | + $ocVersion = implode('.', $ocVersion); |
|
| 338 | + $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
| 339 | + $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []); |
|
| 340 | + $incompatibleShippedApps = []; |
|
| 341 | + $incompatibleDisabledApps = []; |
|
| 342 | + foreach ($incompatibleApps as $appInfo) { |
|
| 343 | + if ($appManager->isShipped($appInfo['id'])) { |
|
| 344 | + $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
| 345 | + } |
|
| 346 | + if (!in_array($appInfo['id'], $incompatibleOverwrites)) { |
|
| 347 | + $incompatibleDisabledApps[] = $appInfo; |
|
| 348 | + } |
|
| 349 | + } |
|
| 350 | + |
|
| 351 | + if (!empty($incompatibleShippedApps)) { |
|
| 352 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
| 353 | + $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)]); |
|
| 354 | + 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); |
|
| 355 | + } |
|
| 356 | + |
|
| 357 | + $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
| 358 | + $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps); |
|
| 359 | + try { |
|
| 360 | + $defaults = new \OC_Defaults(); |
|
| 361 | + $tmpl->assign('productName', $defaults->getName()); |
|
| 362 | + } catch (Throwable $error) { |
|
| 363 | + $tmpl->assign('productName', 'Nextcloud'); |
|
| 364 | + } |
|
| 365 | + $tmpl->assign('oldTheme', $oldTheme); |
|
| 366 | + $tmpl->printPage(); |
|
| 367 | + } |
|
| 368 | + |
|
| 369 | + public static function initSession(): void { |
|
| 370 | + $request = Server::get(IRequest::class); |
|
| 371 | + |
|
| 372 | + // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies |
|
| 373 | + // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments |
|
| 374 | + // TODO: for further information. |
|
| 375 | + // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
| 376 | + // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
| 377 | + // setcookie('cookie_test', 'test', time() + 3600); |
|
| 378 | + // // Do not initialize the session if a request is authenticated directly |
|
| 379 | + // // unless there is a session cookie already sent along |
|
| 380 | + // return; |
|
| 381 | + // } |
|
| 382 | + |
|
| 383 | + if ($request->getServerProtocol() === 'https') { |
|
| 384 | + ini_set('session.cookie_secure', 'true'); |
|
| 385 | + } |
|
| 386 | + |
|
| 387 | + // prevents javascript from accessing php session cookies |
|
| 388 | + ini_set('session.cookie_httponly', 'true'); |
|
| 389 | + |
|
| 390 | + // Do not initialize sessions for 'status.php' requests |
|
| 391 | + // Monitoring endpoints can quickly flood session handlers |
|
| 392 | + // and 'status.php' doesn't require sessions anyway |
|
| 393 | + if (str_ends_with($request->getScriptName(), '/status.php')) { |
|
| 394 | + return; |
|
| 395 | + } |
|
| 396 | + |
|
| 397 | + // set the cookie path to the Nextcloud directory |
|
| 398 | + $cookie_path = OC::$WEBROOT ? : '/'; |
|
| 399 | + ini_set('session.cookie_path', $cookie_path); |
|
| 400 | + |
|
| 401 | + // Let the session name be changed in the initSession Hook |
|
| 402 | + $sessionName = OC_Util::getInstanceId(); |
|
| 403 | + |
|
| 404 | + try { |
|
| 405 | + $logger = null; |
|
| 406 | + if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) { |
|
| 407 | + $logger = logger('core'); |
|
| 408 | + } |
|
| 409 | + |
|
| 410 | + // set the session name to the instance id - which is unique |
|
| 411 | + $session = new \OC\Session\Internal( |
|
| 412 | + $sessionName, |
|
| 413 | + $logger, |
|
| 414 | + ); |
|
| 415 | + |
|
| 416 | + $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
| 417 | + $session = $cryptoWrapper->wrapSession($session); |
|
| 418 | + self::$server->setSession($session); |
|
| 419 | + |
|
| 420 | + // if session can't be started break with http 500 error |
|
| 421 | + } catch (Exception $e) { |
|
| 422 | + Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
| 423 | + //show the user a detailed error page |
|
| 424 | + Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500); |
|
| 425 | + die(); |
|
| 426 | + } |
|
| 427 | + |
|
| 428 | + //try to set the session lifetime |
|
| 429 | + $sessionLifeTime = self::getSessionLifeTime(); |
|
| 430 | + |
|
| 431 | + // session timeout |
|
| 432 | + if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
| 433 | + if (isset($_COOKIE[session_name()])) { |
|
| 434 | + setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
| 435 | + } |
|
| 436 | + Server::get(IUserSession::class)->logout(); |
|
| 437 | + } |
|
| 438 | + |
|
| 439 | + if (!self::hasSessionRelaxedExpiry()) { |
|
| 440 | + $session->set('LAST_ACTIVITY', time()); |
|
| 441 | + } |
|
| 442 | + $session->close(); |
|
| 443 | + } |
|
| 444 | + |
|
| 445 | + private static function getSessionLifeTime(): int { |
|
| 446 | + return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
| 447 | + } |
|
| 448 | + |
|
| 449 | + /** |
|
| 450 | + * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
| 451 | + */ |
|
| 452 | + public static function hasSessionRelaxedExpiry(): bool { |
|
| 453 | + return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
| 454 | + } |
|
| 455 | + |
|
| 456 | + /** |
|
| 457 | + * Try to set some values to the required Nextcloud default |
|
| 458 | + */ |
|
| 459 | + public static function setRequiredIniValues(): void { |
|
| 460 | + // Don't display errors and log them |
|
| 461 | + @ini_set('display_errors', '0'); |
|
| 462 | + @ini_set('log_errors', '1'); |
|
| 463 | + |
|
| 464 | + // Try to configure php to enable big file uploads. |
|
| 465 | + // This doesn't work always depending on the webserver and php configuration. |
|
| 466 | + // Let's try to overwrite some defaults if they are smaller than 1 hour |
|
| 467 | + |
|
| 468 | + if (intval(@ini_get('max_execution_time') ?: 0) < 3600) { |
|
| 469 | + @ini_set('max_execution_time', strval(3600)); |
|
| 470 | + } |
|
| 471 | + |
|
| 472 | + if (intval(@ini_get('max_input_time') ?: 0) < 3600) { |
|
| 473 | + @ini_set('max_input_time', strval(3600)); |
|
| 474 | + } |
|
| 475 | + |
|
| 476 | + // Try to set the maximum execution time to the largest time limit we have |
|
| 477 | + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
| 478 | + @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
| 479 | + } |
|
| 480 | + |
|
| 481 | + @ini_set('default_charset', 'UTF-8'); |
|
| 482 | + @ini_set('gd.jpeg_ignore_warning', '1'); |
|
| 483 | + } |
|
| 484 | + |
|
| 485 | + /** |
|
| 486 | + * Send the same site cookies |
|
| 487 | + */ |
|
| 488 | + private static function sendSameSiteCookies(): void { |
|
| 489 | + $cookieParams = session_get_cookie_params(); |
|
| 490 | + $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
| 491 | + $policies = [ |
|
| 492 | + 'lax', |
|
| 493 | + 'strict', |
|
| 494 | + ]; |
|
| 495 | + |
|
| 496 | + // Append __Host to the cookie if it meets the requirements |
|
| 497 | + $cookiePrefix = ''; |
|
| 498 | + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
| 499 | + $cookiePrefix = '__Host-'; |
|
| 500 | + } |
|
| 501 | + |
|
| 502 | + foreach ($policies as $policy) { |
|
| 503 | + header( |
|
| 504 | + sprintf( |
|
| 505 | + 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
| 506 | + $cookiePrefix, |
|
| 507 | + $policy, |
|
| 508 | + $cookieParams['path'], |
|
| 509 | + $policy |
|
| 510 | + ), |
|
| 511 | + false |
|
| 512 | + ); |
|
| 513 | + } |
|
| 514 | + } |
|
| 515 | + |
|
| 516 | + /** |
|
| 517 | + * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
| 518 | + * be set in every request if cookies are sent to add a second level of |
|
| 519 | + * defense against CSRF. |
|
| 520 | + * |
|
| 521 | + * If the cookie is not sent this will set the cookie and reload the page. |
|
| 522 | + * We use an additional cookie since we want to protect logout CSRF and |
|
| 523 | + * also we can't directly interfere with PHP's session mechanism. |
|
| 524 | + */ |
|
| 525 | + private static function performSameSiteCookieProtection(\OCP\IConfig $config): void { |
|
| 526 | + $request = Server::get(IRequest::class); |
|
| 527 | + |
|
| 528 | + // Some user agents are notorious and don't really properly follow HTTP |
|
| 529 | + // specifications. For those, have an automated opt-out. Since the protection |
|
| 530 | + // for remote.php is applied in base.php as starting point we need to opt out |
|
| 531 | + // here. |
|
| 532 | + $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
| 533 | + |
|
| 534 | + // Fallback, if csrf.optout is unset |
|
| 535 | + if (!is_array($incompatibleUserAgents)) { |
|
| 536 | + $incompatibleUserAgents = [ |
|
| 537 | + // OS X Finder |
|
| 538 | + '/^WebDAVFS/', |
|
| 539 | + // Windows webdav drive |
|
| 540 | + '/^Microsoft-WebDAV-MiniRedir/', |
|
| 541 | + ]; |
|
| 542 | + } |
|
| 543 | + |
|
| 544 | + if ($request->isUserAgent($incompatibleUserAgents)) { |
|
| 545 | + return; |
|
| 546 | + } |
|
| 547 | + |
|
| 548 | + if (count($_COOKIE) > 0) { |
|
| 549 | + $requestUri = $request->getScriptName(); |
|
| 550 | + $processingScript = explode('/', $requestUri); |
|
| 551 | + $processingScript = $processingScript[count($processingScript) - 1]; |
|
| 552 | + |
|
| 553 | + // index.php routes are handled in the middleware |
|
| 554 | + // and cron.php does not need any authentication at all |
|
| 555 | + if ($processingScript === 'index.php' |
|
| 556 | + || $processingScript === 'cron.php') { |
|
| 557 | + return; |
|
| 558 | + } |
|
| 559 | + |
|
| 560 | + // All other endpoints require the lax and the strict cookie |
|
| 561 | + if (!$request->passesStrictCookieCheck()) { |
|
| 562 | + logger('core')->warning('Request does not pass strict cookie check'); |
|
| 563 | + self::sendSameSiteCookies(); |
|
| 564 | + // Debug mode gets access to the resources without strict cookie |
|
| 565 | + // due to the fact that the SabreDAV browser also lives there. |
|
| 566 | + if (!$config->getSystemValueBool('debug', false)) { |
|
| 567 | + http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED); |
|
| 568 | + header('Content-Type: application/json'); |
|
| 569 | + echo json_encode(['error' => 'Strict Cookie has not been found in request']); |
|
| 570 | + exit(); |
|
| 571 | + } |
|
| 572 | + } |
|
| 573 | + } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
| 574 | + self::sendSameSiteCookies(); |
|
| 575 | + } |
|
| 576 | + } |
|
| 577 | + |
|
| 578 | + public static function init(): void { |
|
| 579 | + // First handle PHP configuration and copy auth headers to the expected |
|
| 580 | + // $_SERVER variable before doing anything Server object related |
|
| 581 | + self::setRequiredIniValues(); |
|
| 582 | + self::handleAuthHeaders(); |
|
| 583 | + |
|
| 584 | + // prevent any XML processing from loading external entities |
|
| 585 | + libxml_set_external_entity_loader(static function () { |
|
| 586 | + return null; |
|
| 587 | + }); |
|
| 588 | + |
|
| 589 | + // Set default timezone before the Server object is booted |
|
| 590 | + if (!date_default_timezone_set('UTC')) { |
|
| 591 | + throw new \RuntimeException('Could not set timezone to UTC'); |
|
| 592 | + } |
|
| 593 | + |
|
| 594 | + // calculate the root directories |
|
| 595 | + OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4)); |
|
| 596 | + |
|
| 597 | + // register autoloader |
|
| 598 | + $loaderStart = microtime(true); |
|
| 599 | + require_once __DIR__ . '/autoloader.php'; |
|
| 600 | + self::$loader = new \OC\Autoloader([ |
|
| 601 | + OC::$SERVERROOT . '/lib/private/legacy', |
|
| 602 | + ]); |
|
| 603 | + if (defined('PHPUNIT_RUN')) { |
|
| 604 | + self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
|
| 605 | + } |
|
| 606 | + spl_autoload_register([self::$loader, 'load']); |
|
| 607 | + $loaderEnd = microtime(true); |
|
| 608 | + |
|
| 609 | + self::$CLI = (php_sapi_name() == 'cli'); |
|
| 610 | + |
|
| 611 | + // Add default composer PSR-4 autoloader, ensure apcu to be disabled |
|
| 612 | + self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
| 613 | + self::$composerAutoloader->setApcuPrefix(null); |
|
| 614 | + |
|
| 615 | + |
|
| 616 | + try { |
|
| 617 | + self::initPaths(); |
|
| 618 | + // setup 3rdparty autoloader |
|
| 619 | + $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php'; |
|
| 620 | + if (!file_exists($vendorAutoLoad)) { |
|
| 621 | + 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".'); |
|
| 622 | + } |
|
| 623 | + require_once $vendorAutoLoad; |
|
| 624 | + } catch (\RuntimeException $e) { |
|
| 625 | + if (!self::$CLI) { |
|
| 626 | + http_response_code(503); |
|
| 627 | + } |
|
| 628 | + // we can't use the template error page here, because this needs the |
|
| 629 | + // DI container which isn't available yet |
|
| 630 | + print($e->getMessage()); |
|
| 631 | + exit(); |
|
| 632 | + } |
|
| 633 | + |
|
| 634 | + // setup the basic server |
|
| 635 | + self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
| 636 | + self::$server->boot(); |
|
| 637 | + |
|
| 638 | + if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) { |
|
| 639 | + \OC\Core\Listener\BeforeMessageLoggedEventListener::setup(); |
|
| 640 | + } |
|
| 641 | + |
|
| 642 | + $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
| 643 | + $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
| 644 | + $eventLogger->start('boot', 'Initialize'); |
|
| 645 | + |
|
| 646 | + // Override php.ini and log everything if we're troubleshooting |
|
| 647 | + if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
| 648 | + error_reporting(E_ALL); |
|
| 649 | + } |
|
| 650 | + |
|
| 651 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
| 652 | + self::registerAutoloaderCache($systemConfig); |
|
| 653 | + |
|
| 654 | + // initialize intl fallback if necessary |
|
| 655 | + OC_Util::isSetLocaleWorking(); |
|
| 656 | + |
|
| 657 | + $config = Server::get(\OCP\IConfig::class); |
|
| 658 | + if (!defined('PHPUNIT_RUN')) { |
|
| 659 | + $errorHandler = new OC\Log\ErrorHandler( |
|
| 660 | + \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
| 661 | + ); |
|
| 662 | + $exceptionHandler = [$errorHandler, 'onException']; |
|
| 663 | + if ($config->getSystemValueBool('debug', false)) { |
|
| 664 | + set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
| 665 | + if (\OC::$CLI) { |
|
| 666 | + $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage']; |
|
| 667 | + } |
|
| 668 | + } else { |
|
| 669 | + set_error_handler([$errorHandler, 'onError']); |
|
| 670 | + } |
|
| 671 | + register_shutdown_function([$errorHandler, 'onShutdown']); |
|
| 672 | + set_exception_handler($exceptionHandler); |
|
| 673 | + } |
|
| 674 | + |
|
| 675 | + /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
| 676 | + $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
| 677 | + $bootstrapCoordinator->runInitialRegistration(); |
|
| 678 | + |
|
| 679 | + $eventLogger->start('init_session', 'Initialize session'); |
|
| 680 | + |
|
| 681 | + // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users |
|
| 682 | + // see https://github.com/nextcloud/server/pull/2619 |
|
| 683 | + if (!function_exists('simplexml_load_file')) { |
|
| 684 | + throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.'); |
|
| 685 | + } |
|
| 686 | + |
|
| 687 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 688 | + if ($systemConfig->getValue('installed', false)) { |
|
| 689 | + $appManager->loadApps(['session']); |
|
| 690 | + } |
|
| 691 | + if (!self::$CLI) { |
|
| 692 | + self::initSession(); |
|
| 693 | + } |
|
| 694 | + $eventLogger->end('init_session'); |
|
| 695 | + self::checkConfig(); |
|
| 696 | + self::checkInstalled($systemConfig); |
|
| 697 | + |
|
| 698 | + OC_Response::addSecurityHeaders(); |
|
| 699 | + |
|
| 700 | + self::performSameSiteCookieProtection($config); |
|
| 701 | + |
|
| 702 | + if (!defined('OC_CONSOLE')) { |
|
| 703 | + $errors = OC_Util::checkServer($systemConfig); |
|
| 704 | + if (count($errors) > 0) { |
|
| 705 | + if (!self::$CLI) { |
|
| 706 | + http_response_code(503); |
|
| 707 | + Util::addStyle('guest'); |
|
| 708 | + try { |
|
| 709 | + Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]); |
|
| 710 | + exit; |
|
| 711 | + } catch (\Exception $e) { |
|
| 712 | + // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
| 713 | + // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
| 714 | + } |
|
| 715 | + } |
|
| 716 | + |
|
| 717 | + // Convert l10n string into regular string for usage in database |
|
| 718 | + $staticErrors = []; |
|
| 719 | + foreach ($errors as $error) { |
|
| 720 | + echo $error['error'] . "\n"; |
|
| 721 | + echo $error['hint'] . "\n\n"; |
|
| 722 | + $staticErrors[] = [ |
|
| 723 | + 'error' => (string)$error['error'], |
|
| 724 | + 'hint' => (string)$error['hint'], |
|
| 725 | + ]; |
|
| 726 | + } |
|
| 727 | + |
|
| 728 | + try { |
|
| 729 | + $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
| 730 | + } catch (\Exception $e) { |
|
| 731 | + echo('Writing to database failed'); |
|
| 732 | + } |
|
| 733 | + exit(1); |
|
| 734 | + } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) { |
|
| 735 | + $config->deleteAppValue('core', 'cronErrors'); |
|
| 736 | + } |
|
| 737 | + } |
|
| 738 | + |
|
| 739 | + // User and Groups |
|
| 740 | + if (!$systemConfig->getValue('installed', false)) { |
|
| 741 | + self::$server->getSession()->set('user_id', ''); |
|
| 742 | + } |
|
| 743 | + |
|
| 744 | + Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 745 | + Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
| 746 | + |
|
| 747 | + // Subscribe to the hook |
|
| 748 | + \OCP\Util::connectHook( |
|
| 749 | + '\OCA\Files_Sharing\API\Server2Server', |
|
| 750 | + 'preLoginNameUsedAsUserName', |
|
| 751 | + '\OC\User\Database', |
|
| 752 | + 'preLoginNameUsedAsUserName' |
|
| 753 | + ); |
|
| 754 | + |
|
| 755 | + //setup extra user backends |
|
| 756 | + if (!\OCP\Util::needUpgrade()) { |
|
| 757 | + OC_User::setupBackends(); |
|
| 758 | + } else { |
|
| 759 | + // Run upgrades in incognito mode |
|
| 760 | + OC_User::setIncognitoMode(true); |
|
| 761 | + } |
|
| 762 | + |
|
| 763 | + self::registerCleanupHooks($systemConfig); |
|
| 764 | + self::registerShareHooks($systemConfig); |
|
| 765 | + self::registerEncryptionWrapperAndHooks(); |
|
| 766 | + self::registerAccountHooks(); |
|
| 767 | + self::registerResourceCollectionHooks(); |
|
| 768 | + self::registerFileReferenceEventListener(); |
|
| 769 | + self::registerRenderReferenceEventListener(); |
|
| 770 | + self::registerAppRestrictionsHooks(); |
|
| 771 | + |
|
| 772 | + // Make sure that the application class is not loaded before the database is setup |
|
| 773 | + if ($systemConfig->getValue('installed', false)) { |
|
| 774 | + $appManager->loadApp('settings'); |
|
| 775 | + /* Build core application to make sure that listeners are registered */ |
|
| 776 | + Server::get(\OC\Core\Application::class); |
|
| 777 | + } |
|
| 778 | + |
|
| 779 | + //make sure temporary files are cleaned up |
|
| 780 | + $tmpManager = Server::get(\OCP\ITempManager::class); |
|
| 781 | + register_shutdown_function([$tmpManager, 'clean']); |
|
| 782 | + $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
| 783 | + register_shutdown_function([$lockProvider, 'releaseAll']); |
|
| 784 | + |
|
| 785 | + // Check whether the sample configuration has been copied |
|
| 786 | + if ($systemConfig->getValue('copied_sample_config', false)) { |
|
| 787 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
| 788 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
| 789 | + $l->t('Sample configuration detected'), |
|
| 790 | + $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'), |
|
| 791 | + 503 |
|
| 792 | + ); |
|
| 793 | + return; |
|
| 794 | + } |
|
| 795 | + |
|
| 796 | + $request = Server::get(IRequest::class); |
|
| 797 | + $host = $request->getInsecureServerHost(); |
|
| 798 | + /** |
|
| 799 | + * if the host passed in headers isn't trusted |
|
| 800 | + * FIXME: Should not be in here at all :see_no_evil: |
|
| 801 | + */ |
|
| 802 | + if (!OC::$CLI |
|
| 803 | + && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
| 804 | + && $config->getSystemValueBool('installed', false) |
|
| 805 | + ) { |
|
| 806 | + // Allow access to CSS resources |
|
| 807 | + $isScssRequest = false; |
|
| 808 | + if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
| 809 | + $isScssRequest = true; |
|
| 810 | + } |
|
| 811 | + |
|
| 812 | + if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
| 813 | + http_response_code(400); |
|
| 814 | + header('Content-Type: application/json'); |
|
| 815 | + echo '{"error": "Trusted domain error.", "code": 15}'; |
|
| 816 | + exit(); |
|
| 817 | + } |
|
| 818 | + |
|
| 819 | + if (!$isScssRequest) { |
|
| 820 | + http_response_code(400); |
|
| 821 | + Server::get(LoggerInterface::class)->info( |
|
| 822 | + 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
| 823 | + [ |
|
| 824 | + 'app' => 'core', |
|
| 825 | + 'remoteAddress' => $request->getRemoteAddress(), |
|
| 826 | + 'host' => $host, |
|
| 827 | + ] |
|
| 828 | + ); |
|
| 829 | + |
|
| 830 | + $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest'); |
|
| 831 | + $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
| 832 | + $tmpl->printPage(); |
|
| 833 | + |
|
| 834 | + exit(); |
|
| 835 | + } |
|
| 836 | + } |
|
| 837 | + $eventLogger->end('boot'); |
|
| 838 | + $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
| 839 | + $eventLogger->start('runtime', 'Runtime'); |
|
| 840 | + $eventLogger->start('request', 'Full request after boot'); |
|
| 841 | + register_shutdown_function(function () use ($eventLogger) { |
|
| 842 | + $eventLogger->end('request'); |
|
| 843 | + }); |
|
| 844 | + |
|
| 845 | + register_shutdown_function(function () { |
|
| 846 | + $memoryPeak = memory_get_peak_usage(); |
|
| 847 | + $logLevel = match (true) { |
|
| 848 | + $memoryPeak > 500_000_000 => ILogger::FATAL, |
|
| 849 | + $memoryPeak > 400_000_000 => ILogger::ERROR, |
|
| 850 | + $memoryPeak > 300_000_000 => ILogger::WARN, |
|
| 851 | + default => null, |
|
| 852 | + }; |
|
| 853 | + if ($logLevel !== null) { |
|
| 854 | + $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak); |
|
| 855 | + $logger = Server::get(LoggerInterface::class); |
|
| 856 | + $logger->log($logLevel, $message, ['app' => 'core']); |
|
| 857 | + } |
|
| 858 | + }); |
|
| 859 | + } |
|
| 860 | + |
|
| 861 | + /** |
|
| 862 | + * register hooks for the cleanup of cache and bruteforce protection |
|
| 863 | + */ |
|
| 864 | + public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
| 865 | + //don't try to do this before we are properly setup |
|
| 866 | + if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
| 867 | + // NOTE: This will be replaced to use OCP |
|
| 868 | + $userSession = Server::get(\OC\User\Session::class); |
|
| 869 | + $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
| 870 | + if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
| 871 | + // reset brute force delay for this IP address and username |
|
| 872 | + $uid = $userSession->getUser()->getUID(); |
|
| 873 | + $request = Server::get(IRequest::class); |
|
| 874 | + $throttler = Server::get(IThrottler::class); |
|
| 875 | + $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
| 876 | + } |
|
| 877 | + |
|
| 878 | + try { |
|
| 879 | + $cache = new \OC\Cache\File(); |
|
| 880 | + $cache->gc(); |
|
| 881 | + } catch (\OC\ServerNotAvailableException $e) { |
|
| 882 | + // not a GC exception, pass it on |
|
| 883 | + throw $e; |
|
| 884 | + } catch (\OC\ForbiddenException $e) { |
|
| 885 | + // filesystem blocked for this request, ignore |
|
| 886 | + } catch (\Exception $e) { |
|
| 887 | + // a GC exception should not prevent users from using OC, |
|
| 888 | + // so log the exception |
|
| 889 | + Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
| 890 | + 'app' => 'core', |
|
| 891 | + 'exception' => $e, |
|
| 892 | + ]); |
|
| 893 | + } |
|
| 894 | + }); |
|
| 895 | + } |
|
| 896 | + } |
|
| 897 | + |
|
| 898 | + private static function registerEncryptionWrapperAndHooks(): void { |
|
| 899 | + $manager = Server::get(\OCP\Encryption\IManager::class); |
|
| 900 | + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); |
|
| 901 | + |
|
| 902 | + $enabled = $manager->isEnabled(); |
|
| 903 | + if ($enabled) { |
|
| 904 | + \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared'); |
|
| 905 | + \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared'); |
|
| 906 | + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename'); |
|
| 907 | + \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore'); |
|
| 908 | + } |
|
| 909 | + } |
|
| 910 | + |
|
| 911 | + private static function registerAccountHooks(): void { |
|
| 912 | + /** @var IEventDispatcher $dispatcher */ |
|
| 913 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
| 914 | + $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
| 915 | + } |
|
| 916 | + |
|
| 917 | + private static function registerAppRestrictionsHooks(): void { |
|
| 918 | + /** @var \OC\Group\Manager $groupManager */ |
|
| 919 | + $groupManager = Server::get(\OCP\IGroupManager::class); |
|
| 920 | + $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
| 921 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 922 | + $apps = $appManager->getEnabledAppsForGroup($group); |
|
| 923 | + foreach ($apps as $appId) { |
|
| 924 | + $restrictions = $appManager->getAppRestriction($appId); |
|
| 925 | + if (empty($restrictions)) { |
|
| 926 | + continue; |
|
| 927 | + } |
|
| 928 | + $key = array_search($group->getGID(), $restrictions); |
|
| 929 | + unset($restrictions[$key]); |
|
| 930 | + $restrictions = array_values($restrictions); |
|
| 931 | + if (empty($restrictions)) { |
|
| 932 | + $appManager->disableApp($appId); |
|
| 933 | + } else { |
|
| 934 | + $appManager->enableAppForGroups($appId, $restrictions); |
|
| 935 | + } |
|
| 936 | + } |
|
| 937 | + }); |
|
| 938 | + } |
|
| 939 | + |
|
| 940 | + private static function registerResourceCollectionHooks(): void { |
|
| 941 | + \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class)); |
|
| 942 | + } |
|
| 943 | + |
|
| 944 | + private static function registerFileReferenceEventListener(): void { |
|
| 945 | + \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
| 946 | + } |
|
| 947 | + |
|
| 948 | + private static function registerRenderReferenceEventListener() { |
|
| 949 | + \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
| 950 | + } |
|
| 951 | + |
|
| 952 | + /** |
|
| 953 | + * register hooks for sharing |
|
| 954 | + */ |
|
| 955 | + public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
| 956 | + if ($systemConfig->getValue('installed')) { |
|
| 957 | + |
|
| 958 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
| 959 | + $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class); |
|
| 960 | + $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class); |
|
| 961 | + $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class); |
|
| 962 | + } |
|
| 963 | + } |
|
| 964 | + |
|
| 965 | + protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void { |
|
| 966 | + // The class loader takes an optional low-latency cache, which MUST be |
|
| 967 | + // namespaced. The instanceid is used for namespacing, but might be |
|
| 968 | + // unavailable at this point. Furthermore, it might not be possible to |
|
| 969 | + // generate an instanceid via \OC_Util::getInstanceId() because the |
|
| 970 | + // config file may not be writable. As such, we only register a class |
|
| 971 | + // loader cache if instanceid is available without trying to create one. |
|
| 972 | + $instanceId = $systemConfig->getValue('instanceid', null); |
|
| 973 | + if ($instanceId) { |
|
| 974 | + try { |
|
| 975 | + $memcacheFactory = Server::get(\OCP\ICacheFactory::class); |
|
| 976 | + self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); |
|
| 977 | + } catch (\Exception $ex) { |
|
| 978 | + } |
|
| 979 | + } |
|
| 980 | + } |
|
| 981 | + |
|
| 982 | + /** |
|
| 983 | + * Handle the request |
|
| 984 | + */ |
|
| 985 | + public static function handleRequest(): void { |
|
| 986 | + Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
| 987 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
| 988 | + |
|
| 989 | + // Check if Nextcloud is installed or in maintenance (update) mode |
|
| 990 | + if (!$systemConfig->getValue('installed', false)) { |
|
| 991 | + \OC::$server->getSession()->clear(); |
|
| 992 | + $controller = Server::get(\OC\Core\Controller\SetupController::class); |
|
| 993 | + $controller->run($_POST); |
|
| 994 | + exit(); |
|
| 995 | + } |
|
| 996 | + |
|
| 997 | + $request = Server::get(IRequest::class); |
|
| 998 | + $requestPath = $request->getRawPathInfo(); |
|
| 999 | + if ($requestPath === '/heartbeat') { |
|
| 1000 | + return; |
|
| 1001 | + } |
|
| 1002 | + if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
| 1003 | + self::checkMaintenanceMode($systemConfig); |
|
| 1004 | + |
|
| 1005 | + if (\OCP\Util::needUpgrade()) { |
|
| 1006 | + if (function_exists('opcache_reset')) { |
|
| 1007 | + opcache_reset(); |
|
| 1008 | + } |
|
| 1009 | + if (!((bool)$systemConfig->getValue('maintenance', false))) { |
|
| 1010 | + self::printUpgradePage($systemConfig); |
|
| 1011 | + exit(); |
|
| 1012 | + } |
|
| 1013 | + } |
|
| 1014 | + } |
|
| 1015 | + |
|
| 1016 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
| 1017 | + |
|
| 1018 | + // Always load authentication apps |
|
| 1019 | + $appManager->loadApps(['authentication']); |
|
| 1020 | + $appManager->loadApps(['extended_authentication']); |
|
| 1021 | + |
|
| 1022 | + // Load minimum set of apps |
|
| 1023 | + if (!\OCP\Util::needUpgrade() |
|
| 1024 | + && !((bool)$systemConfig->getValue('maintenance', false))) { |
|
| 1025 | + // For logged-in users: Load everything |
|
| 1026 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
| 1027 | + $appManager->loadApps(); |
|
| 1028 | + } else { |
|
| 1029 | + // For guests: Load only filesystem and logging |
|
| 1030 | + $appManager->loadApps(['filesystem', 'logging']); |
|
| 1031 | + |
|
| 1032 | + // Don't try to login when a client is trying to get a OAuth token. |
|
| 1033 | + // OAuth needs to support basic auth too, so the login is not valid |
|
| 1034 | + // inside Nextcloud and the Login exception would ruin it. |
|
| 1035 | + if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
| 1036 | + self::handleLogin($request); |
|
| 1037 | + } |
|
| 1038 | + } |
|
| 1039 | + } |
|
| 1040 | + |
|
| 1041 | + if (!self::$CLI) { |
|
| 1042 | + try { |
|
| 1043 | + if (!\OCP\Util::needUpgrade()) { |
|
| 1044 | + $appManager->loadApps(['filesystem', 'logging']); |
|
| 1045 | + $appManager->loadApps(); |
|
| 1046 | + } |
|
| 1047 | + Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
| 1048 | + return; |
|
| 1049 | + } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
| 1050 | + //header('HTTP/1.0 404 Not Found'); |
|
| 1051 | + } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
| 1052 | + http_response_code(405); |
|
| 1053 | + return; |
|
| 1054 | + } |
|
| 1055 | + } |
|
| 1056 | + |
|
| 1057 | + // Handle WebDAV |
|
| 1058 | + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
| 1059 | + // not allowed any more to prevent people |
|
| 1060 | + // mounting this root directly. |
|
| 1061 | + // Users need to mount remote.php/webdav instead. |
|
| 1062 | + http_response_code(405); |
|
| 1063 | + return; |
|
| 1064 | + } |
|
| 1065 | + |
|
| 1066 | + // Handle requests for JSON or XML |
|
| 1067 | + $acceptHeader = $request->getHeader('Accept'); |
|
| 1068 | + if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
| 1069 | + http_response_code(404); |
|
| 1070 | + return; |
|
| 1071 | + } |
|
| 1072 | + |
|
| 1073 | + // Handle resources that can't be found |
|
| 1074 | + // This prevents browsers from redirecting to the default page and then |
|
| 1075 | + // attempting to parse HTML as CSS and similar. |
|
| 1076 | + $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
| 1077 | + if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
| 1078 | + http_response_code(404); |
|
| 1079 | + return; |
|
| 1080 | + } |
|
| 1081 | + |
|
| 1082 | + // Redirect to the default app or login only as an entry point |
|
| 1083 | + if ($requestPath === '') { |
|
| 1084 | + // Someone is logged in |
|
| 1085 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
| 1086 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
| 1087 | + } else { |
|
| 1088 | + // Not handled and not logged in |
|
| 1089 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
| 1090 | + } |
|
| 1091 | + return; |
|
| 1092 | + } |
|
| 1093 | + |
|
| 1094 | + try { |
|
| 1095 | + Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
| 1096 | + } catch (\Exception $e) { |
|
| 1097 | + if (!$e instanceof MethodNotAllowedException) { |
|
| 1098 | + logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
| 1099 | + } |
|
| 1100 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
| 1101 | + Server::get(ITemplateManager::class)->printErrorPage( |
|
| 1102 | + '404', |
|
| 1103 | + $l->t('The page could not be found on the server.'), |
|
| 1104 | + 404 |
|
| 1105 | + ); |
|
| 1106 | + } |
|
| 1107 | + } |
|
| 1108 | + |
|
| 1109 | + /** |
|
| 1110 | + * Check login: apache auth, auth token, basic auth |
|
| 1111 | + */ |
|
| 1112 | + public static function handleLogin(OCP\IRequest $request): bool { |
|
| 1113 | + if ($request->getHeader('X-Nextcloud-Federation')) { |
|
| 1114 | + return false; |
|
| 1115 | + } |
|
| 1116 | + $userSession = Server::get(\OC\User\Session::class); |
|
| 1117 | + if (OC_User::handleApacheAuth()) { |
|
| 1118 | + return true; |
|
| 1119 | + } |
|
| 1120 | + if (self::tryAppAPILogin($request)) { |
|
| 1121 | + return true; |
|
| 1122 | + } |
|
| 1123 | + if ($userSession->tryTokenLogin($request)) { |
|
| 1124 | + return true; |
|
| 1125 | + } |
|
| 1126 | + if (isset($_COOKIE['nc_username']) |
|
| 1127 | + && isset($_COOKIE['nc_token']) |
|
| 1128 | + && isset($_COOKIE['nc_session_id']) |
|
| 1129 | + && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
| 1130 | + return true; |
|
| 1131 | + } |
|
| 1132 | + if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) { |
|
| 1133 | + return true; |
|
| 1134 | + } |
|
| 1135 | + return false; |
|
| 1136 | + } |
|
| 1137 | + |
|
| 1138 | + protected static function handleAuthHeaders(): void { |
|
| 1139 | + //copy http auth headers for apache+php-fcgid work around |
|
| 1140 | + if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
| 1141 | + $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
| 1142 | + } |
|
| 1143 | + |
|
| 1144 | + // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
| 1145 | + $vars = [ |
|
| 1146 | + 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
| 1147 | + 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
| 1148 | + ]; |
|
| 1149 | + foreach ($vars as $var) { |
|
| 1150 | + if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
| 1151 | + $credentials = explode(':', base64_decode($matches[1]), 2); |
|
| 1152 | + if (count($credentials) === 2) { |
|
| 1153 | + $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
| 1154 | + $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
| 1155 | + break; |
|
| 1156 | + } |
|
| 1157 | + } |
|
| 1158 | + } |
|
| 1159 | + } |
|
| 1160 | + |
|
| 1161 | + protected static function tryAppAPILogin(OCP\IRequest $request): bool { |
|
| 1162 | + if (!$request->getHeader('AUTHORIZATION-APP-API')) { |
|
| 1163 | + return false; |
|
| 1164 | + } |
|
| 1165 | + $appManager = Server::get(OCP\App\IAppManager::class); |
|
| 1166 | + if (!$appManager->isEnabledForAnyone('app_api')) { |
|
| 1167 | + return false; |
|
| 1168 | + } |
|
| 1169 | + try { |
|
| 1170 | + $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class); |
|
| 1171 | + return $appAPIService->validateExAppRequestToNC($request); |
|
| 1172 | + } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) { |
|
| 1173 | + return false; |
|
| 1174 | + } |
|
| 1175 | + } |
|
| 1176 | 1176 | } |
| 1177 | 1177 | |
| 1178 | 1178 | OC::init(); |
@@ -33,681 +33,681 @@ |
||
| 33 | 33 | * @group DB |
| 34 | 34 | */ |
| 35 | 35 | class TrashbinTest extends \Test\TestCase { |
| 36 | - public const TEST_TRASHBIN_USER1 = 'test-trashbin-user1'; |
|
| 37 | - public const TEST_TRASHBIN_USER2 = 'test-trashbin-user2'; |
|
| 38 | - |
|
| 39 | - private $trashRoot1; |
|
| 40 | - private $trashRoot2; |
|
| 41 | - |
|
| 42 | - private static $rememberRetentionObligation; |
|
| 43 | - |
|
| 44 | - /** |
|
| 45 | - * @var bool |
|
| 46 | - */ |
|
| 47 | - private static $trashBinStatus; |
|
| 48 | - |
|
| 49 | - /** |
|
| 50 | - * @var View |
|
| 51 | - */ |
|
| 52 | - private $rootView; |
|
| 53 | - |
|
| 54 | - public static function setUpBeforeClass(): void { |
|
| 55 | - parent::setUpBeforeClass(); |
|
| 56 | - |
|
| 57 | - $appManager = Server::get(IAppManager::class); |
|
| 58 | - self::$trashBinStatus = $appManager->isEnabledForUser('files_trashbin'); |
|
| 59 | - |
|
| 60 | - // reset backend |
|
| 61 | - Server::get(IUserManager::class)->clearBackends(); |
|
| 62 | - Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 63 | - |
|
| 64 | - // clear share hooks |
|
| 65 | - \OC_Hook::clear('OCP\\Share'); |
|
| 66 | - \OC::registerShareHooks(Server::get(SystemConfig::class)); |
|
| 67 | - |
|
| 68 | - // init files sharing |
|
| 69 | - new Application(); |
|
| 70 | - |
|
| 71 | - //disable encryption |
|
| 72 | - Server::get(IAppManager::class)->disableApp('encryption'); |
|
| 73 | - |
|
| 74 | - $config = Server::get(IConfig::class); |
|
| 75 | - //configure trashbin |
|
| 76 | - self::$rememberRetentionObligation = $config->getSystemValue('trashbin_retention_obligation', Expiration::DEFAULT_RETENTION_OBLIGATION); |
|
| 77 | - /** @var Expiration $expiration */ |
|
| 78 | - $expiration = Server::get(Expiration::class); |
|
| 79 | - $expiration->setRetentionObligation('auto, 2'); |
|
| 80 | - |
|
| 81 | - // register trashbin hooks |
|
| 82 | - $trashbinApp = new TrashbinApplication(); |
|
| 83 | - $trashbinApp->boot(new BootContext(new DIContainer('', [], \OC::$server))); |
|
| 84 | - |
|
| 85 | - // create test user |
|
| 86 | - self::loginHelper(self::TEST_TRASHBIN_USER2, true); |
|
| 87 | - self::loginHelper(self::TEST_TRASHBIN_USER1, true); |
|
| 88 | - } |
|
| 89 | - |
|
| 90 | - |
|
| 91 | - public static function tearDownAfterClass(): void { |
|
| 92 | - // cleanup test user |
|
| 93 | - $user = Server::get(IUserManager::class)->get(self::TEST_TRASHBIN_USER1); |
|
| 94 | - if ($user !== null) { |
|
| 95 | - $user->delete(); |
|
| 96 | - } |
|
| 97 | - |
|
| 98 | - /** @var Expiration $expiration */ |
|
| 99 | - $expiration = Server::get(Expiration::class); |
|
| 100 | - $expiration->setRetentionObligation(self::$rememberRetentionObligation); |
|
| 101 | - |
|
| 102 | - \OC_Hook::clear(); |
|
| 103 | - |
|
| 104 | - Filesystem::getLoader()->removeStorageWrapper('oc_trashbin'); |
|
| 105 | - |
|
| 106 | - if (self::$trashBinStatus) { |
|
| 107 | - Server::get(IAppManager::class)->enableApp('files_trashbin'); |
|
| 108 | - } |
|
| 109 | - |
|
| 110 | - parent::tearDownAfterClass(); |
|
| 111 | - } |
|
| 112 | - |
|
| 113 | - protected function setUp(): void { |
|
| 114 | - parent::setUp(); |
|
| 115 | - |
|
| 116 | - Server::get(IAppManager::class)->enableApp('files_trashbin'); |
|
| 117 | - $config = Server::get(IConfig::class); |
|
| 118 | - $mockConfig = $this->createMock(IConfig::class); |
|
| 119 | - $mockConfig |
|
| 120 | - ->method('getSystemValue') |
|
| 121 | - ->willReturnCallback(static function ($key, $default) use ($config) { |
|
| 122 | - if ($key === 'filesystem_check_changes') { |
|
| 123 | - return Watcher::CHECK_ONCE; |
|
| 124 | - } else { |
|
| 125 | - return $config->getSystemValue($key, $default); |
|
| 126 | - } |
|
| 127 | - }); |
|
| 128 | - $mockConfig |
|
| 129 | - ->method('getUserValue') |
|
| 130 | - ->willReturnCallback(static function ($userId, $appName, $key, $default = '') use ($config) { |
|
| 131 | - return $config->getUserValue($userId, $appName, $key, $default); |
|
| 132 | - }); |
|
| 133 | - $mockConfig |
|
| 134 | - ->method('getAppValue') |
|
| 135 | - ->willReturnCallback(static function ($appName, $key, $default = '') use ($config) { |
|
| 136 | - return $config->getAppValue($appName, $key, $default); |
|
| 137 | - }); |
|
| 138 | - $this->overwriteService(AllConfig::class, $mockConfig); |
|
| 139 | - |
|
| 140 | - $this->trashRoot1 = '/' . self::TEST_TRASHBIN_USER1 . '/files_trashbin'; |
|
| 141 | - $this->trashRoot2 = '/' . self::TEST_TRASHBIN_USER2 . '/files_trashbin'; |
|
| 142 | - $this->rootView = new View(); |
|
| 143 | - self::loginHelper(self::TEST_TRASHBIN_USER1); |
|
| 144 | - } |
|
| 145 | - |
|
| 146 | - protected function tearDown(): void { |
|
| 147 | - $this->restoreService(AllConfig::class); |
|
| 148 | - // disable trashbin to be able to properly clean up |
|
| 149 | - Server::get(IAppManager::class)->disableApp('files_trashbin'); |
|
| 150 | - |
|
| 151 | - $this->rootView->deleteAll('/' . self::TEST_TRASHBIN_USER1 . '/files'); |
|
| 152 | - $this->rootView->deleteAll('/' . self::TEST_TRASHBIN_USER2 . '/files'); |
|
| 153 | - $this->rootView->deleteAll($this->trashRoot1); |
|
| 154 | - $this->rootView->deleteAll($this->trashRoot2); |
|
| 155 | - |
|
| 156 | - // clear trash table |
|
| 157 | - $connection = Server::get(IDBConnection::class); |
|
| 158 | - $connection->executeUpdate('DELETE FROM `*PREFIX*files_trash`'); |
|
| 159 | - |
|
| 160 | - parent::tearDown(); |
|
| 161 | - } |
|
| 162 | - |
|
| 163 | - /** |
|
| 164 | - * test expiration of files older then the max storage time defined for the trash |
|
| 165 | - */ |
|
| 166 | - public function testExpireOldFiles(): void { |
|
| 167 | - |
|
| 168 | - /** @var ITimeFactory $time */ |
|
| 169 | - $time = Server::get(ITimeFactory::class); |
|
| 170 | - $currentTime = $time->getTime(); |
|
| 171 | - $expireAt = $currentTime - 2 * 24 * 60 * 60; |
|
| 172 | - $expiredDate = $currentTime - 3 * 24 * 60 * 60; |
|
| 173 | - |
|
| 174 | - // create some files |
|
| 175 | - Filesystem::file_put_contents('file1.txt', 'file1'); |
|
| 176 | - Filesystem::file_put_contents('file2.txt', 'file2'); |
|
| 177 | - Filesystem::file_put_contents('file3.txt', 'file3'); |
|
| 178 | - |
|
| 179 | - // delete them so that they end up in the trash bin |
|
| 180 | - Filesystem::unlink('file1.txt'); |
|
| 181 | - Filesystem::unlink('file2.txt'); |
|
| 182 | - Filesystem::unlink('file3.txt'); |
|
| 183 | - |
|
| 184 | - //make sure that files are in the trash bin |
|
| 185 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'name'); |
|
| 186 | - $this->assertSame(3, count($filesInTrash)); |
|
| 187 | - |
|
| 188 | - // every second file will get a date in the past so that it will get expired |
|
| 189 | - $manipulatedList = $this->manipulateDeleteTime($filesInTrash, $this->trashRoot1, $expiredDate); |
|
| 190 | - |
|
| 191 | - $testClass = new TrashbinForTesting(); |
|
| 192 | - [$sizeOfDeletedFiles, $count] = $testClass->dummyDeleteExpiredFiles($manipulatedList, $expireAt); |
|
| 193 | - |
|
| 194 | - $this->assertSame(10, $sizeOfDeletedFiles); |
|
| 195 | - $this->assertSame(2, $count); |
|
| 196 | - |
|
| 197 | - // only file2.txt should be left |
|
| 198 | - $remainingFiles = array_slice($manipulatedList, $count); |
|
| 199 | - $this->assertSame(1, count($remainingFiles)); |
|
| 200 | - $remainingFile = reset($remainingFiles); |
|
| 201 | - // TODO: failing test |
|
| 202 | - #$this->assertSame('file2.txt', $remainingFile['name']); |
|
| 203 | - |
|
| 204 | - // check that file1.txt and file3.txt was really deleted |
|
| 205 | - $newTrashContent = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); |
|
| 206 | - $this->assertSame(1, count($newTrashContent)); |
|
| 207 | - $element = reset($newTrashContent); |
|
| 208 | - // TODO: failing test |
|
| 209 | - #$this->assertSame('file2.txt', $element['name']); |
|
| 210 | - } |
|
| 211 | - |
|
| 212 | - /** |
|
| 213 | - * test expiration of files older then the max storage time defined for the trash |
|
| 214 | - * in this test we delete a shared file and check if both trash bins, the one from |
|
| 215 | - * the owner of the file and the one from the user who deleted the file get expired |
|
| 216 | - * correctly |
|
| 217 | - */ |
|
| 218 | - public function testExpireOldFilesShared(): void { |
|
| 219 | - $currentTime = time(); |
|
| 220 | - $folder = 'trashTest-' . $currentTime . '/'; |
|
| 221 | - $expiredDate = $currentTime - 3 * 24 * 60 * 60; |
|
| 222 | - |
|
| 223 | - // create some files |
|
| 224 | - Filesystem::mkdir($folder); |
|
| 225 | - Filesystem::file_put_contents($folder . 'user1-1.txt', 'file1'); |
|
| 226 | - Filesystem::file_put_contents($folder . 'user1-2.txt', 'file2'); |
|
| 227 | - Filesystem::file_put_contents($folder . 'user1-3.txt', 'file3'); |
|
| 228 | - Filesystem::file_put_contents($folder . 'user1-4.txt', 'file4'); |
|
| 229 | - |
|
| 230 | - //share user1-4.txt with user2 |
|
| 231 | - $node = \OC::$server->getUserFolder(self::TEST_TRASHBIN_USER1)->get($folder); |
|
| 232 | - $share = Server::get(\OCP\Share\IManager::class)->newShare(); |
|
| 233 | - $share->setShareType(IShare::TYPE_USER) |
|
| 234 | - ->setNode($node) |
|
| 235 | - ->setSharedBy(self::TEST_TRASHBIN_USER1) |
|
| 236 | - ->setSharedWith(self::TEST_TRASHBIN_USER2) |
|
| 237 | - ->setPermissions(Constants::PERMISSION_ALL); |
|
| 238 | - $share = Server::get(\OCP\Share\IManager::class)->createShare($share); |
|
| 239 | - Server::get(\OCP\Share\IManager::class)->acceptShare($share, self::TEST_TRASHBIN_USER2); |
|
| 240 | - |
|
| 241 | - // delete them so that they end up in the trash bin |
|
| 242 | - Filesystem::unlink($folder . 'user1-1.txt'); |
|
| 243 | - Filesystem::unlink($folder . 'user1-2.txt'); |
|
| 244 | - Filesystem::unlink($folder . 'user1-3.txt'); |
|
| 245 | - |
|
| 246 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'name'); |
|
| 247 | - $this->assertSame(3, count($filesInTrash)); |
|
| 248 | - |
|
| 249 | - // every second file will get a date in the past so that it will get expired |
|
| 250 | - $this->manipulateDeleteTime($filesInTrash, $this->trashRoot1, $expiredDate); |
|
| 251 | - |
|
| 252 | - // login as user2 |
|
| 253 | - self::loginHelper(self::TEST_TRASHBIN_USER2); |
|
| 254 | - |
|
| 255 | - $this->assertTrue(Filesystem::file_exists($folder . 'user1-4.txt')); |
|
| 256 | - |
|
| 257 | - // create some files |
|
| 258 | - Filesystem::file_put_contents('user2-1.txt', 'file1'); |
|
| 259 | - Filesystem::file_put_contents('user2-2.txt', 'file2'); |
|
| 260 | - |
|
| 261 | - // delete them so that they end up in the trash bin |
|
| 262 | - Filesystem::unlink('user2-1.txt'); |
|
| 263 | - Filesystem::unlink('user2-2.txt'); |
|
| 264 | - |
|
| 265 | - $filesInTrashUser2 = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2, 'name'); |
|
| 266 | - $this->assertSame(2, count($filesInTrashUser2)); |
|
| 267 | - |
|
| 268 | - // every second file will get a date in the past so that it will get expired |
|
| 269 | - $this->manipulateDeleteTime($filesInTrashUser2, $this->trashRoot2, $expiredDate); |
|
| 270 | - |
|
| 271 | - Filesystem::unlink($folder . 'user1-4.txt'); |
|
| 272 | - |
|
| 273 | - $this->runCommands(); |
|
| 274 | - |
|
| 275 | - $filesInTrashUser2AfterDelete = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2); |
|
| 276 | - |
|
| 277 | - // user2-1.txt should have been expired |
|
| 278 | - $this->verifyArray($filesInTrashUser2AfterDelete, ['user2-2.txt', 'user1-4.txt']); |
|
| 279 | - |
|
| 280 | - self::loginHelper(self::TEST_TRASHBIN_USER1); |
|
| 281 | - |
|
| 282 | - // user1-1.txt and user1-3.txt should have been expired |
|
| 283 | - $filesInTrashUser1AfterDelete = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); |
|
| 284 | - |
|
| 285 | - $this->verifyArray($filesInTrashUser1AfterDelete, ['user1-2.txt', 'user1-4.txt']); |
|
| 286 | - } |
|
| 287 | - |
|
| 288 | - /** |
|
| 289 | - * verify that the array contains the expected results |
|
| 290 | - * |
|
| 291 | - * @param FileInfo[] $result |
|
| 292 | - * @param string[] $expected |
|
| 293 | - */ |
|
| 294 | - private function verifyArray($result, $expected) { |
|
| 295 | - $this->assertSame(count($expected), count($result)); |
|
| 296 | - foreach ($expected as $expectedFile) { |
|
| 297 | - $found = false; |
|
| 298 | - foreach ($result as $fileInTrash) { |
|
| 299 | - if ($expectedFile === $fileInTrash['name']) { |
|
| 300 | - $found = true; |
|
| 301 | - break; |
|
| 302 | - } |
|
| 303 | - } |
|
| 304 | - if (!$found) { |
|
| 305 | - // if we didn't found the expected file, something went wrong |
|
| 306 | - $this->assertTrue(false, "can't find expected file '" . $expectedFile . "' in trash bin"); |
|
| 307 | - } |
|
| 308 | - } |
|
| 309 | - } |
|
| 310 | - |
|
| 311 | - /** |
|
| 312 | - * @param FileInfo[] $files |
|
| 313 | - * @param string $trashRoot |
|
| 314 | - * @param integer $expireDate |
|
| 315 | - */ |
|
| 316 | - private function manipulateDeleteTime($files, $trashRoot, $expireDate) { |
|
| 317 | - $counter = 0; |
|
| 318 | - foreach ($files as &$file) { |
|
| 319 | - // modify every second file |
|
| 320 | - $counter = ($counter + 1) % 2; |
|
| 321 | - if ($counter === 1) { |
|
| 322 | - $source = $trashRoot . '/files/' . $file['name'] . '.d' . $file['mtime']; |
|
| 323 | - $target = Filesystem::normalizePath($trashRoot . '/files/' . $file['name'] . '.d' . $expireDate); |
|
| 324 | - $this->rootView->rename($source, $target); |
|
| 325 | - $file['mtime'] = $expireDate; |
|
| 326 | - } |
|
| 327 | - } |
|
| 328 | - return \OCA\Files\Helper::sortFiles($files, 'mtime'); |
|
| 329 | - } |
|
| 330 | - |
|
| 331 | - |
|
| 332 | - /** |
|
| 333 | - * test expiration of old files in the trash bin until the max size |
|
| 334 | - * of the trash bin is met again |
|
| 335 | - */ |
|
| 336 | - public function testExpireOldFilesUtilLimitsAreMet(): void { |
|
| 337 | - |
|
| 338 | - // create some files |
|
| 339 | - Filesystem::file_put_contents('file1.txt', 'file1'); |
|
| 340 | - Filesystem::file_put_contents('file2.txt', 'file2'); |
|
| 341 | - Filesystem::file_put_contents('file3.txt', 'file3'); |
|
| 342 | - |
|
| 343 | - // delete them so that they end up in the trash bin |
|
| 344 | - Filesystem::unlink('file3.txt'); |
|
| 345 | - sleep(1); // make sure that every file has a unique mtime |
|
| 346 | - Filesystem::unlink('file2.txt'); |
|
| 347 | - sleep(1); // make sure that every file has a unique mtime |
|
| 348 | - Filesystem::unlink('file1.txt'); |
|
| 349 | - |
|
| 350 | - //make sure that files are in the trash bin |
|
| 351 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 352 | - $this->assertSame(3, count($filesInTrash)); |
|
| 353 | - |
|
| 354 | - $testClass = new TrashbinForTesting(); |
|
| 355 | - $sizeOfDeletedFiles = $testClass->dummyDeleteFiles($filesInTrash, -8); |
|
| 356 | - |
|
| 357 | - // the two oldest files (file3.txt and file2.txt) should be deleted |
|
| 358 | - $this->assertSame(10, $sizeOfDeletedFiles); |
|
| 359 | - |
|
| 360 | - $newTrashContent = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); |
|
| 361 | - $this->assertSame(1, count($newTrashContent)); |
|
| 362 | - $element = reset($newTrashContent); |
|
| 363 | - $this->assertSame('file1.txt', $element['name']); |
|
| 364 | - } |
|
| 365 | - |
|
| 366 | - /** |
|
| 367 | - * Test restoring a file |
|
| 368 | - */ |
|
| 369 | - public function testRestoreFileInRoot(): void { |
|
| 370 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 371 | - $file = $userFolder->newFile('file1.txt'); |
|
| 372 | - $file->putContent('foo'); |
|
| 373 | - |
|
| 374 | - $this->assertTrue($userFolder->nodeExists('file1.txt')); |
|
| 375 | - |
|
| 376 | - $file->delete(); |
|
| 377 | - |
|
| 378 | - $this->assertFalse($userFolder->nodeExists('file1.txt')); |
|
| 379 | - |
|
| 380 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 381 | - $this->assertCount(1, $filesInTrash); |
|
| 382 | - |
|
| 383 | - /** @var FileInfo */ |
|
| 384 | - $trashedFile = $filesInTrash[0]; |
|
| 385 | - |
|
| 386 | - $this->assertTrue( |
|
| 387 | - Trashbin::restore( |
|
| 388 | - 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 389 | - $trashedFile->getName(), |
|
| 390 | - $trashedFile->getMtime() |
|
| 391 | - ) |
|
| 392 | - ); |
|
| 393 | - |
|
| 394 | - $file = $userFolder->get('file1.txt'); |
|
| 395 | - $this->assertEquals('foo', $file->getContent()); |
|
| 396 | - } |
|
| 397 | - |
|
| 398 | - /** |
|
| 399 | - * Test restoring a file in subfolder |
|
| 400 | - */ |
|
| 401 | - public function testRestoreFileInSubfolder(): void { |
|
| 402 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 403 | - $folder = $userFolder->newFolder('folder'); |
|
| 404 | - $file = $folder->newFile('file1.txt'); |
|
| 405 | - $file->putContent('foo'); |
|
| 406 | - |
|
| 407 | - $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 408 | - |
|
| 409 | - $file->delete(); |
|
| 410 | - |
|
| 411 | - $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 412 | - |
|
| 413 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 414 | - $this->assertCount(1, $filesInTrash); |
|
| 415 | - |
|
| 416 | - /** @var FileInfo */ |
|
| 417 | - $trashedFile = $filesInTrash[0]; |
|
| 418 | - |
|
| 419 | - $this->assertTrue( |
|
| 420 | - Trashbin::restore( |
|
| 421 | - 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 422 | - $trashedFile->getName(), |
|
| 423 | - $trashedFile->getMtime() |
|
| 424 | - ) |
|
| 425 | - ); |
|
| 426 | - |
|
| 427 | - $file = $userFolder->get('folder/file1.txt'); |
|
| 428 | - $this->assertEquals('foo', $file->getContent()); |
|
| 429 | - } |
|
| 430 | - |
|
| 431 | - /** |
|
| 432 | - * Test restoring a folder |
|
| 433 | - */ |
|
| 434 | - public function testRestoreFolder(): void { |
|
| 435 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 436 | - $folder = $userFolder->newFolder('folder'); |
|
| 437 | - $file = $folder->newFile('file1.txt'); |
|
| 438 | - $file->putContent('foo'); |
|
| 439 | - |
|
| 440 | - $this->assertTrue($userFolder->nodeExists('folder')); |
|
| 441 | - |
|
| 442 | - $folder->delete(); |
|
| 443 | - |
|
| 444 | - $this->assertFalse($userFolder->nodeExists('folder')); |
|
| 445 | - |
|
| 446 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 447 | - $this->assertCount(1, $filesInTrash); |
|
| 36 | + public const TEST_TRASHBIN_USER1 = 'test-trashbin-user1'; |
|
| 37 | + public const TEST_TRASHBIN_USER2 = 'test-trashbin-user2'; |
|
| 38 | + |
|
| 39 | + private $trashRoot1; |
|
| 40 | + private $trashRoot2; |
|
| 41 | + |
|
| 42 | + private static $rememberRetentionObligation; |
|
| 43 | + |
|
| 44 | + /** |
|
| 45 | + * @var bool |
|
| 46 | + */ |
|
| 47 | + private static $trashBinStatus; |
|
| 48 | + |
|
| 49 | + /** |
|
| 50 | + * @var View |
|
| 51 | + */ |
|
| 52 | + private $rootView; |
|
| 53 | + |
|
| 54 | + public static function setUpBeforeClass(): void { |
|
| 55 | + parent::setUpBeforeClass(); |
|
| 56 | + |
|
| 57 | + $appManager = Server::get(IAppManager::class); |
|
| 58 | + self::$trashBinStatus = $appManager->isEnabledForUser('files_trashbin'); |
|
| 59 | + |
|
| 60 | + // reset backend |
|
| 61 | + Server::get(IUserManager::class)->clearBackends(); |
|
| 62 | + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 63 | + |
|
| 64 | + // clear share hooks |
|
| 65 | + \OC_Hook::clear('OCP\\Share'); |
|
| 66 | + \OC::registerShareHooks(Server::get(SystemConfig::class)); |
|
| 67 | + |
|
| 68 | + // init files sharing |
|
| 69 | + new Application(); |
|
| 70 | + |
|
| 71 | + //disable encryption |
|
| 72 | + Server::get(IAppManager::class)->disableApp('encryption'); |
|
| 73 | + |
|
| 74 | + $config = Server::get(IConfig::class); |
|
| 75 | + //configure trashbin |
|
| 76 | + self::$rememberRetentionObligation = $config->getSystemValue('trashbin_retention_obligation', Expiration::DEFAULT_RETENTION_OBLIGATION); |
|
| 77 | + /** @var Expiration $expiration */ |
|
| 78 | + $expiration = Server::get(Expiration::class); |
|
| 79 | + $expiration->setRetentionObligation('auto, 2'); |
|
| 80 | + |
|
| 81 | + // register trashbin hooks |
|
| 82 | + $trashbinApp = new TrashbinApplication(); |
|
| 83 | + $trashbinApp->boot(new BootContext(new DIContainer('', [], \OC::$server))); |
|
| 84 | + |
|
| 85 | + // create test user |
|
| 86 | + self::loginHelper(self::TEST_TRASHBIN_USER2, true); |
|
| 87 | + self::loginHelper(self::TEST_TRASHBIN_USER1, true); |
|
| 88 | + } |
|
| 89 | + |
|
| 90 | + |
|
| 91 | + public static function tearDownAfterClass(): void { |
|
| 92 | + // cleanup test user |
|
| 93 | + $user = Server::get(IUserManager::class)->get(self::TEST_TRASHBIN_USER1); |
|
| 94 | + if ($user !== null) { |
|
| 95 | + $user->delete(); |
|
| 96 | + } |
|
| 97 | + |
|
| 98 | + /** @var Expiration $expiration */ |
|
| 99 | + $expiration = Server::get(Expiration::class); |
|
| 100 | + $expiration->setRetentionObligation(self::$rememberRetentionObligation); |
|
| 101 | + |
|
| 102 | + \OC_Hook::clear(); |
|
| 103 | + |
|
| 104 | + Filesystem::getLoader()->removeStorageWrapper('oc_trashbin'); |
|
| 105 | + |
|
| 106 | + if (self::$trashBinStatus) { |
|
| 107 | + Server::get(IAppManager::class)->enableApp('files_trashbin'); |
|
| 108 | + } |
|
| 109 | + |
|
| 110 | + parent::tearDownAfterClass(); |
|
| 111 | + } |
|
| 112 | + |
|
| 113 | + protected function setUp(): void { |
|
| 114 | + parent::setUp(); |
|
| 115 | + |
|
| 116 | + Server::get(IAppManager::class)->enableApp('files_trashbin'); |
|
| 117 | + $config = Server::get(IConfig::class); |
|
| 118 | + $mockConfig = $this->createMock(IConfig::class); |
|
| 119 | + $mockConfig |
|
| 120 | + ->method('getSystemValue') |
|
| 121 | + ->willReturnCallback(static function ($key, $default) use ($config) { |
|
| 122 | + if ($key === 'filesystem_check_changes') { |
|
| 123 | + return Watcher::CHECK_ONCE; |
|
| 124 | + } else { |
|
| 125 | + return $config->getSystemValue($key, $default); |
|
| 126 | + } |
|
| 127 | + }); |
|
| 128 | + $mockConfig |
|
| 129 | + ->method('getUserValue') |
|
| 130 | + ->willReturnCallback(static function ($userId, $appName, $key, $default = '') use ($config) { |
|
| 131 | + return $config->getUserValue($userId, $appName, $key, $default); |
|
| 132 | + }); |
|
| 133 | + $mockConfig |
|
| 134 | + ->method('getAppValue') |
|
| 135 | + ->willReturnCallback(static function ($appName, $key, $default = '') use ($config) { |
|
| 136 | + return $config->getAppValue($appName, $key, $default); |
|
| 137 | + }); |
|
| 138 | + $this->overwriteService(AllConfig::class, $mockConfig); |
|
| 139 | + |
|
| 140 | + $this->trashRoot1 = '/' . self::TEST_TRASHBIN_USER1 . '/files_trashbin'; |
|
| 141 | + $this->trashRoot2 = '/' . self::TEST_TRASHBIN_USER2 . '/files_trashbin'; |
|
| 142 | + $this->rootView = new View(); |
|
| 143 | + self::loginHelper(self::TEST_TRASHBIN_USER1); |
|
| 144 | + } |
|
| 145 | + |
|
| 146 | + protected function tearDown(): void { |
|
| 147 | + $this->restoreService(AllConfig::class); |
|
| 148 | + // disable trashbin to be able to properly clean up |
|
| 149 | + Server::get(IAppManager::class)->disableApp('files_trashbin'); |
|
| 150 | + |
|
| 151 | + $this->rootView->deleteAll('/' . self::TEST_TRASHBIN_USER1 . '/files'); |
|
| 152 | + $this->rootView->deleteAll('/' . self::TEST_TRASHBIN_USER2 . '/files'); |
|
| 153 | + $this->rootView->deleteAll($this->trashRoot1); |
|
| 154 | + $this->rootView->deleteAll($this->trashRoot2); |
|
| 155 | + |
|
| 156 | + // clear trash table |
|
| 157 | + $connection = Server::get(IDBConnection::class); |
|
| 158 | + $connection->executeUpdate('DELETE FROM `*PREFIX*files_trash`'); |
|
| 159 | + |
|
| 160 | + parent::tearDown(); |
|
| 161 | + } |
|
| 162 | + |
|
| 163 | + /** |
|
| 164 | + * test expiration of files older then the max storage time defined for the trash |
|
| 165 | + */ |
|
| 166 | + public function testExpireOldFiles(): void { |
|
| 167 | + |
|
| 168 | + /** @var ITimeFactory $time */ |
|
| 169 | + $time = Server::get(ITimeFactory::class); |
|
| 170 | + $currentTime = $time->getTime(); |
|
| 171 | + $expireAt = $currentTime - 2 * 24 * 60 * 60; |
|
| 172 | + $expiredDate = $currentTime - 3 * 24 * 60 * 60; |
|
| 173 | + |
|
| 174 | + // create some files |
|
| 175 | + Filesystem::file_put_contents('file1.txt', 'file1'); |
|
| 176 | + Filesystem::file_put_contents('file2.txt', 'file2'); |
|
| 177 | + Filesystem::file_put_contents('file3.txt', 'file3'); |
|
| 178 | + |
|
| 179 | + // delete them so that they end up in the trash bin |
|
| 180 | + Filesystem::unlink('file1.txt'); |
|
| 181 | + Filesystem::unlink('file2.txt'); |
|
| 182 | + Filesystem::unlink('file3.txt'); |
|
| 183 | + |
|
| 184 | + //make sure that files are in the trash bin |
|
| 185 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'name'); |
|
| 186 | + $this->assertSame(3, count($filesInTrash)); |
|
| 187 | + |
|
| 188 | + // every second file will get a date in the past so that it will get expired |
|
| 189 | + $manipulatedList = $this->manipulateDeleteTime($filesInTrash, $this->trashRoot1, $expiredDate); |
|
| 190 | + |
|
| 191 | + $testClass = new TrashbinForTesting(); |
|
| 192 | + [$sizeOfDeletedFiles, $count] = $testClass->dummyDeleteExpiredFiles($manipulatedList, $expireAt); |
|
| 193 | + |
|
| 194 | + $this->assertSame(10, $sizeOfDeletedFiles); |
|
| 195 | + $this->assertSame(2, $count); |
|
| 196 | + |
|
| 197 | + // only file2.txt should be left |
|
| 198 | + $remainingFiles = array_slice($manipulatedList, $count); |
|
| 199 | + $this->assertSame(1, count($remainingFiles)); |
|
| 200 | + $remainingFile = reset($remainingFiles); |
|
| 201 | + // TODO: failing test |
|
| 202 | + #$this->assertSame('file2.txt', $remainingFile['name']); |
|
| 203 | + |
|
| 204 | + // check that file1.txt and file3.txt was really deleted |
|
| 205 | + $newTrashContent = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); |
|
| 206 | + $this->assertSame(1, count($newTrashContent)); |
|
| 207 | + $element = reset($newTrashContent); |
|
| 208 | + // TODO: failing test |
|
| 209 | + #$this->assertSame('file2.txt', $element['name']); |
|
| 210 | + } |
|
| 211 | + |
|
| 212 | + /** |
|
| 213 | + * test expiration of files older then the max storage time defined for the trash |
|
| 214 | + * in this test we delete a shared file and check if both trash bins, the one from |
|
| 215 | + * the owner of the file and the one from the user who deleted the file get expired |
|
| 216 | + * correctly |
|
| 217 | + */ |
|
| 218 | + public function testExpireOldFilesShared(): void { |
|
| 219 | + $currentTime = time(); |
|
| 220 | + $folder = 'trashTest-' . $currentTime . '/'; |
|
| 221 | + $expiredDate = $currentTime - 3 * 24 * 60 * 60; |
|
| 222 | + |
|
| 223 | + // create some files |
|
| 224 | + Filesystem::mkdir($folder); |
|
| 225 | + Filesystem::file_put_contents($folder . 'user1-1.txt', 'file1'); |
|
| 226 | + Filesystem::file_put_contents($folder . 'user1-2.txt', 'file2'); |
|
| 227 | + Filesystem::file_put_contents($folder . 'user1-3.txt', 'file3'); |
|
| 228 | + Filesystem::file_put_contents($folder . 'user1-4.txt', 'file4'); |
|
| 229 | + |
|
| 230 | + //share user1-4.txt with user2 |
|
| 231 | + $node = \OC::$server->getUserFolder(self::TEST_TRASHBIN_USER1)->get($folder); |
|
| 232 | + $share = Server::get(\OCP\Share\IManager::class)->newShare(); |
|
| 233 | + $share->setShareType(IShare::TYPE_USER) |
|
| 234 | + ->setNode($node) |
|
| 235 | + ->setSharedBy(self::TEST_TRASHBIN_USER1) |
|
| 236 | + ->setSharedWith(self::TEST_TRASHBIN_USER2) |
|
| 237 | + ->setPermissions(Constants::PERMISSION_ALL); |
|
| 238 | + $share = Server::get(\OCP\Share\IManager::class)->createShare($share); |
|
| 239 | + Server::get(\OCP\Share\IManager::class)->acceptShare($share, self::TEST_TRASHBIN_USER2); |
|
| 240 | + |
|
| 241 | + // delete them so that they end up in the trash bin |
|
| 242 | + Filesystem::unlink($folder . 'user1-1.txt'); |
|
| 243 | + Filesystem::unlink($folder . 'user1-2.txt'); |
|
| 244 | + Filesystem::unlink($folder . 'user1-3.txt'); |
|
| 245 | + |
|
| 246 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'name'); |
|
| 247 | + $this->assertSame(3, count($filesInTrash)); |
|
| 248 | + |
|
| 249 | + // every second file will get a date in the past so that it will get expired |
|
| 250 | + $this->manipulateDeleteTime($filesInTrash, $this->trashRoot1, $expiredDate); |
|
| 251 | + |
|
| 252 | + // login as user2 |
|
| 253 | + self::loginHelper(self::TEST_TRASHBIN_USER2); |
|
| 254 | + |
|
| 255 | + $this->assertTrue(Filesystem::file_exists($folder . 'user1-4.txt')); |
|
| 256 | + |
|
| 257 | + // create some files |
|
| 258 | + Filesystem::file_put_contents('user2-1.txt', 'file1'); |
|
| 259 | + Filesystem::file_put_contents('user2-2.txt', 'file2'); |
|
| 260 | + |
|
| 261 | + // delete them so that they end up in the trash bin |
|
| 262 | + Filesystem::unlink('user2-1.txt'); |
|
| 263 | + Filesystem::unlink('user2-2.txt'); |
|
| 264 | + |
|
| 265 | + $filesInTrashUser2 = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2, 'name'); |
|
| 266 | + $this->assertSame(2, count($filesInTrashUser2)); |
|
| 267 | + |
|
| 268 | + // every second file will get a date in the past so that it will get expired |
|
| 269 | + $this->manipulateDeleteTime($filesInTrashUser2, $this->trashRoot2, $expiredDate); |
|
| 270 | + |
|
| 271 | + Filesystem::unlink($folder . 'user1-4.txt'); |
|
| 272 | + |
|
| 273 | + $this->runCommands(); |
|
| 274 | + |
|
| 275 | + $filesInTrashUser2AfterDelete = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER2); |
|
| 276 | + |
|
| 277 | + // user2-1.txt should have been expired |
|
| 278 | + $this->verifyArray($filesInTrashUser2AfterDelete, ['user2-2.txt', 'user1-4.txt']); |
|
| 279 | + |
|
| 280 | + self::loginHelper(self::TEST_TRASHBIN_USER1); |
|
| 281 | + |
|
| 282 | + // user1-1.txt and user1-3.txt should have been expired |
|
| 283 | + $filesInTrashUser1AfterDelete = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); |
|
| 284 | + |
|
| 285 | + $this->verifyArray($filesInTrashUser1AfterDelete, ['user1-2.txt', 'user1-4.txt']); |
|
| 286 | + } |
|
| 287 | + |
|
| 288 | + /** |
|
| 289 | + * verify that the array contains the expected results |
|
| 290 | + * |
|
| 291 | + * @param FileInfo[] $result |
|
| 292 | + * @param string[] $expected |
|
| 293 | + */ |
|
| 294 | + private function verifyArray($result, $expected) { |
|
| 295 | + $this->assertSame(count($expected), count($result)); |
|
| 296 | + foreach ($expected as $expectedFile) { |
|
| 297 | + $found = false; |
|
| 298 | + foreach ($result as $fileInTrash) { |
|
| 299 | + if ($expectedFile === $fileInTrash['name']) { |
|
| 300 | + $found = true; |
|
| 301 | + break; |
|
| 302 | + } |
|
| 303 | + } |
|
| 304 | + if (!$found) { |
|
| 305 | + // if we didn't found the expected file, something went wrong |
|
| 306 | + $this->assertTrue(false, "can't find expected file '" . $expectedFile . "' in trash bin"); |
|
| 307 | + } |
|
| 308 | + } |
|
| 309 | + } |
|
| 310 | + |
|
| 311 | + /** |
|
| 312 | + * @param FileInfo[] $files |
|
| 313 | + * @param string $trashRoot |
|
| 314 | + * @param integer $expireDate |
|
| 315 | + */ |
|
| 316 | + private function manipulateDeleteTime($files, $trashRoot, $expireDate) { |
|
| 317 | + $counter = 0; |
|
| 318 | + foreach ($files as &$file) { |
|
| 319 | + // modify every second file |
|
| 320 | + $counter = ($counter + 1) % 2; |
|
| 321 | + if ($counter === 1) { |
|
| 322 | + $source = $trashRoot . '/files/' . $file['name'] . '.d' . $file['mtime']; |
|
| 323 | + $target = Filesystem::normalizePath($trashRoot . '/files/' . $file['name'] . '.d' . $expireDate); |
|
| 324 | + $this->rootView->rename($source, $target); |
|
| 325 | + $file['mtime'] = $expireDate; |
|
| 326 | + } |
|
| 327 | + } |
|
| 328 | + return \OCA\Files\Helper::sortFiles($files, 'mtime'); |
|
| 329 | + } |
|
| 330 | + |
|
| 331 | + |
|
| 332 | + /** |
|
| 333 | + * test expiration of old files in the trash bin until the max size |
|
| 334 | + * of the trash bin is met again |
|
| 335 | + */ |
|
| 336 | + public function testExpireOldFilesUtilLimitsAreMet(): void { |
|
| 337 | + |
|
| 338 | + // create some files |
|
| 339 | + Filesystem::file_put_contents('file1.txt', 'file1'); |
|
| 340 | + Filesystem::file_put_contents('file2.txt', 'file2'); |
|
| 341 | + Filesystem::file_put_contents('file3.txt', 'file3'); |
|
| 342 | + |
|
| 343 | + // delete them so that they end up in the trash bin |
|
| 344 | + Filesystem::unlink('file3.txt'); |
|
| 345 | + sleep(1); // make sure that every file has a unique mtime |
|
| 346 | + Filesystem::unlink('file2.txt'); |
|
| 347 | + sleep(1); // make sure that every file has a unique mtime |
|
| 348 | + Filesystem::unlink('file1.txt'); |
|
| 349 | + |
|
| 350 | + //make sure that files are in the trash bin |
|
| 351 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 352 | + $this->assertSame(3, count($filesInTrash)); |
|
| 353 | + |
|
| 354 | + $testClass = new TrashbinForTesting(); |
|
| 355 | + $sizeOfDeletedFiles = $testClass->dummyDeleteFiles($filesInTrash, -8); |
|
| 356 | + |
|
| 357 | + // the two oldest files (file3.txt and file2.txt) should be deleted |
|
| 358 | + $this->assertSame(10, $sizeOfDeletedFiles); |
|
| 359 | + |
|
| 360 | + $newTrashContent = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); |
|
| 361 | + $this->assertSame(1, count($newTrashContent)); |
|
| 362 | + $element = reset($newTrashContent); |
|
| 363 | + $this->assertSame('file1.txt', $element['name']); |
|
| 364 | + } |
|
| 365 | + |
|
| 366 | + /** |
|
| 367 | + * Test restoring a file |
|
| 368 | + */ |
|
| 369 | + public function testRestoreFileInRoot(): void { |
|
| 370 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 371 | + $file = $userFolder->newFile('file1.txt'); |
|
| 372 | + $file->putContent('foo'); |
|
| 373 | + |
|
| 374 | + $this->assertTrue($userFolder->nodeExists('file1.txt')); |
|
| 375 | + |
|
| 376 | + $file->delete(); |
|
| 377 | + |
|
| 378 | + $this->assertFalse($userFolder->nodeExists('file1.txt')); |
|
| 379 | + |
|
| 380 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 381 | + $this->assertCount(1, $filesInTrash); |
|
| 382 | + |
|
| 383 | + /** @var FileInfo */ |
|
| 384 | + $trashedFile = $filesInTrash[0]; |
|
| 385 | + |
|
| 386 | + $this->assertTrue( |
|
| 387 | + Trashbin::restore( |
|
| 388 | + 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 389 | + $trashedFile->getName(), |
|
| 390 | + $trashedFile->getMtime() |
|
| 391 | + ) |
|
| 392 | + ); |
|
| 393 | + |
|
| 394 | + $file = $userFolder->get('file1.txt'); |
|
| 395 | + $this->assertEquals('foo', $file->getContent()); |
|
| 396 | + } |
|
| 397 | + |
|
| 398 | + /** |
|
| 399 | + * Test restoring a file in subfolder |
|
| 400 | + */ |
|
| 401 | + public function testRestoreFileInSubfolder(): void { |
|
| 402 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 403 | + $folder = $userFolder->newFolder('folder'); |
|
| 404 | + $file = $folder->newFile('file1.txt'); |
|
| 405 | + $file->putContent('foo'); |
|
| 406 | + |
|
| 407 | + $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 408 | + |
|
| 409 | + $file->delete(); |
|
| 410 | + |
|
| 411 | + $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 412 | + |
|
| 413 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 414 | + $this->assertCount(1, $filesInTrash); |
|
| 415 | + |
|
| 416 | + /** @var FileInfo */ |
|
| 417 | + $trashedFile = $filesInTrash[0]; |
|
| 418 | + |
|
| 419 | + $this->assertTrue( |
|
| 420 | + Trashbin::restore( |
|
| 421 | + 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 422 | + $trashedFile->getName(), |
|
| 423 | + $trashedFile->getMtime() |
|
| 424 | + ) |
|
| 425 | + ); |
|
| 426 | + |
|
| 427 | + $file = $userFolder->get('folder/file1.txt'); |
|
| 428 | + $this->assertEquals('foo', $file->getContent()); |
|
| 429 | + } |
|
| 430 | + |
|
| 431 | + /** |
|
| 432 | + * Test restoring a folder |
|
| 433 | + */ |
|
| 434 | + public function testRestoreFolder(): void { |
|
| 435 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 436 | + $folder = $userFolder->newFolder('folder'); |
|
| 437 | + $file = $folder->newFile('file1.txt'); |
|
| 438 | + $file->putContent('foo'); |
|
| 439 | + |
|
| 440 | + $this->assertTrue($userFolder->nodeExists('folder')); |
|
| 441 | + |
|
| 442 | + $folder->delete(); |
|
| 443 | + |
|
| 444 | + $this->assertFalse($userFolder->nodeExists('folder')); |
|
| 445 | + |
|
| 446 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 447 | + $this->assertCount(1, $filesInTrash); |
|
| 448 | 448 | |
| 449 | - /** @var FileInfo */ |
|
| 450 | - $trashedFolder = $filesInTrash[0]; |
|
| 449 | + /** @var FileInfo */ |
|
| 450 | + $trashedFolder = $filesInTrash[0]; |
|
| 451 | 451 | |
| 452 | - $this->assertTrue( |
|
| 453 | - Trashbin::restore( |
|
| 454 | - 'folder.d' . $trashedFolder->getMtime(), |
|
| 455 | - $trashedFolder->getName(), |
|
| 456 | - $trashedFolder->getMtime() |
|
| 457 | - ) |
|
| 458 | - ); |
|
| 452 | + $this->assertTrue( |
|
| 453 | + Trashbin::restore( |
|
| 454 | + 'folder.d' . $trashedFolder->getMtime(), |
|
| 455 | + $trashedFolder->getName(), |
|
| 456 | + $trashedFolder->getMtime() |
|
| 457 | + ) |
|
| 458 | + ); |
|
| 459 | 459 | |
| 460 | - $file = $userFolder->get('folder/file1.txt'); |
|
| 461 | - $this->assertEquals('foo', $file->getContent()); |
|
| 462 | - } |
|
| 463 | - |
|
| 464 | - /** |
|
| 465 | - * Test restoring a file from inside a trashed folder |
|
| 466 | - */ |
|
| 467 | - public function testRestoreFileFromTrashedSubfolder(): void { |
|
| 468 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 469 | - $folder = $userFolder->newFolder('folder'); |
|
| 470 | - $file = $folder->newFile('file1.txt'); |
|
| 471 | - $file->putContent('foo'); |
|
| 460 | + $file = $userFolder->get('folder/file1.txt'); |
|
| 461 | + $this->assertEquals('foo', $file->getContent()); |
|
| 462 | + } |
|
| 463 | + |
|
| 464 | + /** |
|
| 465 | + * Test restoring a file from inside a trashed folder |
|
| 466 | + */ |
|
| 467 | + public function testRestoreFileFromTrashedSubfolder(): void { |
|
| 468 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 469 | + $folder = $userFolder->newFolder('folder'); |
|
| 470 | + $file = $folder->newFile('file1.txt'); |
|
| 471 | + $file->putContent('foo'); |
|
| 472 | 472 | |
| 473 | - $this->assertTrue($userFolder->nodeExists('folder')); |
|
| 473 | + $this->assertTrue($userFolder->nodeExists('folder')); |
|
| 474 | 474 | |
| 475 | - $folder->delete(); |
|
| 476 | - |
|
| 477 | - $this->assertFalse($userFolder->nodeExists('folder')); |
|
| 478 | - |
|
| 479 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 480 | - $this->assertCount(1, $filesInTrash); |
|
| 481 | - |
|
| 482 | - /** @var FileInfo */ |
|
| 483 | - $trashedFile = $filesInTrash[0]; |
|
| 484 | - |
|
| 485 | - $this->assertTrue( |
|
| 486 | - Trashbin::restore( |
|
| 487 | - 'folder.d' . $trashedFile->getMtime() . '/file1.txt', |
|
| 488 | - 'file1.txt', |
|
| 489 | - $trashedFile->getMtime() |
|
| 490 | - ) |
|
| 491 | - ); |
|
| 475 | + $folder->delete(); |
|
| 476 | + |
|
| 477 | + $this->assertFalse($userFolder->nodeExists('folder')); |
|
| 478 | + |
|
| 479 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 480 | + $this->assertCount(1, $filesInTrash); |
|
| 481 | + |
|
| 482 | + /** @var FileInfo */ |
|
| 483 | + $trashedFile = $filesInTrash[0]; |
|
| 484 | + |
|
| 485 | + $this->assertTrue( |
|
| 486 | + Trashbin::restore( |
|
| 487 | + 'folder.d' . $trashedFile->getMtime() . '/file1.txt', |
|
| 488 | + 'file1.txt', |
|
| 489 | + $trashedFile->getMtime() |
|
| 490 | + ) |
|
| 491 | + ); |
|
| 492 | 492 | |
| 493 | - $file = $userFolder->get('file1.txt'); |
|
| 494 | - $this->assertEquals('foo', $file->getContent()); |
|
| 495 | - } |
|
| 493 | + $file = $userFolder->get('file1.txt'); |
|
| 494 | + $this->assertEquals('foo', $file->getContent()); |
|
| 495 | + } |
|
| 496 | 496 | |
| 497 | - /** |
|
| 498 | - * Test restoring a file whenever the source folder was removed. |
|
| 499 | - * The file should then land in the root. |
|
| 500 | - */ |
|
| 501 | - public function testRestoreFileWithMissingSourceFolder(): void { |
|
| 502 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 503 | - $folder = $userFolder->newFolder('folder'); |
|
| 504 | - $file = $folder->newFile('file1.txt'); |
|
| 505 | - $file->putContent('foo'); |
|
| 497 | + /** |
|
| 498 | + * Test restoring a file whenever the source folder was removed. |
|
| 499 | + * The file should then land in the root. |
|
| 500 | + */ |
|
| 501 | + public function testRestoreFileWithMissingSourceFolder(): void { |
|
| 502 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 503 | + $folder = $userFolder->newFolder('folder'); |
|
| 504 | + $file = $folder->newFile('file1.txt'); |
|
| 505 | + $file->putContent('foo'); |
|
| 506 | 506 | |
| 507 | - $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 507 | + $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 508 | 508 | |
| 509 | - $file->delete(); |
|
| 509 | + $file->delete(); |
|
| 510 | 510 | |
| 511 | - $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 512 | - |
|
| 513 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 514 | - $this->assertCount(1, $filesInTrash); |
|
| 515 | - |
|
| 516 | - /** @var FileInfo */ |
|
| 517 | - $trashedFile = $filesInTrash[0]; |
|
| 518 | - |
|
| 519 | - // delete source folder |
|
| 520 | - $folder->delete(); |
|
| 521 | - |
|
| 522 | - $this->assertTrue( |
|
| 523 | - Trashbin::restore( |
|
| 524 | - 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 525 | - $trashedFile->getName(), |
|
| 526 | - $trashedFile->getMtime() |
|
| 527 | - ) |
|
| 528 | - ); |
|
| 529 | - |
|
| 530 | - $file = $userFolder->get('file1.txt'); |
|
| 531 | - $this->assertEquals('foo', $file->getContent()); |
|
| 532 | - } |
|
| 533 | - |
|
| 534 | - /** |
|
| 535 | - * Test restoring a file in the root folder whenever there is another file |
|
| 536 | - * with the same name in the root folder |
|
| 537 | - */ |
|
| 538 | - public function testRestoreFileDoesNotOverwriteExistingInRoot(): void { |
|
| 539 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 540 | - $file = $userFolder->newFile('file1.txt'); |
|
| 541 | - $file->putContent('foo'); |
|
| 542 | - |
|
| 543 | - $this->assertTrue($userFolder->nodeExists('file1.txt')); |
|
| 544 | - |
|
| 545 | - $file->delete(); |
|
| 546 | - |
|
| 547 | - $this->assertFalse($userFolder->nodeExists('file1.txt')); |
|
| 548 | - |
|
| 549 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 550 | - $this->assertCount(1, $filesInTrash); |
|
| 551 | - |
|
| 552 | - /** @var FileInfo */ |
|
| 553 | - $trashedFile = $filesInTrash[0]; |
|
| 554 | - |
|
| 555 | - // create another file |
|
| 556 | - $file = $userFolder->newFile('file1.txt'); |
|
| 557 | - $file->putContent('bar'); |
|
| 558 | - |
|
| 559 | - $this->assertTrue( |
|
| 560 | - Trashbin::restore( |
|
| 561 | - 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 562 | - $trashedFile->getName(), |
|
| 563 | - $trashedFile->getMtime() |
|
| 564 | - ) |
|
| 565 | - ); |
|
| 566 | - |
|
| 567 | - $anotherFile = $userFolder->get('file1.txt'); |
|
| 568 | - $this->assertEquals('bar', $anotherFile->getContent()); |
|
| 569 | - |
|
| 570 | - $restoredFile = $userFolder->get('file1 (restored).txt'); |
|
| 571 | - $this->assertEquals('foo', $restoredFile->getContent()); |
|
| 572 | - } |
|
| 573 | - |
|
| 574 | - /** |
|
| 575 | - * Test restoring a file whenever there is another file |
|
| 576 | - * with the same name in the source folder |
|
| 577 | - */ |
|
| 578 | - public function testRestoreFileDoesNotOverwriteExistingInSubfolder(): void { |
|
| 579 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 580 | - $folder = $userFolder->newFolder('folder'); |
|
| 581 | - $file = $folder->newFile('file1.txt'); |
|
| 582 | - $file->putContent('foo'); |
|
| 583 | - |
|
| 584 | - $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 585 | - |
|
| 586 | - $file->delete(); |
|
| 587 | - |
|
| 588 | - $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 589 | - |
|
| 590 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 591 | - $this->assertCount(1, $filesInTrash); |
|
| 592 | - |
|
| 593 | - /** @var FileInfo */ |
|
| 594 | - $trashedFile = $filesInTrash[0]; |
|
| 595 | - |
|
| 596 | - // create another file |
|
| 597 | - $file = $folder->newFile('file1.txt'); |
|
| 598 | - $file->putContent('bar'); |
|
| 599 | - |
|
| 600 | - $this->assertTrue( |
|
| 601 | - Trashbin::restore( |
|
| 602 | - 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 603 | - $trashedFile->getName(), |
|
| 604 | - $trashedFile->getMtime() |
|
| 605 | - ) |
|
| 606 | - ); |
|
| 607 | - |
|
| 608 | - $anotherFile = $userFolder->get('folder/file1.txt'); |
|
| 609 | - $this->assertEquals('bar', $anotherFile->getContent()); |
|
| 610 | - |
|
| 611 | - $restoredFile = $userFolder->get('folder/file1 (restored).txt'); |
|
| 612 | - $this->assertEquals('foo', $restoredFile->getContent()); |
|
| 613 | - } |
|
| 614 | - |
|
| 615 | - /** |
|
| 616 | - * Test restoring a non-existing file from trashbin, returns false |
|
| 617 | - */ |
|
| 618 | - public function testRestoreUnexistingFile(): void { |
|
| 619 | - $this->assertFalse( |
|
| 620 | - Trashbin::restore( |
|
| 621 | - 'unexist.txt.d123456', |
|
| 622 | - 'unexist.txt', |
|
| 623 | - '123456' |
|
| 624 | - ) |
|
| 625 | - ); |
|
| 626 | - } |
|
| 627 | - |
|
| 628 | - /** |
|
| 629 | - * Test restoring a file into a read-only folder, will restore |
|
| 630 | - * the file to root instead |
|
| 631 | - */ |
|
| 632 | - public function testRestoreFileIntoReadOnlySourceFolder(): void { |
|
| 633 | - $userFolder = \OC::$server->getUserFolder(); |
|
| 634 | - $folder = $userFolder->newFolder('folder'); |
|
| 635 | - $file = $folder->newFile('file1.txt'); |
|
| 636 | - $file->putContent('foo'); |
|
| 637 | - |
|
| 638 | - $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 639 | - |
|
| 640 | - $file->delete(); |
|
| 641 | - |
|
| 642 | - $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 643 | - |
|
| 644 | - $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 645 | - $this->assertCount(1, $filesInTrash); |
|
| 646 | - |
|
| 647 | - /** @var FileInfo */ |
|
| 648 | - $trashedFile = $filesInTrash[0]; |
|
| 649 | - |
|
| 650 | - // delete source folder |
|
| 651 | - [$storage, $internalPath] = $this->rootView->resolvePath('/' . self::TEST_TRASHBIN_USER1 . '/files/folder'); |
|
| 652 | - if ($storage instanceof Local) { |
|
| 653 | - $folderAbsPath = $storage->getSourcePath($internalPath); |
|
| 654 | - // make folder read-only |
|
| 655 | - chmod($folderAbsPath, 0555); |
|
| 656 | - |
|
| 657 | - $this->assertTrue( |
|
| 658 | - Trashbin::restore( |
|
| 659 | - 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 660 | - $trashedFile->getName(), |
|
| 661 | - $trashedFile->getMtime() |
|
| 662 | - ) |
|
| 663 | - ); |
|
| 664 | - |
|
| 665 | - $file = $userFolder->get('file1.txt'); |
|
| 666 | - $this->assertEquals('foo', $file->getContent()); |
|
| 667 | - |
|
| 668 | - chmod($folderAbsPath, 0755); |
|
| 669 | - } |
|
| 670 | - } |
|
| 671 | - |
|
| 672 | - /** |
|
| 673 | - * @param string $user |
|
| 674 | - * @param bool $create |
|
| 675 | - */ |
|
| 676 | - public static function loginHelper($user, $create = false) { |
|
| 677 | - if ($create) { |
|
| 678 | - try { |
|
| 679 | - Server::get(IUserManager::class)->createUser($user, $user); |
|
| 680 | - } catch (\Exception $e) { // catch username is already being used from previous aborted runs |
|
| 681 | - } |
|
| 682 | - } |
|
| 683 | - |
|
| 684 | - \OC_Util::tearDownFS(); |
|
| 685 | - \OC_User::setUserId(''); |
|
| 686 | - Filesystem::tearDown(); |
|
| 687 | - \OC_User::setUserId($user); |
|
| 688 | - \OC_Util::setupFS($user); |
|
| 689 | - \OC::$server->getUserFolder($user); |
|
| 690 | - } |
|
| 511 | + $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 512 | + |
|
| 513 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 514 | + $this->assertCount(1, $filesInTrash); |
|
| 515 | + |
|
| 516 | + /** @var FileInfo */ |
|
| 517 | + $trashedFile = $filesInTrash[0]; |
|
| 518 | + |
|
| 519 | + // delete source folder |
|
| 520 | + $folder->delete(); |
|
| 521 | + |
|
| 522 | + $this->assertTrue( |
|
| 523 | + Trashbin::restore( |
|
| 524 | + 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 525 | + $trashedFile->getName(), |
|
| 526 | + $trashedFile->getMtime() |
|
| 527 | + ) |
|
| 528 | + ); |
|
| 529 | + |
|
| 530 | + $file = $userFolder->get('file1.txt'); |
|
| 531 | + $this->assertEquals('foo', $file->getContent()); |
|
| 532 | + } |
|
| 533 | + |
|
| 534 | + /** |
|
| 535 | + * Test restoring a file in the root folder whenever there is another file |
|
| 536 | + * with the same name in the root folder |
|
| 537 | + */ |
|
| 538 | + public function testRestoreFileDoesNotOverwriteExistingInRoot(): void { |
|
| 539 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 540 | + $file = $userFolder->newFile('file1.txt'); |
|
| 541 | + $file->putContent('foo'); |
|
| 542 | + |
|
| 543 | + $this->assertTrue($userFolder->nodeExists('file1.txt')); |
|
| 544 | + |
|
| 545 | + $file->delete(); |
|
| 546 | + |
|
| 547 | + $this->assertFalse($userFolder->nodeExists('file1.txt')); |
|
| 548 | + |
|
| 549 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 550 | + $this->assertCount(1, $filesInTrash); |
|
| 551 | + |
|
| 552 | + /** @var FileInfo */ |
|
| 553 | + $trashedFile = $filesInTrash[0]; |
|
| 554 | + |
|
| 555 | + // create another file |
|
| 556 | + $file = $userFolder->newFile('file1.txt'); |
|
| 557 | + $file->putContent('bar'); |
|
| 558 | + |
|
| 559 | + $this->assertTrue( |
|
| 560 | + Trashbin::restore( |
|
| 561 | + 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 562 | + $trashedFile->getName(), |
|
| 563 | + $trashedFile->getMtime() |
|
| 564 | + ) |
|
| 565 | + ); |
|
| 566 | + |
|
| 567 | + $anotherFile = $userFolder->get('file1.txt'); |
|
| 568 | + $this->assertEquals('bar', $anotherFile->getContent()); |
|
| 569 | + |
|
| 570 | + $restoredFile = $userFolder->get('file1 (restored).txt'); |
|
| 571 | + $this->assertEquals('foo', $restoredFile->getContent()); |
|
| 572 | + } |
|
| 573 | + |
|
| 574 | + /** |
|
| 575 | + * Test restoring a file whenever there is another file |
|
| 576 | + * with the same name in the source folder |
|
| 577 | + */ |
|
| 578 | + public function testRestoreFileDoesNotOverwriteExistingInSubfolder(): void { |
|
| 579 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 580 | + $folder = $userFolder->newFolder('folder'); |
|
| 581 | + $file = $folder->newFile('file1.txt'); |
|
| 582 | + $file->putContent('foo'); |
|
| 583 | + |
|
| 584 | + $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 585 | + |
|
| 586 | + $file->delete(); |
|
| 587 | + |
|
| 588 | + $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 589 | + |
|
| 590 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 591 | + $this->assertCount(1, $filesInTrash); |
|
| 592 | + |
|
| 593 | + /** @var FileInfo */ |
|
| 594 | + $trashedFile = $filesInTrash[0]; |
|
| 595 | + |
|
| 596 | + // create another file |
|
| 597 | + $file = $folder->newFile('file1.txt'); |
|
| 598 | + $file->putContent('bar'); |
|
| 599 | + |
|
| 600 | + $this->assertTrue( |
|
| 601 | + Trashbin::restore( |
|
| 602 | + 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 603 | + $trashedFile->getName(), |
|
| 604 | + $trashedFile->getMtime() |
|
| 605 | + ) |
|
| 606 | + ); |
|
| 607 | + |
|
| 608 | + $anotherFile = $userFolder->get('folder/file1.txt'); |
|
| 609 | + $this->assertEquals('bar', $anotherFile->getContent()); |
|
| 610 | + |
|
| 611 | + $restoredFile = $userFolder->get('folder/file1 (restored).txt'); |
|
| 612 | + $this->assertEquals('foo', $restoredFile->getContent()); |
|
| 613 | + } |
|
| 614 | + |
|
| 615 | + /** |
|
| 616 | + * Test restoring a non-existing file from trashbin, returns false |
|
| 617 | + */ |
|
| 618 | + public function testRestoreUnexistingFile(): void { |
|
| 619 | + $this->assertFalse( |
|
| 620 | + Trashbin::restore( |
|
| 621 | + 'unexist.txt.d123456', |
|
| 622 | + 'unexist.txt', |
|
| 623 | + '123456' |
|
| 624 | + ) |
|
| 625 | + ); |
|
| 626 | + } |
|
| 627 | + |
|
| 628 | + /** |
|
| 629 | + * Test restoring a file into a read-only folder, will restore |
|
| 630 | + * the file to root instead |
|
| 631 | + */ |
|
| 632 | + public function testRestoreFileIntoReadOnlySourceFolder(): void { |
|
| 633 | + $userFolder = \OC::$server->getUserFolder(); |
|
| 634 | + $folder = $userFolder->newFolder('folder'); |
|
| 635 | + $file = $folder->newFile('file1.txt'); |
|
| 636 | + $file->putContent('foo'); |
|
| 637 | + |
|
| 638 | + $this->assertTrue($userFolder->nodeExists('folder/file1.txt')); |
|
| 639 | + |
|
| 640 | + $file->delete(); |
|
| 641 | + |
|
| 642 | + $this->assertFalse($userFolder->nodeExists('folder/file1.txt')); |
|
| 643 | + |
|
| 644 | + $filesInTrash = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1, 'mtime'); |
|
| 645 | + $this->assertCount(1, $filesInTrash); |
|
| 646 | + |
|
| 647 | + /** @var FileInfo */ |
|
| 648 | + $trashedFile = $filesInTrash[0]; |
|
| 649 | + |
|
| 650 | + // delete source folder |
|
| 651 | + [$storage, $internalPath] = $this->rootView->resolvePath('/' . self::TEST_TRASHBIN_USER1 . '/files/folder'); |
|
| 652 | + if ($storage instanceof Local) { |
|
| 653 | + $folderAbsPath = $storage->getSourcePath($internalPath); |
|
| 654 | + // make folder read-only |
|
| 655 | + chmod($folderAbsPath, 0555); |
|
| 656 | + |
|
| 657 | + $this->assertTrue( |
|
| 658 | + Trashbin::restore( |
|
| 659 | + 'file1.txt.d' . $trashedFile->getMtime(), |
|
| 660 | + $trashedFile->getName(), |
|
| 661 | + $trashedFile->getMtime() |
|
| 662 | + ) |
|
| 663 | + ); |
|
| 664 | + |
|
| 665 | + $file = $userFolder->get('file1.txt'); |
|
| 666 | + $this->assertEquals('foo', $file->getContent()); |
|
| 667 | + |
|
| 668 | + chmod($folderAbsPath, 0755); |
|
| 669 | + } |
|
| 670 | + } |
|
| 671 | + |
|
| 672 | + /** |
|
| 673 | + * @param string $user |
|
| 674 | + * @param bool $create |
|
| 675 | + */ |
|
| 676 | + public static function loginHelper($user, $create = false) { |
|
| 677 | + if ($create) { |
|
| 678 | + try { |
|
| 679 | + Server::get(IUserManager::class)->createUser($user, $user); |
|
| 680 | + } catch (\Exception $e) { // catch username is already being used from previous aborted runs |
|
| 681 | + } |
|
| 682 | + } |
|
| 683 | + |
|
| 684 | + \OC_Util::tearDownFS(); |
|
| 685 | + \OC_User::setUserId(''); |
|
| 686 | + Filesystem::tearDown(); |
|
| 687 | + \OC_User::setUserId($user); |
|
| 688 | + \OC_Util::setupFS($user); |
|
| 689 | + \OC::$server->getUserFolder($user); |
|
| 690 | + } |
|
| 691 | 691 | } |
| 692 | 692 | |
| 693 | 693 | |
| 694 | 694 | // just a dummy class to make protected methods available for testing |
| 695 | 695 | class TrashbinForTesting extends Trashbin { |
| 696 | 696 | |
| 697 | - /** |
|
| 698 | - * @param FileInfo[] $files |
|
| 699 | - * @param integer $limit |
|
| 700 | - */ |
|
| 701 | - public function dummyDeleteExpiredFiles($files) { |
|
| 702 | - // dummy value for $retention_obligation because it is not needed here |
|
| 703 | - return parent::deleteExpiredFiles($files, TrashbinTest::TEST_TRASHBIN_USER1); |
|
| 704 | - } |
|
| 705 | - |
|
| 706 | - /** |
|
| 707 | - * @param FileInfo[] $files |
|
| 708 | - * @param integer $availableSpace |
|
| 709 | - */ |
|
| 710 | - public function dummyDeleteFiles($files, $availableSpace) { |
|
| 711 | - return parent::deleteFiles($files, TrashbinTest::TEST_TRASHBIN_USER1, $availableSpace); |
|
| 712 | - } |
|
| 697 | + /** |
|
| 698 | + * @param FileInfo[] $files |
|
| 699 | + * @param integer $limit |
|
| 700 | + */ |
|
| 701 | + public function dummyDeleteExpiredFiles($files) { |
|
| 702 | + // dummy value for $retention_obligation because it is not needed here |
|
| 703 | + return parent::deleteExpiredFiles($files, TrashbinTest::TEST_TRASHBIN_USER1); |
|
| 704 | + } |
|
| 705 | + |
|
| 706 | + /** |
|
| 707 | + * @param FileInfo[] $files |
|
| 708 | + * @param integer $availableSpace |
|
| 709 | + */ |
|
| 710 | + public function dummyDeleteFiles($files, $availableSpace) { |
|
| 711 | + return parent::deleteFiles($files, TrashbinTest::TEST_TRASHBIN_USER1, $availableSpace); |
|
| 712 | + } |
|
| 713 | 713 | } |
@@ -22,82 +22,82 @@ |
||
| 22 | 22 | * Base class for sharing tests. |
| 23 | 23 | */ |
| 24 | 24 | abstract class TestCase extends \Test\TestCase { |
| 25 | - public const TEST_FILES_SHARING_API_USER1 = 'test-share-user1'; |
|
| 26 | - public const TEST_FILES_SHARING_API_USER2 = 'test-share-user2'; |
|
| 27 | - |
|
| 28 | - public static function setUpBeforeClass(): void { |
|
| 29 | - parent::setUpBeforeClass(); |
|
| 30 | - |
|
| 31 | - // reset backend |
|
| 32 | - Server::get(IUserManager::class)->clearBackends(); |
|
| 33 | - Server::get(IGroupManager::class)->clearBackends(); |
|
| 34 | - |
|
| 35 | - // create users |
|
| 36 | - $backend = new \Test\Util\User\Dummy(); |
|
| 37 | - Server::get(IUserManager::class)->registerBackend($backend); |
|
| 38 | - $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); |
|
| 39 | - $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); |
|
| 40 | - } |
|
| 41 | - |
|
| 42 | - protected function setUp(): void { |
|
| 43 | - parent::setUp(); |
|
| 44 | - |
|
| 45 | - //login as user1 |
|
| 46 | - self::loginHelper(self::TEST_FILES_SHARING_API_USER1); |
|
| 47 | - } |
|
| 48 | - |
|
| 49 | - public static function tearDownAfterClass(): void { |
|
| 50 | - // cleanup users |
|
| 51 | - $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER1); |
|
| 52 | - if ($user !== null) { |
|
| 53 | - $user->delete(); |
|
| 54 | - } |
|
| 55 | - $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER2); |
|
| 56 | - if ($user !== null) { |
|
| 57 | - $user->delete(); |
|
| 58 | - } |
|
| 59 | - |
|
| 60 | - \OC_Util::tearDownFS(); |
|
| 61 | - \OC_User::setUserId(''); |
|
| 62 | - Filesystem::tearDown(); |
|
| 63 | - |
|
| 64 | - // reset backend |
|
| 65 | - Server::get(IUserManager::class)->clearBackends(); |
|
| 66 | - Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 67 | - Server::get(IGroupManager::class)->clearBackends(); |
|
| 68 | - Server::get(IGroupManager::class)->addBackend(new Database()); |
|
| 69 | - |
|
| 70 | - parent::tearDownAfterClass(); |
|
| 71 | - } |
|
| 72 | - |
|
| 73 | - /** |
|
| 74 | - * @param string $user |
|
| 75 | - * @param bool $create |
|
| 76 | - * @param bool $password |
|
| 77 | - */ |
|
| 78 | - protected static function loginHelper($user, $create = false, $password = false) { |
|
| 79 | - if ($password === false) { |
|
| 80 | - $password = $user; |
|
| 81 | - } |
|
| 82 | - |
|
| 83 | - if ($create) { |
|
| 84 | - $userManager = Server::get(IUserManager::class); |
|
| 85 | - $groupManager = Server::get(IGroupManager::class); |
|
| 86 | - |
|
| 87 | - $userObject = $userManager->createUser($user, $password); |
|
| 88 | - $group = $groupManager->createGroup('group'); |
|
| 89 | - |
|
| 90 | - if ($group and $userObject) { |
|
| 91 | - $group->addUser($userObject); |
|
| 92 | - } |
|
| 93 | - } |
|
| 94 | - |
|
| 95 | - \OC_Util::tearDownFS(); |
|
| 96 | - Server::get(IUserSession::class)->setUser(null); |
|
| 97 | - Filesystem::tearDown(); |
|
| 98 | - Server::get(IUserSession::class)->login($user, $password); |
|
| 99 | - \OC::$server->getUserFolder($user); |
|
| 100 | - |
|
| 101 | - \OC_Util::setupFS($user); |
|
| 102 | - } |
|
| 25 | + public const TEST_FILES_SHARING_API_USER1 = 'test-share-user1'; |
|
| 26 | + public const TEST_FILES_SHARING_API_USER2 = 'test-share-user2'; |
|
| 27 | + |
|
| 28 | + public static function setUpBeforeClass(): void { |
|
| 29 | + parent::setUpBeforeClass(); |
|
| 30 | + |
|
| 31 | + // reset backend |
|
| 32 | + Server::get(IUserManager::class)->clearBackends(); |
|
| 33 | + Server::get(IGroupManager::class)->clearBackends(); |
|
| 34 | + |
|
| 35 | + // create users |
|
| 36 | + $backend = new \Test\Util\User\Dummy(); |
|
| 37 | + Server::get(IUserManager::class)->registerBackend($backend); |
|
| 38 | + $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); |
|
| 39 | + $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); |
|
| 40 | + } |
|
| 41 | + |
|
| 42 | + protected function setUp(): void { |
|
| 43 | + parent::setUp(); |
|
| 44 | + |
|
| 45 | + //login as user1 |
|
| 46 | + self::loginHelper(self::TEST_FILES_SHARING_API_USER1); |
|
| 47 | + } |
|
| 48 | + |
|
| 49 | + public static function tearDownAfterClass(): void { |
|
| 50 | + // cleanup users |
|
| 51 | + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER1); |
|
| 52 | + if ($user !== null) { |
|
| 53 | + $user->delete(); |
|
| 54 | + } |
|
| 55 | + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER2); |
|
| 56 | + if ($user !== null) { |
|
| 57 | + $user->delete(); |
|
| 58 | + } |
|
| 59 | + |
|
| 60 | + \OC_Util::tearDownFS(); |
|
| 61 | + \OC_User::setUserId(''); |
|
| 62 | + Filesystem::tearDown(); |
|
| 63 | + |
|
| 64 | + // reset backend |
|
| 65 | + Server::get(IUserManager::class)->clearBackends(); |
|
| 66 | + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); |
|
| 67 | + Server::get(IGroupManager::class)->clearBackends(); |
|
| 68 | + Server::get(IGroupManager::class)->addBackend(new Database()); |
|
| 69 | + |
|
| 70 | + parent::tearDownAfterClass(); |
|
| 71 | + } |
|
| 72 | + |
|
| 73 | + /** |
|
| 74 | + * @param string $user |
|
| 75 | + * @param bool $create |
|
| 76 | + * @param bool $password |
|
| 77 | + */ |
|
| 78 | + protected static function loginHelper($user, $create = false, $password = false) { |
|
| 79 | + if ($password === false) { |
|
| 80 | + $password = $user; |
|
| 81 | + } |
|
| 82 | + |
|
| 83 | + if ($create) { |
|
| 84 | + $userManager = Server::get(IUserManager::class); |
|
| 85 | + $groupManager = Server::get(IGroupManager::class); |
|
| 86 | + |
|
| 87 | + $userObject = $userManager->createUser($user, $password); |
|
| 88 | + $group = $groupManager->createGroup('group'); |
|
| 89 | + |
|
| 90 | + if ($group and $userObject) { |
|
| 91 | + $group->addUser($userObject); |
|
| 92 | + } |
|
| 93 | + } |
|
| 94 | + |
|
| 95 | + \OC_Util::tearDownFS(); |
|
| 96 | + Server::get(IUserSession::class)->setUser(null); |
|
| 97 | + Filesystem::tearDown(); |
|
| 98 | + Server::get(IUserSession::class)->login($user, $password); |
|
| 99 | + \OC::$server->getUserFolder($user); |
|
| 100 | + |
|
| 101 | + \OC_Util::setupFS($user); |
|
| 102 | + } |
|
| 103 | 103 | } |
@@ -44,108 +44,108 @@ |
||
| 44 | 44 | use Psr\Log\LoggerInterface; |
| 45 | 45 | |
| 46 | 46 | class Application extends App implements IBootstrap { |
| 47 | - public function __construct() { |
|
| 48 | - parent::__construct('user_ldap'); |
|
| 49 | - $container = $this->getContainer(); |
|
| 47 | + public function __construct() { |
|
| 48 | + parent::__construct('user_ldap'); |
|
| 49 | + $container = $this->getContainer(); |
|
| 50 | 50 | |
| 51 | - /** |
|
| 52 | - * Controller |
|
| 53 | - */ |
|
| 54 | - $container->registerService('RenewPasswordController', function (IAppContainer $appContainer) { |
|
| 55 | - /** @var IServerContainer $server */ |
|
| 56 | - $server = $appContainer->get(IServerContainer::class); |
|
| 51 | + /** |
|
| 52 | + * Controller |
|
| 53 | + */ |
|
| 54 | + $container->registerService('RenewPasswordController', function (IAppContainer $appContainer) { |
|
| 55 | + /** @var IServerContainer $server */ |
|
| 56 | + $server = $appContainer->get(IServerContainer::class); |
|
| 57 | 57 | |
| 58 | - return new RenewPasswordController( |
|
| 59 | - $appContainer->get('AppName'), |
|
| 60 | - $server->getRequest(), |
|
| 61 | - $appContainer->get('UserManager'), |
|
| 62 | - $server->getConfig(), |
|
| 63 | - $appContainer->get(IL10N::class), |
|
| 64 | - $appContainer->get('Session'), |
|
| 65 | - $server->getURLGenerator() |
|
| 66 | - ); |
|
| 67 | - }); |
|
| 58 | + return new RenewPasswordController( |
|
| 59 | + $appContainer->get('AppName'), |
|
| 60 | + $server->getRequest(), |
|
| 61 | + $appContainer->get('UserManager'), |
|
| 62 | + $server->getConfig(), |
|
| 63 | + $appContainer->get(IL10N::class), |
|
| 64 | + $appContainer->get('Session'), |
|
| 65 | + $server->getURLGenerator() |
|
| 66 | + ); |
|
| 67 | + }); |
|
| 68 | 68 | |
| 69 | - $container->registerService(ILDAPWrapper::class, function (IAppContainer $appContainer) { |
|
| 70 | - /** @var IServerContainer $server */ |
|
| 71 | - $server = $appContainer->get(IServerContainer::class); |
|
| 69 | + $container->registerService(ILDAPWrapper::class, function (IAppContainer $appContainer) { |
|
| 70 | + /** @var IServerContainer $server */ |
|
| 71 | + $server = $appContainer->get(IServerContainer::class); |
|
| 72 | 72 | |
| 73 | - return new LDAP( |
|
| 74 | - $server->getConfig()->getSystemValueString('ldap_log_file') |
|
| 75 | - ); |
|
| 76 | - }); |
|
| 77 | - } |
|
| 73 | + return new LDAP( |
|
| 74 | + $server->getConfig()->getSystemValueString('ldap_log_file') |
|
| 75 | + ); |
|
| 76 | + }); |
|
| 77 | + } |
|
| 78 | 78 | |
| 79 | - public function register(IRegistrationContext $context): void { |
|
| 80 | - $context->registerNotifierService(Notifier::class); |
|
| 79 | + public function register(IRegistrationContext $context): void { |
|
| 80 | + $context->registerNotifierService(Notifier::class); |
|
| 81 | 81 | |
| 82 | - $context->registerService( |
|
| 83 | - Manager::class, |
|
| 84 | - function (ContainerInterface $c) { |
|
| 85 | - return new Manager( |
|
| 86 | - $c->get(IConfig::class), |
|
| 87 | - $c->get(LoggerInterface::class), |
|
| 88 | - $c->get(IAvatarManager::class), |
|
| 89 | - $c->get(Image::class), |
|
| 90 | - $c->get(IUserManager::class), |
|
| 91 | - $c->get(INotificationManager::class), |
|
| 92 | - $c->get(IShareManager::class), |
|
| 93 | - ); |
|
| 94 | - }, |
|
| 95 | - // the instance is specific to a lazy bound Access instance, thus cannot be shared. |
|
| 96 | - false |
|
| 97 | - ); |
|
| 98 | - $context->registerEventListener(PostLoginEvent::class, LoginListener::class); |
|
| 99 | - $context->registerSetupCheck(LdapInvalidUuids::class); |
|
| 100 | - $context->registerSetupCheck(LdapConnection::class); |
|
| 101 | - } |
|
| 82 | + $context->registerService( |
|
| 83 | + Manager::class, |
|
| 84 | + function (ContainerInterface $c) { |
|
| 85 | + return new Manager( |
|
| 86 | + $c->get(IConfig::class), |
|
| 87 | + $c->get(LoggerInterface::class), |
|
| 88 | + $c->get(IAvatarManager::class), |
|
| 89 | + $c->get(Image::class), |
|
| 90 | + $c->get(IUserManager::class), |
|
| 91 | + $c->get(INotificationManager::class), |
|
| 92 | + $c->get(IShareManager::class), |
|
| 93 | + ); |
|
| 94 | + }, |
|
| 95 | + // the instance is specific to a lazy bound Access instance, thus cannot be shared. |
|
| 96 | + false |
|
| 97 | + ); |
|
| 98 | + $context->registerEventListener(PostLoginEvent::class, LoginListener::class); |
|
| 99 | + $context->registerSetupCheck(LdapInvalidUuids::class); |
|
| 100 | + $context->registerSetupCheck(LdapConnection::class); |
|
| 101 | + } |
|
| 102 | 102 | |
| 103 | - public function boot(IBootContext $context): void { |
|
| 104 | - $context->injectFn(function ( |
|
| 105 | - INotificationManager $notificationManager, |
|
| 106 | - IAppContainer $appContainer, |
|
| 107 | - IEventDispatcher $dispatcher, |
|
| 108 | - IUserManager $userManager, |
|
| 109 | - IGroupManager $groupManager, |
|
| 110 | - User_Proxy $userBackend, |
|
| 111 | - Group_Proxy $groupBackend, |
|
| 112 | - Helper $helper, |
|
| 113 | - ): void { |
|
| 114 | - $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
| 115 | - if (count($configPrefixes) > 0) { |
|
| 116 | - $userPluginManager = $appContainer->get(UserPluginManager::class); |
|
| 117 | - $groupPluginManager = $appContainer->get(GroupPluginManager::class); |
|
| 103 | + public function boot(IBootContext $context): void { |
|
| 104 | + $context->injectFn(function ( |
|
| 105 | + INotificationManager $notificationManager, |
|
| 106 | + IAppContainer $appContainer, |
|
| 107 | + IEventDispatcher $dispatcher, |
|
| 108 | + IUserManager $userManager, |
|
| 109 | + IGroupManager $groupManager, |
|
| 110 | + User_Proxy $userBackend, |
|
| 111 | + Group_Proxy $groupBackend, |
|
| 112 | + Helper $helper, |
|
| 113 | + ): void { |
|
| 114 | + $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
| 115 | + if (count($configPrefixes) > 0) { |
|
| 116 | + $userPluginManager = $appContainer->get(UserPluginManager::class); |
|
| 117 | + $groupPluginManager = $appContainer->get(GroupPluginManager::class); |
|
| 118 | 118 | |
| 119 | - $userManager->registerBackend($userBackend); |
|
| 120 | - $groupManager->addBackend($groupBackend); |
|
| 119 | + $userManager->registerBackend($userBackend); |
|
| 120 | + $groupManager->addBackend($groupBackend); |
|
| 121 | 121 | |
| 122 | - $userBackendRegisteredEvent = new UserBackendRegistered($userBackend, $userPluginManager); |
|
| 123 | - $dispatcher->dispatch('OCA\\User_LDAP\\User\\User::postLDAPBackendAdded', $userBackendRegisteredEvent); |
|
| 124 | - $dispatcher->dispatchTyped($userBackendRegisteredEvent); |
|
| 125 | - $groupBackendRegisteredEvent = new GroupBackendRegistered($groupBackend, $groupPluginManager); |
|
| 126 | - $dispatcher->dispatchTyped($groupBackendRegisteredEvent); |
|
| 127 | - } |
|
| 128 | - }); |
|
| 122 | + $userBackendRegisteredEvent = new UserBackendRegistered($userBackend, $userPluginManager); |
|
| 123 | + $dispatcher->dispatch('OCA\\User_LDAP\\User\\User::postLDAPBackendAdded', $userBackendRegisteredEvent); |
|
| 124 | + $dispatcher->dispatchTyped($userBackendRegisteredEvent); |
|
| 125 | + $groupBackendRegisteredEvent = new GroupBackendRegistered($groupBackend, $groupPluginManager); |
|
| 126 | + $dispatcher->dispatchTyped($groupBackendRegisteredEvent); |
|
| 127 | + } |
|
| 128 | + }); |
|
| 129 | 129 | |
| 130 | - $context->injectFn(Closure::fromCallable([$this, 'registerBackendDependents'])); |
|
| 130 | + $context->injectFn(Closure::fromCallable([$this, 'registerBackendDependents'])); |
|
| 131 | 131 | |
| 132 | - Util::connectHook( |
|
| 133 | - '\OCA\Files_Sharing\API\Server2Server', |
|
| 134 | - 'preLoginNameUsedAsUserName', |
|
| 135 | - '\OCA\User_LDAP\Helper', |
|
| 136 | - 'loginName2UserName' |
|
| 137 | - ); |
|
| 138 | - } |
|
| 132 | + Util::connectHook( |
|
| 133 | + '\OCA\Files_Sharing\API\Server2Server', |
|
| 134 | + 'preLoginNameUsedAsUserName', |
|
| 135 | + '\OCA\User_LDAP\Helper', |
|
| 136 | + 'loginName2UserName' |
|
| 137 | + ); |
|
| 138 | + } |
|
| 139 | 139 | |
| 140 | - private function registerBackendDependents(IAppContainer $appContainer, IEventDispatcher $dispatcher): void { |
|
| 141 | - $dispatcher->addListener( |
|
| 142 | - 'OCA\\Files_External::loadAdditionalBackends', |
|
| 143 | - function () use ($appContainer): void { |
|
| 144 | - $storagesBackendService = $appContainer->get(BackendService::class); |
|
| 145 | - $storagesBackendService->registerConfigHandler('home', function () use ($appContainer) { |
|
| 146 | - return $appContainer->get(ExtStorageConfigHandler::class); |
|
| 147 | - }); |
|
| 148 | - } |
|
| 149 | - ); |
|
| 150 | - } |
|
| 140 | + private function registerBackendDependents(IAppContainer $appContainer, IEventDispatcher $dispatcher): void { |
|
| 141 | + $dispatcher->addListener( |
|
| 142 | + 'OCA\\Files_External::loadAdditionalBackends', |
|
| 143 | + function () use ($appContainer): void { |
|
| 144 | + $storagesBackendService = $appContainer->get(BackendService::class); |
|
| 145 | + $storagesBackendService->registerConfigHandler('home', function () use ($appContainer) { |
|
| 146 | + return $appContainer->get(ExtStorageConfigHandler::class); |
|
| 147 | + }); |
|
| 148 | + } |
|
| 149 | + ); |
|
| 150 | + } |
|
| 151 | 151 | } |
@@ -20,75 +20,75 @@ |
||
| 20 | 20 | require_once __DIR__ . '/../../Bootstrap.php'; |
| 21 | 21 | |
| 22 | 22 | class IntegrationTestUserDisplayName extends AbstractIntegrationTest { |
| 23 | - /** @var UserMapping */ |
|
| 24 | - protected $mapping; |
|
| 23 | + /** @var UserMapping */ |
|
| 24 | + protected $mapping; |
|
| 25 | 25 | |
| 26 | - /** |
|
| 27 | - * prepares the LDAP environment and sets up a test configuration for |
|
| 28 | - * the LDAP backend. |
|
| 29 | - */ |
|
| 30 | - public function init() { |
|
| 31 | - require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php'); |
|
| 32 | - parent::init(); |
|
| 33 | - $this->mapping = new UserMapping(Server::get(IDBConnection::class)); |
|
| 34 | - $this->mapping->clear(); |
|
| 35 | - $this->access->setUserMapper($this->mapping); |
|
| 36 | - $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class)); |
|
| 37 | - Server::get(IUserManager::class)->registerBackend($userBackend); |
|
| 38 | - } |
|
| 26 | + /** |
|
| 27 | + * prepares the LDAP environment and sets up a test configuration for |
|
| 28 | + * the LDAP backend. |
|
| 29 | + */ |
|
| 30 | + public function init() { |
|
| 31 | + require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php'); |
|
| 32 | + parent::init(); |
|
| 33 | + $this->mapping = new UserMapping(Server::get(IDBConnection::class)); |
|
| 34 | + $this->mapping->clear(); |
|
| 35 | + $this->access->setUserMapper($this->mapping); |
|
| 36 | + $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class)); |
|
| 37 | + Server::get(IUserManager::class)->registerBackend($userBackend); |
|
| 38 | + } |
|
| 39 | 39 | |
| 40 | - /** |
|
| 41 | - * adds a map entry for the user, so we know the username |
|
| 42 | - * |
|
| 43 | - * @param $dn |
|
| 44 | - * @param $username |
|
| 45 | - */ |
|
| 46 | - private function prepareUser($dn, $username) { |
|
| 47 | - // assigns our self-picked oc username to the dn |
|
| 48 | - $this->mapping->map($dn, $username, 'fakeUUID-' . $username); |
|
| 49 | - } |
|
| 40 | + /** |
|
| 41 | + * adds a map entry for the user, so we know the username |
|
| 42 | + * |
|
| 43 | + * @param $dn |
|
| 44 | + * @param $username |
|
| 45 | + */ |
|
| 46 | + private function prepareUser($dn, $username) { |
|
| 47 | + // assigns our self-picked oc username to the dn |
|
| 48 | + $this->mapping->map($dn, $username, 'fakeUUID-' . $username); |
|
| 49 | + } |
|
| 50 | 50 | |
| 51 | - /** |
|
| 52 | - * tests whether a display name consisting of two parts is created correctly |
|
| 53 | - * |
|
| 54 | - * @return bool |
|
| 55 | - */ |
|
| 56 | - protected function case1() { |
|
| 57 | - $username = 'alice1337'; |
|
| 58 | - $dn = 'uid=alice,ou=Users,' . $this->base; |
|
| 59 | - $this->prepareUser($dn, $username); |
|
| 60 | - $displayName = Server::get(IUserManager::class)->get($username)->getDisplayName(); |
|
| 51 | + /** |
|
| 52 | + * tests whether a display name consisting of two parts is created correctly |
|
| 53 | + * |
|
| 54 | + * @return bool |
|
| 55 | + */ |
|
| 56 | + protected function case1() { |
|
| 57 | + $username = 'alice1337'; |
|
| 58 | + $dn = 'uid=alice,ou=Users,' . $this->base; |
|
| 59 | + $this->prepareUser($dn, $username); |
|
| 60 | + $displayName = Server::get(IUserManager::class)->get($username)->getDisplayName(); |
|
| 61 | 61 | |
| 62 | - return str_contains($displayName, '([email protected])'); |
|
| 63 | - } |
|
| 62 | + return str_contains($displayName, '([email protected])'); |
|
| 63 | + } |
|
| 64 | 64 | |
| 65 | - /** |
|
| 66 | - * tests whether a display name consisting of one part is created correctly |
|
| 67 | - * |
|
| 68 | - * @return bool |
|
| 69 | - */ |
|
| 70 | - protected function case2() { |
|
| 71 | - $this->connection->setConfiguration([ |
|
| 72 | - 'ldapUserDisplayName2' => '', |
|
| 73 | - ]); |
|
| 74 | - $username = 'boris23421'; |
|
| 75 | - $dn = 'uid=boris,ou=Users,' . $this->base; |
|
| 76 | - $this->prepareUser($dn, $username); |
|
| 77 | - $displayName = Server::get(IUserManager::class)->get($username)->getDisplayName(); |
|
| 65 | + /** |
|
| 66 | + * tests whether a display name consisting of one part is created correctly |
|
| 67 | + * |
|
| 68 | + * @return bool |
|
| 69 | + */ |
|
| 70 | + protected function case2() { |
|
| 71 | + $this->connection->setConfiguration([ |
|
| 72 | + 'ldapUserDisplayName2' => '', |
|
| 73 | + ]); |
|
| 74 | + $username = 'boris23421'; |
|
| 75 | + $dn = 'uid=boris,ou=Users,' . $this->base; |
|
| 76 | + $this->prepareUser($dn, $username); |
|
| 77 | + $displayName = Server::get(IUserManager::class)->get($username)->getDisplayName(); |
|
| 78 | 78 | |
| 79 | - return !str_contains($displayName, '([email protected])'); |
|
| 80 | - } |
|
| 79 | + return !str_contains($displayName, '([email protected])'); |
|
| 80 | + } |
|
| 81 | 81 | |
| 82 | - /** |
|
| 83 | - * sets up the LDAP configuration to be used for the test |
|
| 84 | - */ |
|
| 85 | - protected function initConnection() { |
|
| 86 | - parent::initConnection(); |
|
| 87 | - $this->connection->setConfiguration([ |
|
| 88 | - 'ldapUserDisplayName' => 'displayName', |
|
| 89 | - 'ldapUserDisplayName2' => 'mail', |
|
| 90 | - ]); |
|
| 91 | - } |
|
| 82 | + /** |
|
| 83 | + * sets up the LDAP configuration to be used for the test |
|
| 84 | + */ |
|
| 85 | + protected function initConnection() { |
|
| 86 | + parent::initConnection(); |
|
| 87 | + $this->connection->setConfiguration([ |
|
| 88 | + 'ldapUserDisplayName' => 'displayName', |
|
| 89 | + 'ldapUserDisplayName2' => 'mail', |
|
| 90 | + ]); |
|
| 91 | + } |
|
| 92 | 92 | } |
| 93 | 93 | |
| 94 | 94 | /** @var string $host */ |
@@ -25,120 +25,120 @@ |
||
| 25 | 25 | require_once __DIR__ . '/../../Bootstrap.php'; |
| 26 | 26 | |
| 27 | 27 | class IntegrationTestUserAvatar extends AbstractIntegrationTest { |
| 28 | - /** @var UserMapping */ |
|
| 29 | - protected $mapping; |
|
| 30 | - |
|
| 31 | - /** |
|
| 32 | - * prepares the LDAP environment and sets up a test configuration for |
|
| 33 | - * the LDAP backend. |
|
| 34 | - */ |
|
| 35 | - public function init() { |
|
| 36 | - require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php'); |
|
| 37 | - parent::init(); |
|
| 38 | - $this->mapping = new UserMapping(Server::get(IDBConnection::class)); |
|
| 39 | - $this->mapping->clear(); |
|
| 40 | - $this->access->setUserMapper($this->mapping); |
|
| 41 | - $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class)); |
|
| 42 | - Server::get(IUserManager::class)->registerBackend($userBackend); |
|
| 43 | - } |
|
| 44 | - |
|
| 45 | - /** |
|
| 46 | - * A method that does the common steps of test cases 1 and 2. The evaluation |
|
| 47 | - * is not happening here. |
|
| 48 | - * |
|
| 49 | - * @param string $dn |
|
| 50 | - * @param string $username |
|
| 51 | - * @param string $image |
|
| 52 | - */ |
|
| 53 | - private function execFetchTest($dn, $username, $image) { |
|
| 54 | - $this->setJpegPhotoAttribute($dn, $image); |
|
| 55 | - |
|
| 56 | - // assigns our self-picked oc username to the dn |
|
| 57 | - $this->mapping->map($dn, $username, 'fakeUUID-' . $username); |
|
| 58 | - |
|
| 59 | - // initialize home folder and make sure that the user will update |
|
| 60 | - // also remove an possibly existing avatar |
|
| 61 | - \OC_Util::tearDownFS(); |
|
| 62 | - \OC_Util::setupFS($username); |
|
| 63 | - \OC::$server->getUserFolder($username); |
|
| 64 | - Server::get(IConfig::class)->deleteUserValue($username, 'user_ldap', User::USER_PREFKEY_LASTREFRESH); |
|
| 65 | - if (Server::get(IAvatarManager::class)->getAvatar($username)->exists()) { |
|
| 66 | - Server::get(IAvatarManager::class)->getAvatar($username)->remove(); |
|
| 67 | - } |
|
| 68 | - |
|
| 69 | - // finally attempt to get the avatar set |
|
| 70 | - $user = $this->userManager->get($dn); |
|
| 71 | - $user->updateAvatar(); |
|
| 72 | - } |
|
| 73 | - |
|
| 74 | - /** |
|
| 75 | - * tests whether an avatar can be retrieved from LDAP and stored correctly |
|
| 76 | - * |
|
| 77 | - * @return bool |
|
| 78 | - */ |
|
| 79 | - protected function case1() { |
|
| 80 | - $image = file_get_contents(__DIR__ . '/../../data/avatar-valid.jpg'); |
|
| 81 | - $dn = 'uid=alice,ou=Users,' . $this->base; |
|
| 82 | - $username = 'alice1337'; |
|
| 83 | - |
|
| 84 | - $this->execFetchTest($dn, $username, $image); |
|
| 85 | - |
|
| 86 | - return Server::get(IAvatarManager::class)->getAvatar($username)->exists(); |
|
| 87 | - } |
|
| 88 | - |
|
| 89 | - /** |
|
| 90 | - * tests whether an image received from LDAP which is of an invalid file |
|
| 91 | - * type is dealt with properly (i.e. not set and not dying). |
|
| 92 | - * |
|
| 93 | - * @return bool |
|
| 94 | - */ |
|
| 95 | - protected function case2() { |
|
| 96 | - // gif by Pmspinner from https://commons.wikimedia.org/wiki/File:Avatar2469_3.gif |
|
| 97 | - $image = file_get_contents(__DIR__ . '/../../data/avatar-invalid.gif'); |
|
| 98 | - $dn = 'uid=boris,ou=Users,' . $this->base; |
|
| 99 | - $username = 'boris7844'; |
|
| 100 | - |
|
| 101 | - $this->execFetchTest($dn, $username, $image); |
|
| 102 | - |
|
| 103 | - return !Server::get(IAvatarManager::class)->getAvatar($username)->exists(); |
|
| 104 | - } |
|
| 105 | - |
|
| 106 | - /** |
|
| 107 | - * This writes an image to the 'jpegPhoto' attribute on LDAP. |
|
| 108 | - * |
|
| 109 | - * @param string $dn |
|
| 110 | - * @param string $image An image read via file_get_contents |
|
| 111 | - * @throws \OC\ServerNotAvailableException |
|
| 112 | - */ |
|
| 113 | - private function setJpegPhotoAttribute($dn, $image) { |
|
| 114 | - $changeSet = ['jpegphoto' => $image]; |
|
| 115 | - ldap_mod_add($this->connection->getConnectionResource(), $dn, $changeSet); |
|
| 116 | - } |
|
| 117 | - |
|
| 118 | - protected function initUserManager() { |
|
| 119 | - $this->userManager = new Manager( |
|
| 120 | - Server::get(IConfig::class), |
|
| 121 | - Server::get(LoggerInterface::class), |
|
| 122 | - Server::get(IAvatarManager::class), |
|
| 123 | - new Image(), |
|
| 124 | - Server::get(IDBConnection::class), |
|
| 125 | - Server::get(IUserManager::class), |
|
| 126 | - Server::get(\OCP\Notification\IManager::class) |
|
| 127 | - ); |
|
| 128 | - } |
|
| 129 | - |
|
| 130 | - /** |
|
| 131 | - * sets up the LDAP configuration to be used for the test |
|
| 132 | - */ |
|
| 133 | - protected function initConnection() { |
|
| 134 | - parent::initConnection(); |
|
| 135 | - $this->connection->setConfiguration([ |
|
| 136 | - 'ldapUserFilter' => 'objectclass=inetOrgPerson', |
|
| 137 | - 'ldapUserDisplayName' => 'displayName', |
|
| 138 | - 'ldapGroupDisplayName' => 'cn', |
|
| 139 | - 'ldapLoginFilter' => 'uid=%uid', |
|
| 140 | - ]); |
|
| 141 | - } |
|
| 28 | + /** @var UserMapping */ |
|
| 29 | + protected $mapping; |
|
| 30 | + |
|
| 31 | + /** |
|
| 32 | + * prepares the LDAP environment and sets up a test configuration for |
|
| 33 | + * the LDAP backend. |
|
| 34 | + */ |
|
| 35 | + public function init() { |
|
| 36 | + require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php'); |
|
| 37 | + parent::init(); |
|
| 38 | + $this->mapping = new UserMapping(Server::get(IDBConnection::class)); |
|
| 39 | + $this->mapping->clear(); |
|
| 40 | + $this->access->setUserMapper($this->mapping); |
|
| 41 | + $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class)); |
|
| 42 | + Server::get(IUserManager::class)->registerBackend($userBackend); |
|
| 43 | + } |
|
| 44 | + |
|
| 45 | + /** |
|
| 46 | + * A method that does the common steps of test cases 1 and 2. The evaluation |
|
| 47 | + * is not happening here. |
|
| 48 | + * |
|
| 49 | + * @param string $dn |
|
| 50 | + * @param string $username |
|
| 51 | + * @param string $image |
|
| 52 | + */ |
|
| 53 | + private function execFetchTest($dn, $username, $image) { |
|
| 54 | + $this->setJpegPhotoAttribute($dn, $image); |
|
| 55 | + |
|
| 56 | + // assigns our self-picked oc username to the dn |
|
| 57 | + $this->mapping->map($dn, $username, 'fakeUUID-' . $username); |
|
| 58 | + |
|
| 59 | + // initialize home folder and make sure that the user will update |
|
| 60 | + // also remove an possibly existing avatar |
|
| 61 | + \OC_Util::tearDownFS(); |
|
| 62 | + \OC_Util::setupFS($username); |
|
| 63 | + \OC::$server->getUserFolder($username); |
|
| 64 | + Server::get(IConfig::class)->deleteUserValue($username, 'user_ldap', User::USER_PREFKEY_LASTREFRESH); |
|
| 65 | + if (Server::get(IAvatarManager::class)->getAvatar($username)->exists()) { |
|
| 66 | + Server::get(IAvatarManager::class)->getAvatar($username)->remove(); |
|
| 67 | + } |
|
| 68 | + |
|
| 69 | + // finally attempt to get the avatar set |
|
| 70 | + $user = $this->userManager->get($dn); |
|
| 71 | + $user->updateAvatar(); |
|
| 72 | + } |
|
| 73 | + |
|
| 74 | + /** |
|
| 75 | + * tests whether an avatar can be retrieved from LDAP and stored correctly |
|
| 76 | + * |
|
| 77 | + * @return bool |
|
| 78 | + */ |
|
| 79 | + protected function case1() { |
|
| 80 | + $image = file_get_contents(__DIR__ . '/../../data/avatar-valid.jpg'); |
|
| 81 | + $dn = 'uid=alice,ou=Users,' . $this->base; |
|
| 82 | + $username = 'alice1337'; |
|
| 83 | + |
|
| 84 | + $this->execFetchTest($dn, $username, $image); |
|
| 85 | + |
|
| 86 | + return Server::get(IAvatarManager::class)->getAvatar($username)->exists(); |
|
| 87 | + } |
|
| 88 | + |
|
| 89 | + /** |
|
| 90 | + * tests whether an image received from LDAP which is of an invalid file |
|
| 91 | + * type is dealt with properly (i.e. not set and not dying). |
|
| 92 | + * |
|
| 93 | + * @return bool |
|
| 94 | + */ |
|
| 95 | + protected function case2() { |
|
| 96 | + // gif by Pmspinner from https://commons.wikimedia.org/wiki/File:Avatar2469_3.gif |
|
| 97 | + $image = file_get_contents(__DIR__ . '/../../data/avatar-invalid.gif'); |
|
| 98 | + $dn = 'uid=boris,ou=Users,' . $this->base; |
|
| 99 | + $username = 'boris7844'; |
|
| 100 | + |
|
| 101 | + $this->execFetchTest($dn, $username, $image); |
|
| 102 | + |
|
| 103 | + return !Server::get(IAvatarManager::class)->getAvatar($username)->exists(); |
|
| 104 | + } |
|
| 105 | + |
|
| 106 | + /** |
|
| 107 | + * This writes an image to the 'jpegPhoto' attribute on LDAP. |
|
| 108 | + * |
|
| 109 | + * @param string $dn |
|
| 110 | + * @param string $image An image read via file_get_contents |
|
| 111 | + * @throws \OC\ServerNotAvailableException |
|
| 112 | + */ |
|
| 113 | + private function setJpegPhotoAttribute($dn, $image) { |
|
| 114 | + $changeSet = ['jpegphoto' => $image]; |
|
| 115 | + ldap_mod_add($this->connection->getConnectionResource(), $dn, $changeSet); |
|
| 116 | + } |
|
| 117 | + |
|
| 118 | + protected function initUserManager() { |
|
| 119 | + $this->userManager = new Manager( |
|
| 120 | + Server::get(IConfig::class), |
|
| 121 | + Server::get(LoggerInterface::class), |
|
| 122 | + Server::get(IAvatarManager::class), |
|
| 123 | + new Image(), |
|
| 124 | + Server::get(IDBConnection::class), |
|
| 125 | + Server::get(IUserManager::class), |
|
| 126 | + Server::get(\OCP\Notification\IManager::class) |
|
| 127 | + ); |
|
| 128 | + } |
|
| 129 | + |
|
| 130 | + /** |
|
| 131 | + * sets up the LDAP configuration to be used for the test |
|
| 132 | + */ |
|
| 133 | + protected function initConnection() { |
|
| 134 | + parent::initConnection(); |
|
| 135 | + $this->connection->setConfiguration([ |
|
| 136 | + 'ldapUserFilter' => 'objectclass=inetOrgPerson', |
|
| 137 | + 'ldapUserDisplayName' => 'displayName', |
|
| 138 | + 'ldapGroupDisplayName' => 'cn', |
|
| 139 | + 'ldapLoginFilter' => 'uid=%uid', |
|
| 140 | + ]); |
|
| 141 | + } |
|
| 142 | 142 | } |
| 143 | 143 | |
| 144 | 144 | /** @var string $host */ |