@@ -671,7 +671,7 @@ discard block |
||
| 671 | 671 | * if the size limit for the trash bin is reached, we delete the oldest |
| 672 | 672 | * files in the trash bin until we meet the limit again |
| 673 | 673 | * |
| 674 | - * @param array $files |
|
| 674 | + * @param \OCP\Files\FileInfo[] $files |
|
| 675 | 675 | * @param string $user |
| 676 | 676 | * @param int $availableSpace available disc space |
| 677 | 677 | * @return int size of deleted files |
@@ -699,7 +699,7 @@ discard block |
||
| 699 | 699 | /** |
| 700 | 700 | * delete files older then max storage time |
| 701 | 701 | * |
| 702 | - * @param array $files list of files sorted by mtime |
|
| 702 | + * @param \OCP\Files\FileInfo[] $files list of files sorted by mtime |
|
| 703 | 703 | * @param string $user |
| 704 | 704 | * @return integer[] size of deleted files and number of deleted files |
| 705 | 705 | */ |
@@ -49,956 +49,956 @@ |
||
| 49 | 49 | |
| 50 | 50 | class Trashbin { |
| 51 | 51 | |
| 52 | - // unit: percentage; 50% of available disk space/quota |
|
| 53 | - const DEFAULTMAXSIZE = 50; |
|
| 54 | - |
|
| 55 | - /** |
|
| 56 | - * Whether versions have already be rescanned during this PHP request |
|
| 57 | - * |
|
| 58 | - * @var bool |
|
| 59 | - */ |
|
| 60 | - private static $scannedVersions = false; |
|
| 61 | - |
|
| 62 | - /** |
|
| 63 | - * Ensure we don't need to scan the file during the move to trash |
|
| 64 | - * by triggering the scan in the pre-hook |
|
| 65 | - * |
|
| 66 | - * @param array $params |
|
| 67 | - */ |
|
| 68 | - public static function ensureFileScannedHook($params) { |
|
| 69 | - try { |
|
| 70 | - self::getUidAndFilename($params['path']); |
|
| 71 | - } catch (NotFoundException $e) { |
|
| 72 | - // nothing to scan for non existing files |
|
| 73 | - } |
|
| 74 | - } |
|
| 75 | - |
|
| 76 | - /** |
|
| 77 | - * get the UID of the owner of the file and the path to the file relative to |
|
| 78 | - * owners files folder |
|
| 79 | - * |
|
| 80 | - * @param string $filename |
|
| 81 | - * @return array |
|
| 82 | - * @throws \OC\User\NoUserException |
|
| 83 | - */ |
|
| 84 | - public static function getUidAndFilename($filename) { |
|
| 85 | - $uid = Filesystem::getOwner($filename); |
|
| 86 | - $userManager = \OC::$server->getUserManager(); |
|
| 87 | - // if the user with the UID doesn't exists, e.g. because the UID points |
|
| 88 | - // to a remote user with a federated cloud ID we use the current logged-in |
|
| 89 | - // user. We need a valid local user to move the file to the right trash bin |
|
| 90 | - if (!$userManager->userExists($uid)) { |
|
| 91 | - $uid = User::getUser(); |
|
| 92 | - } |
|
| 93 | - if (!$uid) { |
|
| 94 | - // no owner, usually because of share link from ext storage |
|
| 95 | - return [null, null]; |
|
| 96 | - } |
|
| 97 | - Filesystem::initMountPoints($uid); |
|
| 98 | - if ($uid !== User::getUser()) { |
|
| 99 | - $info = Filesystem::getFileInfo($filename); |
|
| 100 | - $ownerView = new View('/' . $uid . '/files'); |
|
| 101 | - try { |
|
| 102 | - $filename = $ownerView->getPath($info['fileid']); |
|
| 103 | - } catch (NotFoundException $e) { |
|
| 104 | - $filename = null; |
|
| 105 | - } |
|
| 106 | - } |
|
| 107 | - return [$uid, $filename]; |
|
| 108 | - } |
|
| 109 | - |
|
| 110 | - /** |
|
| 111 | - * get original location of files for user |
|
| 112 | - * |
|
| 113 | - * @param string $user |
|
| 114 | - * @return array (filename => array (timestamp => original location)) |
|
| 115 | - */ |
|
| 116 | - public static function getLocations($user) { |
|
| 117 | - $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`' |
|
| 118 | - . ' FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
| 119 | - $result = $query->execute(array($user)); |
|
| 120 | - $array = array(); |
|
| 121 | - while ($row = $result->fetchRow()) { |
|
| 122 | - if (isset($array[$row['id']])) { |
|
| 123 | - $array[$row['id']][$row['timestamp']] = $row['location']; |
|
| 124 | - } else { |
|
| 125 | - $array[$row['id']] = array($row['timestamp'] => $row['location']); |
|
| 126 | - } |
|
| 127 | - } |
|
| 128 | - return $array; |
|
| 129 | - } |
|
| 130 | - |
|
| 131 | - /** |
|
| 132 | - * get original location of file |
|
| 133 | - * |
|
| 134 | - * @param string $user |
|
| 135 | - * @param string $filename |
|
| 136 | - * @param string $timestamp |
|
| 137 | - * @return string original location |
|
| 138 | - */ |
|
| 139 | - public static function getLocation($user, $filename, $timestamp) { |
|
| 140 | - $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`' |
|
| 141 | - . ' WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
| 142 | - $result = $query->execute(array($user, $filename, $timestamp))->fetchAll(); |
|
| 143 | - if (isset($result[0]['location'])) { |
|
| 144 | - return $result[0]['location']; |
|
| 145 | - } else { |
|
| 146 | - return false; |
|
| 147 | - } |
|
| 148 | - } |
|
| 149 | - |
|
| 150 | - private static function setUpTrash($user) { |
|
| 151 | - $view = new View('/' . $user); |
|
| 152 | - if (!$view->is_dir('files_trashbin')) { |
|
| 153 | - $view->mkdir('files_trashbin'); |
|
| 154 | - } |
|
| 155 | - if (!$view->is_dir('files_trashbin/files')) { |
|
| 156 | - $view->mkdir('files_trashbin/files'); |
|
| 157 | - } |
|
| 158 | - if (!$view->is_dir('files_trashbin/versions')) { |
|
| 159 | - $view->mkdir('files_trashbin/versions'); |
|
| 160 | - } |
|
| 161 | - if (!$view->is_dir('files_trashbin/keys')) { |
|
| 162 | - $view->mkdir('files_trashbin/keys'); |
|
| 163 | - } |
|
| 164 | - } |
|
| 165 | - |
|
| 166 | - |
|
| 167 | - /** |
|
| 168 | - * copy file to owners trash |
|
| 169 | - * |
|
| 170 | - * @param string $sourcePath |
|
| 171 | - * @param string $owner |
|
| 172 | - * @param string $targetPath |
|
| 173 | - * @param $user |
|
| 174 | - * @param integer $timestamp |
|
| 175 | - */ |
|
| 176 | - private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) { |
|
| 177 | - self::setUpTrash($owner); |
|
| 178 | - |
|
| 179 | - $targetFilename = basename($targetPath); |
|
| 180 | - $targetLocation = dirname($targetPath); |
|
| 181 | - |
|
| 182 | - $sourceFilename = basename($sourcePath); |
|
| 183 | - |
|
| 184 | - $view = new View('/'); |
|
| 185 | - |
|
| 186 | - $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp; |
|
| 187 | - $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp; |
|
| 188 | - self::copy_recursive($source, $target, $view); |
|
| 189 | - |
|
| 190 | - |
|
| 191 | - if ($view->file_exists($target)) { |
|
| 192 | - $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
| 193 | - $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user)); |
|
| 194 | - if (!$result) { |
|
| 195 | - \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR); |
|
| 196 | - } |
|
| 197 | - } |
|
| 198 | - } |
|
| 199 | - |
|
| 200 | - |
|
| 201 | - /** |
|
| 202 | - * move file to the trash bin |
|
| 203 | - * |
|
| 204 | - * @param string $file_path path to the deleted file/directory relative to the files root directory |
|
| 205 | - * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder) |
|
| 206 | - * |
|
| 207 | - * @return bool |
|
| 208 | - */ |
|
| 209 | - public static function move2trash($file_path, $ownerOnly = false) { |
|
| 210 | - // get the user for which the filesystem is setup |
|
| 211 | - $root = Filesystem::getRoot(); |
|
| 212 | - list(, $user) = explode('/', $root); |
|
| 213 | - list($owner, $ownerPath) = self::getUidAndFilename($file_path); |
|
| 214 | - |
|
| 215 | - // if no owner found (ex: ext storage + share link), will use the current user's trashbin then |
|
| 216 | - if (is_null($owner)) { |
|
| 217 | - $owner = $user; |
|
| 218 | - $ownerPath = $file_path; |
|
| 219 | - } |
|
| 220 | - |
|
| 221 | - $ownerView = new View('/' . $owner); |
|
| 222 | - // file has been deleted in between |
|
| 223 | - if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) { |
|
| 224 | - return true; |
|
| 225 | - } |
|
| 226 | - |
|
| 227 | - self::setUpTrash($user); |
|
| 228 | - if ($owner !== $user) { |
|
| 229 | - // also setup for owner |
|
| 230 | - self::setUpTrash($owner); |
|
| 231 | - } |
|
| 232 | - |
|
| 233 | - $path_parts = pathinfo($ownerPath); |
|
| 234 | - |
|
| 235 | - $filename = $path_parts['basename']; |
|
| 236 | - $location = $path_parts['dirname']; |
|
| 237 | - $timestamp = time(); |
|
| 238 | - |
|
| 239 | - // disable proxy to prevent recursive calls |
|
| 240 | - $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; |
|
| 241 | - |
|
| 242 | - /** @var \OC\Files\Storage\Storage $trashStorage */ |
|
| 243 | - list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); |
|
| 244 | - /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
| 245 | - list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); |
|
| 246 | - try { |
|
| 247 | - $moveSuccessful = true; |
|
| 248 | - if ($trashStorage->file_exists($trashInternalPath)) { |
|
| 249 | - $trashStorage->unlink($trashInternalPath); |
|
| 250 | - } |
|
| 251 | - $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
| 252 | - } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) { |
|
| 253 | - $moveSuccessful = false; |
|
| 254 | - if ($trashStorage->file_exists($trashInternalPath)) { |
|
| 255 | - $trashStorage->unlink($trashInternalPath); |
|
| 256 | - } |
|
| 257 | - \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR); |
|
| 258 | - } |
|
| 259 | - |
|
| 260 | - if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort |
|
| 261 | - if ($sourceStorage->is_dir($sourceInternalPath)) { |
|
| 262 | - $sourceStorage->rmdir($sourceInternalPath); |
|
| 263 | - } else { |
|
| 264 | - $sourceStorage->unlink($sourceInternalPath); |
|
| 265 | - } |
|
| 266 | - return false; |
|
| 267 | - } |
|
| 268 | - |
|
| 269 | - $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
| 270 | - |
|
| 271 | - if ($moveSuccessful) { |
|
| 272 | - $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
| 273 | - $result = $query->execute(array($filename, $timestamp, $location, $owner)); |
|
| 274 | - if (!$result) { |
|
| 275 | - \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR); |
|
| 276 | - } |
|
| 277 | - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path), |
|
| 278 | - 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp))); |
|
| 279 | - |
|
| 280 | - self::retainVersions($filename, $owner, $ownerPath, $timestamp); |
|
| 281 | - |
|
| 282 | - // if owner !== user we need to also add a copy to the users trash |
|
| 283 | - if ($user !== $owner && $ownerOnly === false) { |
|
| 284 | - self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp); |
|
| 285 | - } |
|
| 286 | - } |
|
| 287 | - |
|
| 288 | - self::scheduleExpire($user); |
|
| 289 | - |
|
| 290 | - // if owner !== user we also need to update the owners trash size |
|
| 291 | - if ($owner !== $user) { |
|
| 292 | - self::scheduleExpire($owner); |
|
| 293 | - } |
|
| 294 | - |
|
| 295 | - return $moveSuccessful; |
|
| 296 | - } |
|
| 297 | - |
|
| 298 | - /** |
|
| 299 | - * Move file versions to trash so that they can be restored later |
|
| 300 | - * |
|
| 301 | - * @param string $filename of deleted file |
|
| 302 | - * @param string $owner owner user id |
|
| 303 | - * @param string $ownerPath path relative to the owner's home storage |
|
| 304 | - * @param integer $timestamp when the file was deleted |
|
| 305 | - */ |
|
| 306 | - private static function retainVersions($filename, $owner, $ownerPath, $timestamp) { |
|
| 307 | - if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) { |
|
| 308 | - |
|
| 309 | - $user = User::getUser(); |
|
| 310 | - $rootView = new View('/'); |
|
| 311 | - |
|
| 312 | - if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { |
|
| 313 | - if ($owner !== $user) { |
|
| 314 | - self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView); |
|
| 315 | - } |
|
| 316 | - self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); |
|
| 317 | - } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { |
|
| 318 | - |
|
| 319 | - foreach ($versions as $v) { |
|
| 320 | - if ($owner !== $user) { |
|
| 321 | - self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); |
|
| 322 | - } |
|
| 323 | - self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp); |
|
| 324 | - } |
|
| 325 | - } |
|
| 326 | - } |
|
| 327 | - } |
|
| 328 | - |
|
| 329 | - /** |
|
| 330 | - * Move a file or folder on storage level |
|
| 331 | - * |
|
| 332 | - * @param View $view |
|
| 333 | - * @param string $source |
|
| 334 | - * @param string $target |
|
| 335 | - * @return bool |
|
| 336 | - */ |
|
| 337 | - private static function move(View $view, $source, $target) { |
|
| 338 | - /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
| 339 | - list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
| 340 | - /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
| 341 | - list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
| 342 | - /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
| 343 | - |
|
| 344 | - $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
| 345 | - if ($result) { |
|
| 346 | - $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
| 347 | - } |
|
| 348 | - return $result; |
|
| 349 | - } |
|
| 350 | - |
|
| 351 | - /** |
|
| 352 | - * Copy a file or folder on storage level |
|
| 353 | - * |
|
| 354 | - * @param View $view |
|
| 355 | - * @param string $source |
|
| 356 | - * @param string $target |
|
| 357 | - * @return bool |
|
| 358 | - */ |
|
| 359 | - private static function copy(View $view, $source, $target) { |
|
| 360 | - /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
| 361 | - list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
| 362 | - /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
| 363 | - list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
| 364 | - /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
| 365 | - |
|
| 366 | - $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
| 367 | - if ($result) { |
|
| 368 | - $targetStorage->getUpdater()->update($targetInternalPath); |
|
| 369 | - } |
|
| 370 | - return $result; |
|
| 371 | - } |
|
| 372 | - |
|
| 373 | - /** |
|
| 374 | - * Restore a file or folder from trash bin |
|
| 375 | - * |
|
| 376 | - * @param string $file path to the deleted file/folder relative to "files_trashbin/files/", |
|
| 377 | - * including the timestamp suffix ".d12345678" |
|
| 378 | - * @param string $filename name of the file/folder |
|
| 379 | - * @param int $timestamp time when the file/folder was deleted |
|
| 380 | - * |
|
| 381 | - * @return bool true on success, false otherwise |
|
| 382 | - */ |
|
| 383 | - public static function restore($file, $filename, $timestamp) { |
|
| 384 | - $user = User::getUser(); |
|
| 385 | - $view = new View('/' . $user); |
|
| 386 | - |
|
| 387 | - $location = ''; |
|
| 388 | - if ($timestamp) { |
|
| 389 | - $location = self::getLocation($user, $filename, $timestamp); |
|
| 390 | - if ($location === false) { |
|
| 391 | - \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR); |
|
| 392 | - } else { |
|
| 393 | - // if location no longer exists, restore file in the root directory |
|
| 394 | - if ($location !== '/' && |
|
| 395 | - (!$view->is_dir('files/' . $location) || |
|
| 396 | - !$view->isCreatable('files/' . $location)) |
|
| 397 | - ) { |
|
| 398 | - $location = ''; |
|
| 399 | - } |
|
| 400 | - } |
|
| 401 | - } |
|
| 402 | - |
|
| 403 | - // we need a extension in case a file/dir with the same name already exists |
|
| 404 | - $uniqueFilename = self::getUniqueFilename($location, $filename, $view); |
|
| 405 | - |
|
| 406 | - $source = Filesystem::normalizePath('files_trashbin/files/' . $file); |
|
| 407 | - $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); |
|
| 408 | - if (!$view->file_exists($source)) { |
|
| 409 | - return false; |
|
| 410 | - } |
|
| 411 | - $mtime = $view->filemtime($source); |
|
| 412 | - |
|
| 413 | - // restore file |
|
| 414 | - $restoreResult = $view->rename($source, $target); |
|
| 415 | - |
|
| 416 | - // handle the restore result |
|
| 417 | - if ($restoreResult) { |
|
| 418 | - $fakeRoot = $view->getRoot(); |
|
| 419 | - $view->chroot('/' . $user . '/files'); |
|
| 420 | - $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); |
|
| 421 | - $view->chroot($fakeRoot); |
|
| 422 | - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), |
|
| 423 | - 'trashPath' => Filesystem::normalizePath($file))); |
|
| 424 | - |
|
| 425 | - self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); |
|
| 426 | - |
|
| 427 | - if ($timestamp) { |
|
| 428 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
| 429 | - $query->execute(array($user, $filename, $timestamp)); |
|
| 430 | - } |
|
| 431 | - |
|
| 432 | - return true; |
|
| 433 | - } |
|
| 434 | - |
|
| 435 | - return false; |
|
| 436 | - } |
|
| 437 | - |
|
| 438 | - /** |
|
| 439 | - * restore versions from trash bin |
|
| 440 | - * |
|
| 441 | - * @param View $view file view |
|
| 442 | - * @param string $file complete path to file |
|
| 443 | - * @param string $filename name of file once it was deleted |
|
| 444 | - * @param string $uniqueFilename new file name to restore the file without overwriting existing files |
|
| 445 | - * @param string $location location if file |
|
| 446 | - * @param int $timestamp deletion time |
|
| 447 | - * @return false|null |
|
| 448 | - */ |
|
| 449 | - private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) { |
|
| 450 | - |
|
| 451 | - if (\OCP\App::isEnabled('files_versions')) { |
|
| 452 | - |
|
| 453 | - $user = User::getUser(); |
|
| 454 | - $rootView = new View('/'); |
|
| 455 | - |
|
| 456 | - $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); |
|
| 457 | - |
|
| 458 | - list($owner, $ownerPath) = self::getUidAndFilename($target); |
|
| 459 | - |
|
| 460 | - // file has been deleted in between |
|
| 461 | - if (empty($ownerPath)) { |
|
| 462 | - return false; |
|
| 463 | - } |
|
| 464 | - |
|
| 465 | - if ($timestamp) { |
|
| 466 | - $versionedFile = $filename; |
|
| 467 | - } else { |
|
| 468 | - $versionedFile = $file; |
|
| 469 | - } |
|
| 470 | - |
|
| 471 | - if ($view->is_dir('/files_trashbin/versions/' . $file)) { |
|
| 472 | - $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath)); |
|
| 473 | - } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) { |
|
| 474 | - foreach ($versions as $v) { |
|
| 475 | - if ($timestamp) { |
|
| 476 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
| 477 | - } else { |
|
| 478 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
| 479 | - } |
|
| 480 | - } |
|
| 481 | - } |
|
| 482 | - } |
|
| 483 | - } |
|
| 484 | - |
|
| 485 | - /** |
|
| 486 | - * delete all files from the trash |
|
| 487 | - */ |
|
| 488 | - public static function deleteAll() { |
|
| 489 | - $user = User::getUser(); |
|
| 490 | - $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
| 491 | - $view = new View('/' . $user); |
|
| 492 | - $fileInfos = $view->getDirectoryContent('files_trashbin/files'); |
|
| 493 | - |
|
| 494 | - try { |
|
| 495 | - $trash = $userRoot->get('files_trashbin'); |
|
| 496 | - } catch (NotFoundException $e) { |
|
| 497 | - return false; |
|
| 498 | - } |
|
| 499 | - |
|
| 500 | - // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) |
|
| 501 | - $filePaths = array(); |
|
| 502 | - foreach($fileInfos as $fileInfo){ |
|
| 503 | - $filePaths[] = $view->getRelativePath($fileInfo->getPath()); |
|
| 504 | - } |
|
| 505 | - unset($fileInfos); // save memory |
|
| 506 | - |
|
| 507 | - // Bulk PreDelete-Hook |
|
| 508 | - \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths)); |
|
| 509 | - |
|
| 510 | - // Single-File Hooks |
|
| 511 | - foreach($filePaths as $path){ |
|
| 512 | - self::emitTrashbinPreDelete($path); |
|
| 513 | - } |
|
| 514 | - |
|
| 515 | - // actual file deletion |
|
| 516 | - $trash->delete(); |
|
| 517 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
| 518 | - $query->execute(array($user)); |
|
| 519 | - |
|
| 520 | - // Bulk PostDelete-Hook |
|
| 521 | - \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths)); |
|
| 522 | - |
|
| 523 | - // Single-File Hooks |
|
| 524 | - foreach($filePaths as $path){ |
|
| 525 | - self::emitTrashbinPostDelete($path); |
|
| 526 | - } |
|
| 527 | - |
|
| 528 | - $trash = $userRoot->newFolder('files_trashbin'); |
|
| 529 | - $trash->newFolder('files'); |
|
| 530 | - |
|
| 531 | - return true; |
|
| 532 | - } |
|
| 533 | - |
|
| 534 | - /** |
|
| 535 | - * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted |
|
| 536 | - * @param string $path |
|
| 537 | - */ |
|
| 538 | - protected static function emitTrashbinPreDelete($path){ |
|
| 539 | - \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path)); |
|
| 540 | - } |
|
| 541 | - |
|
| 542 | - /** |
|
| 543 | - * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted |
|
| 544 | - * @param string $path |
|
| 545 | - */ |
|
| 546 | - protected static function emitTrashbinPostDelete($path){ |
|
| 547 | - \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path)); |
|
| 548 | - } |
|
| 549 | - |
|
| 550 | - /** |
|
| 551 | - * delete file from trash bin permanently |
|
| 552 | - * |
|
| 553 | - * @param string $filename path to the file |
|
| 554 | - * @param string $user |
|
| 555 | - * @param int $timestamp of deletion time |
|
| 556 | - * |
|
| 557 | - * @return int size of deleted files |
|
| 558 | - */ |
|
| 559 | - public static function delete($filename, $user, $timestamp = null) { |
|
| 560 | - $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
| 561 | - $view = new View('/' . $user); |
|
| 562 | - $size = 0; |
|
| 563 | - |
|
| 564 | - if ($timestamp) { |
|
| 565 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
| 566 | - $query->execute(array($user, $filename, $timestamp)); |
|
| 567 | - $file = $filename . '.d' . $timestamp; |
|
| 568 | - } else { |
|
| 569 | - $file = $filename; |
|
| 570 | - } |
|
| 571 | - |
|
| 572 | - $size += self::deleteVersions($view, $file, $filename, $timestamp, $user); |
|
| 573 | - |
|
| 574 | - try { |
|
| 575 | - $node = $userRoot->get('/files_trashbin/files/' . $file); |
|
| 576 | - } catch (NotFoundException $e) { |
|
| 577 | - return $size; |
|
| 578 | - } |
|
| 579 | - |
|
| 580 | - if ($node instanceof Folder) { |
|
| 581 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file)); |
|
| 582 | - } else if ($node instanceof File) { |
|
| 583 | - $size += $view->filesize('/files_trashbin/files/' . $file); |
|
| 584 | - } |
|
| 585 | - |
|
| 586 | - self::emitTrashbinPreDelete('/files_trashbin/files/' . $file); |
|
| 587 | - $node->delete(); |
|
| 588 | - self::emitTrashbinPostDelete('/files_trashbin/files/' . $file); |
|
| 589 | - |
|
| 590 | - return $size; |
|
| 591 | - } |
|
| 592 | - |
|
| 593 | - /** |
|
| 594 | - * @param View $view |
|
| 595 | - * @param string $file |
|
| 596 | - * @param string $filename |
|
| 597 | - * @param integer|null $timestamp |
|
| 598 | - * @param string $user |
|
| 599 | - * @return int |
|
| 600 | - */ |
|
| 601 | - private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) { |
|
| 602 | - $size = 0; |
|
| 603 | - if (\OCP\App::isEnabled('files_versions')) { |
|
| 604 | - if ($view->is_dir('files_trashbin/versions/' . $file)) { |
|
| 605 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file)); |
|
| 606 | - $view->unlink('files_trashbin/versions/' . $file); |
|
| 607 | - } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) { |
|
| 608 | - foreach ($versions as $v) { |
|
| 609 | - if ($timestamp) { |
|
| 610 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
| 611 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
| 612 | - } else { |
|
| 613 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
| 614 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
| 615 | - } |
|
| 616 | - } |
|
| 617 | - } |
|
| 618 | - } |
|
| 619 | - return $size; |
|
| 620 | - } |
|
| 621 | - |
|
| 622 | - /** |
|
| 623 | - * check to see whether a file exists in trashbin |
|
| 624 | - * |
|
| 625 | - * @param string $filename path to the file |
|
| 626 | - * @param int $timestamp of deletion time |
|
| 627 | - * @return bool true if file exists, otherwise false |
|
| 628 | - */ |
|
| 629 | - public static function file_exists($filename, $timestamp = null) { |
|
| 630 | - $user = User::getUser(); |
|
| 631 | - $view = new View('/' . $user); |
|
| 632 | - |
|
| 633 | - if ($timestamp) { |
|
| 634 | - $filename = $filename . '.d' . $timestamp; |
|
| 635 | - } else { |
|
| 636 | - $filename = $filename; |
|
| 637 | - } |
|
| 638 | - |
|
| 639 | - $target = Filesystem::normalizePath('files_trashbin/files/' . $filename); |
|
| 640 | - return $view->file_exists($target); |
|
| 641 | - } |
|
| 642 | - |
|
| 643 | - /** |
|
| 644 | - * deletes used space for trash bin in db if user was deleted |
|
| 645 | - * |
|
| 646 | - * @param string $uid id of deleted user |
|
| 647 | - * @return bool result of db delete operation |
|
| 648 | - */ |
|
| 649 | - public static function deleteUser($uid) { |
|
| 650 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
| 651 | - return $query->execute(array($uid)); |
|
| 652 | - } |
|
| 653 | - |
|
| 654 | - /** |
|
| 655 | - * calculate remaining free space for trash bin |
|
| 656 | - * |
|
| 657 | - * @param integer $trashbinSize current size of the trash bin |
|
| 658 | - * @param string $user |
|
| 659 | - * @return int available free space for trash bin |
|
| 660 | - */ |
|
| 661 | - private static function calculateFreeSpace($trashbinSize, $user) { |
|
| 662 | - $softQuota = true; |
|
| 663 | - $userObject = \OC::$server->getUserManager()->get($user); |
|
| 664 | - if(is_null($userObject)) { |
|
| 665 | - return 0; |
|
| 666 | - } |
|
| 667 | - $quota = $userObject->getQuota(); |
|
| 668 | - if ($quota === null || $quota === 'none') { |
|
| 669 | - $quota = Filesystem::free_space('/'); |
|
| 670 | - $softQuota = false; |
|
| 671 | - // inf or unknown free space |
|
| 672 | - if ($quota < 0) { |
|
| 673 | - $quota = PHP_INT_MAX; |
|
| 674 | - } |
|
| 675 | - } else { |
|
| 676 | - $quota = \OCP\Util::computerFileSize($quota); |
|
| 677 | - } |
|
| 678 | - |
|
| 679 | - // calculate available space for trash bin |
|
| 680 | - // subtract size of files and current trash bin size from quota |
|
| 681 | - if ($softQuota) { |
|
| 682 | - $userFolder = \OC::$server->getUserFolder($user); |
|
| 683 | - if(is_null($userFolder)) { |
|
| 684 | - return 0; |
|
| 685 | - } |
|
| 686 | - $free = $quota - $userFolder->getSize(); // remaining free space for user |
|
| 687 | - if ($free > 0) { |
|
| 688 | - $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions |
|
| 689 | - } else { |
|
| 690 | - $availableSpace = $free - $trashbinSize; |
|
| 691 | - } |
|
| 692 | - } else { |
|
| 693 | - $availableSpace = $quota; |
|
| 694 | - } |
|
| 695 | - |
|
| 696 | - return $availableSpace; |
|
| 697 | - } |
|
| 698 | - |
|
| 699 | - /** |
|
| 700 | - * resize trash bin if necessary after a new file was added to Nextcloud |
|
| 701 | - * |
|
| 702 | - * @param string $user user id |
|
| 703 | - */ |
|
| 704 | - public static function resizeTrash($user) { |
|
| 705 | - |
|
| 706 | - $size = self::getTrashbinSize($user); |
|
| 707 | - |
|
| 708 | - $freeSpace = self::calculateFreeSpace($size, $user); |
|
| 709 | - |
|
| 710 | - if ($freeSpace < 0) { |
|
| 711 | - self::scheduleExpire($user); |
|
| 712 | - } |
|
| 713 | - } |
|
| 714 | - |
|
| 715 | - /** |
|
| 716 | - * clean up the trash bin |
|
| 717 | - * |
|
| 718 | - * @param string $user |
|
| 719 | - */ |
|
| 720 | - public static function expire($user) { |
|
| 721 | - $trashBinSize = self::getTrashbinSize($user); |
|
| 722 | - $availableSpace = self::calculateFreeSpace($trashBinSize, $user); |
|
| 723 | - |
|
| 724 | - $dirContent = Helper::getTrashFiles('/', $user, 'mtime'); |
|
| 725 | - |
|
| 726 | - // delete all files older then $retention_obligation |
|
| 727 | - list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user); |
|
| 728 | - |
|
| 729 | - $availableSpace += $delSize; |
|
| 730 | - |
|
| 731 | - // delete files from trash until we meet the trash bin size limit again |
|
| 732 | - self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace); |
|
| 733 | - } |
|
| 734 | - |
|
| 735 | - /** |
|
| 736 | - * @param string $user |
|
| 737 | - */ |
|
| 738 | - private static function scheduleExpire($user) { |
|
| 739 | - // let the admin disable auto expire |
|
| 740 | - $application = new Application(); |
|
| 741 | - $expiration = $application->getContainer()->query('Expiration'); |
|
| 742 | - if ($expiration->isEnabled()) { |
|
| 743 | - \OC::$server->getCommandBus()->push(new Expire($user)); |
|
| 744 | - } |
|
| 745 | - } |
|
| 746 | - |
|
| 747 | - /** |
|
| 748 | - * if the size limit for the trash bin is reached, we delete the oldest |
|
| 749 | - * files in the trash bin until we meet the limit again |
|
| 750 | - * |
|
| 751 | - * @param array $files |
|
| 752 | - * @param string $user |
|
| 753 | - * @param int $availableSpace available disc space |
|
| 754 | - * @return int size of deleted files |
|
| 755 | - */ |
|
| 756 | - protected static function deleteFiles($files, $user, $availableSpace) { |
|
| 757 | - $application = new Application(); |
|
| 758 | - $expiration = $application->getContainer()->query('Expiration'); |
|
| 759 | - $size = 0; |
|
| 760 | - |
|
| 761 | - if ($availableSpace < 0) { |
|
| 762 | - foreach ($files as $file) { |
|
| 763 | - if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) { |
|
| 764 | - $tmp = self::delete($file['name'], $user, $file['mtime']); |
|
| 765 | - \OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO); |
|
| 766 | - $availableSpace += $tmp; |
|
| 767 | - $size += $tmp; |
|
| 768 | - } else { |
|
| 769 | - break; |
|
| 770 | - } |
|
| 771 | - } |
|
| 772 | - } |
|
| 773 | - return $size; |
|
| 774 | - } |
|
| 775 | - |
|
| 776 | - /** |
|
| 777 | - * delete files older then max storage time |
|
| 778 | - * |
|
| 779 | - * @param array $files list of files sorted by mtime |
|
| 780 | - * @param string $user |
|
| 781 | - * @return integer[] size of deleted files and number of deleted files |
|
| 782 | - */ |
|
| 783 | - public static function deleteExpiredFiles($files, $user) { |
|
| 784 | - $application = new Application(); |
|
| 785 | - $expiration = $application->getContainer()->query('Expiration'); |
|
| 786 | - $size = 0; |
|
| 787 | - $count = 0; |
|
| 788 | - foreach ($files as $file) { |
|
| 789 | - $timestamp = $file['mtime']; |
|
| 790 | - $filename = $file['name']; |
|
| 791 | - if ($expiration->isExpired($timestamp)) { |
|
| 792 | - $count++; |
|
| 793 | - $size += self::delete($filename, $user, $timestamp); |
|
| 794 | - \OC::$server->getLogger()->info( |
|
| 795 | - 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.', |
|
| 796 | - ['app' => 'files_trashbin'] |
|
| 797 | - ); |
|
| 798 | - } else { |
|
| 799 | - break; |
|
| 800 | - } |
|
| 801 | - } |
|
| 802 | - |
|
| 803 | - return array($size, $count); |
|
| 804 | - } |
|
| 805 | - |
|
| 806 | - /** |
|
| 807 | - * recursive copy to copy a whole directory |
|
| 808 | - * |
|
| 809 | - * @param string $source source path, relative to the users files directory |
|
| 810 | - * @param string $destination destination path relative to the users root directoy |
|
| 811 | - * @param View $view file view for the users root directory |
|
| 812 | - * @return int |
|
| 813 | - * @throws Exceptions\CopyRecursiveException |
|
| 814 | - */ |
|
| 815 | - private static function copy_recursive($source, $destination, View $view) { |
|
| 816 | - $size = 0; |
|
| 817 | - if ($view->is_dir($source)) { |
|
| 818 | - $view->mkdir($destination); |
|
| 819 | - $view->touch($destination, $view->filemtime($source)); |
|
| 820 | - foreach ($view->getDirectoryContent($source) as $i) { |
|
| 821 | - $pathDir = $source . '/' . $i['name']; |
|
| 822 | - if ($view->is_dir($pathDir)) { |
|
| 823 | - $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view); |
|
| 824 | - } else { |
|
| 825 | - $size += $view->filesize($pathDir); |
|
| 826 | - $result = $view->copy($pathDir, $destination . '/' . $i['name']); |
|
| 827 | - if (!$result) { |
|
| 828 | - throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
| 829 | - } |
|
| 830 | - $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir)); |
|
| 831 | - } |
|
| 832 | - } |
|
| 833 | - } else { |
|
| 834 | - $size += $view->filesize($source); |
|
| 835 | - $result = $view->copy($source, $destination); |
|
| 836 | - if (!$result) { |
|
| 837 | - throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
| 838 | - } |
|
| 839 | - $view->touch($destination, $view->filemtime($source)); |
|
| 840 | - } |
|
| 841 | - return $size; |
|
| 842 | - } |
|
| 843 | - |
|
| 844 | - /** |
|
| 845 | - * find all versions which belong to the file we want to restore |
|
| 846 | - * |
|
| 847 | - * @param string $filename name of the file which should be restored |
|
| 848 | - * @param int $timestamp timestamp when the file was deleted |
|
| 849 | - * @return array |
|
| 850 | - */ |
|
| 851 | - private static function getVersionsFromTrash($filename, $timestamp, $user) { |
|
| 852 | - $view = new View('/' . $user . '/files_trashbin/versions'); |
|
| 853 | - $versions = array(); |
|
| 854 | - |
|
| 855 | - //force rescan of versions, local storage may not have updated the cache |
|
| 856 | - if (!self::$scannedVersions) { |
|
| 857 | - /** @var \OC\Files\Storage\Storage $storage */ |
|
| 858 | - list($storage,) = $view->resolvePath('/'); |
|
| 859 | - $storage->getScanner()->scan('files_trashbin/versions'); |
|
| 860 | - self::$scannedVersions = true; |
|
| 861 | - } |
|
| 862 | - |
|
| 863 | - if ($timestamp) { |
|
| 864 | - // fetch for old versions |
|
| 865 | - $matches = $view->searchRaw($filename . '.v%.d' . $timestamp); |
|
| 866 | - $offset = -strlen($timestamp) - 2; |
|
| 867 | - } else { |
|
| 868 | - $matches = $view->searchRaw($filename . '.v%'); |
|
| 869 | - } |
|
| 870 | - |
|
| 871 | - if (is_array($matches)) { |
|
| 872 | - foreach ($matches as $ma) { |
|
| 873 | - if ($timestamp) { |
|
| 874 | - $parts = explode('.v', substr($ma['path'], 0, $offset)); |
|
| 875 | - $versions[] = (end($parts)); |
|
| 876 | - } else { |
|
| 877 | - $parts = explode('.v', $ma); |
|
| 878 | - $versions[] = (end($parts)); |
|
| 879 | - } |
|
| 880 | - } |
|
| 881 | - } |
|
| 882 | - return $versions; |
|
| 883 | - } |
|
| 884 | - |
|
| 885 | - /** |
|
| 886 | - * find unique extension for restored file if a file with the same name already exists |
|
| 887 | - * |
|
| 888 | - * @param string $location where the file should be restored |
|
| 889 | - * @param string $filename name of the file |
|
| 890 | - * @param View $view filesystem view relative to users root directory |
|
| 891 | - * @return string with unique extension |
|
| 892 | - */ |
|
| 893 | - private static function getUniqueFilename($location, $filename, View $view) { |
|
| 894 | - $ext = pathinfo($filename, PATHINFO_EXTENSION); |
|
| 895 | - $name = pathinfo($filename, PATHINFO_FILENAME); |
|
| 896 | - $l = \OC::$server->getL10N('files_trashbin'); |
|
| 897 | - |
|
| 898 | - $location = '/' . trim($location, '/'); |
|
| 899 | - |
|
| 900 | - // if extension is not empty we set a dot in front of it |
|
| 901 | - if ($ext !== '') { |
|
| 902 | - $ext = '.' . $ext; |
|
| 903 | - } |
|
| 904 | - |
|
| 905 | - if ($view->file_exists('files' . $location . '/' . $filename)) { |
|
| 906 | - $i = 2; |
|
| 907 | - $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext; |
|
| 908 | - while ($view->file_exists('files' . $location . '/' . $uniqueName)) { |
|
| 909 | - $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext; |
|
| 910 | - $i++; |
|
| 911 | - } |
|
| 912 | - |
|
| 913 | - return $uniqueName; |
|
| 914 | - } |
|
| 915 | - |
|
| 916 | - return $filename; |
|
| 917 | - } |
|
| 918 | - |
|
| 919 | - /** |
|
| 920 | - * get the size from a given root folder |
|
| 921 | - * |
|
| 922 | - * @param View $view file view on the root folder |
|
| 923 | - * @return integer size of the folder |
|
| 924 | - */ |
|
| 925 | - private static function calculateSize($view) { |
|
| 926 | - $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath(''); |
|
| 927 | - if (!file_exists($root)) { |
|
| 928 | - return 0; |
|
| 929 | - } |
|
| 930 | - $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST); |
|
| 931 | - $size = 0; |
|
| 932 | - |
|
| 933 | - /** |
|
| 934 | - * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach |
|
| 935 | - * This bug is fixed in PHP 5.5.9 or before |
|
| 936 | - * See #8376 |
|
| 937 | - */ |
|
| 938 | - $iterator->rewind(); |
|
| 939 | - while ($iterator->valid()) { |
|
| 940 | - $path = $iterator->current(); |
|
| 941 | - $relpath = substr($path, strlen($root) - 1); |
|
| 942 | - if (!$view->is_dir($relpath)) { |
|
| 943 | - $size += $view->filesize($relpath); |
|
| 944 | - } |
|
| 945 | - $iterator->next(); |
|
| 946 | - } |
|
| 947 | - return $size; |
|
| 948 | - } |
|
| 949 | - |
|
| 950 | - /** |
|
| 951 | - * get current size of trash bin from a given user |
|
| 952 | - * |
|
| 953 | - * @param string $user user who owns the trash bin |
|
| 954 | - * @return integer trash bin size |
|
| 955 | - */ |
|
| 956 | - private static function getTrashbinSize($user) { |
|
| 957 | - $view = new View('/' . $user); |
|
| 958 | - $fileInfo = $view->getFileInfo('/files_trashbin'); |
|
| 959 | - return isset($fileInfo['size']) ? $fileInfo['size'] : 0; |
|
| 960 | - } |
|
| 961 | - |
|
| 962 | - /** |
|
| 963 | - * register hooks |
|
| 964 | - */ |
|
| 965 | - public static function registerHooks() { |
|
| 966 | - // create storage wrapper on setup |
|
| 967 | - \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage'); |
|
| 968 | - //Listen to delete user signal |
|
| 969 | - \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook'); |
|
| 970 | - //Listen to post write hook |
|
| 971 | - \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook'); |
|
| 972 | - // pre and post-rename, disable trash logic for the copy+unlink case |
|
| 973 | - \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook'); |
|
| 974 | - \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook'); |
|
| 975 | - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook'); |
|
| 976 | - } |
|
| 977 | - |
|
| 978 | - /** |
|
| 979 | - * check if trash bin is empty for a given user |
|
| 980 | - * |
|
| 981 | - * @param string $user |
|
| 982 | - * @return bool |
|
| 983 | - */ |
|
| 984 | - public static function isEmpty($user) { |
|
| 985 | - |
|
| 986 | - $view = new View('/' . $user . '/files_trashbin'); |
|
| 987 | - if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { |
|
| 988 | - while ($file = readdir($dh)) { |
|
| 989 | - if (!Filesystem::isIgnoredDir($file)) { |
|
| 990 | - return false; |
|
| 991 | - } |
|
| 992 | - } |
|
| 993 | - } |
|
| 994 | - return true; |
|
| 995 | - } |
|
| 996 | - |
|
| 997 | - /** |
|
| 998 | - * @param $path |
|
| 999 | - * @return string |
|
| 1000 | - */ |
|
| 1001 | - public static function preview_icon($path) { |
|
| 1002 | - return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path)); |
|
| 1003 | - } |
|
| 52 | + // unit: percentage; 50% of available disk space/quota |
|
| 53 | + const DEFAULTMAXSIZE = 50; |
|
| 54 | + |
|
| 55 | + /** |
|
| 56 | + * Whether versions have already be rescanned during this PHP request |
|
| 57 | + * |
|
| 58 | + * @var bool |
|
| 59 | + */ |
|
| 60 | + private static $scannedVersions = false; |
|
| 61 | + |
|
| 62 | + /** |
|
| 63 | + * Ensure we don't need to scan the file during the move to trash |
|
| 64 | + * by triggering the scan in the pre-hook |
|
| 65 | + * |
|
| 66 | + * @param array $params |
|
| 67 | + */ |
|
| 68 | + public static function ensureFileScannedHook($params) { |
|
| 69 | + try { |
|
| 70 | + self::getUidAndFilename($params['path']); |
|
| 71 | + } catch (NotFoundException $e) { |
|
| 72 | + // nothing to scan for non existing files |
|
| 73 | + } |
|
| 74 | + } |
|
| 75 | + |
|
| 76 | + /** |
|
| 77 | + * get the UID of the owner of the file and the path to the file relative to |
|
| 78 | + * owners files folder |
|
| 79 | + * |
|
| 80 | + * @param string $filename |
|
| 81 | + * @return array |
|
| 82 | + * @throws \OC\User\NoUserException |
|
| 83 | + */ |
|
| 84 | + public static function getUidAndFilename($filename) { |
|
| 85 | + $uid = Filesystem::getOwner($filename); |
|
| 86 | + $userManager = \OC::$server->getUserManager(); |
|
| 87 | + // if the user with the UID doesn't exists, e.g. because the UID points |
|
| 88 | + // to a remote user with a federated cloud ID we use the current logged-in |
|
| 89 | + // user. We need a valid local user to move the file to the right trash bin |
|
| 90 | + if (!$userManager->userExists($uid)) { |
|
| 91 | + $uid = User::getUser(); |
|
| 92 | + } |
|
| 93 | + if (!$uid) { |
|
| 94 | + // no owner, usually because of share link from ext storage |
|
| 95 | + return [null, null]; |
|
| 96 | + } |
|
| 97 | + Filesystem::initMountPoints($uid); |
|
| 98 | + if ($uid !== User::getUser()) { |
|
| 99 | + $info = Filesystem::getFileInfo($filename); |
|
| 100 | + $ownerView = new View('/' . $uid . '/files'); |
|
| 101 | + try { |
|
| 102 | + $filename = $ownerView->getPath($info['fileid']); |
|
| 103 | + } catch (NotFoundException $e) { |
|
| 104 | + $filename = null; |
|
| 105 | + } |
|
| 106 | + } |
|
| 107 | + return [$uid, $filename]; |
|
| 108 | + } |
|
| 109 | + |
|
| 110 | + /** |
|
| 111 | + * get original location of files for user |
|
| 112 | + * |
|
| 113 | + * @param string $user |
|
| 114 | + * @return array (filename => array (timestamp => original location)) |
|
| 115 | + */ |
|
| 116 | + public static function getLocations($user) { |
|
| 117 | + $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`' |
|
| 118 | + . ' FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
| 119 | + $result = $query->execute(array($user)); |
|
| 120 | + $array = array(); |
|
| 121 | + while ($row = $result->fetchRow()) { |
|
| 122 | + if (isset($array[$row['id']])) { |
|
| 123 | + $array[$row['id']][$row['timestamp']] = $row['location']; |
|
| 124 | + } else { |
|
| 125 | + $array[$row['id']] = array($row['timestamp'] => $row['location']); |
|
| 126 | + } |
|
| 127 | + } |
|
| 128 | + return $array; |
|
| 129 | + } |
|
| 130 | + |
|
| 131 | + /** |
|
| 132 | + * get original location of file |
|
| 133 | + * |
|
| 134 | + * @param string $user |
|
| 135 | + * @param string $filename |
|
| 136 | + * @param string $timestamp |
|
| 137 | + * @return string original location |
|
| 138 | + */ |
|
| 139 | + public static function getLocation($user, $filename, $timestamp) { |
|
| 140 | + $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`' |
|
| 141 | + . ' WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
| 142 | + $result = $query->execute(array($user, $filename, $timestamp))->fetchAll(); |
|
| 143 | + if (isset($result[0]['location'])) { |
|
| 144 | + return $result[0]['location']; |
|
| 145 | + } else { |
|
| 146 | + return false; |
|
| 147 | + } |
|
| 148 | + } |
|
| 149 | + |
|
| 150 | + private static function setUpTrash($user) { |
|
| 151 | + $view = new View('/' . $user); |
|
| 152 | + if (!$view->is_dir('files_trashbin')) { |
|
| 153 | + $view->mkdir('files_trashbin'); |
|
| 154 | + } |
|
| 155 | + if (!$view->is_dir('files_trashbin/files')) { |
|
| 156 | + $view->mkdir('files_trashbin/files'); |
|
| 157 | + } |
|
| 158 | + if (!$view->is_dir('files_trashbin/versions')) { |
|
| 159 | + $view->mkdir('files_trashbin/versions'); |
|
| 160 | + } |
|
| 161 | + if (!$view->is_dir('files_trashbin/keys')) { |
|
| 162 | + $view->mkdir('files_trashbin/keys'); |
|
| 163 | + } |
|
| 164 | + } |
|
| 165 | + |
|
| 166 | + |
|
| 167 | + /** |
|
| 168 | + * copy file to owners trash |
|
| 169 | + * |
|
| 170 | + * @param string $sourcePath |
|
| 171 | + * @param string $owner |
|
| 172 | + * @param string $targetPath |
|
| 173 | + * @param $user |
|
| 174 | + * @param integer $timestamp |
|
| 175 | + */ |
|
| 176 | + private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) { |
|
| 177 | + self::setUpTrash($owner); |
|
| 178 | + |
|
| 179 | + $targetFilename = basename($targetPath); |
|
| 180 | + $targetLocation = dirname($targetPath); |
|
| 181 | + |
|
| 182 | + $sourceFilename = basename($sourcePath); |
|
| 183 | + |
|
| 184 | + $view = new View('/'); |
|
| 185 | + |
|
| 186 | + $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp; |
|
| 187 | + $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp; |
|
| 188 | + self::copy_recursive($source, $target, $view); |
|
| 189 | + |
|
| 190 | + |
|
| 191 | + if ($view->file_exists($target)) { |
|
| 192 | + $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
| 193 | + $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user)); |
|
| 194 | + if (!$result) { |
|
| 195 | + \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR); |
|
| 196 | + } |
|
| 197 | + } |
|
| 198 | + } |
|
| 199 | + |
|
| 200 | + |
|
| 201 | + /** |
|
| 202 | + * move file to the trash bin |
|
| 203 | + * |
|
| 204 | + * @param string $file_path path to the deleted file/directory relative to the files root directory |
|
| 205 | + * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder) |
|
| 206 | + * |
|
| 207 | + * @return bool |
|
| 208 | + */ |
|
| 209 | + public static function move2trash($file_path, $ownerOnly = false) { |
|
| 210 | + // get the user for which the filesystem is setup |
|
| 211 | + $root = Filesystem::getRoot(); |
|
| 212 | + list(, $user) = explode('/', $root); |
|
| 213 | + list($owner, $ownerPath) = self::getUidAndFilename($file_path); |
|
| 214 | + |
|
| 215 | + // if no owner found (ex: ext storage + share link), will use the current user's trashbin then |
|
| 216 | + if (is_null($owner)) { |
|
| 217 | + $owner = $user; |
|
| 218 | + $ownerPath = $file_path; |
|
| 219 | + } |
|
| 220 | + |
|
| 221 | + $ownerView = new View('/' . $owner); |
|
| 222 | + // file has been deleted in between |
|
| 223 | + if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) { |
|
| 224 | + return true; |
|
| 225 | + } |
|
| 226 | + |
|
| 227 | + self::setUpTrash($user); |
|
| 228 | + if ($owner !== $user) { |
|
| 229 | + // also setup for owner |
|
| 230 | + self::setUpTrash($owner); |
|
| 231 | + } |
|
| 232 | + |
|
| 233 | + $path_parts = pathinfo($ownerPath); |
|
| 234 | + |
|
| 235 | + $filename = $path_parts['basename']; |
|
| 236 | + $location = $path_parts['dirname']; |
|
| 237 | + $timestamp = time(); |
|
| 238 | + |
|
| 239 | + // disable proxy to prevent recursive calls |
|
| 240 | + $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; |
|
| 241 | + |
|
| 242 | + /** @var \OC\Files\Storage\Storage $trashStorage */ |
|
| 243 | + list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); |
|
| 244 | + /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
| 245 | + list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); |
|
| 246 | + try { |
|
| 247 | + $moveSuccessful = true; |
|
| 248 | + if ($trashStorage->file_exists($trashInternalPath)) { |
|
| 249 | + $trashStorage->unlink($trashInternalPath); |
|
| 250 | + } |
|
| 251 | + $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
| 252 | + } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) { |
|
| 253 | + $moveSuccessful = false; |
|
| 254 | + if ($trashStorage->file_exists($trashInternalPath)) { |
|
| 255 | + $trashStorage->unlink($trashInternalPath); |
|
| 256 | + } |
|
| 257 | + \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR); |
|
| 258 | + } |
|
| 259 | + |
|
| 260 | + if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort |
|
| 261 | + if ($sourceStorage->is_dir($sourceInternalPath)) { |
|
| 262 | + $sourceStorage->rmdir($sourceInternalPath); |
|
| 263 | + } else { |
|
| 264 | + $sourceStorage->unlink($sourceInternalPath); |
|
| 265 | + } |
|
| 266 | + return false; |
|
| 267 | + } |
|
| 268 | + |
|
| 269 | + $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
| 270 | + |
|
| 271 | + if ($moveSuccessful) { |
|
| 272 | + $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
| 273 | + $result = $query->execute(array($filename, $timestamp, $location, $owner)); |
|
| 274 | + if (!$result) { |
|
| 275 | + \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR); |
|
| 276 | + } |
|
| 277 | + \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path), |
|
| 278 | + 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp))); |
|
| 279 | + |
|
| 280 | + self::retainVersions($filename, $owner, $ownerPath, $timestamp); |
|
| 281 | + |
|
| 282 | + // if owner !== user we need to also add a copy to the users trash |
|
| 283 | + if ($user !== $owner && $ownerOnly === false) { |
|
| 284 | + self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp); |
|
| 285 | + } |
|
| 286 | + } |
|
| 287 | + |
|
| 288 | + self::scheduleExpire($user); |
|
| 289 | + |
|
| 290 | + // if owner !== user we also need to update the owners trash size |
|
| 291 | + if ($owner !== $user) { |
|
| 292 | + self::scheduleExpire($owner); |
|
| 293 | + } |
|
| 294 | + |
|
| 295 | + return $moveSuccessful; |
|
| 296 | + } |
|
| 297 | + |
|
| 298 | + /** |
|
| 299 | + * Move file versions to trash so that they can be restored later |
|
| 300 | + * |
|
| 301 | + * @param string $filename of deleted file |
|
| 302 | + * @param string $owner owner user id |
|
| 303 | + * @param string $ownerPath path relative to the owner's home storage |
|
| 304 | + * @param integer $timestamp when the file was deleted |
|
| 305 | + */ |
|
| 306 | + private static function retainVersions($filename, $owner, $ownerPath, $timestamp) { |
|
| 307 | + if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) { |
|
| 308 | + |
|
| 309 | + $user = User::getUser(); |
|
| 310 | + $rootView = new View('/'); |
|
| 311 | + |
|
| 312 | + if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { |
|
| 313 | + if ($owner !== $user) { |
|
| 314 | + self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView); |
|
| 315 | + } |
|
| 316 | + self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); |
|
| 317 | + } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { |
|
| 318 | + |
|
| 319 | + foreach ($versions as $v) { |
|
| 320 | + if ($owner !== $user) { |
|
| 321 | + self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); |
|
| 322 | + } |
|
| 323 | + self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp); |
|
| 324 | + } |
|
| 325 | + } |
|
| 326 | + } |
|
| 327 | + } |
|
| 328 | + |
|
| 329 | + /** |
|
| 330 | + * Move a file or folder on storage level |
|
| 331 | + * |
|
| 332 | + * @param View $view |
|
| 333 | + * @param string $source |
|
| 334 | + * @param string $target |
|
| 335 | + * @return bool |
|
| 336 | + */ |
|
| 337 | + private static function move(View $view, $source, $target) { |
|
| 338 | + /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
| 339 | + list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
| 340 | + /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
| 341 | + list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
| 342 | + /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
| 343 | + |
|
| 344 | + $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
| 345 | + if ($result) { |
|
| 346 | + $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
| 347 | + } |
|
| 348 | + return $result; |
|
| 349 | + } |
|
| 350 | + |
|
| 351 | + /** |
|
| 352 | + * Copy a file or folder on storage level |
|
| 353 | + * |
|
| 354 | + * @param View $view |
|
| 355 | + * @param string $source |
|
| 356 | + * @param string $target |
|
| 357 | + * @return bool |
|
| 358 | + */ |
|
| 359 | + private static function copy(View $view, $source, $target) { |
|
| 360 | + /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
| 361 | + list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
| 362 | + /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
| 363 | + list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
| 364 | + /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
| 365 | + |
|
| 366 | + $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
| 367 | + if ($result) { |
|
| 368 | + $targetStorage->getUpdater()->update($targetInternalPath); |
|
| 369 | + } |
|
| 370 | + return $result; |
|
| 371 | + } |
|
| 372 | + |
|
| 373 | + /** |
|
| 374 | + * Restore a file or folder from trash bin |
|
| 375 | + * |
|
| 376 | + * @param string $file path to the deleted file/folder relative to "files_trashbin/files/", |
|
| 377 | + * including the timestamp suffix ".d12345678" |
|
| 378 | + * @param string $filename name of the file/folder |
|
| 379 | + * @param int $timestamp time when the file/folder was deleted |
|
| 380 | + * |
|
| 381 | + * @return bool true on success, false otherwise |
|
| 382 | + */ |
|
| 383 | + public static function restore($file, $filename, $timestamp) { |
|
| 384 | + $user = User::getUser(); |
|
| 385 | + $view = new View('/' . $user); |
|
| 386 | + |
|
| 387 | + $location = ''; |
|
| 388 | + if ($timestamp) { |
|
| 389 | + $location = self::getLocation($user, $filename, $timestamp); |
|
| 390 | + if ($location === false) { |
|
| 391 | + \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR); |
|
| 392 | + } else { |
|
| 393 | + // if location no longer exists, restore file in the root directory |
|
| 394 | + if ($location !== '/' && |
|
| 395 | + (!$view->is_dir('files/' . $location) || |
|
| 396 | + !$view->isCreatable('files/' . $location)) |
|
| 397 | + ) { |
|
| 398 | + $location = ''; |
|
| 399 | + } |
|
| 400 | + } |
|
| 401 | + } |
|
| 402 | + |
|
| 403 | + // we need a extension in case a file/dir with the same name already exists |
|
| 404 | + $uniqueFilename = self::getUniqueFilename($location, $filename, $view); |
|
| 405 | + |
|
| 406 | + $source = Filesystem::normalizePath('files_trashbin/files/' . $file); |
|
| 407 | + $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); |
|
| 408 | + if (!$view->file_exists($source)) { |
|
| 409 | + return false; |
|
| 410 | + } |
|
| 411 | + $mtime = $view->filemtime($source); |
|
| 412 | + |
|
| 413 | + // restore file |
|
| 414 | + $restoreResult = $view->rename($source, $target); |
|
| 415 | + |
|
| 416 | + // handle the restore result |
|
| 417 | + if ($restoreResult) { |
|
| 418 | + $fakeRoot = $view->getRoot(); |
|
| 419 | + $view->chroot('/' . $user . '/files'); |
|
| 420 | + $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); |
|
| 421 | + $view->chroot($fakeRoot); |
|
| 422 | + \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), |
|
| 423 | + 'trashPath' => Filesystem::normalizePath($file))); |
|
| 424 | + |
|
| 425 | + self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); |
|
| 426 | + |
|
| 427 | + if ($timestamp) { |
|
| 428 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
| 429 | + $query->execute(array($user, $filename, $timestamp)); |
|
| 430 | + } |
|
| 431 | + |
|
| 432 | + return true; |
|
| 433 | + } |
|
| 434 | + |
|
| 435 | + return false; |
|
| 436 | + } |
|
| 437 | + |
|
| 438 | + /** |
|
| 439 | + * restore versions from trash bin |
|
| 440 | + * |
|
| 441 | + * @param View $view file view |
|
| 442 | + * @param string $file complete path to file |
|
| 443 | + * @param string $filename name of file once it was deleted |
|
| 444 | + * @param string $uniqueFilename new file name to restore the file without overwriting existing files |
|
| 445 | + * @param string $location location if file |
|
| 446 | + * @param int $timestamp deletion time |
|
| 447 | + * @return false|null |
|
| 448 | + */ |
|
| 449 | + private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) { |
|
| 450 | + |
|
| 451 | + if (\OCP\App::isEnabled('files_versions')) { |
|
| 452 | + |
|
| 453 | + $user = User::getUser(); |
|
| 454 | + $rootView = new View('/'); |
|
| 455 | + |
|
| 456 | + $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); |
|
| 457 | + |
|
| 458 | + list($owner, $ownerPath) = self::getUidAndFilename($target); |
|
| 459 | + |
|
| 460 | + // file has been deleted in between |
|
| 461 | + if (empty($ownerPath)) { |
|
| 462 | + return false; |
|
| 463 | + } |
|
| 464 | + |
|
| 465 | + if ($timestamp) { |
|
| 466 | + $versionedFile = $filename; |
|
| 467 | + } else { |
|
| 468 | + $versionedFile = $file; |
|
| 469 | + } |
|
| 470 | + |
|
| 471 | + if ($view->is_dir('/files_trashbin/versions/' . $file)) { |
|
| 472 | + $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath)); |
|
| 473 | + } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) { |
|
| 474 | + foreach ($versions as $v) { |
|
| 475 | + if ($timestamp) { |
|
| 476 | + $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
| 477 | + } else { |
|
| 478 | + $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
| 479 | + } |
|
| 480 | + } |
|
| 481 | + } |
|
| 482 | + } |
|
| 483 | + } |
|
| 484 | + |
|
| 485 | + /** |
|
| 486 | + * delete all files from the trash |
|
| 487 | + */ |
|
| 488 | + public static function deleteAll() { |
|
| 489 | + $user = User::getUser(); |
|
| 490 | + $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
| 491 | + $view = new View('/' . $user); |
|
| 492 | + $fileInfos = $view->getDirectoryContent('files_trashbin/files'); |
|
| 493 | + |
|
| 494 | + try { |
|
| 495 | + $trash = $userRoot->get('files_trashbin'); |
|
| 496 | + } catch (NotFoundException $e) { |
|
| 497 | + return false; |
|
| 498 | + } |
|
| 499 | + |
|
| 500 | + // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) |
|
| 501 | + $filePaths = array(); |
|
| 502 | + foreach($fileInfos as $fileInfo){ |
|
| 503 | + $filePaths[] = $view->getRelativePath($fileInfo->getPath()); |
|
| 504 | + } |
|
| 505 | + unset($fileInfos); // save memory |
|
| 506 | + |
|
| 507 | + // Bulk PreDelete-Hook |
|
| 508 | + \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths)); |
|
| 509 | + |
|
| 510 | + // Single-File Hooks |
|
| 511 | + foreach($filePaths as $path){ |
|
| 512 | + self::emitTrashbinPreDelete($path); |
|
| 513 | + } |
|
| 514 | + |
|
| 515 | + // actual file deletion |
|
| 516 | + $trash->delete(); |
|
| 517 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
| 518 | + $query->execute(array($user)); |
|
| 519 | + |
|
| 520 | + // Bulk PostDelete-Hook |
|
| 521 | + \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths)); |
|
| 522 | + |
|
| 523 | + // Single-File Hooks |
|
| 524 | + foreach($filePaths as $path){ |
|
| 525 | + self::emitTrashbinPostDelete($path); |
|
| 526 | + } |
|
| 527 | + |
|
| 528 | + $trash = $userRoot->newFolder('files_trashbin'); |
|
| 529 | + $trash->newFolder('files'); |
|
| 530 | + |
|
| 531 | + return true; |
|
| 532 | + } |
|
| 533 | + |
|
| 534 | + /** |
|
| 535 | + * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted |
|
| 536 | + * @param string $path |
|
| 537 | + */ |
|
| 538 | + protected static function emitTrashbinPreDelete($path){ |
|
| 539 | + \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path)); |
|
| 540 | + } |
|
| 541 | + |
|
| 542 | + /** |
|
| 543 | + * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted |
|
| 544 | + * @param string $path |
|
| 545 | + */ |
|
| 546 | + protected static function emitTrashbinPostDelete($path){ |
|
| 547 | + \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path)); |
|
| 548 | + } |
|
| 549 | + |
|
| 550 | + /** |
|
| 551 | + * delete file from trash bin permanently |
|
| 552 | + * |
|
| 553 | + * @param string $filename path to the file |
|
| 554 | + * @param string $user |
|
| 555 | + * @param int $timestamp of deletion time |
|
| 556 | + * |
|
| 557 | + * @return int size of deleted files |
|
| 558 | + */ |
|
| 559 | + public static function delete($filename, $user, $timestamp = null) { |
|
| 560 | + $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
| 561 | + $view = new View('/' . $user); |
|
| 562 | + $size = 0; |
|
| 563 | + |
|
| 564 | + if ($timestamp) { |
|
| 565 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
| 566 | + $query->execute(array($user, $filename, $timestamp)); |
|
| 567 | + $file = $filename . '.d' . $timestamp; |
|
| 568 | + } else { |
|
| 569 | + $file = $filename; |
|
| 570 | + } |
|
| 571 | + |
|
| 572 | + $size += self::deleteVersions($view, $file, $filename, $timestamp, $user); |
|
| 573 | + |
|
| 574 | + try { |
|
| 575 | + $node = $userRoot->get('/files_trashbin/files/' . $file); |
|
| 576 | + } catch (NotFoundException $e) { |
|
| 577 | + return $size; |
|
| 578 | + } |
|
| 579 | + |
|
| 580 | + if ($node instanceof Folder) { |
|
| 581 | + $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file)); |
|
| 582 | + } else if ($node instanceof File) { |
|
| 583 | + $size += $view->filesize('/files_trashbin/files/' . $file); |
|
| 584 | + } |
|
| 585 | + |
|
| 586 | + self::emitTrashbinPreDelete('/files_trashbin/files/' . $file); |
|
| 587 | + $node->delete(); |
|
| 588 | + self::emitTrashbinPostDelete('/files_trashbin/files/' . $file); |
|
| 589 | + |
|
| 590 | + return $size; |
|
| 591 | + } |
|
| 592 | + |
|
| 593 | + /** |
|
| 594 | + * @param View $view |
|
| 595 | + * @param string $file |
|
| 596 | + * @param string $filename |
|
| 597 | + * @param integer|null $timestamp |
|
| 598 | + * @param string $user |
|
| 599 | + * @return int |
|
| 600 | + */ |
|
| 601 | + private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) { |
|
| 602 | + $size = 0; |
|
| 603 | + if (\OCP\App::isEnabled('files_versions')) { |
|
| 604 | + if ($view->is_dir('files_trashbin/versions/' . $file)) { |
|
| 605 | + $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file)); |
|
| 606 | + $view->unlink('files_trashbin/versions/' . $file); |
|
| 607 | + } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) { |
|
| 608 | + foreach ($versions as $v) { |
|
| 609 | + if ($timestamp) { |
|
| 610 | + $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
| 611 | + $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
| 612 | + } else { |
|
| 613 | + $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
| 614 | + $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
| 615 | + } |
|
| 616 | + } |
|
| 617 | + } |
|
| 618 | + } |
|
| 619 | + return $size; |
|
| 620 | + } |
|
| 621 | + |
|
| 622 | + /** |
|
| 623 | + * check to see whether a file exists in trashbin |
|
| 624 | + * |
|
| 625 | + * @param string $filename path to the file |
|
| 626 | + * @param int $timestamp of deletion time |
|
| 627 | + * @return bool true if file exists, otherwise false |
|
| 628 | + */ |
|
| 629 | + public static function file_exists($filename, $timestamp = null) { |
|
| 630 | + $user = User::getUser(); |
|
| 631 | + $view = new View('/' . $user); |
|
| 632 | + |
|
| 633 | + if ($timestamp) { |
|
| 634 | + $filename = $filename . '.d' . $timestamp; |
|
| 635 | + } else { |
|
| 636 | + $filename = $filename; |
|
| 637 | + } |
|
| 638 | + |
|
| 639 | + $target = Filesystem::normalizePath('files_trashbin/files/' . $filename); |
|
| 640 | + return $view->file_exists($target); |
|
| 641 | + } |
|
| 642 | + |
|
| 643 | + /** |
|
| 644 | + * deletes used space for trash bin in db if user was deleted |
|
| 645 | + * |
|
| 646 | + * @param string $uid id of deleted user |
|
| 647 | + * @return bool result of db delete operation |
|
| 648 | + */ |
|
| 649 | + public static function deleteUser($uid) { |
|
| 650 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
| 651 | + return $query->execute(array($uid)); |
|
| 652 | + } |
|
| 653 | + |
|
| 654 | + /** |
|
| 655 | + * calculate remaining free space for trash bin |
|
| 656 | + * |
|
| 657 | + * @param integer $trashbinSize current size of the trash bin |
|
| 658 | + * @param string $user |
|
| 659 | + * @return int available free space for trash bin |
|
| 660 | + */ |
|
| 661 | + private static function calculateFreeSpace($trashbinSize, $user) { |
|
| 662 | + $softQuota = true; |
|
| 663 | + $userObject = \OC::$server->getUserManager()->get($user); |
|
| 664 | + if(is_null($userObject)) { |
|
| 665 | + return 0; |
|
| 666 | + } |
|
| 667 | + $quota = $userObject->getQuota(); |
|
| 668 | + if ($quota === null || $quota === 'none') { |
|
| 669 | + $quota = Filesystem::free_space('/'); |
|
| 670 | + $softQuota = false; |
|
| 671 | + // inf or unknown free space |
|
| 672 | + if ($quota < 0) { |
|
| 673 | + $quota = PHP_INT_MAX; |
|
| 674 | + } |
|
| 675 | + } else { |
|
| 676 | + $quota = \OCP\Util::computerFileSize($quota); |
|
| 677 | + } |
|
| 678 | + |
|
| 679 | + // calculate available space for trash bin |
|
| 680 | + // subtract size of files and current trash bin size from quota |
|
| 681 | + if ($softQuota) { |
|
| 682 | + $userFolder = \OC::$server->getUserFolder($user); |
|
| 683 | + if(is_null($userFolder)) { |
|
| 684 | + return 0; |
|
| 685 | + } |
|
| 686 | + $free = $quota - $userFolder->getSize(); // remaining free space for user |
|
| 687 | + if ($free > 0) { |
|
| 688 | + $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions |
|
| 689 | + } else { |
|
| 690 | + $availableSpace = $free - $trashbinSize; |
|
| 691 | + } |
|
| 692 | + } else { |
|
| 693 | + $availableSpace = $quota; |
|
| 694 | + } |
|
| 695 | + |
|
| 696 | + return $availableSpace; |
|
| 697 | + } |
|
| 698 | + |
|
| 699 | + /** |
|
| 700 | + * resize trash bin if necessary after a new file was added to Nextcloud |
|
| 701 | + * |
|
| 702 | + * @param string $user user id |
|
| 703 | + */ |
|
| 704 | + public static function resizeTrash($user) { |
|
| 705 | + |
|
| 706 | + $size = self::getTrashbinSize($user); |
|
| 707 | + |
|
| 708 | + $freeSpace = self::calculateFreeSpace($size, $user); |
|
| 709 | + |
|
| 710 | + if ($freeSpace < 0) { |
|
| 711 | + self::scheduleExpire($user); |
|
| 712 | + } |
|
| 713 | + } |
|
| 714 | + |
|
| 715 | + /** |
|
| 716 | + * clean up the trash bin |
|
| 717 | + * |
|
| 718 | + * @param string $user |
|
| 719 | + */ |
|
| 720 | + public static function expire($user) { |
|
| 721 | + $trashBinSize = self::getTrashbinSize($user); |
|
| 722 | + $availableSpace = self::calculateFreeSpace($trashBinSize, $user); |
|
| 723 | + |
|
| 724 | + $dirContent = Helper::getTrashFiles('/', $user, 'mtime'); |
|
| 725 | + |
|
| 726 | + // delete all files older then $retention_obligation |
|
| 727 | + list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user); |
|
| 728 | + |
|
| 729 | + $availableSpace += $delSize; |
|
| 730 | + |
|
| 731 | + // delete files from trash until we meet the trash bin size limit again |
|
| 732 | + self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace); |
|
| 733 | + } |
|
| 734 | + |
|
| 735 | + /** |
|
| 736 | + * @param string $user |
|
| 737 | + */ |
|
| 738 | + private static function scheduleExpire($user) { |
|
| 739 | + // let the admin disable auto expire |
|
| 740 | + $application = new Application(); |
|
| 741 | + $expiration = $application->getContainer()->query('Expiration'); |
|
| 742 | + if ($expiration->isEnabled()) { |
|
| 743 | + \OC::$server->getCommandBus()->push(new Expire($user)); |
|
| 744 | + } |
|
| 745 | + } |
|
| 746 | + |
|
| 747 | + /** |
|
| 748 | + * if the size limit for the trash bin is reached, we delete the oldest |
|
| 749 | + * files in the trash bin until we meet the limit again |
|
| 750 | + * |
|
| 751 | + * @param array $files |
|
| 752 | + * @param string $user |
|
| 753 | + * @param int $availableSpace available disc space |
|
| 754 | + * @return int size of deleted files |
|
| 755 | + */ |
|
| 756 | + protected static function deleteFiles($files, $user, $availableSpace) { |
|
| 757 | + $application = new Application(); |
|
| 758 | + $expiration = $application->getContainer()->query('Expiration'); |
|
| 759 | + $size = 0; |
|
| 760 | + |
|
| 761 | + if ($availableSpace < 0) { |
|
| 762 | + foreach ($files as $file) { |
|
| 763 | + if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) { |
|
| 764 | + $tmp = self::delete($file['name'], $user, $file['mtime']); |
|
| 765 | + \OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO); |
|
| 766 | + $availableSpace += $tmp; |
|
| 767 | + $size += $tmp; |
|
| 768 | + } else { |
|
| 769 | + break; |
|
| 770 | + } |
|
| 771 | + } |
|
| 772 | + } |
|
| 773 | + return $size; |
|
| 774 | + } |
|
| 775 | + |
|
| 776 | + /** |
|
| 777 | + * delete files older then max storage time |
|
| 778 | + * |
|
| 779 | + * @param array $files list of files sorted by mtime |
|
| 780 | + * @param string $user |
|
| 781 | + * @return integer[] size of deleted files and number of deleted files |
|
| 782 | + */ |
|
| 783 | + public static function deleteExpiredFiles($files, $user) { |
|
| 784 | + $application = new Application(); |
|
| 785 | + $expiration = $application->getContainer()->query('Expiration'); |
|
| 786 | + $size = 0; |
|
| 787 | + $count = 0; |
|
| 788 | + foreach ($files as $file) { |
|
| 789 | + $timestamp = $file['mtime']; |
|
| 790 | + $filename = $file['name']; |
|
| 791 | + if ($expiration->isExpired($timestamp)) { |
|
| 792 | + $count++; |
|
| 793 | + $size += self::delete($filename, $user, $timestamp); |
|
| 794 | + \OC::$server->getLogger()->info( |
|
| 795 | + 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.', |
|
| 796 | + ['app' => 'files_trashbin'] |
|
| 797 | + ); |
|
| 798 | + } else { |
|
| 799 | + break; |
|
| 800 | + } |
|
| 801 | + } |
|
| 802 | + |
|
| 803 | + return array($size, $count); |
|
| 804 | + } |
|
| 805 | + |
|
| 806 | + /** |
|
| 807 | + * recursive copy to copy a whole directory |
|
| 808 | + * |
|
| 809 | + * @param string $source source path, relative to the users files directory |
|
| 810 | + * @param string $destination destination path relative to the users root directoy |
|
| 811 | + * @param View $view file view for the users root directory |
|
| 812 | + * @return int |
|
| 813 | + * @throws Exceptions\CopyRecursiveException |
|
| 814 | + */ |
|
| 815 | + private static function copy_recursive($source, $destination, View $view) { |
|
| 816 | + $size = 0; |
|
| 817 | + if ($view->is_dir($source)) { |
|
| 818 | + $view->mkdir($destination); |
|
| 819 | + $view->touch($destination, $view->filemtime($source)); |
|
| 820 | + foreach ($view->getDirectoryContent($source) as $i) { |
|
| 821 | + $pathDir = $source . '/' . $i['name']; |
|
| 822 | + if ($view->is_dir($pathDir)) { |
|
| 823 | + $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view); |
|
| 824 | + } else { |
|
| 825 | + $size += $view->filesize($pathDir); |
|
| 826 | + $result = $view->copy($pathDir, $destination . '/' . $i['name']); |
|
| 827 | + if (!$result) { |
|
| 828 | + throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
| 829 | + } |
|
| 830 | + $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir)); |
|
| 831 | + } |
|
| 832 | + } |
|
| 833 | + } else { |
|
| 834 | + $size += $view->filesize($source); |
|
| 835 | + $result = $view->copy($source, $destination); |
|
| 836 | + if (!$result) { |
|
| 837 | + throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
| 838 | + } |
|
| 839 | + $view->touch($destination, $view->filemtime($source)); |
|
| 840 | + } |
|
| 841 | + return $size; |
|
| 842 | + } |
|
| 843 | + |
|
| 844 | + /** |
|
| 845 | + * find all versions which belong to the file we want to restore |
|
| 846 | + * |
|
| 847 | + * @param string $filename name of the file which should be restored |
|
| 848 | + * @param int $timestamp timestamp when the file was deleted |
|
| 849 | + * @return array |
|
| 850 | + */ |
|
| 851 | + private static function getVersionsFromTrash($filename, $timestamp, $user) { |
|
| 852 | + $view = new View('/' . $user . '/files_trashbin/versions'); |
|
| 853 | + $versions = array(); |
|
| 854 | + |
|
| 855 | + //force rescan of versions, local storage may not have updated the cache |
|
| 856 | + if (!self::$scannedVersions) { |
|
| 857 | + /** @var \OC\Files\Storage\Storage $storage */ |
|
| 858 | + list($storage,) = $view->resolvePath('/'); |
|
| 859 | + $storage->getScanner()->scan('files_trashbin/versions'); |
|
| 860 | + self::$scannedVersions = true; |
|
| 861 | + } |
|
| 862 | + |
|
| 863 | + if ($timestamp) { |
|
| 864 | + // fetch for old versions |
|
| 865 | + $matches = $view->searchRaw($filename . '.v%.d' . $timestamp); |
|
| 866 | + $offset = -strlen($timestamp) - 2; |
|
| 867 | + } else { |
|
| 868 | + $matches = $view->searchRaw($filename . '.v%'); |
|
| 869 | + } |
|
| 870 | + |
|
| 871 | + if (is_array($matches)) { |
|
| 872 | + foreach ($matches as $ma) { |
|
| 873 | + if ($timestamp) { |
|
| 874 | + $parts = explode('.v', substr($ma['path'], 0, $offset)); |
|
| 875 | + $versions[] = (end($parts)); |
|
| 876 | + } else { |
|
| 877 | + $parts = explode('.v', $ma); |
|
| 878 | + $versions[] = (end($parts)); |
|
| 879 | + } |
|
| 880 | + } |
|
| 881 | + } |
|
| 882 | + return $versions; |
|
| 883 | + } |
|
| 884 | + |
|
| 885 | + /** |
|
| 886 | + * find unique extension for restored file if a file with the same name already exists |
|
| 887 | + * |
|
| 888 | + * @param string $location where the file should be restored |
|
| 889 | + * @param string $filename name of the file |
|
| 890 | + * @param View $view filesystem view relative to users root directory |
|
| 891 | + * @return string with unique extension |
|
| 892 | + */ |
|
| 893 | + private static function getUniqueFilename($location, $filename, View $view) { |
|
| 894 | + $ext = pathinfo($filename, PATHINFO_EXTENSION); |
|
| 895 | + $name = pathinfo($filename, PATHINFO_FILENAME); |
|
| 896 | + $l = \OC::$server->getL10N('files_trashbin'); |
|
| 897 | + |
|
| 898 | + $location = '/' . trim($location, '/'); |
|
| 899 | + |
|
| 900 | + // if extension is not empty we set a dot in front of it |
|
| 901 | + if ($ext !== '') { |
|
| 902 | + $ext = '.' . $ext; |
|
| 903 | + } |
|
| 904 | + |
|
| 905 | + if ($view->file_exists('files' . $location . '/' . $filename)) { |
|
| 906 | + $i = 2; |
|
| 907 | + $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext; |
|
| 908 | + while ($view->file_exists('files' . $location . '/' . $uniqueName)) { |
|
| 909 | + $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext; |
|
| 910 | + $i++; |
|
| 911 | + } |
|
| 912 | + |
|
| 913 | + return $uniqueName; |
|
| 914 | + } |
|
| 915 | + |
|
| 916 | + return $filename; |
|
| 917 | + } |
|
| 918 | + |
|
| 919 | + /** |
|
| 920 | + * get the size from a given root folder |
|
| 921 | + * |
|
| 922 | + * @param View $view file view on the root folder |
|
| 923 | + * @return integer size of the folder |
|
| 924 | + */ |
|
| 925 | + private static function calculateSize($view) { |
|
| 926 | + $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath(''); |
|
| 927 | + if (!file_exists($root)) { |
|
| 928 | + return 0; |
|
| 929 | + } |
|
| 930 | + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST); |
|
| 931 | + $size = 0; |
|
| 932 | + |
|
| 933 | + /** |
|
| 934 | + * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach |
|
| 935 | + * This bug is fixed in PHP 5.5.9 or before |
|
| 936 | + * See #8376 |
|
| 937 | + */ |
|
| 938 | + $iterator->rewind(); |
|
| 939 | + while ($iterator->valid()) { |
|
| 940 | + $path = $iterator->current(); |
|
| 941 | + $relpath = substr($path, strlen($root) - 1); |
|
| 942 | + if (!$view->is_dir($relpath)) { |
|
| 943 | + $size += $view->filesize($relpath); |
|
| 944 | + } |
|
| 945 | + $iterator->next(); |
|
| 946 | + } |
|
| 947 | + return $size; |
|
| 948 | + } |
|
| 949 | + |
|
| 950 | + /** |
|
| 951 | + * get current size of trash bin from a given user |
|
| 952 | + * |
|
| 953 | + * @param string $user user who owns the trash bin |
|
| 954 | + * @return integer trash bin size |
|
| 955 | + */ |
|
| 956 | + private static function getTrashbinSize($user) { |
|
| 957 | + $view = new View('/' . $user); |
|
| 958 | + $fileInfo = $view->getFileInfo('/files_trashbin'); |
|
| 959 | + return isset($fileInfo['size']) ? $fileInfo['size'] : 0; |
|
| 960 | + } |
|
| 961 | + |
|
| 962 | + /** |
|
| 963 | + * register hooks |
|
| 964 | + */ |
|
| 965 | + public static function registerHooks() { |
|
| 966 | + // create storage wrapper on setup |
|
| 967 | + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage'); |
|
| 968 | + //Listen to delete user signal |
|
| 969 | + \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook'); |
|
| 970 | + //Listen to post write hook |
|
| 971 | + \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook'); |
|
| 972 | + // pre and post-rename, disable trash logic for the copy+unlink case |
|
| 973 | + \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook'); |
|
| 974 | + \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook'); |
|
| 975 | + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook'); |
|
| 976 | + } |
|
| 977 | + |
|
| 978 | + /** |
|
| 979 | + * check if trash bin is empty for a given user |
|
| 980 | + * |
|
| 981 | + * @param string $user |
|
| 982 | + * @return bool |
|
| 983 | + */ |
|
| 984 | + public static function isEmpty($user) { |
|
| 985 | + |
|
| 986 | + $view = new View('/' . $user . '/files_trashbin'); |
|
| 987 | + if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { |
|
| 988 | + while ($file = readdir($dh)) { |
|
| 989 | + if (!Filesystem::isIgnoredDir($file)) { |
|
| 990 | + return false; |
|
| 991 | + } |
|
| 992 | + } |
|
| 993 | + } |
|
| 994 | + return true; |
|
| 995 | + } |
|
| 996 | + |
|
| 997 | + /** |
|
| 998 | + * @param $path |
|
| 999 | + * @return string |
|
| 1000 | + */ |
|
| 1001 | + public static function preview_icon($path) { |
|
| 1002 | + return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path)); |
|
| 1003 | + } |
|
| 1004 | 1004 | } |
@@ -97,7 +97,7 @@ discard block |
||
| 97 | 97 | Filesystem::initMountPoints($uid); |
| 98 | 98 | if ($uid !== User::getUser()) { |
| 99 | 99 | $info = Filesystem::getFileInfo($filename); |
| 100 | - $ownerView = new View('/' . $uid . '/files'); |
|
| 100 | + $ownerView = new View('/'.$uid.'/files'); |
|
| 101 | 101 | try { |
| 102 | 102 | $filename = $ownerView->getPath($info['fileid']); |
| 103 | 103 | } catch (NotFoundException $e) { |
@@ -148,7 +148,7 @@ discard block |
||
| 148 | 148 | } |
| 149 | 149 | |
| 150 | 150 | private static function setUpTrash($user) { |
| 151 | - $view = new View('/' . $user); |
|
| 151 | + $view = new View('/'.$user); |
|
| 152 | 152 | if (!$view->is_dir('files_trashbin')) { |
| 153 | 153 | $view->mkdir('files_trashbin'); |
| 154 | 154 | } |
@@ -183,8 +183,8 @@ discard block |
||
| 183 | 183 | |
| 184 | 184 | $view = new View('/'); |
| 185 | 185 | |
| 186 | - $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp; |
|
| 187 | - $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp; |
|
| 186 | + $target = $user.'/files_trashbin/files/'.$targetFilename.'.d'.$timestamp; |
|
| 187 | + $source = $owner.'/files_trashbin/files/'.$sourceFilename.'.d'.$timestamp; |
|
| 188 | 188 | self::copy_recursive($source, $target, $view); |
| 189 | 189 | |
| 190 | 190 | |
@@ -218,9 +218,9 @@ discard block |
||
| 218 | 218 | $ownerPath = $file_path; |
| 219 | 219 | } |
| 220 | 220 | |
| 221 | - $ownerView = new View('/' . $owner); |
|
| 221 | + $ownerView = new View('/'.$owner); |
|
| 222 | 222 | // file has been deleted in between |
| 223 | - if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) { |
|
| 223 | + if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/'.$ownerPath)) { |
|
| 224 | 224 | return true; |
| 225 | 225 | } |
| 226 | 226 | |
@@ -237,12 +237,12 @@ discard block |
||
| 237 | 237 | $timestamp = time(); |
| 238 | 238 | |
| 239 | 239 | // disable proxy to prevent recursive calls |
| 240 | - $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; |
|
| 240 | + $trashPath = '/files_trashbin/files/'.$filename.'.d'.$timestamp; |
|
| 241 | 241 | |
| 242 | 242 | /** @var \OC\Files\Storage\Storage $trashStorage */ |
| 243 | 243 | list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); |
| 244 | 244 | /** @var \OC\Files\Storage\Storage $sourceStorage */ |
| 245 | - list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); |
|
| 245 | + list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/'.$ownerPath); |
|
| 246 | 246 | try { |
| 247 | 247 | $moveSuccessful = true; |
| 248 | 248 | if ($trashStorage->file_exists($trashInternalPath)) { |
@@ -254,7 +254,7 @@ discard block |
||
| 254 | 254 | if ($trashStorage->file_exists($trashInternalPath)) { |
| 255 | 255 | $trashStorage->unlink($trashInternalPath); |
| 256 | 256 | } |
| 257 | - \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR); |
|
| 257 | + \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move '.$file_path.' to the trash bin', \OCP\Util::ERROR); |
|
| 258 | 258 | } |
| 259 | 259 | |
| 260 | 260 | if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort |
@@ -275,7 +275,7 @@ discard block |
||
| 275 | 275 | \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR); |
| 276 | 276 | } |
| 277 | 277 | \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path), |
| 278 | - 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp))); |
|
| 278 | + 'trashPath' => Filesystem::normalizePath($filename.'.d'.$timestamp))); |
|
| 279 | 279 | |
| 280 | 280 | self::retainVersions($filename, $owner, $ownerPath, $timestamp); |
| 281 | 281 | |
@@ -309,18 +309,18 @@ discard block |
||
| 309 | 309 | $user = User::getUser(); |
| 310 | 310 | $rootView = new View('/'); |
| 311 | 311 | |
| 312 | - if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { |
|
| 312 | + if ($rootView->is_dir($owner.'/files_versions/'.$ownerPath)) { |
|
| 313 | 313 | if ($owner !== $user) { |
| 314 | - self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView); |
|
| 314 | + self::copy_recursive($owner.'/files_versions/'.$ownerPath, $owner.'/files_trashbin/versions/'.basename($ownerPath).'.d'.$timestamp, $rootView); |
|
| 315 | 315 | } |
| 316 | - self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); |
|
| 316 | + self::move($rootView, $owner.'/files_versions/'.$ownerPath, $user.'/files_trashbin/versions/'.$filename.'.d'.$timestamp); |
|
| 317 | 317 | } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { |
| 318 | 318 | |
| 319 | 319 | foreach ($versions as $v) { |
| 320 | 320 | if ($owner !== $user) { |
| 321 | - self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); |
|
| 321 | + self::copy($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $owner.'/files_trashbin/versions/'.$v['name'].'.v'.$v['version'].'.d'.$timestamp); |
|
| 322 | 322 | } |
| 323 | - self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp); |
|
| 323 | + self::move($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $user.'/files_trashbin/versions/'.$filename.'.v'.$v['version'].'.d'.$timestamp); |
|
| 324 | 324 | } |
| 325 | 325 | } |
| 326 | 326 | } |
@@ -382,18 +382,18 @@ discard block |
||
| 382 | 382 | */ |
| 383 | 383 | public static function restore($file, $filename, $timestamp) { |
| 384 | 384 | $user = User::getUser(); |
| 385 | - $view = new View('/' . $user); |
|
| 385 | + $view = new View('/'.$user); |
|
| 386 | 386 | |
| 387 | 387 | $location = ''; |
| 388 | 388 | if ($timestamp) { |
| 389 | 389 | $location = self::getLocation($user, $filename, $timestamp); |
| 390 | 390 | if ($location === false) { |
| 391 | - \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR); |
|
| 391 | + \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: '.$user.' $filename: '.$filename.', $timestamp: '.$timestamp.')', \OCP\Util::ERROR); |
|
| 392 | 392 | } else { |
| 393 | 393 | // if location no longer exists, restore file in the root directory |
| 394 | 394 | if ($location !== '/' && |
| 395 | - (!$view->is_dir('files/' . $location) || |
|
| 396 | - !$view->isCreatable('files/' . $location)) |
|
| 395 | + (!$view->is_dir('files/'.$location) || |
|
| 396 | + !$view->isCreatable('files/'.$location)) |
|
| 397 | 397 | ) { |
| 398 | 398 | $location = ''; |
| 399 | 399 | } |
@@ -403,8 +403,8 @@ discard block |
||
| 403 | 403 | // we need a extension in case a file/dir with the same name already exists |
| 404 | 404 | $uniqueFilename = self::getUniqueFilename($location, $filename, $view); |
| 405 | 405 | |
| 406 | - $source = Filesystem::normalizePath('files_trashbin/files/' . $file); |
|
| 407 | - $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); |
|
| 406 | + $source = Filesystem::normalizePath('files_trashbin/files/'.$file); |
|
| 407 | + $target = Filesystem::normalizePath('files/'.$location.'/'.$uniqueFilename); |
|
| 408 | 408 | if (!$view->file_exists($source)) { |
| 409 | 409 | return false; |
| 410 | 410 | } |
@@ -416,10 +416,10 @@ discard block |
||
| 416 | 416 | // handle the restore result |
| 417 | 417 | if ($restoreResult) { |
| 418 | 418 | $fakeRoot = $view->getRoot(); |
| 419 | - $view->chroot('/' . $user . '/files'); |
|
| 420 | - $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); |
|
| 419 | + $view->chroot('/'.$user.'/files'); |
|
| 420 | + $view->touch('/'.$location.'/'.$uniqueFilename, $mtime); |
|
| 421 | 421 | $view->chroot($fakeRoot); |
| 422 | - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), |
|
| 422 | + \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename), |
|
| 423 | 423 | 'trashPath' => Filesystem::normalizePath($file))); |
| 424 | 424 | |
| 425 | 425 | self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); |
@@ -453,7 +453,7 @@ discard block |
||
| 453 | 453 | $user = User::getUser(); |
| 454 | 454 | $rootView = new View('/'); |
| 455 | 455 | |
| 456 | - $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); |
|
| 456 | + $target = Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename); |
|
| 457 | 457 | |
| 458 | 458 | list($owner, $ownerPath) = self::getUidAndFilename($target); |
| 459 | 459 | |
@@ -468,14 +468,14 @@ discard block |
||
| 468 | 468 | $versionedFile = $file; |
| 469 | 469 | } |
| 470 | 470 | |
| 471 | - if ($view->is_dir('/files_trashbin/versions/' . $file)) { |
|
| 472 | - $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath)); |
|
| 471 | + if ($view->is_dir('/files_trashbin/versions/'.$file)) { |
|
| 472 | + $rootView->rename(Filesystem::normalizePath($user.'/files_trashbin/versions/'.$file), Filesystem::normalizePath($owner.'/files_versions/'.$ownerPath)); |
|
| 473 | 473 | } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) { |
| 474 | 474 | foreach ($versions as $v) { |
| 475 | 475 | if ($timestamp) { |
| 476 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
| 476 | + $rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v.'.d'.$timestamp, $owner.'/files_versions/'.$ownerPath.'.v'.$v); |
|
| 477 | 477 | } else { |
| 478 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
| 478 | + $rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v, $owner.'/files_versions/'.$ownerPath.'.v'.$v); |
|
| 479 | 479 | } |
| 480 | 480 | } |
| 481 | 481 | } |
@@ -488,7 +488,7 @@ discard block |
||
| 488 | 488 | public static function deleteAll() { |
| 489 | 489 | $user = User::getUser(); |
| 490 | 490 | $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
| 491 | - $view = new View('/' . $user); |
|
| 491 | + $view = new View('/'.$user); |
|
| 492 | 492 | $fileInfos = $view->getDirectoryContent('files_trashbin/files'); |
| 493 | 493 | |
| 494 | 494 | try { |
@@ -499,7 +499,7 @@ discard block |
||
| 499 | 499 | |
| 500 | 500 | // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) |
| 501 | 501 | $filePaths = array(); |
| 502 | - foreach($fileInfos as $fileInfo){ |
|
| 502 | + foreach ($fileInfos as $fileInfo) { |
|
| 503 | 503 | $filePaths[] = $view->getRelativePath($fileInfo->getPath()); |
| 504 | 504 | } |
| 505 | 505 | unset($fileInfos); // save memory |
@@ -508,7 +508,7 @@ discard block |
||
| 508 | 508 | \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths)); |
| 509 | 509 | |
| 510 | 510 | // Single-File Hooks |
| 511 | - foreach($filePaths as $path){ |
|
| 511 | + foreach ($filePaths as $path) { |
|
| 512 | 512 | self::emitTrashbinPreDelete($path); |
| 513 | 513 | } |
| 514 | 514 | |
@@ -521,7 +521,7 @@ discard block |
||
| 521 | 521 | \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths)); |
| 522 | 522 | |
| 523 | 523 | // Single-File Hooks |
| 524 | - foreach($filePaths as $path){ |
|
| 524 | + foreach ($filePaths as $path) { |
|
| 525 | 525 | self::emitTrashbinPostDelete($path); |
| 526 | 526 | } |
| 527 | 527 | |
@@ -535,7 +535,7 @@ discard block |
||
| 535 | 535 | * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted |
| 536 | 536 | * @param string $path |
| 537 | 537 | */ |
| 538 | - protected static function emitTrashbinPreDelete($path){ |
|
| 538 | + protected static function emitTrashbinPreDelete($path) { |
|
| 539 | 539 | \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path)); |
| 540 | 540 | } |
| 541 | 541 | |
@@ -543,7 +543,7 @@ discard block |
||
| 543 | 543 | * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted |
| 544 | 544 | * @param string $path |
| 545 | 545 | */ |
| 546 | - protected static function emitTrashbinPostDelete($path){ |
|
| 546 | + protected static function emitTrashbinPostDelete($path) { |
|
| 547 | 547 | \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path)); |
| 548 | 548 | } |
| 549 | 549 | |
@@ -558,13 +558,13 @@ discard block |
||
| 558 | 558 | */ |
| 559 | 559 | public static function delete($filename, $user, $timestamp = null) { |
| 560 | 560 | $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
| 561 | - $view = new View('/' . $user); |
|
| 561 | + $view = new View('/'.$user); |
|
| 562 | 562 | $size = 0; |
| 563 | 563 | |
| 564 | 564 | if ($timestamp) { |
| 565 | 565 | $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
| 566 | 566 | $query->execute(array($user, $filename, $timestamp)); |
| 567 | - $file = $filename . '.d' . $timestamp; |
|
| 567 | + $file = $filename.'.d'.$timestamp; |
|
| 568 | 568 | } else { |
| 569 | 569 | $file = $filename; |
| 570 | 570 | } |
@@ -572,20 +572,20 @@ discard block |
||
| 572 | 572 | $size += self::deleteVersions($view, $file, $filename, $timestamp, $user); |
| 573 | 573 | |
| 574 | 574 | try { |
| 575 | - $node = $userRoot->get('/files_trashbin/files/' . $file); |
|
| 575 | + $node = $userRoot->get('/files_trashbin/files/'.$file); |
|
| 576 | 576 | } catch (NotFoundException $e) { |
| 577 | 577 | return $size; |
| 578 | 578 | } |
| 579 | 579 | |
| 580 | 580 | if ($node instanceof Folder) { |
| 581 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file)); |
|
| 581 | + $size += self::calculateSize(new View('/'.$user.'/files_trashbin/files/'.$file)); |
|
| 582 | 582 | } else if ($node instanceof File) { |
| 583 | - $size += $view->filesize('/files_trashbin/files/' . $file); |
|
| 583 | + $size += $view->filesize('/files_trashbin/files/'.$file); |
|
| 584 | 584 | } |
| 585 | 585 | |
| 586 | - self::emitTrashbinPreDelete('/files_trashbin/files/' . $file); |
|
| 586 | + self::emitTrashbinPreDelete('/files_trashbin/files/'.$file); |
|
| 587 | 587 | $node->delete(); |
| 588 | - self::emitTrashbinPostDelete('/files_trashbin/files/' . $file); |
|
| 588 | + self::emitTrashbinPostDelete('/files_trashbin/files/'.$file); |
|
| 589 | 589 | |
| 590 | 590 | return $size; |
| 591 | 591 | } |
@@ -601,17 +601,17 @@ discard block |
||
| 601 | 601 | private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) { |
| 602 | 602 | $size = 0; |
| 603 | 603 | if (\OCP\App::isEnabled('files_versions')) { |
| 604 | - if ($view->is_dir('files_trashbin/versions/' . $file)) { |
|
| 605 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file)); |
|
| 606 | - $view->unlink('files_trashbin/versions/' . $file); |
|
| 604 | + if ($view->is_dir('files_trashbin/versions/'.$file)) { |
|
| 605 | + $size += self::calculateSize(new View('/'.$user.'/files_trashbin/versions/'.$file)); |
|
| 606 | + $view->unlink('files_trashbin/versions/'.$file); |
|
| 607 | 607 | } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) { |
| 608 | 608 | foreach ($versions as $v) { |
| 609 | 609 | if ($timestamp) { |
| 610 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
| 611 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
| 610 | + $size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp); |
|
| 611 | + $view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp); |
|
| 612 | 612 | } else { |
| 613 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
| 614 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
| 613 | + $size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v); |
|
| 614 | + $view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v); |
|
| 615 | 615 | } |
| 616 | 616 | } |
| 617 | 617 | } |
@@ -628,15 +628,15 @@ discard block |
||
| 628 | 628 | */ |
| 629 | 629 | public static function file_exists($filename, $timestamp = null) { |
| 630 | 630 | $user = User::getUser(); |
| 631 | - $view = new View('/' . $user); |
|
| 631 | + $view = new View('/'.$user); |
|
| 632 | 632 | |
| 633 | 633 | if ($timestamp) { |
| 634 | - $filename = $filename . '.d' . $timestamp; |
|
| 634 | + $filename = $filename.'.d'.$timestamp; |
|
| 635 | 635 | } else { |
| 636 | 636 | $filename = $filename; |
| 637 | 637 | } |
| 638 | 638 | |
| 639 | - $target = Filesystem::normalizePath('files_trashbin/files/' . $filename); |
|
| 639 | + $target = Filesystem::normalizePath('files_trashbin/files/'.$filename); |
|
| 640 | 640 | return $view->file_exists($target); |
| 641 | 641 | } |
| 642 | 642 | |
@@ -661,7 +661,7 @@ discard block |
||
| 661 | 661 | private static function calculateFreeSpace($trashbinSize, $user) { |
| 662 | 662 | $softQuota = true; |
| 663 | 663 | $userObject = \OC::$server->getUserManager()->get($user); |
| 664 | - if(is_null($userObject)) { |
|
| 664 | + if (is_null($userObject)) { |
|
| 665 | 665 | return 0; |
| 666 | 666 | } |
| 667 | 667 | $quota = $userObject->getQuota(); |
@@ -680,7 +680,7 @@ discard block |
||
| 680 | 680 | // subtract size of files and current trash bin size from quota |
| 681 | 681 | if ($softQuota) { |
| 682 | 682 | $userFolder = \OC::$server->getUserFolder($user); |
| 683 | - if(is_null($userFolder)) { |
|
| 683 | + if (is_null($userFolder)) { |
|
| 684 | 684 | return 0; |
| 685 | 685 | } |
| 686 | 686 | $free = $quota - $userFolder->getSize(); // remaining free space for user |
@@ -762,7 +762,7 @@ discard block |
||
| 762 | 762 | foreach ($files as $file) { |
| 763 | 763 | if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) { |
| 764 | 764 | $tmp = self::delete($file['name'], $user, $file['mtime']); |
| 765 | - \OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO); |
|
| 765 | + \OCP\Util::writeLog('files_trashbin', 'remove "'.$file['name'].'" ('.$tmp.'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO); |
|
| 766 | 766 | $availableSpace += $tmp; |
| 767 | 767 | $size += $tmp; |
| 768 | 768 | } else { |
@@ -792,7 +792,7 @@ discard block |
||
| 792 | 792 | $count++; |
| 793 | 793 | $size += self::delete($filename, $user, $timestamp); |
| 794 | 794 | \OC::$server->getLogger()->info( |
| 795 | - 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.', |
|
| 795 | + 'Remove "'.$filename.'" from trashbin because it exceeds max retention obligation term.', |
|
| 796 | 796 | ['app' => 'files_trashbin'] |
| 797 | 797 | ); |
| 798 | 798 | } else { |
@@ -818,16 +818,16 @@ discard block |
||
| 818 | 818 | $view->mkdir($destination); |
| 819 | 819 | $view->touch($destination, $view->filemtime($source)); |
| 820 | 820 | foreach ($view->getDirectoryContent($source) as $i) { |
| 821 | - $pathDir = $source . '/' . $i['name']; |
|
| 821 | + $pathDir = $source.'/'.$i['name']; |
|
| 822 | 822 | if ($view->is_dir($pathDir)) { |
| 823 | - $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view); |
|
| 823 | + $size += self::copy_recursive($pathDir, $destination.'/'.$i['name'], $view); |
|
| 824 | 824 | } else { |
| 825 | 825 | $size += $view->filesize($pathDir); |
| 826 | - $result = $view->copy($pathDir, $destination . '/' . $i['name']); |
|
| 826 | + $result = $view->copy($pathDir, $destination.'/'.$i['name']); |
|
| 827 | 827 | if (!$result) { |
| 828 | 828 | throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
| 829 | 829 | } |
| 830 | - $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir)); |
|
| 830 | + $view->touch($destination.'/'.$i['name'], $view->filemtime($pathDir)); |
|
| 831 | 831 | } |
| 832 | 832 | } |
| 833 | 833 | } else { |
@@ -849,7 +849,7 @@ discard block |
||
| 849 | 849 | * @return array |
| 850 | 850 | */ |
| 851 | 851 | private static function getVersionsFromTrash($filename, $timestamp, $user) { |
| 852 | - $view = new View('/' . $user . '/files_trashbin/versions'); |
|
| 852 | + $view = new View('/'.$user.'/files_trashbin/versions'); |
|
| 853 | 853 | $versions = array(); |
| 854 | 854 | |
| 855 | 855 | //force rescan of versions, local storage may not have updated the cache |
@@ -862,10 +862,10 @@ discard block |
||
| 862 | 862 | |
| 863 | 863 | if ($timestamp) { |
| 864 | 864 | // fetch for old versions |
| 865 | - $matches = $view->searchRaw($filename . '.v%.d' . $timestamp); |
|
| 865 | + $matches = $view->searchRaw($filename.'.v%.d'.$timestamp); |
|
| 866 | 866 | $offset = -strlen($timestamp) - 2; |
| 867 | 867 | } else { |
| 868 | - $matches = $view->searchRaw($filename . '.v%'); |
|
| 868 | + $matches = $view->searchRaw($filename.'.v%'); |
|
| 869 | 869 | } |
| 870 | 870 | |
| 871 | 871 | if (is_array($matches)) { |
@@ -895,18 +895,18 @@ discard block |
||
| 895 | 895 | $name = pathinfo($filename, PATHINFO_FILENAME); |
| 896 | 896 | $l = \OC::$server->getL10N('files_trashbin'); |
| 897 | 897 | |
| 898 | - $location = '/' . trim($location, '/'); |
|
| 898 | + $location = '/'.trim($location, '/'); |
|
| 899 | 899 | |
| 900 | 900 | // if extension is not empty we set a dot in front of it |
| 901 | 901 | if ($ext !== '') { |
| 902 | - $ext = '.' . $ext; |
|
| 902 | + $ext = '.'.$ext; |
|
| 903 | 903 | } |
| 904 | 904 | |
| 905 | - if ($view->file_exists('files' . $location . '/' . $filename)) { |
|
| 905 | + if ($view->file_exists('files'.$location.'/'.$filename)) { |
|
| 906 | 906 | $i = 2; |
| 907 | - $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext; |
|
| 908 | - while ($view->file_exists('files' . $location . '/' . $uniqueName)) { |
|
| 909 | - $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext; |
|
| 907 | + $uniqueName = $name." (".$l->t("restored").")".$ext; |
|
| 908 | + while ($view->file_exists('files'.$location.'/'.$uniqueName)) { |
|
| 909 | + $uniqueName = $name." (".$l->t("restored")." ".$i.")".$ext; |
|
| 910 | 910 | $i++; |
| 911 | 911 | } |
| 912 | 912 | |
@@ -923,7 +923,7 @@ discard block |
||
| 923 | 923 | * @return integer size of the folder |
| 924 | 924 | */ |
| 925 | 925 | private static function calculateSize($view) { |
| 926 | - $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath(''); |
|
| 926 | + $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').$view->getAbsolutePath(''); |
|
| 927 | 927 | if (!file_exists($root)) { |
| 928 | 928 | return 0; |
| 929 | 929 | } |
@@ -954,7 +954,7 @@ discard block |
||
| 954 | 954 | * @return integer trash bin size |
| 955 | 955 | */ |
| 956 | 956 | private static function getTrashbinSize($user) { |
| 957 | - $view = new View('/' . $user); |
|
| 957 | + $view = new View('/'.$user); |
|
| 958 | 958 | $fileInfo = $view->getFileInfo('/files_trashbin'); |
| 959 | 959 | return isset($fileInfo['size']) ? $fileInfo['size'] : 0; |
| 960 | 960 | } |
@@ -983,7 +983,7 @@ discard block |
||
| 983 | 983 | */ |
| 984 | 984 | public static function isEmpty($user) { |
| 985 | 985 | |
| 986 | - $view = new View('/' . $user . '/files_trashbin'); |
|
| 986 | + $view = new View('/'.$user.'/files_trashbin'); |
|
| 987 | 987 | if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { |
| 988 | 988 | while ($file = readdir($dh)) { |
| 989 | 989 | if (!Filesystem::isIgnoredDir($file)) { |
@@ -102,6 +102,9 @@ |
||
| 102 | 102 | return \OC_App::getAppVersions(); |
| 103 | 103 | } |
| 104 | 104 | |
| 105 | + /** |
|
| 106 | + * @param string $appId |
|
| 107 | + */ |
|
| 105 | 108 | protected function getAppInfo($appId) { |
| 106 | 109 | return \OC_App::getAppInfo($appId); |
| 107 | 110 | } |
@@ -91,7 +91,7 @@ discard block |
||
| 91 | 91 | $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); |
| 92 | 92 | |
| 93 | 93 | if ($this->isAdmin()) { |
| 94 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); |
|
| 94 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index').'#updater'); |
|
| 95 | 95 | } |
| 96 | 96 | } else { |
| 97 | 97 | $appInfo = $this->getAppInfo($notification->getObjectType()); |
@@ -111,7 +111,7 @@ discard block |
||
| 111 | 111 | ]); |
| 112 | 112 | |
| 113 | 113 | if ($this->isAdmin()) { |
| 114 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType()); |
|
| 114 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps').'#app-'.$notification->getObjectType()); |
|
| 115 | 115 | } |
| 116 | 116 | } |
| 117 | 117 | |
@@ -36,141 +36,141 @@ |
||
| 36 | 36 | |
| 37 | 37 | class Notifier implements INotifier { |
| 38 | 38 | |
| 39 | - /** @var IURLGenerator */ |
|
| 40 | - protected $url; |
|
| 41 | - |
|
| 42 | - /** @var IConfig */ |
|
| 43 | - protected $config; |
|
| 44 | - |
|
| 45 | - /** @var IManager */ |
|
| 46 | - protected $notificationManager; |
|
| 47 | - |
|
| 48 | - /** @var IFactory */ |
|
| 49 | - protected $l10NFactory; |
|
| 50 | - |
|
| 51 | - /** @var IUserSession */ |
|
| 52 | - protected $userSession; |
|
| 53 | - |
|
| 54 | - /** @var IGroupManager */ |
|
| 55 | - protected $groupManager; |
|
| 56 | - |
|
| 57 | - /** @var string[] */ |
|
| 58 | - protected $appVersions; |
|
| 59 | - |
|
| 60 | - /** |
|
| 61 | - * Notifier constructor. |
|
| 62 | - * |
|
| 63 | - * @param IURLGenerator $url |
|
| 64 | - * @param IConfig $config |
|
| 65 | - * @param IManager $notificationManager |
|
| 66 | - * @param IFactory $l10NFactory |
|
| 67 | - * @param IUserSession $userSession |
|
| 68 | - * @param IGroupManager $groupManager |
|
| 69 | - */ |
|
| 70 | - public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) { |
|
| 71 | - $this->url = $url; |
|
| 72 | - $this->notificationManager = $notificationManager; |
|
| 73 | - $this->config = $config; |
|
| 74 | - $this->l10NFactory = $l10NFactory; |
|
| 75 | - $this->userSession = $userSession; |
|
| 76 | - $this->groupManager = $groupManager; |
|
| 77 | - $this->appVersions = $this->getAppVersions(); |
|
| 78 | - } |
|
| 79 | - |
|
| 80 | - /** |
|
| 81 | - * @param INotification $notification |
|
| 82 | - * @param string $languageCode The code of the language that should be used to prepare the notification |
|
| 83 | - * @return INotification |
|
| 84 | - * @throws \InvalidArgumentException When the notification was not prepared by a notifier |
|
| 85 | - * @since 9.0.0 |
|
| 86 | - */ |
|
| 87 | - public function prepare(INotification $notification, $languageCode) { |
|
| 88 | - if ($notification->getApp() !== 'updatenotification') { |
|
| 89 | - throw new \InvalidArgumentException(); |
|
| 90 | - } |
|
| 91 | - |
|
| 92 | - $l = $this->l10NFactory->get('updatenotification', $languageCode); |
|
| 93 | - if ($notification->getSubject() === 'connection_error') { |
|
| 94 | - $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); |
|
| 95 | - if ($errors === 0) { |
|
| 96 | - $this->notificationManager->markProcessed($notification); |
|
| 97 | - throw new \InvalidArgumentException(); |
|
| 98 | - } |
|
| 99 | - |
|
| 100 | - $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) |
|
| 101 | - ->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.')); |
|
| 102 | - } elseif ($notification->getObjectType() === 'core') { |
|
| 103 | - $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions()); |
|
| 104 | - |
|
| 105 | - $parameters = $notification->getSubjectParameters(); |
|
| 106 | - $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); |
|
| 107 | - |
|
| 108 | - if ($this->isAdmin()) { |
|
| 109 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); |
|
| 110 | - } |
|
| 111 | - } else { |
|
| 112 | - $appInfo = $this->getAppInfo($notification->getObjectType()); |
|
| 113 | - $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name']; |
|
| 114 | - |
|
| 115 | - if (isset($this->appVersions[$notification->getObjectType()])) { |
|
| 116 | - $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]); |
|
| 117 | - } |
|
| 118 | - |
|
| 119 | - $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()])) |
|
| 120 | - ->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [ |
|
| 121 | - 'app' => [ |
|
| 122 | - 'type' => 'app', |
|
| 123 | - 'id' => $notification->getObjectType(), |
|
| 124 | - 'name' => $appName, |
|
| 125 | - ] |
|
| 126 | - ]); |
|
| 127 | - |
|
| 128 | - if ($this->isAdmin()) { |
|
| 129 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType()); |
|
| 130 | - } |
|
| 131 | - } |
|
| 132 | - |
|
| 133 | - $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg'))); |
|
| 134 | - |
|
| 135 | - return $notification; |
|
| 136 | - } |
|
| 137 | - |
|
| 138 | - /** |
|
| 139 | - * Remove the notification and prevent rendering, when the update is installed |
|
| 140 | - * |
|
| 141 | - * @param INotification $notification |
|
| 142 | - * @param string $installedVersion |
|
| 143 | - * @throws \InvalidArgumentException When the update is already installed |
|
| 144 | - */ |
|
| 145 | - protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { |
|
| 146 | - if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { |
|
| 147 | - $this->notificationManager->markProcessed($notification); |
|
| 148 | - throw new \InvalidArgumentException(); |
|
| 149 | - } |
|
| 150 | - } |
|
| 151 | - |
|
| 152 | - /** |
|
| 153 | - * @return bool |
|
| 154 | - */ |
|
| 155 | - protected function isAdmin() { |
|
| 156 | - $user = $this->userSession->getUser(); |
|
| 157 | - |
|
| 158 | - if ($user instanceof IUser) { |
|
| 159 | - return $this->groupManager->isAdmin($user->getUID()); |
|
| 160 | - } |
|
| 161 | - |
|
| 162 | - return false; |
|
| 163 | - } |
|
| 164 | - |
|
| 165 | - protected function getCoreVersions() { |
|
| 166 | - return implode('.', \OCP\Util::getVersion()); |
|
| 167 | - } |
|
| 168 | - |
|
| 169 | - protected function getAppVersions() { |
|
| 170 | - return \OC_App::getAppVersions(); |
|
| 171 | - } |
|
| 172 | - |
|
| 173 | - protected function getAppInfo($appId) { |
|
| 174 | - return \OC_App::getAppInfo($appId); |
|
| 175 | - } |
|
| 39 | + /** @var IURLGenerator */ |
|
| 40 | + protected $url; |
|
| 41 | + |
|
| 42 | + /** @var IConfig */ |
|
| 43 | + protected $config; |
|
| 44 | + |
|
| 45 | + /** @var IManager */ |
|
| 46 | + protected $notificationManager; |
|
| 47 | + |
|
| 48 | + /** @var IFactory */ |
|
| 49 | + protected $l10NFactory; |
|
| 50 | + |
|
| 51 | + /** @var IUserSession */ |
|
| 52 | + protected $userSession; |
|
| 53 | + |
|
| 54 | + /** @var IGroupManager */ |
|
| 55 | + protected $groupManager; |
|
| 56 | + |
|
| 57 | + /** @var string[] */ |
|
| 58 | + protected $appVersions; |
|
| 59 | + |
|
| 60 | + /** |
|
| 61 | + * Notifier constructor. |
|
| 62 | + * |
|
| 63 | + * @param IURLGenerator $url |
|
| 64 | + * @param IConfig $config |
|
| 65 | + * @param IManager $notificationManager |
|
| 66 | + * @param IFactory $l10NFactory |
|
| 67 | + * @param IUserSession $userSession |
|
| 68 | + * @param IGroupManager $groupManager |
|
| 69 | + */ |
|
| 70 | + public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) { |
|
| 71 | + $this->url = $url; |
|
| 72 | + $this->notificationManager = $notificationManager; |
|
| 73 | + $this->config = $config; |
|
| 74 | + $this->l10NFactory = $l10NFactory; |
|
| 75 | + $this->userSession = $userSession; |
|
| 76 | + $this->groupManager = $groupManager; |
|
| 77 | + $this->appVersions = $this->getAppVersions(); |
|
| 78 | + } |
|
| 79 | + |
|
| 80 | + /** |
|
| 81 | + * @param INotification $notification |
|
| 82 | + * @param string $languageCode The code of the language that should be used to prepare the notification |
|
| 83 | + * @return INotification |
|
| 84 | + * @throws \InvalidArgumentException When the notification was not prepared by a notifier |
|
| 85 | + * @since 9.0.0 |
|
| 86 | + */ |
|
| 87 | + public function prepare(INotification $notification, $languageCode) { |
|
| 88 | + if ($notification->getApp() !== 'updatenotification') { |
|
| 89 | + throw new \InvalidArgumentException(); |
|
| 90 | + } |
|
| 91 | + |
|
| 92 | + $l = $this->l10NFactory->get('updatenotification', $languageCode); |
|
| 93 | + if ($notification->getSubject() === 'connection_error') { |
|
| 94 | + $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); |
|
| 95 | + if ($errors === 0) { |
|
| 96 | + $this->notificationManager->markProcessed($notification); |
|
| 97 | + throw new \InvalidArgumentException(); |
|
| 98 | + } |
|
| 99 | + |
|
| 100 | + $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) |
|
| 101 | + ->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.')); |
|
| 102 | + } elseif ($notification->getObjectType() === 'core') { |
|
| 103 | + $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions()); |
|
| 104 | + |
|
| 105 | + $parameters = $notification->getSubjectParameters(); |
|
| 106 | + $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); |
|
| 107 | + |
|
| 108 | + if ($this->isAdmin()) { |
|
| 109 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); |
|
| 110 | + } |
|
| 111 | + } else { |
|
| 112 | + $appInfo = $this->getAppInfo($notification->getObjectType()); |
|
| 113 | + $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name']; |
|
| 114 | + |
|
| 115 | + if (isset($this->appVersions[$notification->getObjectType()])) { |
|
| 116 | + $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]); |
|
| 117 | + } |
|
| 118 | + |
|
| 119 | + $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()])) |
|
| 120 | + ->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [ |
|
| 121 | + 'app' => [ |
|
| 122 | + 'type' => 'app', |
|
| 123 | + 'id' => $notification->getObjectType(), |
|
| 124 | + 'name' => $appName, |
|
| 125 | + ] |
|
| 126 | + ]); |
|
| 127 | + |
|
| 128 | + if ($this->isAdmin()) { |
|
| 129 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType()); |
|
| 130 | + } |
|
| 131 | + } |
|
| 132 | + |
|
| 133 | + $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg'))); |
|
| 134 | + |
|
| 135 | + return $notification; |
|
| 136 | + } |
|
| 137 | + |
|
| 138 | + /** |
|
| 139 | + * Remove the notification and prevent rendering, when the update is installed |
|
| 140 | + * |
|
| 141 | + * @param INotification $notification |
|
| 142 | + * @param string $installedVersion |
|
| 143 | + * @throws \InvalidArgumentException When the update is already installed |
|
| 144 | + */ |
|
| 145 | + protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { |
|
| 146 | + if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { |
|
| 147 | + $this->notificationManager->markProcessed($notification); |
|
| 148 | + throw new \InvalidArgumentException(); |
|
| 149 | + } |
|
| 150 | + } |
|
| 151 | + |
|
| 152 | + /** |
|
| 153 | + * @return bool |
|
| 154 | + */ |
|
| 155 | + protected function isAdmin() { |
|
| 156 | + $user = $this->userSession->getUser(); |
|
| 157 | + |
|
| 158 | + if ($user instanceof IUser) { |
|
| 159 | + return $this->groupManager->isAdmin($user->getUID()); |
|
| 160 | + } |
|
| 161 | + |
|
| 162 | + return false; |
|
| 163 | + } |
|
| 164 | + |
|
| 165 | + protected function getCoreVersions() { |
|
| 166 | + return implode('.', \OCP\Util::getVersion()); |
|
| 167 | + } |
|
| 168 | + |
|
| 169 | + protected function getAppVersions() { |
|
| 170 | + return \OC_App::getAppVersions(); |
|
| 171 | + } |
|
| 172 | + |
|
| 173 | + protected function getAppInfo($appId) { |
|
| 174 | + return \OC_App::getAppInfo($appId); |
|
| 175 | + } |
|
| 176 | 176 | } |
@@ -74,8 +74,6 @@ |
||
| 74 | 74 | /** |
| 75 | 75 | * save the configuration value as provided |
| 76 | 76 | * @param string $configID |
| 77 | - * @param string $configKey |
|
| 78 | - * @param string $configValue |
|
| 79 | 77 | */ |
| 80 | 78 | protected function setValue($configID, $key, $value) { |
| 81 | 79 | $configHolder = new Configuration($configID); |
@@ -34,53 +34,53 @@ |
||
| 34 | 34 | |
| 35 | 35 | class SetConfig extends Command { |
| 36 | 36 | |
| 37 | - protected function configure() { |
|
| 38 | - $this |
|
| 39 | - ->setName('ldap:set-config') |
|
| 40 | - ->setDescription('modifies an LDAP configuration') |
|
| 41 | - ->addArgument( |
|
| 42 | - 'configID', |
|
| 43 | - InputArgument::REQUIRED, |
|
| 44 | - 'the configuration ID' |
|
| 45 | - ) |
|
| 46 | - ->addArgument( |
|
| 47 | - 'configKey', |
|
| 48 | - InputArgument::REQUIRED, |
|
| 49 | - 'the configuration key' |
|
| 50 | - ) |
|
| 51 | - ->addArgument( |
|
| 52 | - 'configValue', |
|
| 53 | - InputArgument::REQUIRED, |
|
| 54 | - 'the new configuration value' |
|
| 55 | - ) |
|
| 56 | - ; |
|
| 57 | - } |
|
| 37 | + protected function configure() { |
|
| 38 | + $this |
|
| 39 | + ->setName('ldap:set-config') |
|
| 40 | + ->setDescription('modifies an LDAP configuration') |
|
| 41 | + ->addArgument( |
|
| 42 | + 'configID', |
|
| 43 | + InputArgument::REQUIRED, |
|
| 44 | + 'the configuration ID' |
|
| 45 | + ) |
|
| 46 | + ->addArgument( |
|
| 47 | + 'configKey', |
|
| 48 | + InputArgument::REQUIRED, |
|
| 49 | + 'the configuration key' |
|
| 50 | + ) |
|
| 51 | + ->addArgument( |
|
| 52 | + 'configValue', |
|
| 53 | + InputArgument::REQUIRED, |
|
| 54 | + 'the new configuration value' |
|
| 55 | + ) |
|
| 56 | + ; |
|
| 57 | + } |
|
| 58 | 58 | |
| 59 | - protected function execute(InputInterface $input, OutputInterface $output) { |
|
| 60 | - $helper = new Helper(\OC::$server->getConfig()); |
|
| 61 | - $availableConfigs = $helper->getServerConfigurationPrefixes(); |
|
| 62 | - $configID = $input->getArgument('configID'); |
|
| 63 | - if(!in_array($configID, $availableConfigs)) { |
|
| 64 | - $output->writeln("Invalid configID"); |
|
| 65 | - return; |
|
| 66 | - } |
|
| 59 | + protected function execute(InputInterface $input, OutputInterface $output) { |
|
| 60 | + $helper = new Helper(\OC::$server->getConfig()); |
|
| 61 | + $availableConfigs = $helper->getServerConfigurationPrefixes(); |
|
| 62 | + $configID = $input->getArgument('configID'); |
|
| 63 | + if(!in_array($configID, $availableConfigs)) { |
|
| 64 | + $output->writeln("Invalid configID"); |
|
| 65 | + return; |
|
| 66 | + } |
|
| 67 | 67 | |
| 68 | - $this->setValue( |
|
| 69 | - $configID, |
|
| 70 | - $input->getArgument('configKey'), |
|
| 71 | - $input->getArgument('configValue') |
|
| 72 | - ); |
|
| 73 | - } |
|
| 68 | + $this->setValue( |
|
| 69 | + $configID, |
|
| 70 | + $input->getArgument('configKey'), |
|
| 71 | + $input->getArgument('configValue') |
|
| 72 | + ); |
|
| 73 | + } |
|
| 74 | 74 | |
| 75 | - /** |
|
| 76 | - * save the configuration value as provided |
|
| 77 | - * @param string $configID |
|
| 78 | - * @param string $configKey |
|
| 79 | - * @param string $configValue |
|
| 80 | - */ |
|
| 81 | - protected function setValue($configID, $key, $value) { |
|
| 82 | - $configHolder = new Configuration($configID); |
|
| 83 | - $configHolder->$key = $value; |
|
| 84 | - $configHolder->saveConfiguration(); |
|
| 85 | - } |
|
| 75 | + /** |
|
| 76 | + * save the configuration value as provided |
|
| 77 | + * @param string $configID |
|
| 78 | + * @param string $configKey |
|
| 79 | + * @param string $configValue |
|
| 80 | + */ |
|
| 81 | + protected function setValue($configID, $key, $value) { |
|
| 82 | + $configHolder = new Configuration($configID); |
|
| 83 | + $configHolder->$key = $value; |
|
| 84 | + $configHolder->saveConfiguration(); |
|
| 85 | + } |
|
| 86 | 86 | } |
@@ -60,7 +60,7 @@ |
||
| 60 | 60 | $helper = new Helper(\OC::$server->getConfig()); |
| 61 | 61 | $availableConfigs = $helper->getServerConfigurationPrefixes(); |
| 62 | 62 | $configID = $input->getArgument('configID'); |
| 63 | - if(!in_array($configID, $availableConfigs)) { |
|
| 63 | + if (!in_array($configID, $availableConfigs)) { |
|
| 64 | 64 | $output->writeln("Invalid configID"); |
| 65 | 65 | return; |
| 66 | 66 | } |
@@ -77,7 +77,7 @@ |
||
| 77 | 77 | } |
| 78 | 78 | |
| 79 | 79 | /** |
| 80 | - * @return int |
|
| 80 | + * @return string |
|
| 81 | 81 | */ |
| 82 | 82 | static private function getRefreshInterval() { |
| 83 | 83 | //defaults to every hour |
@@ -45,14 +45,14 @@ discard block |
||
| 45 | 45 | |
| 46 | 46 | static private $groupBE; |
| 47 | 47 | |
| 48 | - public function __construct(){ |
|
| 48 | + public function __construct() { |
|
| 49 | 49 | $this->interval = self::getRefreshInterval(); |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | /** |
| 53 | 53 | * @param mixed $argument |
| 54 | 54 | */ |
| 55 | - public function run($argument){ |
|
| 55 | + public function run($argument) { |
|
| 56 | 56 | self::updateGroups(); |
| 57 | 57 | } |
| 58 | 58 | |
@@ -62,7 +62,7 @@ discard block |
||
| 62 | 62 | $knownGroups = array_keys(self::getKnownGroups()); |
| 63 | 63 | $actualGroups = self::getGroupBE()->getGroups(); |
| 64 | 64 | |
| 65 | - if(empty($actualGroups) && empty($knownGroups)) { |
|
| 65 | + if (empty($actualGroups) && empty($knownGroups)) { |
|
| 66 | 66 | \OCP\Util::writeLog('user_ldap', |
| 67 | 67 | 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
| 68 | 68 | \OCP\Util::INFO); |
@@ -94,26 +94,26 @@ discard block |
||
| 94 | 94 | SET `owncloudusers` = ? |
| 95 | 95 | WHERE `owncloudname` = ? |
| 96 | 96 | '); |
| 97 | - foreach($groups as $group) { |
|
| 97 | + foreach ($groups as $group) { |
|
| 98 | 98 | //we assume, that self::$groupsFromDB has been retrieved already |
| 99 | 99 | $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); |
| 100 | 100 | $actualUsers = self::getGroupBE()->usersInGroup($group); |
| 101 | 101 | $hasChanged = false; |
| 102 | - foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
| 102 | + foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
| 103 | 103 | \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); |
| 104 | 104 | \OCP\Util::writeLog('user_ldap', |
| 105 | 105 | 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', |
| 106 | 106 | \OCP\Util::INFO); |
| 107 | 107 | $hasChanged = true; |
| 108 | 108 | } |
| 109 | - foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
| 109 | + foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
| 110 | 110 | \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); |
| 111 | 111 | \OCP\Util::writeLog('user_ldap', |
| 112 | 112 | 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', |
| 113 | 113 | \OCP\Util::INFO); |
| 114 | 114 | $hasChanged = true; |
| 115 | 115 | } |
| 116 | - if($hasChanged) { |
|
| 116 | + if ($hasChanged) { |
|
| 117 | 117 | $query->execute(array(serialize($actualUsers), $group)); |
| 118 | 118 | } |
| 119 | 119 | } |
@@ -132,7 +132,7 @@ discard block |
||
| 132 | 132 | INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`) |
| 133 | 133 | VALUES (?, ?) |
| 134 | 134 | '); |
| 135 | - foreach($createdGroups as $createdGroup) { |
|
| 135 | + foreach ($createdGroups as $createdGroup) { |
|
| 136 | 136 | \OCP\Util::writeLog('user_ldap', |
| 137 | 137 | 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
| 138 | 138 | \OCP\Util::INFO); |
@@ -154,7 +154,7 @@ discard block |
||
| 154 | 154 | FROM `*PREFIX*ldap_group_members` |
| 155 | 155 | WHERE `owncloudname` = ? |
| 156 | 156 | '); |
| 157 | - foreach($removedGroups as $removedGroup) { |
|
| 157 | + foreach ($removedGroups as $removedGroup) { |
|
| 158 | 158 | \OCP\Util::writeLog('user_ldap', |
| 159 | 159 | 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
| 160 | 160 | \OCP\Util::INFO); |
@@ -169,13 +169,13 @@ discard block |
||
| 169 | 169 | * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy |
| 170 | 170 | */ |
| 171 | 171 | static private function getGroupBE() { |
| 172 | - if(!is_null(self::$groupBE)) { |
|
| 172 | + if (!is_null(self::$groupBE)) { |
|
| 173 | 173 | return self::$groupBE; |
| 174 | 174 | } |
| 175 | 175 | $helper = new Helper(\OC::$server->getConfig()); |
| 176 | 176 | $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
| 177 | 177 | $ldapWrapper = new LDAP(); |
| 178 | - if(count($configPrefixes) === 1) { |
|
| 178 | + if (count($configPrefixes) === 1) { |
|
| 179 | 179 | //avoid the proxy when there is only one LDAP server configured |
| 180 | 180 | $dbc = \OC::$server->getDatabaseConnection(); |
| 181 | 181 | $userManager = new Manager( |
@@ -204,7 +204,7 @@ discard block |
||
| 204 | 204 | * @return array |
| 205 | 205 | */ |
| 206 | 206 | static private function getKnownGroups() { |
| 207 | - if(is_array(self::$groupsFromDB)) { |
|
| 207 | + if (is_array(self::$groupsFromDB)) { |
|
| 208 | 208 | return self::$groupsFromDB; |
| 209 | 209 | } |
| 210 | 210 | $query = \OCP\DB::prepare(' |
@@ -213,7 +213,7 @@ discard block |
||
| 213 | 213 | '); |
| 214 | 214 | $result = $query->execute()->fetchAll(); |
| 215 | 215 | self::$groupsFromDB = array(); |
| 216 | - foreach($result as $dataset) { |
|
| 216 | + foreach ($result as $dataset) { |
|
| 217 | 217 | self::$groupsFromDB[$dataset['owncloudname']] = $dataset; |
| 218 | 218 | } |
| 219 | 219 | |
@@ -41,183 +41,183 @@ |
||
| 41 | 41 | use OCA\User_LDAP\User\Manager; |
| 42 | 42 | |
| 43 | 43 | class UpdateGroups extends \OC\BackgroundJob\TimedJob { |
| 44 | - static private $groupsFromDB; |
|
| 45 | - |
|
| 46 | - static private $groupBE; |
|
| 47 | - |
|
| 48 | - public function __construct(){ |
|
| 49 | - $this->interval = self::getRefreshInterval(); |
|
| 50 | - } |
|
| 51 | - |
|
| 52 | - /** |
|
| 53 | - * @param mixed $argument |
|
| 54 | - */ |
|
| 55 | - public function run($argument){ |
|
| 56 | - self::updateGroups(); |
|
| 57 | - } |
|
| 58 | - |
|
| 59 | - static public function updateGroups() { |
|
| 60 | - \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG); |
|
| 61 | - |
|
| 62 | - $knownGroups = array_keys(self::getKnownGroups()); |
|
| 63 | - $actualGroups = self::getGroupBE()->getGroups(); |
|
| 64 | - |
|
| 65 | - if(empty($actualGroups) && empty($knownGroups)) { |
|
| 66 | - \OCP\Util::writeLog('user_ldap', |
|
| 67 | - 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
|
| 68 | - \OCP\Util::INFO); |
|
| 69 | - return; |
|
| 70 | - } |
|
| 71 | - |
|
| 72 | - self::handleKnownGroups(array_intersect($actualGroups, $knownGroups)); |
|
| 73 | - self::handleCreatedGroups(array_diff($actualGroups, $knownGroups)); |
|
| 74 | - self::handleRemovedGroups(array_diff($knownGroups, $actualGroups)); |
|
| 75 | - |
|
| 76 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG); |
|
| 77 | - } |
|
| 78 | - |
|
| 79 | - /** |
|
| 80 | - * @return int |
|
| 81 | - */ |
|
| 82 | - static private function getRefreshInterval() { |
|
| 83 | - //defaults to every hour |
|
| 84 | - return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600); |
|
| 85 | - } |
|
| 86 | - |
|
| 87 | - /** |
|
| 88 | - * @param string[] $groups |
|
| 89 | - */ |
|
| 90 | - static private function handleKnownGroups($groups) { |
|
| 91 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG); |
|
| 92 | - $query = \OCP\DB::prepare(' |
|
| 44 | + static private $groupsFromDB; |
|
| 45 | + |
|
| 46 | + static private $groupBE; |
|
| 47 | + |
|
| 48 | + public function __construct(){ |
|
| 49 | + $this->interval = self::getRefreshInterval(); |
|
| 50 | + } |
|
| 51 | + |
|
| 52 | + /** |
|
| 53 | + * @param mixed $argument |
|
| 54 | + */ |
|
| 55 | + public function run($argument){ |
|
| 56 | + self::updateGroups(); |
|
| 57 | + } |
|
| 58 | + |
|
| 59 | + static public function updateGroups() { |
|
| 60 | + \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG); |
|
| 61 | + |
|
| 62 | + $knownGroups = array_keys(self::getKnownGroups()); |
|
| 63 | + $actualGroups = self::getGroupBE()->getGroups(); |
|
| 64 | + |
|
| 65 | + if(empty($actualGroups) && empty($knownGroups)) { |
|
| 66 | + \OCP\Util::writeLog('user_ldap', |
|
| 67 | + 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
|
| 68 | + \OCP\Util::INFO); |
|
| 69 | + return; |
|
| 70 | + } |
|
| 71 | + |
|
| 72 | + self::handleKnownGroups(array_intersect($actualGroups, $knownGroups)); |
|
| 73 | + self::handleCreatedGroups(array_diff($actualGroups, $knownGroups)); |
|
| 74 | + self::handleRemovedGroups(array_diff($knownGroups, $actualGroups)); |
|
| 75 | + |
|
| 76 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG); |
|
| 77 | + } |
|
| 78 | + |
|
| 79 | + /** |
|
| 80 | + * @return int |
|
| 81 | + */ |
|
| 82 | + static private function getRefreshInterval() { |
|
| 83 | + //defaults to every hour |
|
| 84 | + return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600); |
|
| 85 | + } |
|
| 86 | + |
|
| 87 | + /** |
|
| 88 | + * @param string[] $groups |
|
| 89 | + */ |
|
| 90 | + static private function handleKnownGroups($groups) { |
|
| 91 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG); |
|
| 92 | + $query = \OCP\DB::prepare(' |
|
| 93 | 93 | UPDATE `*PREFIX*ldap_group_members` |
| 94 | 94 | SET `owncloudusers` = ? |
| 95 | 95 | WHERE `owncloudname` = ? |
| 96 | 96 | '); |
| 97 | - foreach($groups as $group) { |
|
| 98 | - //we assume, that self::$groupsFromDB has been retrieved already |
|
| 99 | - $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); |
|
| 100 | - $actualUsers = self::getGroupBE()->usersInGroup($group); |
|
| 101 | - $hasChanged = false; |
|
| 102 | - foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
| 103 | - \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); |
|
| 104 | - \OCP\Util::writeLog('user_ldap', |
|
| 105 | - 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', |
|
| 106 | - \OCP\Util::INFO); |
|
| 107 | - $hasChanged = true; |
|
| 108 | - } |
|
| 109 | - foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
| 110 | - \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); |
|
| 111 | - \OCP\Util::writeLog('user_ldap', |
|
| 112 | - 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', |
|
| 113 | - \OCP\Util::INFO); |
|
| 114 | - $hasChanged = true; |
|
| 115 | - } |
|
| 116 | - if($hasChanged) { |
|
| 117 | - $query->execute(array(serialize($actualUsers), $group)); |
|
| 118 | - } |
|
| 119 | - } |
|
| 120 | - \OCP\Util::writeLog('user_ldap', |
|
| 121 | - 'bgJ "updateGroups" – FINISHED dealing with known Groups.', |
|
| 122 | - \OCP\Util::DEBUG); |
|
| 123 | - } |
|
| 124 | - |
|
| 125 | - /** |
|
| 126 | - * @param string[] $createdGroups |
|
| 127 | - */ |
|
| 128 | - static private function handleCreatedGroups($createdGroups) { |
|
| 129 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG); |
|
| 130 | - $query = \OCP\DB::prepare(' |
|
| 97 | + foreach($groups as $group) { |
|
| 98 | + //we assume, that self::$groupsFromDB has been retrieved already |
|
| 99 | + $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); |
|
| 100 | + $actualUsers = self::getGroupBE()->usersInGroup($group); |
|
| 101 | + $hasChanged = false; |
|
| 102 | + foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
| 103 | + \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); |
|
| 104 | + \OCP\Util::writeLog('user_ldap', |
|
| 105 | + 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', |
|
| 106 | + \OCP\Util::INFO); |
|
| 107 | + $hasChanged = true; |
|
| 108 | + } |
|
| 109 | + foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
| 110 | + \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); |
|
| 111 | + \OCP\Util::writeLog('user_ldap', |
|
| 112 | + 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', |
|
| 113 | + \OCP\Util::INFO); |
|
| 114 | + $hasChanged = true; |
|
| 115 | + } |
|
| 116 | + if($hasChanged) { |
|
| 117 | + $query->execute(array(serialize($actualUsers), $group)); |
|
| 118 | + } |
|
| 119 | + } |
|
| 120 | + \OCP\Util::writeLog('user_ldap', |
|
| 121 | + 'bgJ "updateGroups" – FINISHED dealing with known Groups.', |
|
| 122 | + \OCP\Util::DEBUG); |
|
| 123 | + } |
|
| 124 | + |
|
| 125 | + /** |
|
| 126 | + * @param string[] $createdGroups |
|
| 127 | + */ |
|
| 128 | + static private function handleCreatedGroups($createdGroups) { |
|
| 129 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG); |
|
| 130 | + $query = \OCP\DB::prepare(' |
|
| 131 | 131 | INSERT |
| 132 | 132 | INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`) |
| 133 | 133 | VALUES (?, ?) |
| 134 | 134 | '); |
| 135 | - foreach($createdGroups as $createdGroup) { |
|
| 136 | - \OCP\Util::writeLog('user_ldap', |
|
| 137 | - 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
|
| 138 | - \OCP\Util::INFO); |
|
| 139 | - $users = serialize(self::getGroupBE()->usersInGroup($createdGroup)); |
|
| 140 | - $query->execute(array($createdGroup, $users)); |
|
| 141 | - } |
|
| 142 | - \OCP\Util::writeLog('user_ldap', |
|
| 143 | - 'bgJ "updateGroups" – FINISHED dealing with created Groups.', |
|
| 144 | - \OCP\Util::DEBUG); |
|
| 145 | - } |
|
| 146 | - |
|
| 147 | - /** |
|
| 148 | - * @param string[] $removedGroups |
|
| 149 | - */ |
|
| 150 | - static private function handleRemovedGroups($removedGroups) { |
|
| 151 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG); |
|
| 152 | - $query = \OCP\DB::prepare(' |
|
| 135 | + foreach($createdGroups as $createdGroup) { |
|
| 136 | + \OCP\Util::writeLog('user_ldap', |
|
| 137 | + 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
|
| 138 | + \OCP\Util::INFO); |
|
| 139 | + $users = serialize(self::getGroupBE()->usersInGroup($createdGroup)); |
|
| 140 | + $query->execute(array($createdGroup, $users)); |
|
| 141 | + } |
|
| 142 | + \OCP\Util::writeLog('user_ldap', |
|
| 143 | + 'bgJ "updateGroups" – FINISHED dealing with created Groups.', |
|
| 144 | + \OCP\Util::DEBUG); |
|
| 145 | + } |
|
| 146 | + |
|
| 147 | + /** |
|
| 148 | + * @param string[] $removedGroups |
|
| 149 | + */ |
|
| 150 | + static private function handleRemovedGroups($removedGroups) { |
|
| 151 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG); |
|
| 152 | + $query = \OCP\DB::prepare(' |
|
| 153 | 153 | DELETE |
| 154 | 154 | FROM `*PREFIX*ldap_group_members` |
| 155 | 155 | WHERE `owncloudname` = ? |
| 156 | 156 | '); |
| 157 | - foreach($removedGroups as $removedGroup) { |
|
| 158 | - \OCP\Util::writeLog('user_ldap', |
|
| 159 | - 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
|
| 160 | - \OCP\Util::INFO); |
|
| 161 | - $query->execute(array($removedGroup)); |
|
| 162 | - } |
|
| 163 | - \OCP\Util::writeLog('user_ldap', |
|
| 164 | - 'bgJ "updateGroups" – FINISHED dealing with removed groups.', |
|
| 165 | - \OCP\Util::DEBUG); |
|
| 166 | - } |
|
| 167 | - |
|
| 168 | - /** |
|
| 169 | - * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy |
|
| 170 | - */ |
|
| 171 | - static private function getGroupBE() { |
|
| 172 | - if(!is_null(self::$groupBE)) { |
|
| 173 | - return self::$groupBE; |
|
| 174 | - } |
|
| 175 | - $helper = new Helper(\OC::$server->getConfig()); |
|
| 176 | - $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
| 177 | - $ldapWrapper = new LDAP(); |
|
| 178 | - if(count($configPrefixes) === 1) { |
|
| 179 | - //avoid the proxy when there is only one LDAP server configured |
|
| 180 | - $dbc = \OC::$server->getDatabaseConnection(); |
|
| 181 | - $userManager = new Manager( |
|
| 182 | - \OC::$server->getConfig(), |
|
| 183 | - new FilesystemHelper(), |
|
| 184 | - new LogWrapper(), |
|
| 185 | - \OC::$server->getAvatarManager(), |
|
| 186 | - new \OCP\Image(), |
|
| 187 | - $dbc, |
|
| 188 | - \OC::$server->getUserManager(), |
|
| 189 | - \OC::$server->getNotificationManager()); |
|
| 190 | - $connector = new Connection($ldapWrapper, $configPrefixes[0]); |
|
| 191 | - $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper); |
|
| 192 | - $groupMapper = new GroupMapping($dbc); |
|
| 193 | - $userMapper = new UserMapping($dbc); |
|
| 194 | - $ldapAccess->setGroupMapper($groupMapper); |
|
| 195 | - $ldapAccess->setUserMapper($userMapper); |
|
| 196 | - self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager')); |
|
| 197 | - } else { |
|
| 198 | - self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager')); |
|
| 199 | - } |
|
| 200 | - |
|
| 201 | - return self::$groupBE; |
|
| 202 | - } |
|
| 203 | - |
|
| 204 | - /** |
|
| 205 | - * @return array |
|
| 206 | - */ |
|
| 207 | - static private function getKnownGroups() { |
|
| 208 | - if(is_array(self::$groupsFromDB)) { |
|
| 209 | - return self::$groupsFromDB; |
|
| 210 | - } |
|
| 211 | - $query = \OCP\DB::prepare(' |
|
| 157 | + foreach($removedGroups as $removedGroup) { |
|
| 158 | + \OCP\Util::writeLog('user_ldap', |
|
| 159 | + 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
|
| 160 | + \OCP\Util::INFO); |
|
| 161 | + $query->execute(array($removedGroup)); |
|
| 162 | + } |
|
| 163 | + \OCP\Util::writeLog('user_ldap', |
|
| 164 | + 'bgJ "updateGroups" – FINISHED dealing with removed groups.', |
|
| 165 | + \OCP\Util::DEBUG); |
|
| 166 | + } |
|
| 167 | + |
|
| 168 | + /** |
|
| 169 | + * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy |
|
| 170 | + */ |
|
| 171 | + static private function getGroupBE() { |
|
| 172 | + if(!is_null(self::$groupBE)) { |
|
| 173 | + return self::$groupBE; |
|
| 174 | + } |
|
| 175 | + $helper = new Helper(\OC::$server->getConfig()); |
|
| 176 | + $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
| 177 | + $ldapWrapper = new LDAP(); |
|
| 178 | + if(count($configPrefixes) === 1) { |
|
| 179 | + //avoid the proxy when there is only one LDAP server configured |
|
| 180 | + $dbc = \OC::$server->getDatabaseConnection(); |
|
| 181 | + $userManager = new Manager( |
|
| 182 | + \OC::$server->getConfig(), |
|
| 183 | + new FilesystemHelper(), |
|
| 184 | + new LogWrapper(), |
|
| 185 | + \OC::$server->getAvatarManager(), |
|
| 186 | + new \OCP\Image(), |
|
| 187 | + $dbc, |
|
| 188 | + \OC::$server->getUserManager(), |
|
| 189 | + \OC::$server->getNotificationManager()); |
|
| 190 | + $connector = new Connection($ldapWrapper, $configPrefixes[0]); |
|
| 191 | + $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper); |
|
| 192 | + $groupMapper = new GroupMapping($dbc); |
|
| 193 | + $userMapper = new UserMapping($dbc); |
|
| 194 | + $ldapAccess->setGroupMapper($groupMapper); |
|
| 195 | + $ldapAccess->setUserMapper($userMapper); |
|
| 196 | + self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager')); |
|
| 197 | + } else { |
|
| 198 | + self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager')); |
|
| 199 | + } |
|
| 200 | + |
|
| 201 | + return self::$groupBE; |
|
| 202 | + } |
|
| 203 | + |
|
| 204 | + /** |
|
| 205 | + * @return array |
|
| 206 | + */ |
|
| 207 | + static private function getKnownGroups() { |
|
| 208 | + if(is_array(self::$groupsFromDB)) { |
|
| 209 | + return self::$groupsFromDB; |
|
| 210 | + } |
|
| 211 | + $query = \OCP\DB::prepare(' |
|
| 212 | 212 | SELECT `owncloudname`, `owncloudusers` |
| 213 | 213 | FROM `*PREFIX*ldap_group_members` |
| 214 | 214 | '); |
| 215 | - $result = $query->execute()->fetchAll(); |
|
| 216 | - self::$groupsFromDB = array(); |
|
| 217 | - foreach($result as $dataset) { |
|
| 218 | - self::$groupsFromDB[$dataset['owncloudname']] = $dataset; |
|
| 219 | - } |
|
| 220 | - |
|
| 221 | - return self::$groupsFromDB; |
|
| 222 | - } |
|
| 215 | + $result = $query->execute()->fetchAll(); |
|
| 216 | + self::$groupsFromDB = array(); |
|
| 217 | + foreach($result as $dataset) { |
|
| 218 | + self::$groupsFromDB[$dataset['owncloudname']] = $dataset; |
|
| 219 | + } |
|
| 220 | + |
|
| 221 | + return self::$groupsFromDB; |
|
| 222 | + } |
|
| 223 | 223 | } |
@@ -112,7 +112,7 @@ |
||
| 112 | 112 | * Looks up a system wide defined value |
| 113 | 113 | * |
| 114 | 114 | * @param string $key the key of the value, under which it was saved |
| 115 | - * @param mixed $default the default value to be returned if the value isn't set |
|
| 115 | + * @param string $default the default value to be returned if the value isn't set |
|
| 116 | 116 | * @return mixed the value or $default |
| 117 | 117 | */ |
| 118 | 118 | public function getSystemValue($key, $default = '') { |
@@ -37,427 +37,427 @@ |
||
| 37 | 37 | * Class to combine all the configuration options ownCloud offers |
| 38 | 38 | */ |
| 39 | 39 | class AllConfig implements \OCP\IConfig { |
| 40 | - /** @var SystemConfig */ |
|
| 41 | - private $systemConfig; |
|
| 42 | - |
|
| 43 | - /** @var IDBConnection */ |
|
| 44 | - private $connection; |
|
| 45 | - |
|
| 46 | - /** |
|
| 47 | - * 3 dimensional array with the following structure: |
|
| 48 | - * [ $userId => |
|
| 49 | - * [ $appId => |
|
| 50 | - * [ $key => $value ] |
|
| 51 | - * ] |
|
| 52 | - * ] |
|
| 53 | - * |
|
| 54 | - * database table: preferences |
|
| 55 | - * |
|
| 56 | - * methods that use this: |
|
| 57 | - * - setUserValue |
|
| 58 | - * - getUserValue |
|
| 59 | - * - getUserKeys |
|
| 60 | - * - deleteUserValue |
|
| 61 | - * - deleteAllUserValues |
|
| 62 | - * - deleteAppFromAllUsers |
|
| 63 | - * |
|
| 64 | - * @var CappedMemoryCache $userCache |
|
| 65 | - */ |
|
| 66 | - private $userCache; |
|
| 67 | - |
|
| 68 | - /** |
|
| 69 | - * @param SystemConfig $systemConfig |
|
| 70 | - */ |
|
| 71 | - public function __construct(SystemConfig $systemConfig) { |
|
| 72 | - $this->userCache = new CappedMemoryCache(); |
|
| 73 | - $this->systemConfig = $systemConfig; |
|
| 74 | - } |
|
| 75 | - |
|
| 76 | - /** |
|
| 77 | - * TODO - FIXME This fixes an issue with base.php that cause cyclic |
|
| 78 | - * dependencies, especially with autoconfig setup |
|
| 79 | - * |
|
| 80 | - * Replace this by properly injected database connection. Currently the |
|
| 81 | - * base.php triggers the getDatabaseConnection too early which causes in |
|
| 82 | - * autoconfig setup case a too early distributed database connection and |
|
| 83 | - * the autoconfig then needs to reinit all already initialized dependencies |
|
| 84 | - * that use the database connection. |
|
| 85 | - * |
|
| 86 | - * otherwise a SQLite database is created in the wrong directory |
|
| 87 | - * because the database connection was created with an uninitialized config |
|
| 88 | - */ |
|
| 89 | - private function fixDIInit() { |
|
| 90 | - if($this->connection === null) { |
|
| 91 | - $this->connection = \OC::$server->getDatabaseConnection(); |
|
| 92 | - } |
|
| 93 | - } |
|
| 94 | - |
|
| 95 | - /** |
|
| 96 | - * Sets and deletes system wide values |
|
| 97 | - * |
|
| 98 | - * @param array $configs Associative array with `key => value` pairs |
|
| 99 | - * If value is null, the config key will be deleted |
|
| 100 | - */ |
|
| 101 | - public function setSystemValues(array $configs) { |
|
| 102 | - $this->systemConfig->setValues($configs); |
|
| 103 | - } |
|
| 104 | - |
|
| 105 | - /** |
|
| 106 | - * Sets a new system wide value |
|
| 107 | - * |
|
| 108 | - * @param string $key the key of the value, under which will be saved |
|
| 109 | - * @param mixed $value the value that should be stored |
|
| 110 | - */ |
|
| 111 | - public function setSystemValue($key, $value) { |
|
| 112 | - $this->systemConfig->setValue($key, $value); |
|
| 113 | - } |
|
| 114 | - |
|
| 115 | - /** |
|
| 116 | - * Looks up a system wide defined value |
|
| 117 | - * |
|
| 118 | - * @param string $key the key of the value, under which it was saved |
|
| 119 | - * @param mixed $default the default value to be returned if the value isn't set |
|
| 120 | - * @return mixed the value or $default |
|
| 121 | - */ |
|
| 122 | - public function getSystemValue($key, $default = '') { |
|
| 123 | - return $this->systemConfig->getValue($key, $default); |
|
| 124 | - } |
|
| 125 | - |
|
| 126 | - /** |
|
| 127 | - * Looks up a system wide defined value and filters out sensitive data |
|
| 128 | - * |
|
| 129 | - * @param string $key the key of the value, under which it was saved |
|
| 130 | - * @param mixed $default the default value to be returned if the value isn't set |
|
| 131 | - * @return mixed the value or $default |
|
| 132 | - */ |
|
| 133 | - public function getFilteredSystemValue($key, $default = '') { |
|
| 134 | - return $this->systemConfig->getFilteredValue($key, $default); |
|
| 135 | - } |
|
| 136 | - |
|
| 137 | - /** |
|
| 138 | - * Delete a system wide defined value |
|
| 139 | - * |
|
| 140 | - * @param string $key the key of the value, under which it was saved |
|
| 141 | - */ |
|
| 142 | - public function deleteSystemValue($key) { |
|
| 143 | - $this->systemConfig->deleteValue($key); |
|
| 144 | - } |
|
| 145 | - |
|
| 146 | - /** |
|
| 147 | - * Get all keys stored for an app |
|
| 148 | - * |
|
| 149 | - * @param string $appName the appName that we stored the value under |
|
| 150 | - * @return string[] the keys stored for the app |
|
| 151 | - */ |
|
| 152 | - public function getAppKeys($appName) { |
|
| 153 | - return \OC::$server->getAppConfig()->getKeys($appName); |
|
| 154 | - } |
|
| 155 | - |
|
| 156 | - /** |
|
| 157 | - * Writes a new app wide value |
|
| 158 | - * |
|
| 159 | - * @param string $appName the appName that we want to store the value under |
|
| 160 | - * @param string $key the key of the value, under which will be saved |
|
| 161 | - * @param string|float|int $value the value that should be stored |
|
| 162 | - */ |
|
| 163 | - public function setAppValue($appName, $key, $value) { |
|
| 164 | - \OC::$server->getAppConfig()->setValue($appName, $key, $value); |
|
| 165 | - } |
|
| 166 | - |
|
| 167 | - /** |
|
| 168 | - * Looks up an app wide defined value |
|
| 169 | - * |
|
| 170 | - * @param string $appName the appName that we stored the value under |
|
| 171 | - * @param string $key the key of the value, under which it was saved |
|
| 172 | - * @param string $default the default value to be returned if the value isn't set |
|
| 173 | - * @return string the saved value |
|
| 174 | - */ |
|
| 175 | - public function getAppValue($appName, $key, $default = '') { |
|
| 176 | - return \OC::$server->getAppConfig()->getValue($appName, $key, $default); |
|
| 177 | - } |
|
| 178 | - |
|
| 179 | - /** |
|
| 180 | - * Delete an app wide defined value |
|
| 181 | - * |
|
| 182 | - * @param string $appName the appName that we stored the value under |
|
| 183 | - * @param string $key the key of the value, under which it was saved |
|
| 184 | - */ |
|
| 185 | - public function deleteAppValue($appName, $key) { |
|
| 186 | - \OC::$server->getAppConfig()->deleteKey($appName, $key); |
|
| 187 | - } |
|
| 188 | - |
|
| 189 | - /** |
|
| 190 | - * Removes all keys in appconfig belonging to the app |
|
| 191 | - * |
|
| 192 | - * @param string $appName the appName the configs are stored under |
|
| 193 | - */ |
|
| 194 | - public function deleteAppValues($appName) { |
|
| 195 | - \OC::$server->getAppConfig()->deleteApp($appName); |
|
| 196 | - } |
|
| 197 | - |
|
| 198 | - |
|
| 199 | - /** |
|
| 200 | - * Set a user defined value |
|
| 201 | - * |
|
| 202 | - * @param string $userId the userId of the user that we want to store the value under |
|
| 203 | - * @param string $appName the appName that we want to store the value under |
|
| 204 | - * @param string $key the key under which the value is being stored |
|
| 205 | - * @param string|float|int $value the value that you want to store |
|
| 206 | - * @param string $preCondition only update if the config value was previously the value passed as $preCondition |
|
| 207 | - * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met |
|
| 208 | - * @throws \UnexpectedValueException when trying to store an unexpected value |
|
| 209 | - */ |
|
| 210 | - public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { |
|
| 211 | - if (!is_int($value) && !is_float($value) && !is_string($value)) { |
|
| 212 | - throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); |
|
| 213 | - } |
|
| 214 | - |
|
| 215 | - // TODO - FIXME |
|
| 216 | - $this->fixDIInit(); |
|
| 217 | - |
|
| 218 | - $prevValue = $this->getUserValue($userId, $appName, $key, null); |
|
| 219 | - |
|
| 220 | - if ($prevValue !== null) { |
|
| 221 | - if ($prevValue === (string)$value) { |
|
| 222 | - return; |
|
| 223 | - } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
| 224 | - throw new PreConditionNotMetException(); |
|
| 225 | - } else { |
|
| 226 | - $qb = $this->connection->getQueryBuilder(); |
|
| 227 | - $qb->update('preferences') |
|
| 228 | - ->set('configvalue', $qb->createNamedParameter($value)) |
|
| 229 | - ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) |
|
| 230 | - ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName))) |
|
| 231 | - ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
|
| 232 | - $qb->execute(); |
|
| 233 | - |
|
| 234 | - $this->userCache[$userId][$appName][$key] = $value; |
|
| 235 | - return; |
|
| 236 | - } |
|
| 237 | - } |
|
| 238 | - |
|
| 239 | - $preconditionArray = []; |
|
| 240 | - if (isset($preCondition)) { |
|
| 241 | - $preconditionArray = [ |
|
| 242 | - 'configvalue' => $preCondition, |
|
| 243 | - ]; |
|
| 244 | - } |
|
| 245 | - |
|
| 246 | - $this->connection->setValues('preferences', [ |
|
| 247 | - 'userid' => $userId, |
|
| 248 | - 'appid' => $appName, |
|
| 249 | - 'configkey' => $key, |
|
| 250 | - ], [ |
|
| 251 | - 'configvalue' => $value, |
|
| 252 | - ], $preconditionArray); |
|
| 253 | - |
|
| 254 | - // only add to the cache if we already loaded data for the user |
|
| 255 | - if (isset($this->userCache[$userId])) { |
|
| 256 | - if (!isset($this->userCache[$userId][$appName])) { |
|
| 257 | - $this->userCache[$userId][$appName] = array(); |
|
| 258 | - } |
|
| 259 | - $this->userCache[$userId][$appName][$key] = $value; |
|
| 260 | - } |
|
| 261 | - } |
|
| 262 | - |
|
| 263 | - /** |
|
| 264 | - * Getting a user defined value |
|
| 265 | - * |
|
| 266 | - * @param string $userId the userId of the user that we want to store the value under |
|
| 267 | - * @param string $appName the appName that we stored the value under |
|
| 268 | - * @param string $key the key under which the value is being stored |
|
| 269 | - * @param mixed $default the default value to be returned if the value isn't set |
|
| 270 | - * @return string |
|
| 271 | - */ |
|
| 272 | - public function getUserValue($userId, $appName, $key, $default = '') { |
|
| 273 | - $data = $this->getUserValues($userId); |
|
| 274 | - if (isset($data[$appName]) and isset($data[$appName][$key])) { |
|
| 275 | - return $data[$appName][$key]; |
|
| 276 | - } else { |
|
| 277 | - return $default; |
|
| 278 | - } |
|
| 279 | - } |
|
| 280 | - |
|
| 281 | - /** |
|
| 282 | - * Get the keys of all stored by an app for the user |
|
| 283 | - * |
|
| 284 | - * @param string $userId the userId of the user that we want to store the value under |
|
| 285 | - * @param string $appName the appName that we stored the value under |
|
| 286 | - * @return string[] |
|
| 287 | - */ |
|
| 288 | - public function getUserKeys($userId, $appName) { |
|
| 289 | - $data = $this->getUserValues($userId); |
|
| 290 | - if (isset($data[$appName])) { |
|
| 291 | - return array_keys($data[$appName]); |
|
| 292 | - } else { |
|
| 293 | - return array(); |
|
| 294 | - } |
|
| 295 | - } |
|
| 296 | - |
|
| 297 | - /** |
|
| 298 | - * Delete a user value |
|
| 299 | - * |
|
| 300 | - * @param string $userId the userId of the user that we want to store the value under |
|
| 301 | - * @param string $appName the appName that we stored the value under |
|
| 302 | - * @param string $key the key under which the value is being stored |
|
| 303 | - */ |
|
| 304 | - public function deleteUserValue($userId, $appName, $key) { |
|
| 305 | - // TODO - FIXME |
|
| 306 | - $this->fixDIInit(); |
|
| 307 | - |
|
| 308 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 309 | - 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
|
| 310 | - $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
|
| 311 | - |
|
| 312 | - if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { |
|
| 313 | - unset($this->userCache[$userId][$appName][$key]); |
|
| 314 | - } |
|
| 315 | - } |
|
| 316 | - |
|
| 317 | - /** |
|
| 318 | - * Delete all user values |
|
| 319 | - * |
|
| 320 | - * @param string $userId the userId of the user that we want to remove all values from |
|
| 321 | - */ |
|
| 322 | - public function deleteAllUserValues($userId) { |
|
| 323 | - // TODO - FIXME |
|
| 324 | - $this->fixDIInit(); |
|
| 325 | - |
|
| 326 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 327 | - 'WHERE `userid` = ?'; |
|
| 328 | - $this->connection->executeUpdate($sql, array($userId)); |
|
| 329 | - |
|
| 330 | - unset($this->userCache[$userId]); |
|
| 331 | - } |
|
| 332 | - |
|
| 333 | - /** |
|
| 334 | - * Delete all user related values of one app |
|
| 335 | - * |
|
| 336 | - * @param string $appName the appName of the app that we want to remove all values from |
|
| 337 | - */ |
|
| 338 | - public function deleteAppFromAllUsers($appName) { |
|
| 339 | - // TODO - FIXME |
|
| 340 | - $this->fixDIInit(); |
|
| 341 | - |
|
| 342 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 343 | - 'WHERE `appid` = ?'; |
|
| 344 | - $this->connection->executeUpdate($sql, array($appName)); |
|
| 345 | - |
|
| 346 | - foreach ($this->userCache as &$userCache) { |
|
| 347 | - unset($userCache[$appName]); |
|
| 348 | - } |
|
| 349 | - } |
|
| 350 | - |
|
| 351 | - /** |
|
| 352 | - * Returns all user configs sorted by app of one user |
|
| 353 | - * |
|
| 354 | - * @param string $userId the user ID to get the app configs from |
|
| 355 | - * @return array[] - 2 dimensional array with the following structure: |
|
| 356 | - * [ $appId => |
|
| 357 | - * [ $key => $value ] |
|
| 358 | - * ] |
|
| 359 | - */ |
|
| 360 | - private function getUserValues($userId) { |
|
| 361 | - if (isset($this->userCache[$userId])) { |
|
| 362 | - return $this->userCache[$userId]; |
|
| 363 | - } |
|
| 364 | - if ($userId === null || $userId === '') { |
|
| 365 | - $this->userCache[$userId]=array(); |
|
| 366 | - return $this->userCache[$userId]; |
|
| 367 | - } |
|
| 368 | - |
|
| 369 | - // TODO - FIXME |
|
| 370 | - $this->fixDIInit(); |
|
| 371 | - |
|
| 372 | - $data = array(); |
|
| 373 | - $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; |
|
| 374 | - $result = $this->connection->executeQuery($query, array($userId)); |
|
| 375 | - while ($row = $result->fetch()) { |
|
| 376 | - $appId = $row['appid']; |
|
| 377 | - if (!isset($data[$appId])) { |
|
| 378 | - $data[$appId] = array(); |
|
| 379 | - } |
|
| 380 | - $data[$appId][$row['configkey']] = $row['configvalue']; |
|
| 381 | - } |
|
| 382 | - $this->userCache[$userId] = $data; |
|
| 383 | - return $data; |
|
| 384 | - } |
|
| 385 | - |
|
| 386 | - /** |
|
| 387 | - * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs. |
|
| 388 | - * |
|
| 389 | - * @param string $appName app to get the value for |
|
| 390 | - * @param string $key the key to get the value for |
|
| 391 | - * @param array $userIds the user IDs to fetch the values for |
|
| 392 | - * @return array Mapped values: userId => value |
|
| 393 | - */ |
|
| 394 | - public function getUserValueForUsers($appName, $key, $userIds) { |
|
| 395 | - // TODO - FIXME |
|
| 396 | - $this->fixDIInit(); |
|
| 397 | - |
|
| 398 | - if (empty($userIds) || !is_array($userIds)) { |
|
| 399 | - return array(); |
|
| 400 | - } |
|
| 401 | - |
|
| 402 | - $chunkedUsers = array_chunk($userIds, 50, true); |
|
| 403 | - $placeholders50 = implode(',', array_fill(0, 50, '?')); |
|
| 404 | - |
|
| 405 | - $userValues = array(); |
|
| 406 | - foreach ($chunkedUsers as $chunk) { |
|
| 407 | - $queryParams = $chunk; |
|
| 408 | - // create [$app, $key, $chunkedUsers] |
|
| 409 | - array_unshift($queryParams, $key); |
|
| 410 | - array_unshift($queryParams, $appName); |
|
| 411 | - |
|
| 412 | - $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
| 413 | - |
|
| 414 | - $query = 'SELECT `userid`, `configvalue` ' . |
|
| 415 | - 'FROM `*PREFIX*preferences` ' . |
|
| 416 | - 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
| 417 | - 'AND `userid` IN (' . $placeholders . ')'; |
|
| 418 | - $result = $this->connection->executeQuery($query, $queryParams); |
|
| 419 | - |
|
| 420 | - while ($row = $result->fetch()) { |
|
| 421 | - $userValues[$row['userid']] = $row['configvalue']; |
|
| 422 | - } |
|
| 423 | - } |
|
| 424 | - |
|
| 425 | - return $userValues; |
|
| 426 | - } |
|
| 427 | - |
|
| 428 | - /** |
|
| 429 | - * Determines the users that have the given value set for a specific app-key-pair |
|
| 430 | - * |
|
| 431 | - * @param string $appName the app to get the user for |
|
| 432 | - * @param string $key the key to get the user for |
|
| 433 | - * @param string $value the value to get the user for |
|
| 434 | - * @return array of user IDs |
|
| 435 | - */ |
|
| 436 | - public function getUsersForUserValue($appName, $key, $value) { |
|
| 437 | - // TODO - FIXME |
|
| 438 | - $this->fixDIInit(); |
|
| 439 | - |
|
| 440 | - $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
| 441 | - 'WHERE `appid` = ? AND `configkey` = ? '; |
|
| 442 | - |
|
| 443 | - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
| 444 | - //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
|
| 445 | - $sql .= 'AND to_char(`configvalue`) = ?'; |
|
| 446 | - } else { |
|
| 447 | - $sql .= 'AND `configvalue` = ?'; |
|
| 448 | - } |
|
| 449 | - |
|
| 450 | - $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); |
|
| 451 | - |
|
| 452 | - $userIDs = array(); |
|
| 453 | - while ($row = $result->fetch()) { |
|
| 454 | - $userIDs[] = $row['userid']; |
|
| 455 | - } |
|
| 456 | - |
|
| 457 | - return $userIDs; |
|
| 458 | - } |
|
| 459 | - |
|
| 460 | - public function getSystemConfig() { |
|
| 461 | - return $this->systemConfig; |
|
| 462 | - } |
|
| 40 | + /** @var SystemConfig */ |
|
| 41 | + private $systemConfig; |
|
| 42 | + |
|
| 43 | + /** @var IDBConnection */ |
|
| 44 | + private $connection; |
|
| 45 | + |
|
| 46 | + /** |
|
| 47 | + * 3 dimensional array with the following structure: |
|
| 48 | + * [ $userId => |
|
| 49 | + * [ $appId => |
|
| 50 | + * [ $key => $value ] |
|
| 51 | + * ] |
|
| 52 | + * ] |
|
| 53 | + * |
|
| 54 | + * database table: preferences |
|
| 55 | + * |
|
| 56 | + * methods that use this: |
|
| 57 | + * - setUserValue |
|
| 58 | + * - getUserValue |
|
| 59 | + * - getUserKeys |
|
| 60 | + * - deleteUserValue |
|
| 61 | + * - deleteAllUserValues |
|
| 62 | + * - deleteAppFromAllUsers |
|
| 63 | + * |
|
| 64 | + * @var CappedMemoryCache $userCache |
|
| 65 | + */ |
|
| 66 | + private $userCache; |
|
| 67 | + |
|
| 68 | + /** |
|
| 69 | + * @param SystemConfig $systemConfig |
|
| 70 | + */ |
|
| 71 | + public function __construct(SystemConfig $systemConfig) { |
|
| 72 | + $this->userCache = new CappedMemoryCache(); |
|
| 73 | + $this->systemConfig = $systemConfig; |
|
| 74 | + } |
|
| 75 | + |
|
| 76 | + /** |
|
| 77 | + * TODO - FIXME This fixes an issue with base.php that cause cyclic |
|
| 78 | + * dependencies, especially with autoconfig setup |
|
| 79 | + * |
|
| 80 | + * Replace this by properly injected database connection. Currently the |
|
| 81 | + * base.php triggers the getDatabaseConnection too early which causes in |
|
| 82 | + * autoconfig setup case a too early distributed database connection and |
|
| 83 | + * the autoconfig then needs to reinit all already initialized dependencies |
|
| 84 | + * that use the database connection. |
|
| 85 | + * |
|
| 86 | + * otherwise a SQLite database is created in the wrong directory |
|
| 87 | + * because the database connection was created with an uninitialized config |
|
| 88 | + */ |
|
| 89 | + private function fixDIInit() { |
|
| 90 | + if($this->connection === null) { |
|
| 91 | + $this->connection = \OC::$server->getDatabaseConnection(); |
|
| 92 | + } |
|
| 93 | + } |
|
| 94 | + |
|
| 95 | + /** |
|
| 96 | + * Sets and deletes system wide values |
|
| 97 | + * |
|
| 98 | + * @param array $configs Associative array with `key => value` pairs |
|
| 99 | + * If value is null, the config key will be deleted |
|
| 100 | + */ |
|
| 101 | + public function setSystemValues(array $configs) { |
|
| 102 | + $this->systemConfig->setValues($configs); |
|
| 103 | + } |
|
| 104 | + |
|
| 105 | + /** |
|
| 106 | + * Sets a new system wide value |
|
| 107 | + * |
|
| 108 | + * @param string $key the key of the value, under which will be saved |
|
| 109 | + * @param mixed $value the value that should be stored |
|
| 110 | + */ |
|
| 111 | + public function setSystemValue($key, $value) { |
|
| 112 | + $this->systemConfig->setValue($key, $value); |
|
| 113 | + } |
|
| 114 | + |
|
| 115 | + /** |
|
| 116 | + * Looks up a system wide defined value |
|
| 117 | + * |
|
| 118 | + * @param string $key the key of the value, under which it was saved |
|
| 119 | + * @param mixed $default the default value to be returned if the value isn't set |
|
| 120 | + * @return mixed the value or $default |
|
| 121 | + */ |
|
| 122 | + public function getSystemValue($key, $default = '') { |
|
| 123 | + return $this->systemConfig->getValue($key, $default); |
|
| 124 | + } |
|
| 125 | + |
|
| 126 | + /** |
|
| 127 | + * Looks up a system wide defined value and filters out sensitive data |
|
| 128 | + * |
|
| 129 | + * @param string $key the key of the value, under which it was saved |
|
| 130 | + * @param mixed $default the default value to be returned if the value isn't set |
|
| 131 | + * @return mixed the value or $default |
|
| 132 | + */ |
|
| 133 | + public function getFilteredSystemValue($key, $default = '') { |
|
| 134 | + return $this->systemConfig->getFilteredValue($key, $default); |
|
| 135 | + } |
|
| 136 | + |
|
| 137 | + /** |
|
| 138 | + * Delete a system wide defined value |
|
| 139 | + * |
|
| 140 | + * @param string $key the key of the value, under which it was saved |
|
| 141 | + */ |
|
| 142 | + public function deleteSystemValue($key) { |
|
| 143 | + $this->systemConfig->deleteValue($key); |
|
| 144 | + } |
|
| 145 | + |
|
| 146 | + /** |
|
| 147 | + * Get all keys stored for an app |
|
| 148 | + * |
|
| 149 | + * @param string $appName the appName that we stored the value under |
|
| 150 | + * @return string[] the keys stored for the app |
|
| 151 | + */ |
|
| 152 | + public function getAppKeys($appName) { |
|
| 153 | + return \OC::$server->getAppConfig()->getKeys($appName); |
|
| 154 | + } |
|
| 155 | + |
|
| 156 | + /** |
|
| 157 | + * Writes a new app wide value |
|
| 158 | + * |
|
| 159 | + * @param string $appName the appName that we want to store the value under |
|
| 160 | + * @param string $key the key of the value, under which will be saved |
|
| 161 | + * @param string|float|int $value the value that should be stored |
|
| 162 | + */ |
|
| 163 | + public function setAppValue($appName, $key, $value) { |
|
| 164 | + \OC::$server->getAppConfig()->setValue($appName, $key, $value); |
|
| 165 | + } |
|
| 166 | + |
|
| 167 | + /** |
|
| 168 | + * Looks up an app wide defined value |
|
| 169 | + * |
|
| 170 | + * @param string $appName the appName that we stored the value under |
|
| 171 | + * @param string $key the key of the value, under which it was saved |
|
| 172 | + * @param string $default the default value to be returned if the value isn't set |
|
| 173 | + * @return string the saved value |
|
| 174 | + */ |
|
| 175 | + public function getAppValue($appName, $key, $default = '') { |
|
| 176 | + return \OC::$server->getAppConfig()->getValue($appName, $key, $default); |
|
| 177 | + } |
|
| 178 | + |
|
| 179 | + /** |
|
| 180 | + * Delete an app wide defined value |
|
| 181 | + * |
|
| 182 | + * @param string $appName the appName that we stored the value under |
|
| 183 | + * @param string $key the key of the value, under which it was saved |
|
| 184 | + */ |
|
| 185 | + public function deleteAppValue($appName, $key) { |
|
| 186 | + \OC::$server->getAppConfig()->deleteKey($appName, $key); |
|
| 187 | + } |
|
| 188 | + |
|
| 189 | + /** |
|
| 190 | + * Removes all keys in appconfig belonging to the app |
|
| 191 | + * |
|
| 192 | + * @param string $appName the appName the configs are stored under |
|
| 193 | + */ |
|
| 194 | + public function deleteAppValues($appName) { |
|
| 195 | + \OC::$server->getAppConfig()->deleteApp($appName); |
|
| 196 | + } |
|
| 197 | + |
|
| 198 | + |
|
| 199 | + /** |
|
| 200 | + * Set a user defined value |
|
| 201 | + * |
|
| 202 | + * @param string $userId the userId of the user that we want to store the value under |
|
| 203 | + * @param string $appName the appName that we want to store the value under |
|
| 204 | + * @param string $key the key under which the value is being stored |
|
| 205 | + * @param string|float|int $value the value that you want to store |
|
| 206 | + * @param string $preCondition only update if the config value was previously the value passed as $preCondition |
|
| 207 | + * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met |
|
| 208 | + * @throws \UnexpectedValueException when trying to store an unexpected value |
|
| 209 | + */ |
|
| 210 | + public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { |
|
| 211 | + if (!is_int($value) && !is_float($value) && !is_string($value)) { |
|
| 212 | + throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); |
|
| 213 | + } |
|
| 214 | + |
|
| 215 | + // TODO - FIXME |
|
| 216 | + $this->fixDIInit(); |
|
| 217 | + |
|
| 218 | + $prevValue = $this->getUserValue($userId, $appName, $key, null); |
|
| 219 | + |
|
| 220 | + if ($prevValue !== null) { |
|
| 221 | + if ($prevValue === (string)$value) { |
|
| 222 | + return; |
|
| 223 | + } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
| 224 | + throw new PreConditionNotMetException(); |
|
| 225 | + } else { |
|
| 226 | + $qb = $this->connection->getQueryBuilder(); |
|
| 227 | + $qb->update('preferences') |
|
| 228 | + ->set('configvalue', $qb->createNamedParameter($value)) |
|
| 229 | + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) |
|
| 230 | + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName))) |
|
| 231 | + ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
|
| 232 | + $qb->execute(); |
|
| 233 | + |
|
| 234 | + $this->userCache[$userId][$appName][$key] = $value; |
|
| 235 | + return; |
|
| 236 | + } |
|
| 237 | + } |
|
| 238 | + |
|
| 239 | + $preconditionArray = []; |
|
| 240 | + if (isset($preCondition)) { |
|
| 241 | + $preconditionArray = [ |
|
| 242 | + 'configvalue' => $preCondition, |
|
| 243 | + ]; |
|
| 244 | + } |
|
| 245 | + |
|
| 246 | + $this->connection->setValues('preferences', [ |
|
| 247 | + 'userid' => $userId, |
|
| 248 | + 'appid' => $appName, |
|
| 249 | + 'configkey' => $key, |
|
| 250 | + ], [ |
|
| 251 | + 'configvalue' => $value, |
|
| 252 | + ], $preconditionArray); |
|
| 253 | + |
|
| 254 | + // only add to the cache if we already loaded data for the user |
|
| 255 | + if (isset($this->userCache[$userId])) { |
|
| 256 | + if (!isset($this->userCache[$userId][$appName])) { |
|
| 257 | + $this->userCache[$userId][$appName] = array(); |
|
| 258 | + } |
|
| 259 | + $this->userCache[$userId][$appName][$key] = $value; |
|
| 260 | + } |
|
| 261 | + } |
|
| 262 | + |
|
| 263 | + /** |
|
| 264 | + * Getting a user defined value |
|
| 265 | + * |
|
| 266 | + * @param string $userId the userId of the user that we want to store the value under |
|
| 267 | + * @param string $appName the appName that we stored the value under |
|
| 268 | + * @param string $key the key under which the value is being stored |
|
| 269 | + * @param mixed $default the default value to be returned if the value isn't set |
|
| 270 | + * @return string |
|
| 271 | + */ |
|
| 272 | + public function getUserValue($userId, $appName, $key, $default = '') { |
|
| 273 | + $data = $this->getUserValues($userId); |
|
| 274 | + if (isset($data[$appName]) and isset($data[$appName][$key])) { |
|
| 275 | + return $data[$appName][$key]; |
|
| 276 | + } else { |
|
| 277 | + return $default; |
|
| 278 | + } |
|
| 279 | + } |
|
| 280 | + |
|
| 281 | + /** |
|
| 282 | + * Get the keys of all stored by an app for the user |
|
| 283 | + * |
|
| 284 | + * @param string $userId the userId of the user that we want to store the value under |
|
| 285 | + * @param string $appName the appName that we stored the value under |
|
| 286 | + * @return string[] |
|
| 287 | + */ |
|
| 288 | + public function getUserKeys($userId, $appName) { |
|
| 289 | + $data = $this->getUserValues($userId); |
|
| 290 | + if (isset($data[$appName])) { |
|
| 291 | + return array_keys($data[$appName]); |
|
| 292 | + } else { |
|
| 293 | + return array(); |
|
| 294 | + } |
|
| 295 | + } |
|
| 296 | + |
|
| 297 | + /** |
|
| 298 | + * Delete a user value |
|
| 299 | + * |
|
| 300 | + * @param string $userId the userId of the user that we want to store the value under |
|
| 301 | + * @param string $appName the appName that we stored the value under |
|
| 302 | + * @param string $key the key under which the value is being stored |
|
| 303 | + */ |
|
| 304 | + public function deleteUserValue($userId, $appName, $key) { |
|
| 305 | + // TODO - FIXME |
|
| 306 | + $this->fixDIInit(); |
|
| 307 | + |
|
| 308 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 309 | + 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
|
| 310 | + $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
|
| 311 | + |
|
| 312 | + if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { |
|
| 313 | + unset($this->userCache[$userId][$appName][$key]); |
|
| 314 | + } |
|
| 315 | + } |
|
| 316 | + |
|
| 317 | + /** |
|
| 318 | + * Delete all user values |
|
| 319 | + * |
|
| 320 | + * @param string $userId the userId of the user that we want to remove all values from |
|
| 321 | + */ |
|
| 322 | + public function deleteAllUserValues($userId) { |
|
| 323 | + // TODO - FIXME |
|
| 324 | + $this->fixDIInit(); |
|
| 325 | + |
|
| 326 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 327 | + 'WHERE `userid` = ?'; |
|
| 328 | + $this->connection->executeUpdate($sql, array($userId)); |
|
| 329 | + |
|
| 330 | + unset($this->userCache[$userId]); |
|
| 331 | + } |
|
| 332 | + |
|
| 333 | + /** |
|
| 334 | + * Delete all user related values of one app |
|
| 335 | + * |
|
| 336 | + * @param string $appName the appName of the app that we want to remove all values from |
|
| 337 | + */ |
|
| 338 | + public function deleteAppFromAllUsers($appName) { |
|
| 339 | + // TODO - FIXME |
|
| 340 | + $this->fixDIInit(); |
|
| 341 | + |
|
| 342 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 343 | + 'WHERE `appid` = ?'; |
|
| 344 | + $this->connection->executeUpdate($sql, array($appName)); |
|
| 345 | + |
|
| 346 | + foreach ($this->userCache as &$userCache) { |
|
| 347 | + unset($userCache[$appName]); |
|
| 348 | + } |
|
| 349 | + } |
|
| 350 | + |
|
| 351 | + /** |
|
| 352 | + * Returns all user configs sorted by app of one user |
|
| 353 | + * |
|
| 354 | + * @param string $userId the user ID to get the app configs from |
|
| 355 | + * @return array[] - 2 dimensional array with the following structure: |
|
| 356 | + * [ $appId => |
|
| 357 | + * [ $key => $value ] |
|
| 358 | + * ] |
|
| 359 | + */ |
|
| 360 | + private function getUserValues($userId) { |
|
| 361 | + if (isset($this->userCache[$userId])) { |
|
| 362 | + return $this->userCache[$userId]; |
|
| 363 | + } |
|
| 364 | + if ($userId === null || $userId === '') { |
|
| 365 | + $this->userCache[$userId]=array(); |
|
| 366 | + return $this->userCache[$userId]; |
|
| 367 | + } |
|
| 368 | + |
|
| 369 | + // TODO - FIXME |
|
| 370 | + $this->fixDIInit(); |
|
| 371 | + |
|
| 372 | + $data = array(); |
|
| 373 | + $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; |
|
| 374 | + $result = $this->connection->executeQuery($query, array($userId)); |
|
| 375 | + while ($row = $result->fetch()) { |
|
| 376 | + $appId = $row['appid']; |
|
| 377 | + if (!isset($data[$appId])) { |
|
| 378 | + $data[$appId] = array(); |
|
| 379 | + } |
|
| 380 | + $data[$appId][$row['configkey']] = $row['configvalue']; |
|
| 381 | + } |
|
| 382 | + $this->userCache[$userId] = $data; |
|
| 383 | + return $data; |
|
| 384 | + } |
|
| 385 | + |
|
| 386 | + /** |
|
| 387 | + * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs. |
|
| 388 | + * |
|
| 389 | + * @param string $appName app to get the value for |
|
| 390 | + * @param string $key the key to get the value for |
|
| 391 | + * @param array $userIds the user IDs to fetch the values for |
|
| 392 | + * @return array Mapped values: userId => value |
|
| 393 | + */ |
|
| 394 | + public function getUserValueForUsers($appName, $key, $userIds) { |
|
| 395 | + // TODO - FIXME |
|
| 396 | + $this->fixDIInit(); |
|
| 397 | + |
|
| 398 | + if (empty($userIds) || !is_array($userIds)) { |
|
| 399 | + return array(); |
|
| 400 | + } |
|
| 401 | + |
|
| 402 | + $chunkedUsers = array_chunk($userIds, 50, true); |
|
| 403 | + $placeholders50 = implode(',', array_fill(0, 50, '?')); |
|
| 404 | + |
|
| 405 | + $userValues = array(); |
|
| 406 | + foreach ($chunkedUsers as $chunk) { |
|
| 407 | + $queryParams = $chunk; |
|
| 408 | + // create [$app, $key, $chunkedUsers] |
|
| 409 | + array_unshift($queryParams, $key); |
|
| 410 | + array_unshift($queryParams, $appName); |
|
| 411 | + |
|
| 412 | + $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
| 413 | + |
|
| 414 | + $query = 'SELECT `userid`, `configvalue` ' . |
|
| 415 | + 'FROM `*PREFIX*preferences` ' . |
|
| 416 | + 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
| 417 | + 'AND `userid` IN (' . $placeholders . ')'; |
|
| 418 | + $result = $this->connection->executeQuery($query, $queryParams); |
|
| 419 | + |
|
| 420 | + while ($row = $result->fetch()) { |
|
| 421 | + $userValues[$row['userid']] = $row['configvalue']; |
|
| 422 | + } |
|
| 423 | + } |
|
| 424 | + |
|
| 425 | + return $userValues; |
|
| 426 | + } |
|
| 427 | + |
|
| 428 | + /** |
|
| 429 | + * Determines the users that have the given value set for a specific app-key-pair |
|
| 430 | + * |
|
| 431 | + * @param string $appName the app to get the user for |
|
| 432 | + * @param string $key the key to get the user for |
|
| 433 | + * @param string $value the value to get the user for |
|
| 434 | + * @return array of user IDs |
|
| 435 | + */ |
|
| 436 | + public function getUsersForUserValue($appName, $key, $value) { |
|
| 437 | + // TODO - FIXME |
|
| 438 | + $this->fixDIInit(); |
|
| 439 | + |
|
| 440 | + $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
| 441 | + 'WHERE `appid` = ? AND `configkey` = ? '; |
|
| 442 | + |
|
| 443 | + if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
| 444 | + //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
|
| 445 | + $sql .= 'AND to_char(`configvalue`) = ?'; |
|
| 446 | + } else { |
|
| 447 | + $sql .= 'AND `configvalue` = ?'; |
|
| 448 | + } |
|
| 449 | + |
|
| 450 | + $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); |
|
| 451 | + |
|
| 452 | + $userIDs = array(); |
|
| 453 | + while ($row = $result->fetch()) { |
|
| 454 | + $userIDs[] = $row['userid']; |
|
| 455 | + } |
|
| 456 | + |
|
| 457 | + return $userIDs; |
|
| 458 | + } |
|
| 459 | + |
|
| 460 | + public function getSystemConfig() { |
|
| 461 | + return $this->systemConfig; |
|
| 462 | + } |
|
| 463 | 463 | } |
@@ -87,7 +87,7 @@ discard block |
||
| 87 | 87 | * because the database connection was created with an uninitialized config |
| 88 | 88 | */ |
| 89 | 89 | private function fixDIInit() { |
| 90 | - if($this->connection === null) { |
|
| 90 | + if ($this->connection === null) { |
|
| 91 | 91 | $this->connection = \OC::$server->getDatabaseConnection(); |
| 92 | 92 | } |
| 93 | 93 | } |
@@ -218,9 +218,9 @@ discard block |
||
| 218 | 218 | $prevValue = $this->getUserValue($userId, $appName, $key, null); |
| 219 | 219 | |
| 220 | 220 | if ($prevValue !== null) { |
| 221 | - if ($prevValue === (string)$value) { |
|
| 221 | + if ($prevValue === (string) $value) { |
|
| 222 | 222 | return; |
| 223 | - } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
| 223 | + } else if ($preCondition !== null && $prevValue !== (string) $preCondition) { |
|
| 224 | 224 | throw new PreConditionNotMetException(); |
| 225 | 225 | } else { |
| 226 | 226 | $qb = $this->connection->getQueryBuilder(); |
@@ -305,7 +305,7 @@ discard block |
||
| 305 | 305 | // TODO - FIXME |
| 306 | 306 | $this->fixDIInit(); |
| 307 | 307 | |
| 308 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 308 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 309 | 309 | 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
| 310 | 310 | $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
| 311 | 311 | |
@@ -323,7 +323,7 @@ discard block |
||
| 323 | 323 | // TODO - FIXME |
| 324 | 324 | $this->fixDIInit(); |
| 325 | 325 | |
| 326 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 326 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 327 | 327 | 'WHERE `userid` = ?'; |
| 328 | 328 | $this->connection->executeUpdate($sql, array($userId)); |
| 329 | 329 | |
@@ -339,7 +339,7 @@ discard block |
||
| 339 | 339 | // TODO - FIXME |
| 340 | 340 | $this->fixDIInit(); |
| 341 | 341 | |
| 342 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 342 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
| 343 | 343 | 'WHERE `appid` = ?'; |
| 344 | 344 | $this->connection->executeUpdate($sql, array($appName)); |
| 345 | 345 | |
@@ -362,7 +362,7 @@ discard block |
||
| 362 | 362 | return $this->userCache[$userId]; |
| 363 | 363 | } |
| 364 | 364 | if ($userId === null || $userId === '') { |
| 365 | - $this->userCache[$userId]=array(); |
|
| 365 | + $this->userCache[$userId] = array(); |
|
| 366 | 366 | return $this->userCache[$userId]; |
| 367 | 367 | } |
| 368 | 368 | |
@@ -409,12 +409,12 @@ discard block |
||
| 409 | 409 | array_unshift($queryParams, $key); |
| 410 | 410 | array_unshift($queryParams, $appName); |
| 411 | 411 | |
| 412 | - $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
| 412 | + $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
| 413 | 413 | |
| 414 | - $query = 'SELECT `userid`, `configvalue` ' . |
|
| 415 | - 'FROM `*PREFIX*preferences` ' . |
|
| 416 | - 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
| 417 | - 'AND `userid` IN (' . $placeholders . ')'; |
|
| 414 | + $query = 'SELECT `userid`, `configvalue` '. |
|
| 415 | + 'FROM `*PREFIX*preferences` '. |
|
| 416 | + 'WHERE `appid` = ? AND `configkey` = ? '. |
|
| 417 | + 'AND `userid` IN ('.$placeholders.')'; |
|
| 418 | 418 | $result = $this->connection->executeQuery($query, $queryParams); |
| 419 | 419 | |
| 420 | 420 | while ($row = $result->fetch()) { |
@@ -437,10 +437,10 @@ discard block |
||
| 437 | 437 | // TODO - FIXME |
| 438 | 438 | $this->fixDIInit(); |
| 439 | 439 | |
| 440 | - $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
| 440 | + $sql = 'SELECT `userid` FROM `*PREFIX*preferences` '. |
|
| 441 | 441 | 'WHERE `appid` = ? AND `configkey` = ? '; |
| 442 | 442 | |
| 443 | - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
| 443 | + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
| 444 | 444 | //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
| 445 | 445 | $sql .= 'AND to_char(`configvalue`) = ?'; |
| 446 | 446 | } else { |
@@ -296,6 +296,9 @@ |
||
| 296 | 296 | } |
| 297 | 297 | } |
| 298 | 298 | |
| 299 | + /** |
|
| 300 | + * @param string $name |
|
| 301 | + */ |
|
| 299 | 302 | private function buildReason($name, $errorCode) { |
| 300 | 303 | if (isset($this->errorMessages[$errorCode])) { |
| 301 | 304 | $desc = $this->list->getDescription($errorCode, $name); |
@@ -29,280 +29,280 @@ |
||
| 29 | 29 | use PhpParser\NodeVisitorAbstract; |
| 30 | 30 | |
| 31 | 31 | class NodeVisitor extends NodeVisitorAbstract { |
| 32 | - /** @var ICheck */ |
|
| 33 | - protected $list; |
|
| 34 | - |
|
| 35 | - /** @var string */ |
|
| 36 | - protected $blackListDescription; |
|
| 37 | - /** @var string[] */ |
|
| 38 | - protected $blackListedClassNames; |
|
| 39 | - /** @var string[] */ |
|
| 40 | - protected $blackListedConstants; |
|
| 41 | - /** @var string[] */ |
|
| 42 | - protected $blackListedFunctions; |
|
| 43 | - /** @var string[] */ |
|
| 44 | - protected $blackListedMethods; |
|
| 45 | - /** @var bool */ |
|
| 46 | - protected $checkEqualOperatorUsage; |
|
| 47 | - /** @var string[] */ |
|
| 48 | - protected $errorMessages; |
|
| 49 | - |
|
| 50 | - /** |
|
| 51 | - * @param ICheck $list |
|
| 52 | - */ |
|
| 53 | - public function __construct(ICheck $list) { |
|
| 54 | - $this->list = $list; |
|
| 55 | - |
|
| 56 | - $this->blackListedClassNames = []; |
|
| 57 | - foreach ($list->getClasses() as $class => $blackListInfo) { |
|
| 58 | - if (is_numeric($class) && is_string($blackListInfo)) { |
|
| 59 | - $class = $blackListInfo; |
|
| 60 | - $blackListInfo = null; |
|
| 61 | - } |
|
| 62 | - |
|
| 63 | - $class = strtolower($class); |
|
| 64 | - $this->blackListedClassNames[$class] = $class; |
|
| 65 | - } |
|
| 66 | - |
|
| 67 | - $this->blackListedConstants = []; |
|
| 68 | - foreach ($list->getConstants() as $constantName => $blackListInfo) { |
|
| 69 | - $constantName = strtolower($constantName); |
|
| 70 | - $this->blackListedConstants[$constantName] = $constantName; |
|
| 71 | - } |
|
| 72 | - |
|
| 73 | - $this->blackListedFunctions = []; |
|
| 74 | - foreach ($list->getFunctions() as $functionName => $blackListInfo) { |
|
| 75 | - $functionName = strtolower($functionName); |
|
| 76 | - $this->blackListedFunctions[$functionName] = $functionName; |
|
| 77 | - } |
|
| 78 | - |
|
| 79 | - $this->blackListedMethods = []; |
|
| 80 | - foreach ($list->getMethods() as $functionName => $blackListInfo) { |
|
| 81 | - $functionName = strtolower($functionName); |
|
| 82 | - $this->blackListedMethods[$functionName] = $functionName; |
|
| 83 | - } |
|
| 84 | - |
|
| 85 | - $this->checkEqualOperatorUsage = $list->checkStrongComparisons(); |
|
| 86 | - |
|
| 87 | - $this->errorMessages = [ |
|
| 88 | - CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended", |
|
| 89 | - CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented", |
|
| 90 | - CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called", |
|
| 91 | - CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched", |
|
| 92 | - CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated", |
|
| 93 | - CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement", |
|
| 94 | - CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called", |
|
| 95 | - |
|
| 96 | - CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged", |
|
| 97 | - ]; |
|
| 98 | - } |
|
| 99 | - |
|
| 100 | - /** @var array */ |
|
| 101 | - public $errors = []; |
|
| 102 | - |
|
| 103 | - public function enterNode(Node $node) { |
|
| 104 | - if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) { |
|
| 105 | - $this->errors[]= [ |
|
| 106 | - 'disallowedToken' => '==', |
|
| 107 | - 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
| 108 | - 'line' => $node->getLine(), |
|
| 109 | - 'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
| 110 | - ]; |
|
| 111 | - } |
|
| 112 | - if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) { |
|
| 113 | - $this->errors[]= [ |
|
| 114 | - 'disallowedToken' => '!=', |
|
| 115 | - 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
| 116 | - 'line' => $node->getLine(), |
|
| 117 | - 'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
| 118 | - ]; |
|
| 119 | - } |
|
| 120 | - if ($node instanceof Node\Stmt\Class_) { |
|
| 121 | - if (!is_null($node->extends)) { |
|
| 122 | - $this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node); |
|
| 123 | - } |
|
| 124 | - foreach ($node->implements as $implements) { |
|
| 125 | - $this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node); |
|
| 126 | - } |
|
| 127 | - } |
|
| 128 | - if ($node instanceof Node\Expr\StaticCall) { |
|
| 129 | - if (!is_null($node->class)) { |
|
| 130 | - if ($node->class instanceof Name) { |
|
| 131 | - $this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node); |
|
| 132 | - |
|
| 133 | - $this->checkBlackListFunction($node->class->toString(), $node->name, $node); |
|
| 134 | - $this->checkBlackListMethod($node->class->toString(), $node->name, $node); |
|
| 135 | - } |
|
| 136 | - |
|
| 137 | - if ($node->class instanceof Node\Expr\Variable) { |
|
| 138 | - /** |
|
| 139 | - * TODO: find a way to detect something like this: |
|
| 140 | - * $c = "OC_API"; |
|
| 141 | - * $n = $c::call(); |
|
| 142 | - */ |
|
| 143 | - // $this->checkBlackListMethod($node->class->..., $node->name, $node); |
|
| 144 | - } |
|
| 145 | - } |
|
| 146 | - } |
|
| 147 | - if ($node instanceof Node\Expr\MethodCall) { |
|
| 148 | - if (!is_null($node->var)) { |
|
| 149 | - if ($node->var instanceof Node\Expr\Variable) { |
|
| 150 | - /** |
|
| 151 | - * TODO: find a way to detect something like this: |
|
| 152 | - * $c = new OC_API(); |
|
| 153 | - * $n = $c::call(); |
|
| 154 | - * $n = $c->call(); |
|
| 155 | - */ |
|
| 156 | - // $this->checkBlackListMethod($node->var->..., $node->name, $node); |
|
| 157 | - } |
|
| 158 | - } |
|
| 159 | - } |
|
| 160 | - if ($node instanceof Node\Expr\ClassConstFetch) { |
|
| 161 | - if (!is_null($node->class)) { |
|
| 162 | - if ($node->class instanceof Name) { |
|
| 163 | - $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node); |
|
| 164 | - } |
|
| 165 | - if ($node->class instanceof Node\Expr\Variable) { |
|
| 166 | - /** |
|
| 167 | - * TODO: find a way to detect something like this: |
|
| 168 | - * $c = "OC_API"; |
|
| 169 | - * $n = $i::ADMIN_AUTH; |
|
| 170 | - */ |
|
| 171 | - } else { |
|
| 172 | - $this->checkBlackListConstant($node->class->toString(), $node->name, $node); |
|
| 173 | - } |
|
| 174 | - } |
|
| 175 | - } |
|
| 176 | - if ($node instanceof Node\Expr\New_) { |
|
| 177 | - if (!is_null($node->class)) { |
|
| 178 | - if ($node->class instanceof Name) { |
|
| 179 | - $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node); |
|
| 180 | - } |
|
| 181 | - if ($node->class instanceof Node\Expr\Variable) { |
|
| 182 | - /** |
|
| 183 | - * TODO: find a way to detect something like this: |
|
| 184 | - * $c = "OC_API"; |
|
| 185 | - * $n = new $i; |
|
| 186 | - */ |
|
| 187 | - } |
|
| 188 | - } |
|
| 189 | - } |
|
| 190 | - if ($node instanceof Node\Stmt\UseUse) { |
|
| 191 | - $this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node); |
|
| 192 | - if ($node->alias) { |
|
| 193 | - $this->addUseNameToBlackList($node->name->toString(), $node->alias); |
|
| 194 | - } else { |
|
| 195 | - $this->addUseNameToBlackList($node->name->toString(), $node->name->getLast()); |
|
| 196 | - } |
|
| 197 | - } |
|
| 198 | - } |
|
| 199 | - |
|
| 200 | - /** |
|
| 201 | - * Check whether an alias was introduced for a namespace of a blacklisted class |
|
| 202 | - * |
|
| 203 | - * Example: |
|
| 204 | - * - Blacklist entry: OCP\AppFramework\IApi |
|
| 205 | - * - Name: OCP\AppFramework |
|
| 206 | - * - Alias: OAF |
|
| 207 | - * => new blacklist entry: OAF\IApi |
|
| 208 | - * |
|
| 209 | - * @param string $name |
|
| 210 | - * @param string $alias |
|
| 211 | - */ |
|
| 212 | - private function addUseNameToBlackList($name, $alias) { |
|
| 213 | - $name = strtolower($name); |
|
| 214 | - $alias = strtolower($alias); |
|
| 215 | - |
|
| 216 | - foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) { |
|
| 217 | - if (strpos($blackListedClassName, $name . '\\') === 0) { |
|
| 218 | - $aliasedClassName = str_replace($name, $alias, $blackListedClassName); |
|
| 219 | - $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName; |
|
| 220 | - } |
|
| 221 | - } |
|
| 222 | - |
|
| 223 | - foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) { |
|
| 224 | - if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) { |
|
| 225 | - $aliasedConstantName = str_replace($name, $alias, $blackListedConstant); |
|
| 226 | - $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant; |
|
| 227 | - } |
|
| 228 | - } |
|
| 229 | - |
|
| 230 | - foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) { |
|
| 231 | - if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) { |
|
| 232 | - $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction); |
|
| 233 | - $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction; |
|
| 234 | - } |
|
| 235 | - } |
|
| 236 | - |
|
| 237 | - foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) { |
|
| 238 | - if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) { |
|
| 239 | - $aliasedMethodName = str_replace($name, $alias, $blackListedMethod); |
|
| 240 | - $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod; |
|
| 241 | - } |
|
| 242 | - } |
|
| 243 | - } |
|
| 244 | - |
|
| 245 | - private function checkBlackList($name, $errorCode, Node $node) { |
|
| 246 | - $lowerName = strtolower($name); |
|
| 247 | - |
|
| 248 | - if (isset($this->blackListedClassNames[$lowerName])) { |
|
| 249 | - $this->errors[]= [ |
|
| 250 | - 'disallowedToken' => $name, |
|
| 251 | - 'errorCode' => $errorCode, |
|
| 252 | - 'line' => $node->getLine(), |
|
| 253 | - 'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode) |
|
| 254 | - ]; |
|
| 255 | - } |
|
| 256 | - } |
|
| 257 | - |
|
| 258 | - private function checkBlackListConstant($class, $constantName, Node $node) { |
|
| 259 | - $name = $class . '::' . $constantName; |
|
| 260 | - $lowerName = strtolower($name); |
|
| 261 | - |
|
| 262 | - if (isset($this->blackListedConstants[$lowerName])) { |
|
| 263 | - $this->errors[]= [ |
|
| 264 | - 'disallowedToken' => $name, |
|
| 265 | - 'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, |
|
| 266 | - 'line' => $node->getLine(), |
|
| 267 | - 'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED) |
|
| 268 | - ]; |
|
| 269 | - } |
|
| 270 | - } |
|
| 271 | - |
|
| 272 | - private function checkBlackListFunction($class, $functionName, Node $node) { |
|
| 273 | - $name = $class . '::' . $functionName; |
|
| 274 | - $lowerName = strtolower($name); |
|
| 275 | - |
|
| 276 | - if (isset($this->blackListedFunctions[$lowerName])) { |
|
| 277 | - $this->errors[]= [ |
|
| 278 | - 'disallowedToken' => $name, |
|
| 279 | - 'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED, |
|
| 280 | - 'line' => $node->getLine(), |
|
| 281 | - 'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED) |
|
| 282 | - ]; |
|
| 283 | - } |
|
| 284 | - } |
|
| 285 | - |
|
| 286 | - private function checkBlackListMethod($class, $functionName, Node $node) { |
|
| 287 | - $name = $class . '::' . $functionName; |
|
| 288 | - $lowerName = strtolower($name); |
|
| 289 | - |
|
| 290 | - if (isset($this->blackListedMethods[$lowerName])) { |
|
| 291 | - $this->errors[]= [ |
|
| 292 | - 'disallowedToken' => $name, |
|
| 293 | - 'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED, |
|
| 294 | - 'line' => $node->getLine(), |
|
| 295 | - 'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED) |
|
| 296 | - ]; |
|
| 297 | - } |
|
| 298 | - } |
|
| 299 | - |
|
| 300 | - private function buildReason($name, $errorCode) { |
|
| 301 | - if (isset($this->errorMessages[$errorCode])) { |
|
| 302 | - $desc = $this->list->getDescription($errorCode, $name); |
|
| 303 | - return sprintf($this->errorMessages[$errorCode], $desc); |
|
| 304 | - } |
|
| 305 | - |
|
| 306 | - return "$name usage not allowed - error: $errorCode"; |
|
| 307 | - } |
|
| 32 | + /** @var ICheck */ |
|
| 33 | + protected $list; |
|
| 34 | + |
|
| 35 | + /** @var string */ |
|
| 36 | + protected $blackListDescription; |
|
| 37 | + /** @var string[] */ |
|
| 38 | + protected $blackListedClassNames; |
|
| 39 | + /** @var string[] */ |
|
| 40 | + protected $blackListedConstants; |
|
| 41 | + /** @var string[] */ |
|
| 42 | + protected $blackListedFunctions; |
|
| 43 | + /** @var string[] */ |
|
| 44 | + protected $blackListedMethods; |
|
| 45 | + /** @var bool */ |
|
| 46 | + protected $checkEqualOperatorUsage; |
|
| 47 | + /** @var string[] */ |
|
| 48 | + protected $errorMessages; |
|
| 49 | + |
|
| 50 | + /** |
|
| 51 | + * @param ICheck $list |
|
| 52 | + */ |
|
| 53 | + public function __construct(ICheck $list) { |
|
| 54 | + $this->list = $list; |
|
| 55 | + |
|
| 56 | + $this->blackListedClassNames = []; |
|
| 57 | + foreach ($list->getClasses() as $class => $blackListInfo) { |
|
| 58 | + if (is_numeric($class) && is_string($blackListInfo)) { |
|
| 59 | + $class = $blackListInfo; |
|
| 60 | + $blackListInfo = null; |
|
| 61 | + } |
|
| 62 | + |
|
| 63 | + $class = strtolower($class); |
|
| 64 | + $this->blackListedClassNames[$class] = $class; |
|
| 65 | + } |
|
| 66 | + |
|
| 67 | + $this->blackListedConstants = []; |
|
| 68 | + foreach ($list->getConstants() as $constantName => $blackListInfo) { |
|
| 69 | + $constantName = strtolower($constantName); |
|
| 70 | + $this->blackListedConstants[$constantName] = $constantName; |
|
| 71 | + } |
|
| 72 | + |
|
| 73 | + $this->blackListedFunctions = []; |
|
| 74 | + foreach ($list->getFunctions() as $functionName => $blackListInfo) { |
|
| 75 | + $functionName = strtolower($functionName); |
|
| 76 | + $this->blackListedFunctions[$functionName] = $functionName; |
|
| 77 | + } |
|
| 78 | + |
|
| 79 | + $this->blackListedMethods = []; |
|
| 80 | + foreach ($list->getMethods() as $functionName => $blackListInfo) { |
|
| 81 | + $functionName = strtolower($functionName); |
|
| 82 | + $this->blackListedMethods[$functionName] = $functionName; |
|
| 83 | + } |
|
| 84 | + |
|
| 85 | + $this->checkEqualOperatorUsage = $list->checkStrongComparisons(); |
|
| 86 | + |
|
| 87 | + $this->errorMessages = [ |
|
| 88 | + CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended", |
|
| 89 | + CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented", |
|
| 90 | + CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called", |
|
| 91 | + CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched", |
|
| 92 | + CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated", |
|
| 93 | + CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement", |
|
| 94 | + CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called", |
|
| 95 | + |
|
| 96 | + CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged", |
|
| 97 | + ]; |
|
| 98 | + } |
|
| 99 | + |
|
| 100 | + /** @var array */ |
|
| 101 | + public $errors = []; |
|
| 102 | + |
|
| 103 | + public function enterNode(Node $node) { |
|
| 104 | + if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) { |
|
| 105 | + $this->errors[]= [ |
|
| 106 | + 'disallowedToken' => '==', |
|
| 107 | + 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
| 108 | + 'line' => $node->getLine(), |
|
| 109 | + 'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
| 110 | + ]; |
|
| 111 | + } |
|
| 112 | + if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) { |
|
| 113 | + $this->errors[]= [ |
|
| 114 | + 'disallowedToken' => '!=', |
|
| 115 | + 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
| 116 | + 'line' => $node->getLine(), |
|
| 117 | + 'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
| 118 | + ]; |
|
| 119 | + } |
|
| 120 | + if ($node instanceof Node\Stmt\Class_) { |
|
| 121 | + if (!is_null($node->extends)) { |
|
| 122 | + $this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node); |
|
| 123 | + } |
|
| 124 | + foreach ($node->implements as $implements) { |
|
| 125 | + $this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node); |
|
| 126 | + } |
|
| 127 | + } |
|
| 128 | + if ($node instanceof Node\Expr\StaticCall) { |
|
| 129 | + if (!is_null($node->class)) { |
|
| 130 | + if ($node->class instanceof Name) { |
|
| 131 | + $this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node); |
|
| 132 | + |
|
| 133 | + $this->checkBlackListFunction($node->class->toString(), $node->name, $node); |
|
| 134 | + $this->checkBlackListMethod($node->class->toString(), $node->name, $node); |
|
| 135 | + } |
|
| 136 | + |
|
| 137 | + if ($node->class instanceof Node\Expr\Variable) { |
|
| 138 | + /** |
|
| 139 | + * TODO: find a way to detect something like this: |
|
| 140 | + * $c = "OC_API"; |
|
| 141 | + * $n = $c::call(); |
|
| 142 | + */ |
|
| 143 | + // $this->checkBlackListMethod($node->class->..., $node->name, $node); |
|
| 144 | + } |
|
| 145 | + } |
|
| 146 | + } |
|
| 147 | + if ($node instanceof Node\Expr\MethodCall) { |
|
| 148 | + if (!is_null($node->var)) { |
|
| 149 | + if ($node->var instanceof Node\Expr\Variable) { |
|
| 150 | + /** |
|
| 151 | + * TODO: find a way to detect something like this: |
|
| 152 | + * $c = new OC_API(); |
|
| 153 | + * $n = $c::call(); |
|
| 154 | + * $n = $c->call(); |
|
| 155 | + */ |
|
| 156 | + // $this->checkBlackListMethod($node->var->..., $node->name, $node); |
|
| 157 | + } |
|
| 158 | + } |
|
| 159 | + } |
|
| 160 | + if ($node instanceof Node\Expr\ClassConstFetch) { |
|
| 161 | + if (!is_null($node->class)) { |
|
| 162 | + if ($node->class instanceof Name) { |
|
| 163 | + $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node); |
|
| 164 | + } |
|
| 165 | + if ($node->class instanceof Node\Expr\Variable) { |
|
| 166 | + /** |
|
| 167 | + * TODO: find a way to detect something like this: |
|
| 168 | + * $c = "OC_API"; |
|
| 169 | + * $n = $i::ADMIN_AUTH; |
|
| 170 | + */ |
|
| 171 | + } else { |
|
| 172 | + $this->checkBlackListConstant($node->class->toString(), $node->name, $node); |
|
| 173 | + } |
|
| 174 | + } |
|
| 175 | + } |
|
| 176 | + if ($node instanceof Node\Expr\New_) { |
|
| 177 | + if (!is_null($node->class)) { |
|
| 178 | + if ($node->class instanceof Name) { |
|
| 179 | + $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node); |
|
| 180 | + } |
|
| 181 | + if ($node->class instanceof Node\Expr\Variable) { |
|
| 182 | + /** |
|
| 183 | + * TODO: find a way to detect something like this: |
|
| 184 | + * $c = "OC_API"; |
|
| 185 | + * $n = new $i; |
|
| 186 | + */ |
|
| 187 | + } |
|
| 188 | + } |
|
| 189 | + } |
|
| 190 | + if ($node instanceof Node\Stmt\UseUse) { |
|
| 191 | + $this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node); |
|
| 192 | + if ($node->alias) { |
|
| 193 | + $this->addUseNameToBlackList($node->name->toString(), $node->alias); |
|
| 194 | + } else { |
|
| 195 | + $this->addUseNameToBlackList($node->name->toString(), $node->name->getLast()); |
|
| 196 | + } |
|
| 197 | + } |
|
| 198 | + } |
|
| 199 | + |
|
| 200 | + /** |
|
| 201 | + * Check whether an alias was introduced for a namespace of a blacklisted class |
|
| 202 | + * |
|
| 203 | + * Example: |
|
| 204 | + * - Blacklist entry: OCP\AppFramework\IApi |
|
| 205 | + * - Name: OCP\AppFramework |
|
| 206 | + * - Alias: OAF |
|
| 207 | + * => new blacklist entry: OAF\IApi |
|
| 208 | + * |
|
| 209 | + * @param string $name |
|
| 210 | + * @param string $alias |
|
| 211 | + */ |
|
| 212 | + private function addUseNameToBlackList($name, $alias) { |
|
| 213 | + $name = strtolower($name); |
|
| 214 | + $alias = strtolower($alias); |
|
| 215 | + |
|
| 216 | + foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) { |
|
| 217 | + if (strpos($blackListedClassName, $name . '\\') === 0) { |
|
| 218 | + $aliasedClassName = str_replace($name, $alias, $blackListedClassName); |
|
| 219 | + $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName; |
|
| 220 | + } |
|
| 221 | + } |
|
| 222 | + |
|
| 223 | + foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) { |
|
| 224 | + if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) { |
|
| 225 | + $aliasedConstantName = str_replace($name, $alias, $blackListedConstant); |
|
| 226 | + $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant; |
|
| 227 | + } |
|
| 228 | + } |
|
| 229 | + |
|
| 230 | + foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) { |
|
| 231 | + if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) { |
|
| 232 | + $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction); |
|
| 233 | + $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction; |
|
| 234 | + } |
|
| 235 | + } |
|
| 236 | + |
|
| 237 | + foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) { |
|
| 238 | + if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) { |
|
| 239 | + $aliasedMethodName = str_replace($name, $alias, $blackListedMethod); |
|
| 240 | + $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod; |
|
| 241 | + } |
|
| 242 | + } |
|
| 243 | + } |
|
| 244 | + |
|
| 245 | + private function checkBlackList($name, $errorCode, Node $node) { |
|
| 246 | + $lowerName = strtolower($name); |
|
| 247 | + |
|
| 248 | + if (isset($this->blackListedClassNames[$lowerName])) { |
|
| 249 | + $this->errors[]= [ |
|
| 250 | + 'disallowedToken' => $name, |
|
| 251 | + 'errorCode' => $errorCode, |
|
| 252 | + 'line' => $node->getLine(), |
|
| 253 | + 'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode) |
|
| 254 | + ]; |
|
| 255 | + } |
|
| 256 | + } |
|
| 257 | + |
|
| 258 | + private function checkBlackListConstant($class, $constantName, Node $node) { |
|
| 259 | + $name = $class . '::' . $constantName; |
|
| 260 | + $lowerName = strtolower($name); |
|
| 261 | + |
|
| 262 | + if (isset($this->blackListedConstants[$lowerName])) { |
|
| 263 | + $this->errors[]= [ |
|
| 264 | + 'disallowedToken' => $name, |
|
| 265 | + 'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, |
|
| 266 | + 'line' => $node->getLine(), |
|
| 267 | + 'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED) |
|
| 268 | + ]; |
|
| 269 | + } |
|
| 270 | + } |
|
| 271 | + |
|
| 272 | + private function checkBlackListFunction($class, $functionName, Node $node) { |
|
| 273 | + $name = $class . '::' . $functionName; |
|
| 274 | + $lowerName = strtolower($name); |
|
| 275 | + |
|
| 276 | + if (isset($this->blackListedFunctions[$lowerName])) { |
|
| 277 | + $this->errors[]= [ |
|
| 278 | + 'disallowedToken' => $name, |
|
| 279 | + 'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED, |
|
| 280 | + 'line' => $node->getLine(), |
|
| 281 | + 'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED) |
|
| 282 | + ]; |
|
| 283 | + } |
|
| 284 | + } |
|
| 285 | + |
|
| 286 | + private function checkBlackListMethod($class, $functionName, Node $node) { |
|
| 287 | + $name = $class . '::' . $functionName; |
|
| 288 | + $lowerName = strtolower($name); |
|
| 289 | + |
|
| 290 | + if (isset($this->blackListedMethods[$lowerName])) { |
|
| 291 | + $this->errors[]= [ |
|
| 292 | + 'disallowedToken' => $name, |
|
| 293 | + 'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED, |
|
| 294 | + 'line' => $node->getLine(), |
|
| 295 | + 'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED) |
|
| 296 | + ]; |
|
| 297 | + } |
|
| 298 | + } |
|
| 299 | + |
|
| 300 | + private function buildReason($name, $errorCode) { |
|
| 301 | + if (isset($this->errorMessages[$errorCode])) { |
|
| 302 | + $desc = $this->list->getDescription($errorCode, $name); |
|
| 303 | + return sprintf($this->errorMessages[$errorCode], $desc); |
|
| 304 | + } |
|
| 305 | + |
|
| 306 | + return "$name usage not allowed - error: $errorCode"; |
|
| 307 | + } |
|
| 308 | 308 | } |
@@ -102,7 +102,7 @@ discard block |
||
| 102 | 102 | |
| 103 | 103 | public function enterNode(Node $node) { |
| 104 | 104 | if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) { |
| 105 | - $this->errors[]= [ |
|
| 105 | + $this->errors[] = [ |
|
| 106 | 106 | 'disallowedToken' => '==', |
| 107 | 107 | 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
| 108 | 108 | 'line' => $node->getLine(), |
@@ -110,7 +110,7 @@ discard block |
||
| 110 | 110 | ]; |
| 111 | 111 | } |
| 112 | 112 | if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) { |
| 113 | - $this->errors[]= [ |
|
| 113 | + $this->errors[] = [ |
|
| 114 | 114 | 'disallowedToken' => '!=', |
| 115 | 115 | 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
| 116 | 116 | 'line' => $node->getLine(), |
@@ -214,28 +214,28 @@ discard block |
||
| 214 | 214 | $alias = strtolower($alias); |
| 215 | 215 | |
| 216 | 216 | foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) { |
| 217 | - if (strpos($blackListedClassName, $name . '\\') === 0) { |
|
| 217 | + if (strpos($blackListedClassName, $name.'\\') === 0) { |
|
| 218 | 218 | $aliasedClassName = str_replace($name, $alias, $blackListedClassName); |
| 219 | 219 | $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName; |
| 220 | 220 | } |
| 221 | 221 | } |
| 222 | 222 | |
| 223 | 223 | foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) { |
| 224 | - if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) { |
|
| 224 | + if (strpos($blackListedConstant, $name.'\\') === 0 || strpos($blackListedConstant, $name.'::') === 0) { |
|
| 225 | 225 | $aliasedConstantName = str_replace($name, $alias, $blackListedConstant); |
| 226 | 226 | $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant; |
| 227 | 227 | } |
| 228 | 228 | } |
| 229 | 229 | |
| 230 | 230 | foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) { |
| 231 | - if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) { |
|
| 231 | + if (strpos($blackListedFunction, $name.'\\') === 0 || strpos($blackListedFunction, $name.'::') === 0) { |
|
| 232 | 232 | $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction); |
| 233 | 233 | $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction; |
| 234 | 234 | } |
| 235 | 235 | } |
| 236 | 236 | |
| 237 | 237 | foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) { |
| 238 | - if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) { |
|
| 238 | + if (strpos($blackListedMethod, $name.'\\') === 0 || strpos($blackListedMethod, $name.'::') === 0) { |
|
| 239 | 239 | $aliasedMethodName = str_replace($name, $alias, $blackListedMethod); |
| 240 | 240 | $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod; |
| 241 | 241 | } |
@@ -246,7 +246,7 @@ discard block |
||
| 246 | 246 | $lowerName = strtolower($name); |
| 247 | 247 | |
| 248 | 248 | if (isset($this->blackListedClassNames[$lowerName])) { |
| 249 | - $this->errors[]= [ |
|
| 249 | + $this->errors[] = [ |
|
| 250 | 250 | 'disallowedToken' => $name, |
| 251 | 251 | 'errorCode' => $errorCode, |
| 252 | 252 | 'line' => $node->getLine(), |
@@ -256,11 +256,11 @@ discard block |
||
| 256 | 256 | } |
| 257 | 257 | |
| 258 | 258 | private function checkBlackListConstant($class, $constantName, Node $node) { |
| 259 | - $name = $class . '::' . $constantName; |
|
| 259 | + $name = $class.'::'.$constantName; |
|
| 260 | 260 | $lowerName = strtolower($name); |
| 261 | 261 | |
| 262 | 262 | if (isset($this->blackListedConstants[$lowerName])) { |
| 263 | - $this->errors[]= [ |
|
| 263 | + $this->errors[] = [ |
|
| 264 | 264 | 'disallowedToken' => $name, |
| 265 | 265 | 'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, |
| 266 | 266 | 'line' => $node->getLine(), |
@@ -270,11 +270,11 @@ discard block |
||
| 270 | 270 | } |
| 271 | 271 | |
| 272 | 272 | private function checkBlackListFunction($class, $functionName, Node $node) { |
| 273 | - $name = $class . '::' . $functionName; |
|
| 273 | + $name = $class.'::'.$functionName; |
|
| 274 | 274 | $lowerName = strtolower($name); |
| 275 | 275 | |
| 276 | 276 | if (isset($this->blackListedFunctions[$lowerName])) { |
| 277 | - $this->errors[]= [ |
|
| 277 | + $this->errors[] = [ |
|
| 278 | 278 | 'disallowedToken' => $name, |
| 279 | 279 | 'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED, |
| 280 | 280 | 'line' => $node->getLine(), |
@@ -284,11 +284,11 @@ discard block |
||
| 284 | 284 | } |
| 285 | 285 | |
| 286 | 286 | private function checkBlackListMethod($class, $functionName, Node $node) { |
| 287 | - $name = $class . '::' . $functionName; |
|
| 287 | + $name = $class.'::'.$functionName; |
|
| 288 | 288 | $lowerName = strtolower($name); |
| 289 | 289 | |
| 290 | 290 | if (isset($this->blackListedMethods[$lowerName])) { |
| 291 | - $this->errors[]= [ |
|
| 291 | + $this->errors[] = [ |
|
| 292 | 292 | 'disallowedToken' => $name, |
| 293 | 293 | 'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED, |
| 294 | 294 | 'line' => $node->getLine(), |
@@ -205,7 +205,7 @@ |
||
| 205 | 205 | /** |
| 206 | 206 | * removes an entry from the comments run time cache |
| 207 | 207 | * |
| 208 | - * @param mixed $id the comment's id |
|
| 208 | + * @param string $id the comment's id |
|
| 209 | 209 | */ |
| 210 | 210 | protected function uncache($id) { |
| 211 | 211 | $id = strval($id); |
@@ -38,850 +38,850 @@ |
||
| 38 | 38 | |
| 39 | 39 | class Manager implements ICommentsManager { |
| 40 | 40 | |
| 41 | - /** @var IDBConnection */ |
|
| 42 | - protected $dbConn; |
|
| 43 | - |
|
| 44 | - /** @var ILogger */ |
|
| 45 | - protected $logger; |
|
| 46 | - |
|
| 47 | - /** @var IConfig */ |
|
| 48 | - protected $config; |
|
| 49 | - |
|
| 50 | - /** @var IComment[] */ |
|
| 51 | - protected $commentsCache = []; |
|
| 52 | - |
|
| 53 | - /** @var \Closure[] */ |
|
| 54 | - protected $eventHandlerClosures = []; |
|
| 55 | - |
|
| 56 | - /** @var ICommentsEventHandler[] */ |
|
| 57 | - protected $eventHandlers = []; |
|
| 58 | - |
|
| 59 | - /** @var \Closure[] */ |
|
| 60 | - protected $displayNameResolvers = []; |
|
| 61 | - |
|
| 62 | - /** |
|
| 63 | - * Manager constructor. |
|
| 64 | - * |
|
| 65 | - * @param IDBConnection $dbConn |
|
| 66 | - * @param ILogger $logger |
|
| 67 | - * @param IConfig $config |
|
| 68 | - */ |
|
| 69 | - public function __construct( |
|
| 70 | - IDBConnection $dbConn, |
|
| 71 | - ILogger $logger, |
|
| 72 | - IConfig $config |
|
| 73 | - ) { |
|
| 74 | - $this->dbConn = $dbConn; |
|
| 75 | - $this->logger = $logger; |
|
| 76 | - $this->config = $config; |
|
| 77 | - } |
|
| 78 | - |
|
| 79 | - /** |
|
| 80 | - * converts data base data into PHP native, proper types as defined by |
|
| 81 | - * IComment interface. |
|
| 82 | - * |
|
| 83 | - * @param array $data |
|
| 84 | - * @return array |
|
| 85 | - */ |
|
| 86 | - protected function normalizeDatabaseData(array $data) { |
|
| 87 | - $data['id'] = strval($data['id']); |
|
| 88 | - $data['parent_id'] = strval($data['parent_id']); |
|
| 89 | - $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
| 90 | - $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
| 91 | - if (!is_null($data['latest_child_timestamp'])) { |
|
| 92 | - $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
| 93 | - } |
|
| 94 | - $data['children_count'] = intval($data['children_count']); |
|
| 95 | - return $data; |
|
| 96 | - } |
|
| 97 | - |
|
| 98 | - /** |
|
| 99 | - * prepares a comment for an insert or update operation after making sure |
|
| 100 | - * all necessary fields have a value assigned. |
|
| 101 | - * |
|
| 102 | - * @param IComment $comment |
|
| 103 | - * @return IComment returns the same updated IComment instance as provided |
|
| 104 | - * by parameter for convenience |
|
| 105 | - * @throws \UnexpectedValueException |
|
| 106 | - */ |
|
| 107 | - protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
| 108 | - if (!$comment->getActorType() |
|
| 109 | - || !$comment->getActorId() |
|
| 110 | - || !$comment->getObjectType() |
|
| 111 | - || !$comment->getObjectId() |
|
| 112 | - || !$comment->getVerb() |
|
| 113 | - ) { |
|
| 114 | - throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
| 115 | - } |
|
| 116 | - |
|
| 117 | - if ($comment->getId() === '') { |
|
| 118 | - $comment->setChildrenCount(0); |
|
| 119 | - $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
| 120 | - $comment->setLatestChildDateTime(null); |
|
| 121 | - } |
|
| 122 | - |
|
| 123 | - if (is_null($comment->getCreationDateTime())) { |
|
| 124 | - $comment->setCreationDateTime(new \DateTime()); |
|
| 125 | - } |
|
| 126 | - |
|
| 127 | - if ($comment->getParentId() !== '0') { |
|
| 128 | - $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
| 129 | - } else { |
|
| 130 | - $comment->setTopmostParentId('0'); |
|
| 131 | - } |
|
| 132 | - |
|
| 133 | - $this->cache($comment); |
|
| 134 | - |
|
| 135 | - return $comment; |
|
| 136 | - } |
|
| 137 | - |
|
| 138 | - /** |
|
| 139 | - * returns the topmost parent id of a given comment identified by ID |
|
| 140 | - * |
|
| 141 | - * @param string $id |
|
| 142 | - * @return string |
|
| 143 | - * @throws NotFoundException |
|
| 144 | - */ |
|
| 145 | - protected function determineTopmostParentId($id) { |
|
| 146 | - $comment = $this->get($id); |
|
| 147 | - if ($comment->getParentId() === '0') { |
|
| 148 | - return $comment->getId(); |
|
| 149 | - } else { |
|
| 150 | - return $this->determineTopmostParentId($comment->getId()); |
|
| 151 | - } |
|
| 152 | - } |
|
| 153 | - |
|
| 154 | - /** |
|
| 155 | - * updates child information of a comment |
|
| 156 | - * |
|
| 157 | - * @param string $id |
|
| 158 | - * @param \DateTime $cDateTime the date time of the most recent child |
|
| 159 | - * @throws NotFoundException |
|
| 160 | - */ |
|
| 161 | - protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
| 162 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 163 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
| 164 | - ->from('comments') |
|
| 165 | - ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
| 166 | - ->setParameter('id', $id); |
|
| 167 | - |
|
| 168 | - $resultStatement = $query->execute(); |
|
| 169 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
| 170 | - $resultStatement->closeCursor(); |
|
| 171 | - $children = intval($data[0]); |
|
| 172 | - |
|
| 173 | - $comment = $this->get($id); |
|
| 174 | - $comment->setChildrenCount($children); |
|
| 175 | - $comment->setLatestChildDateTime($cDateTime); |
|
| 176 | - $this->save($comment); |
|
| 177 | - } |
|
| 178 | - |
|
| 179 | - /** |
|
| 180 | - * Tests whether actor or object type and id parameters are acceptable. |
|
| 181 | - * Throws exception if not. |
|
| 182 | - * |
|
| 183 | - * @param string $role |
|
| 184 | - * @param string $type |
|
| 185 | - * @param string $id |
|
| 186 | - * @throws \InvalidArgumentException |
|
| 187 | - */ |
|
| 188 | - protected function checkRoleParameters($role, $type, $id) { |
|
| 189 | - if ( |
|
| 190 | - !is_string($type) || empty($type) |
|
| 191 | - || !is_string($id) || empty($id) |
|
| 192 | - ) { |
|
| 193 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
| 194 | - } |
|
| 195 | - } |
|
| 196 | - |
|
| 197 | - /** |
|
| 198 | - * run-time caches a comment |
|
| 199 | - * |
|
| 200 | - * @param IComment $comment |
|
| 201 | - */ |
|
| 202 | - protected function cache(IComment $comment) { |
|
| 203 | - $id = $comment->getId(); |
|
| 204 | - if (empty($id)) { |
|
| 205 | - return; |
|
| 206 | - } |
|
| 207 | - $this->commentsCache[strval($id)] = $comment; |
|
| 208 | - } |
|
| 209 | - |
|
| 210 | - /** |
|
| 211 | - * removes an entry from the comments run time cache |
|
| 212 | - * |
|
| 213 | - * @param mixed $id the comment's id |
|
| 214 | - */ |
|
| 215 | - protected function uncache($id) { |
|
| 216 | - $id = strval($id); |
|
| 217 | - if (isset($this->commentsCache[$id])) { |
|
| 218 | - unset($this->commentsCache[$id]); |
|
| 219 | - } |
|
| 220 | - } |
|
| 221 | - |
|
| 222 | - /** |
|
| 223 | - * returns a comment instance |
|
| 224 | - * |
|
| 225 | - * @param string $id the ID of the comment |
|
| 226 | - * @return IComment |
|
| 227 | - * @throws NotFoundException |
|
| 228 | - * @throws \InvalidArgumentException |
|
| 229 | - * @since 9.0.0 |
|
| 230 | - */ |
|
| 231 | - public function get($id) { |
|
| 232 | - if (intval($id) === 0) { |
|
| 233 | - throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
| 234 | - } |
|
| 235 | - |
|
| 236 | - if (isset($this->commentsCache[$id])) { |
|
| 237 | - return $this->commentsCache[$id]; |
|
| 238 | - } |
|
| 239 | - |
|
| 240 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 241 | - $resultStatement = $qb->select('*') |
|
| 242 | - ->from('comments') |
|
| 243 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
| 244 | - ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
| 245 | - ->execute(); |
|
| 246 | - |
|
| 247 | - $data = $resultStatement->fetch(); |
|
| 248 | - $resultStatement->closeCursor(); |
|
| 249 | - if (!$data) { |
|
| 250 | - throw new NotFoundException(); |
|
| 251 | - } |
|
| 252 | - |
|
| 253 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
| 254 | - $this->cache($comment); |
|
| 255 | - return $comment; |
|
| 256 | - } |
|
| 257 | - |
|
| 258 | - /** |
|
| 259 | - * returns the comment specified by the id and all it's child comments. |
|
| 260 | - * At this point of time, we do only support one level depth. |
|
| 261 | - * |
|
| 262 | - * @param string $id |
|
| 263 | - * @param int $limit max number of entries to return, 0 returns all |
|
| 264 | - * @param int $offset the start entry |
|
| 265 | - * @return array |
|
| 266 | - * @since 9.0.0 |
|
| 267 | - * |
|
| 268 | - * The return array looks like this |
|
| 269 | - * [ |
|
| 270 | - * 'comment' => IComment, // root comment |
|
| 271 | - * 'replies' => |
|
| 272 | - * [ |
|
| 273 | - * 0 => |
|
| 274 | - * [ |
|
| 275 | - * 'comment' => IComment, |
|
| 276 | - * 'replies' => [] |
|
| 277 | - * ] |
|
| 278 | - * 1 => |
|
| 279 | - * [ |
|
| 280 | - * 'comment' => IComment, |
|
| 281 | - * 'replies'=> [] |
|
| 282 | - * ], |
|
| 283 | - * … |
|
| 284 | - * ] |
|
| 285 | - * ] |
|
| 286 | - */ |
|
| 287 | - public function getTree($id, $limit = 0, $offset = 0) { |
|
| 288 | - $tree = []; |
|
| 289 | - $tree['comment'] = $this->get($id); |
|
| 290 | - $tree['replies'] = []; |
|
| 291 | - |
|
| 292 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 293 | - $query = $qb->select('*') |
|
| 294 | - ->from('comments') |
|
| 295 | - ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
| 296 | - ->orderBy('creation_timestamp', 'DESC') |
|
| 297 | - ->setParameter('id', $id); |
|
| 298 | - |
|
| 299 | - if ($limit > 0) { |
|
| 300 | - $query->setMaxResults($limit); |
|
| 301 | - } |
|
| 302 | - if ($offset > 0) { |
|
| 303 | - $query->setFirstResult($offset); |
|
| 304 | - } |
|
| 305 | - |
|
| 306 | - $resultStatement = $query->execute(); |
|
| 307 | - while ($data = $resultStatement->fetch()) { |
|
| 308 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
| 309 | - $this->cache($comment); |
|
| 310 | - $tree['replies'][] = [ |
|
| 311 | - 'comment' => $comment, |
|
| 312 | - 'replies' => [] |
|
| 313 | - ]; |
|
| 314 | - } |
|
| 315 | - $resultStatement->closeCursor(); |
|
| 316 | - |
|
| 317 | - return $tree; |
|
| 318 | - } |
|
| 319 | - |
|
| 320 | - /** |
|
| 321 | - * returns comments for a specific object (e.g. a file). |
|
| 322 | - * |
|
| 323 | - * The sort order is always newest to oldest. |
|
| 324 | - * |
|
| 325 | - * @param string $objectType the object type, e.g. 'files' |
|
| 326 | - * @param string $objectId the id of the object |
|
| 327 | - * @param int $limit optional, number of maximum comments to be returned. if |
|
| 328 | - * not specified, all comments are returned. |
|
| 329 | - * @param int $offset optional, starting point |
|
| 330 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
| 331 | - * that may be returned |
|
| 332 | - * @return IComment[] |
|
| 333 | - * @since 9.0.0 |
|
| 334 | - */ |
|
| 335 | - public function getForObject( |
|
| 336 | - $objectType, |
|
| 337 | - $objectId, |
|
| 338 | - $limit = 0, |
|
| 339 | - $offset = 0, |
|
| 340 | - \DateTime $notOlderThan = null |
|
| 341 | - ) { |
|
| 342 | - $comments = []; |
|
| 343 | - |
|
| 344 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 345 | - $query = $qb->select('*') |
|
| 346 | - ->from('comments') |
|
| 347 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
| 348 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
| 349 | - ->orderBy('creation_timestamp', 'DESC') |
|
| 350 | - ->setParameter('type', $objectType) |
|
| 351 | - ->setParameter('id', $objectId); |
|
| 352 | - |
|
| 353 | - if ($limit > 0) { |
|
| 354 | - $query->setMaxResults($limit); |
|
| 355 | - } |
|
| 356 | - if ($offset > 0) { |
|
| 357 | - $query->setFirstResult($offset); |
|
| 358 | - } |
|
| 359 | - if (!is_null($notOlderThan)) { |
|
| 360 | - $query |
|
| 361 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
| 362 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
| 363 | - } |
|
| 364 | - |
|
| 365 | - $resultStatement = $query->execute(); |
|
| 366 | - while ($data = $resultStatement->fetch()) { |
|
| 367 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
| 368 | - $this->cache($comment); |
|
| 369 | - $comments[] = $comment; |
|
| 370 | - } |
|
| 371 | - $resultStatement->closeCursor(); |
|
| 372 | - |
|
| 373 | - return $comments; |
|
| 374 | - } |
|
| 375 | - |
|
| 376 | - /** |
|
| 377 | - * @param $objectType string the object type, e.g. 'files' |
|
| 378 | - * @param $objectId string the id of the object |
|
| 379 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
| 380 | - * that may be returned |
|
| 381 | - * @return Int |
|
| 382 | - * @since 9.0.0 |
|
| 383 | - */ |
|
| 384 | - public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
| 385 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 386 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
| 387 | - ->from('comments') |
|
| 388 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
| 389 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
| 390 | - ->setParameter('type', $objectType) |
|
| 391 | - ->setParameter('id', $objectId); |
|
| 392 | - |
|
| 393 | - if (!is_null($notOlderThan)) { |
|
| 394 | - $query |
|
| 395 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
| 396 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
| 397 | - } |
|
| 398 | - |
|
| 399 | - $resultStatement = $query->execute(); |
|
| 400 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
| 401 | - $resultStatement->closeCursor(); |
|
| 402 | - return intval($data[0]); |
|
| 403 | - } |
|
| 404 | - |
|
| 405 | - /** |
|
| 406 | - * Get the number of unread comments for all files in a folder |
|
| 407 | - * |
|
| 408 | - * @param int $folderId |
|
| 409 | - * @param IUser $user |
|
| 410 | - * @return array [$fileId => $unreadCount] |
|
| 411 | - */ |
|
| 412 | - public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
|
| 413 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 414 | - $query = $qb->select('f.fileid') |
|
| 415 | - ->selectAlias( |
|
| 416 | - $qb->createFunction('COUNT(' . $qb->getColumnName('c.id') . ')'), |
|
| 417 | - 'num_ids' |
|
| 418 | - ) |
|
| 419 | - ->from('comments', 'c') |
|
| 420 | - ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
|
| 421 | - $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
|
| 422 | - $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)) |
|
| 423 | - )) |
|
| 424 | - ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX( |
|
| 425 | - $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')), |
|
| 426 | - $qb->expr()->eq('m.object_id', 'c.object_id'), |
|
| 427 | - $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())) |
|
| 428 | - )) |
|
| 429 | - ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId))) |
|
| 430 | - ->andWhere($qb->expr()->orX( |
|
| 431 | - $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'), |
|
| 432 | - $qb->expr()->isNull('marker_datetime') |
|
| 433 | - )) |
|
| 434 | - ->groupBy('f.fileid'); |
|
| 435 | - |
|
| 436 | - $resultStatement = $query->execute(); |
|
| 437 | - |
|
| 438 | - $results = []; |
|
| 439 | - while ($row = $resultStatement->fetch()) { |
|
| 440 | - $results[$row['fileid']] = (int) $row['num_ids']; |
|
| 441 | - } |
|
| 442 | - $resultStatement->closeCursor(); |
|
| 443 | - return $results; |
|
| 444 | - } |
|
| 445 | - |
|
| 446 | - /** |
|
| 447 | - * creates a new comment and returns it. At this point of time, it is not |
|
| 448 | - * saved in the used data storage. Use save() after setting other fields |
|
| 449 | - * of the comment (e.g. message or verb). |
|
| 450 | - * |
|
| 451 | - * @param string $actorType the actor type (e.g. 'users') |
|
| 452 | - * @param string $actorId a user id |
|
| 453 | - * @param string $objectType the object type the comment is attached to |
|
| 454 | - * @param string $objectId the object id the comment is attached to |
|
| 455 | - * @return IComment |
|
| 456 | - * @since 9.0.0 |
|
| 457 | - */ |
|
| 458 | - public function create($actorType, $actorId, $objectType, $objectId) { |
|
| 459 | - $comment = new Comment(); |
|
| 460 | - $comment |
|
| 461 | - ->setActor($actorType, $actorId) |
|
| 462 | - ->setObject($objectType, $objectId); |
|
| 463 | - return $comment; |
|
| 464 | - } |
|
| 465 | - |
|
| 466 | - /** |
|
| 467 | - * permanently deletes the comment specified by the ID |
|
| 468 | - * |
|
| 469 | - * When the comment has child comments, their parent ID will be changed to |
|
| 470 | - * the parent ID of the item that is to be deleted. |
|
| 471 | - * |
|
| 472 | - * @param string $id |
|
| 473 | - * @return bool |
|
| 474 | - * @throws \InvalidArgumentException |
|
| 475 | - * @since 9.0.0 |
|
| 476 | - */ |
|
| 477 | - public function delete($id) { |
|
| 478 | - if (!is_string($id)) { |
|
| 479 | - throw new \InvalidArgumentException('Parameter must be string'); |
|
| 480 | - } |
|
| 481 | - |
|
| 482 | - try { |
|
| 483 | - $comment = $this->get($id); |
|
| 484 | - } catch (\Exception $e) { |
|
| 485 | - // Ignore exceptions, we just don't fire a hook then |
|
| 486 | - $comment = null; |
|
| 487 | - } |
|
| 488 | - |
|
| 489 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 490 | - $query = $qb->delete('comments') |
|
| 491 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
| 492 | - ->setParameter('id', $id); |
|
| 493 | - |
|
| 494 | - try { |
|
| 495 | - $affectedRows = $query->execute(); |
|
| 496 | - $this->uncache($id); |
|
| 497 | - } catch (DriverException $e) { |
|
| 498 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
| 499 | - return false; |
|
| 500 | - } |
|
| 501 | - |
|
| 502 | - if ($affectedRows > 0 && $comment instanceof IComment) { |
|
| 503 | - $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
| 504 | - } |
|
| 505 | - |
|
| 506 | - return ($affectedRows > 0); |
|
| 507 | - } |
|
| 508 | - |
|
| 509 | - /** |
|
| 510 | - * saves the comment permanently |
|
| 511 | - * |
|
| 512 | - * if the supplied comment has an empty ID, a new entry comment will be |
|
| 513 | - * saved and the instance updated with the new ID. |
|
| 514 | - * |
|
| 515 | - * Otherwise, an existing comment will be updated. |
|
| 516 | - * |
|
| 517 | - * Throws NotFoundException when a comment that is to be updated does not |
|
| 518 | - * exist anymore at this point of time. |
|
| 519 | - * |
|
| 520 | - * @param IComment $comment |
|
| 521 | - * @return bool |
|
| 522 | - * @throws NotFoundException |
|
| 523 | - * @since 9.0.0 |
|
| 524 | - */ |
|
| 525 | - public function save(IComment $comment) { |
|
| 526 | - if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
| 527 | - $result = $this->insert($comment); |
|
| 528 | - } else { |
|
| 529 | - $result = $this->update($comment); |
|
| 530 | - } |
|
| 531 | - |
|
| 532 | - if ($result && !!$comment->getParentId()) { |
|
| 533 | - $this->updateChildrenInformation( |
|
| 534 | - $comment->getParentId(), |
|
| 535 | - $comment->getCreationDateTime() |
|
| 536 | - ); |
|
| 537 | - $this->cache($comment); |
|
| 538 | - } |
|
| 539 | - |
|
| 540 | - return $result; |
|
| 541 | - } |
|
| 542 | - |
|
| 543 | - /** |
|
| 544 | - * inserts the provided comment in the database |
|
| 545 | - * |
|
| 546 | - * @param IComment $comment |
|
| 547 | - * @return bool |
|
| 548 | - */ |
|
| 549 | - protected function insert(IComment &$comment) { |
|
| 550 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 551 | - $affectedRows = $qb |
|
| 552 | - ->insert('comments') |
|
| 553 | - ->values([ |
|
| 554 | - 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
| 555 | - 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
| 556 | - 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
| 557 | - 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
| 558 | - 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
| 559 | - 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
| 560 | - 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
| 561 | - 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
| 562 | - 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
| 563 | - 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
| 564 | - 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
| 565 | - ]) |
|
| 566 | - ->execute(); |
|
| 567 | - |
|
| 568 | - if ($affectedRows > 0) { |
|
| 569 | - $comment->setId(strval($qb->getLastInsertId())); |
|
| 570 | - $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
| 571 | - } |
|
| 572 | - |
|
| 573 | - return $affectedRows > 0; |
|
| 574 | - } |
|
| 575 | - |
|
| 576 | - /** |
|
| 577 | - * updates a Comment data row |
|
| 578 | - * |
|
| 579 | - * @param IComment $comment |
|
| 580 | - * @return bool |
|
| 581 | - * @throws NotFoundException |
|
| 582 | - */ |
|
| 583 | - protected function update(IComment $comment) { |
|
| 584 | - // for properly working preUpdate Events we need the old comments as is |
|
| 585 | - // in the DB and overcome caching. Also avoid that outdated information stays. |
|
| 586 | - $this->uncache($comment->getId()); |
|
| 587 | - $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
| 588 | - $this->uncache($comment->getId()); |
|
| 589 | - |
|
| 590 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 591 | - $affectedRows = $qb |
|
| 592 | - ->update('comments') |
|
| 593 | - ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
| 594 | - ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
| 595 | - ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
| 596 | - ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
| 597 | - ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
| 598 | - ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
| 599 | - ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
| 600 | - ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
| 601 | - ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
| 602 | - ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
| 603 | - ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
| 604 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
| 605 | - ->setParameter('id', $comment->getId()) |
|
| 606 | - ->execute(); |
|
| 607 | - |
|
| 608 | - if ($affectedRows === 0) { |
|
| 609 | - throw new NotFoundException('Comment to update does ceased to exist'); |
|
| 610 | - } |
|
| 611 | - |
|
| 612 | - $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
| 613 | - |
|
| 614 | - return $affectedRows > 0; |
|
| 615 | - } |
|
| 616 | - |
|
| 617 | - /** |
|
| 618 | - * removes references to specific actor (e.g. on user delete) of a comment. |
|
| 619 | - * The comment itself must not get lost/deleted. |
|
| 620 | - * |
|
| 621 | - * @param string $actorType the actor type (e.g. 'users') |
|
| 622 | - * @param string $actorId a user id |
|
| 623 | - * @return boolean |
|
| 624 | - * @since 9.0.0 |
|
| 625 | - */ |
|
| 626 | - public function deleteReferencesOfActor($actorType, $actorId) { |
|
| 627 | - $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
| 628 | - |
|
| 629 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 630 | - $affectedRows = $qb |
|
| 631 | - ->update('comments') |
|
| 632 | - ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
| 633 | - ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
| 634 | - ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
| 635 | - ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
| 636 | - ->setParameter('type', $actorType) |
|
| 637 | - ->setParameter('id', $actorId) |
|
| 638 | - ->execute(); |
|
| 639 | - |
|
| 640 | - $this->commentsCache = []; |
|
| 641 | - |
|
| 642 | - return is_int($affectedRows); |
|
| 643 | - } |
|
| 644 | - |
|
| 645 | - /** |
|
| 646 | - * deletes all comments made of a specific object (e.g. on file delete) |
|
| 647 | - * |
|
| 648 | - * @param string $objectType the object type (e.g. 'files') |
|
| 649 | - * @param string $objectId e.g. the file id |
|
| 650 | - * @return boolean |
|
| 651 | - * @since 9.0.0 |
|
| 652 | - */ |
|
| 653 | - public function deleteCommentsAtObject($objectType, $objectId) { |
|
| 654 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
| 655 | - |
|
| 656 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 657 | - $affectedRows = $qb |
|
| 658 | - ->delete('comments') |
|
| 659 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
| 660 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
| 661 | - ->setParameter('type', $objectType) |
|
| 662 | - ->setParameter('id', $objectId) |
|
| 663 | - ->execute(); |
|
| 664 | - |
|
| 665 | - $this->commentsCache = []; |
|
| 666 | - |
|
| 667 | - return is_int($affectedRows); |
|
| 668 | - } |
|
| 669 | - |
|
| 670 | - /** |
|
| 671 | - * deletes the read markers for the specified user |
|
| 672 | - * |
|
| 673 | - * @param \OCP\IUser $user |
|
| 674 | - * @return bool |
|
| 675 | - * @since 9.0.0 |
|
| 676 | - */ |
|
| 677 | - public function deleteReadMarksFromUser(IUser $user) { |
|
| 678 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 679 | - $query = $qb->delete('comments_read_markers') |
|
| 680 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
| 681 | - ->setParameter('user_id', $user->getUID()); |
|
| 682 | - |
|
| 683 | - try { |
|
| 684 | - $affectedRows = $query->execute(); |
|
| 685 | - } catch (DriverException $e) { |
|
| 686 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
| 687 | - return false; |
|
| 688 | - } |
|
| 689 | - return ($affectedRows > 0); |
|
| 690 | - } |
|
| 691 | - |
|
| 692 | - /** |
|
| 693 | - * sets the read marker for a given file to the specified date for the |
|
| 694 | - * provided user |
|
| 695 | - * |
|
| 696 | - * @param string $objectType |
|
| 697 | - * @param string $objectId |
|
| 698 | - * @param \DateTime $dateTime |
|
| 699 | - * @param IUser $user |
|
| 700 | - * @since 9.0.0 |
|
| 701 | - * @suppress SqlInjectionChecker |
|
| 702 | - */ |
|
| 703 | - public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
| 704 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
| 705 | - |
|
| 706 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 707 | - $values = [ |
|
| 708 | - 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
| 709 | - 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
| 710 | - 'object_type' => $qb->createNamedParameter($objectType), |
|
| 711 | - 'object_id' => $qb->createNamedParameter($objectId), |
|
| 712 | - ]; |
|
| 713 | - |
|
| 714 | - // Strategy: try to update, if this does not return affected rows, do an insert. |
|
| 715 | - $affectedRows = $qb |
|
| 716 | - ->update('comments_read_markers') |
|
| 717 | - ->set('user_id', $values['user_id']) |
|
| 718 | - ->set('marker_datetime', $values['marker_datetime']) |
|
| 719 | - ->set('object_type', $values['object_type']) |
|
| 720 | - ->set('object_id', $values['object_id']) |
|
| 721 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
| 722 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
| 723 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
| 724 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
| 725 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
| 726 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
| 727 | - ->execute(); |
|
| 728 | - |
|
| 729 | - if ($affectedRows > 0) { |
|
| 730 | - return; |
|
| 731 | - } |
|
| 732 | - |
|
| 733 | - $qb->insert('comments_read_markers') |
|
| 734 | - ->values($values) |
|
| 735 | - ->execute(); |
|
| 736 | - } |
|
| 737 | - |
|
| 738 | - /** |
|
| 739 | - * returns the read marker for a given file to the specified date for the |
|
| 740 | - * provided user. It returns null, when the marker is not present, i.e. |
|
| 741 | - * no comments were marked as read. |
|
| 742 | - * |
|
| 743 | - * @param string $objectType |
|
| 744 | - * @param string $objectId |
|
| 745 | - * @param IUser $user |
|
| 746 | - * @return \DateTime|null |
|
| 747 | - * @since 9.0.0 |
|
| 748 | - */ |
|
| 749 | - public function getReadMark($objectType, $objectId, IUser $user) { |
|
| 750 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 751 | - $resultStatement = $qb->select('marker_datetime') |
|
| 752 | - ->from('comments_read_markers') |
|
| 753 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
| 754 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
| 755 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
| 756 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
| 757 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
| 758 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
| 759 | - ->execute(); |
|
| 760 | - |
|
| 761 | - $data = $resultStatement->fetch(); |
|
| 762 | - $resultStatement->closeCursor(); |
|
| 763 | - if (!$data || is_null($data['marker_datetime'])) { |
|
| 764 | - return null; |
|
| 765 | - } |
|
| 766 | - |
|
| 767 | - return new \DateTime($data['marker_datetime']); |
|
| 768 | - } |
|
| 769 | - |
|
| 770 | - /** |
|
| 771 | - * deletes the read markers on the specified object |
|
| 772 | - * |
|
| 773 | - * @param string $objectType |
|
| 774 | - * @param string $objectId |
|
| 775 | - * @return bool |
|
| 776 | - * @since 9.0.0 |
|
| 777 | - */ |
|
| 778 | - public function deleteReadMarksOnObject($objectType, $objectId) { |
|
| 779 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
| 780 | - |
|
| 781 | - $qb = $this->dbConn->getQueryBuilder(); |
|
| 782 | - $query = $qb->delete('comments_read_markers') |
|
| 783 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
| 784 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
| 785 | - ->setParameter('object_type', $objectType) |
|
| 786 | - ->setParameter('object_id', $objectId); |
|
| 787 | - |
|
| 788 | - try { |
|
| 789 | - $affectedRows = $query->execute(); |
|
| 790 | - } catch (DriverException $e) { |
|
| 791 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
| 792 | - return false; |
|
| 793 | - } |
|
| 794 | - return ($affectedRows > 0); |
|
| 795 | - } |
|
| 796 | - |
|
| 797 | - /** |
|
| 798 | - * registers an Entity to the manager, so event notifications can be send |
|
| 799 | - * to consumers of the comments infrastructure |
|
| 800 | - * |
|
| 801 | - * @param \Closure $closure |
|
| 802 | - */ |
|
| 803 | - public function registerEventHandler(\Closure $closure) { |
|
| 804 | - $this->eventHandlerClosures[] = $closure; |
|
| 805 | - $this->eventHandlers = []; |
|
| 806 | - } |
|
| 807 | - |
|
| 808 | - /** |
|
| 809 | - * registers a method that resolves an ID to a display name for a given type |
|
| 810 | - * |
|
| 811 | - * @param string $type |
|
| 812 | - * @param \Closure $closure |
|
| 813 | - * @throws \OutOfBoundsException |
|
| 814 | - * @since 11.0.0 |
|
| 815 | - * |
|
| 816 | - * Only one resolver shall be registered per type. Otherwise a |
|
| 817 | - * \OutOfBoundsException has to thrown. |
|
| 818 | - */ |
|
| 819 | - public function registerDisplayNameResolver($type, \Closure $closure) { |
|
| 820 | - if (!is_string($type)) { |
|
| 821 | - throw new \InvalidArgumentException('String expected.'); |
|
| 822 | - } |
|
| 823 | - if (isset($this->displayNameResolvers[$type])) { |
|
| 824 | - throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
| 825 | - } |
|
| 826 | - $this->displayNameResolvers[$type] = $closure; |
|
| 827 | - } |
|
| 828 | - |
|
| 829 | - /** |
|
| 830 | - * resolves a given ID of a given Type to a display name. |
|
| 831 | - * |
|
| 832 | - * @param string $type |
|
| 833 | - * @param string $id |
|
| 834 | - * @return string |
|
| 835 | - * @throws \OutOfBoundsException |
|
| 836 | - * @since 11.0.0 |
|
| 837 | - * |
|
| 838 | - * If a provided type was not registered, an \OutOfBoundsException shall |
|
| 839 | - * be thrown. It is upon the resolver discretion what to return of the |
|
| 840 | - * provided ID is unknown. It must be ensured that a string is returned. |
|
| 841 | - */ |
|
| 842 | - public function resolveDisplayName($type, $id) { |
|
| 843 | - if (!is_string($type)) { |
|
| 844 | - throw new \InvalidArgumentException('String expected.'); |
|
| 845 | - } |
|
| 846 | - if (!isset($this->displayNameResolvers[$type])) { |
|
| 847 | - throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
| 848 | - } |
|
| 849 | - return (string)$this->displayNameResolvers[$type]($id); |
|
| 850 | - } |
|
| 851 | - |
|
| 852 | - /** |
|
| 853 | - * returns valid, registered entities |
|
| 854 | - * |
|
| 855 | - * @return \OCP\Comments\ICommentsEventHandler[] |
|
| 856 | - */ |
|
| 857 | - private function getEventHandlers() { |
|
| 858 | - if (!empty($this->eventHandlers)) { |
|
| 859 | - return $this->eventHandlers; |
|
| 860 | - } |
|
| 861 | - |
|
| 862 | - $this->eventHandlers = []; |
|
| 863 | - foreach ($this->eventHandlerClosures as $name => $closure) { |
|
| 864 | - $entity = $closure(); |
|
| 865 | - if (!($entity instanceof ICommentsEventHandler)) { |
|
| 866 | - throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
| 867 | - } |
|
| 868 | - $this->eventHandlers[$name] = $entity; |
|
| 869 | - } |
|
| 870 | - |
|
| 871 | - return $this->eventHandlers; |
|
| 872 | - } |
|
| 873 | - |
|
| 874 | - /** |
|
| 875 | - * sends notifications to the registered entities |
|
| 876 | - * |
|
| 877 | - * @param $eventType |
|
| 878 | - * @param IComment $comment |
|
| 879 | - */ |
|
| 880 | - private function sendEvent($eventType, IComment $comment) { |
|
| 881 | - $entities = $this->getEventHandlers(); |
|
| 882 | - $event = new CommentsEvent($eventType, $comment); |
|
| 883 | - foreach ($entities as $entity) { |
|
| 884 | - $entity->handle($event); |
|
| 885 | - } |
|
| 886 | - } |
|
| 41 | + /** @var IDBConnection */ |
|
| 42 | + protected $dbConn; |
|
| 43 | + |
|
| 44 | + /** @var ILogger */ |
|
| 45 | + protected $logger; |
|
| 46 | + |
|
| 47 | + /** @var IConfig */ |
|
| 48 | + protected $config; |
|
| 49 | + |
|
| 50 | + /** @var IComment[] */ |
|
| 51 | + protected $commentsCache = []; |
|
| 52 | + |
|
| 53 | + /** @var \Closure[] */ |
|
| 54 | + protected $eventHandlerClosures = []; |
|
| 55 | + |
|
| 56 | + /** @var ICommentsEventHandler[] */ |
|
| 57 | + protected $eventHandlers = []; |
|
| 58 | + |
|
| 59 | + /** @var \Closure[] */ |
|
| 60 | + protected $displayNameResolvers = []; |
|
| 61 | + |
|
| 62 | + /** |
|
| 63 | + * Manager constructor. |
|
| 64 | + * |
|
| 65 | + * @param IDBConnection $dbConn |
|
| 66 | + * @param ILogger $logger |
|
| 67 | + * @param IConfig $config |
|
| 68 | + */ |
|
| 69 | + public function __construct( |
|
| 70 | + IDBConnection $dbConn, |
|
| 71 | + ILogger $logger, |
|
| 72 | + IConfig $config |
|
| 73 | + ) { |
|
| 74 | + $this->dbConn = $dbConn; |
|
| 75 | + $this->logger = $logger; |
|
| 76 | + $this->config = $config; |
|
| 77 | + } |
|
| 78 | + |
|
| 79 | + /** |
|
| 80 | + * converts data base data into PHP native, proper types as defined by |
|
| 81 | + * IComment interface. |
|
| 82 | + * |
|
| 83 | + * @param array $data |
|
| 84 | + * @return array |
|
| 85 | + */ |
|
| 86 | + protected function normalizeDatabaseData(array $data) { |
|
| 87 | + $data['id'] = strval($data['id']); |
|
| 88 | + $data['parent_id'] = strval($data['parent_id']); |
|
| 89 | + $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
| 90 | + $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
| 91 | + if (!is_null($data['latest_child_timestamp'])) { |
|
| 92 | + $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
| 93 | + } |
|
| 94 | + $data['children_count'] = intval($data['children_count']); |
|
| 95 | + return $data; |
|
| 96 | + } |
|
| 97 | + |
|
| 98 | + /** |
|
| 99 | + * prepares a comment for an insert or update operation after making sure |
|
| 100 | + * all necessary fields have a value assigned. |
|
| 101 | + * |
|
| 102 | + * @param IComment $comment |
|
| 103 | + * @return IComment returns the same updated IComment instance as provided |
|
| 104 | + * by parameter for convenience |
|
| 105 | + * @throws \UnexpectedValueException |
|
| 106 | + */ |
|
| 107 | + protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
| 108 | + if (!$comment->getActorType() |
|
| 109 | + || !$comment->getActorId() |
|
| 110 | + || !$comment->getObjectType() |
|
| 111 | + || !$comment->getObjectId() |
|
| 112 | + || !$comment->getVerb() |
|
| 113 | + ) { |
|
| 114 | + throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
| 115 | + } |
|
| 116 | + |
|
| 117 | + if ($comment->getId() === '') { |
|
| 118 | + $comment->setChildrenCount(0); |
|
| 119 | + $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
| 120 | + $comment->setLatestChildDateTime(null); |
|
| 121 | + } |
|
| 122 | + |
|
| 123 | + if (is_null($comment->getCreationDateTime())) { |
|
| 124 | + $comment->setCreationDateTime(new \DateTime()); |
|
| 125 | + } |
|
| 126 | + |
|
| 127 | + if ($comment->getParentId() !== '0') { |
|
| 128 | + $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
| 129 | + } else { |
|
| 130 | + $comment->setTopmostParentId('0'); |
|
| 131 | + } |
|
| 132 | + |
|
| 133 | + $this->cache($comment); |
|
| 134 | + |
|
| 135 | + return $comment; |
|
| 136 | + } |
|
| 137 | + |
|
| 138 | + /** |
|
| 139 | + * returns the topmost parent id of a given comment identified by ID |
|
| 140 | + * |
|
| 141 | + * @param string $id |
|
| 142 | + * @return string |
|
| 143 | + * @throws NotFoundException |
|
| 144 | + */ |
|
| 145 | + protected function determineTopmostParentId($id) { |
|
| 146 | + $comment = $this->get($id); |
|
| 147 | + if ($comment->getParentId() === '0') { |
|
| 148 | + return $comment->getId(); |
|
| 149 | + } else { |
|
| 150 | + return $this->determineTopmostParentId($comment->getId()); |
|
| 151 | + } |
|
| 152 | + } |
|
| 153 | + |
|
| 154 | + /** |
|
| 155 | + * updates child information of a comment |
|
| 156 | + * |
|
| 157 | + * @param string $id |
|
| 158 | + * @param \DateTime $cDateTime the date time of the most recent child |
|
| 159 | + * @throws NotFoundException |
|
| 160 | + */ |
|
| 161 | + protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
| 162 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 163 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
| 164 | + ->from('comments') |
|
| 165 | + ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
| 166 | + ->setParameter('id', $id); |
|
| 167 | + |
|
| 168 | + $resultStatement = $query->execute(); |
|
| 169 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
| 170 | + $resultStatement->closeCursor(); |
|
| 171 | + $children = intval($data[0]); |
|
| 172 | + |
|
| 173 | + $comment = $this->get($id); |
|
| 174 | + $comment->setChildrenCount($children); |
|
| 175 | + $comment->setLatestChildDateTime($cDateTime); |
|
| 176 | + $this->save($comment); |
|
| 177 | + } |
|
| 178 | + |
|
| 179 | + /** |
|
| 180 | + * Tests whether actor or object type and id parameters are acceptable. |
|
| 181 | + * Throws exception if not. |
|
| 182 | + * |
|
| 183 | + * @param string $role |
|
| 184 | + * @param string $type |
|
| 185 | + * @param string $id |
|
| 186 | + * @throws \InvalidArgumentException |
|
| 187 | + */ |
|
| 188 | + protected function checkRoleParameters($role, $type, $id) { |
|
| 189 | + if ( |
|
| 190 | + !is_string($type) || empty($type) |
|
| 191 | + || !is_string($id) || empty($id) |
|
| 192 | + ) { |
|
| 193 | + throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
| 194 | + } |
|
| 195 | + } |
|
| 196 | + |
|
| 197 | + /** |
|
| 198 | + * run-time caches a comment |
|
| 199 | + * |
|
| 200 | + * @param IComment $comment |
|
| 201 | + */ |
|
| 202 | + protected function cache(IComment $comment) { |
|
| 203 | + $id = $comment->getId(); |
|
| 204 | + if (empty($id)) { |
|
| 205 | + return; |
|
| 206 | + } |
|
| 207 | + $this->commentsCache[strval($id)] = $comment; |
|
| 208 | + } |
|
| 209 | + |
|
| 210 | + /** |
|
| 211 | + * removes an entry from the comments run time cache |
|
| 212 | + * |
|
| 213 | + * @param mixed $id the comment's id |
|
| 214 | + */ |
|
| 215 | + protected function uncache($id) { |
|
| 216 | + $id = strval($id); |
|
| 217 | + if (isset($this->commentsCache[$id])) { |
|
| 218 | + unset($this->commentsCache[$id]); |
|
| 219 | + } |
|
| 220 | + } |
|
| 221 | + |
|
| 222 | + /** |
|
| 223 | + * returns a comment instance |
|
| 224 | + * |
|
| 225 | + * @param string $id the ID of the comment |
|
| 226 | + * @return IComment |
|
| 227 | + * @throws NotFoundException |
|
| 228 | + * @throws \InvalidArgumentException |
|
| 229 | + * @since 9.0.0 |
|
| 230 | + */ |
|
| 231 | + public function get($id) { |
|
| 232 | + if (intval($id) === 0) { |
|
| 233 | + throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
| 234 | + } |
|
| 235 | + |
|
| 236 | + if (isset($this->commentsCache[$id])) { |
|
| 237 | + return $this->commentsCache[$id]; |
|
| 238 | + } |
|
| 239 | + |
|
| 240 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 241 | + $resultStatement = $qb->select('*') |
|
| 242 | + ->from('comments') |
|
| 243 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
| 244 | + ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
| 245 | + ->execute(); |
|
| 246 | + |
|
| 247 | + $data = $resultStatement->fetch(); |
|
| 248 | + $resultStatement->closeCursor(); |
|
| 249 | + if (!$data) { |
|
| 250 | + throw new NotFoundException(); |
|
| 251 | + } |
|
| 252 | + |
|
| 253 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
| 254 | + $this->cache($comment); |
|
| 255 | + return $comment; |
|
| 256 | + } |
|
| 257 | + |
|
| 258 | + /** |
|
| 259 | + * returns the comment specified by the id and all it's child comments. |
|
| 260 | + * At this point of time, we do only support one level depth. |
|
| 261 | + * |
|
| 262 | + * @param string $id |
|
| 263 | + * @param int $limit max number of entries to return, 0 returns all |
|
| 264 | + * @param int $offset the start entry |
|
| 265 | + * @return array |
|
| 266 | + * @since 9.0.0 |
|
| 267 | + * |
|
| 268 | + * The return array looks like this |
|
| 269 | + * [ |
|
| 270 | + * 'comment' => IComment, // root comment |
|
| 271 | + * 'replies' => |
|
| 272 | + * [ |
|
| 273 | + * 0 => |
|
| 274 | + * [ |
|
| 275 | + * 'comment' => IComment, |
|
| 276 | + * 'replies' => [] |
|
| 277 | + * ] |
|
| 278 | + * 1 => |
|
| 279 | + * [ |
|
| 280 | + * 'comment' => IComment, |
|
| 281 | + * 'replies'=> [] |
|
| 282 | + * ], |
|
| 283 | + * … |
|
| 284 | + * ] |
|
| 285 | + * ] |
|
| 286 | + */ |
|
| 287 | + public function getTree($id, $limit = 0, $offset = 0) { |
|
| 288 | + $tree = []; |
|
| 289 | + $tree['comment'] = $this->get($id); |
|
| 290 | + $tree['replies'] = []; |
|
| 291 | + |
|
| 292 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 293 | + $query = $qb->select('*') |
|
| 294 | + ->from('comments') |
|
| 295 | + ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
| 296 | + ->orderBy('creation_timestamp', 'DESC') |
|
| 297 | + ->setParameter('id', $id); |
|
| 298 | + |
|
| 299 | + if ($limit > 0) { |
|
| 300 | + $query->setMaxResults($limit); |
|
| 301 | + } |
|
| 302 | + if ($offset > 0) { |
|
| 303 | + $query->setFirstResult($offset); |
|
| 304 | + } |
|
| 305 | + |
|
| 306 | + $resultStatement = $query->execute(); |
|
| 307 | + while ($data = $resultStatement->fetch()) { |
|
| 308 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
| 309 | + $this->cache($comment); |
|
| 310 | + $tree['replies'][] = [ |
|
| 311 | + 'comment' => $comment, |
|
| 312 | + 'replies' => [] |
|
| 313 | + ]; |
|
| 314 | + } |
|
| 315 | + $resultStatement->closeCursor(); |
|
| 316 | + |
|
| 317 | + return $tree; |
|
| 318 | + } |
|
| 319 | + |
|
| 320 | + /** |
|
| 321 | + * returns comments for a specific object (e.g. a file). |
|
| 322 | + * |
|
| 323 | + * The sort order is always newest to oldest. |
|
| 324 | + * |
|
| 325 | + * @param string $objectType the object type, e.g. 'files' |
|
| 326 | + * @param string $objectId the id of the object |
|
| 327 | + * @param int $limit optional, number of maximum comments to be returned. if |
|
| 328 | + * not specified, all comments are returned. |
|
| 329 | + * @param int $offset optional, starting point |
|
| 330 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
| 331 | + * that may be returned |
|
| 332 | + * @return IComment[] |
|
| 333 | + * @since 9.0.0 |
|
| 334 | + */ |
|
| 335 | + public function getForObject( |
|
| 336 | + $objectType, |
|
| 337 | + $objectId, |
|
| 338 | + $limit = 0, |
|
| 339 | + $offset = 0, |
|
| 340 | + \DateTime $notOlderThan = null |
|
| 341 | + ) { |
|
| 342 | + $comments = []; |
|
| 343 | + |
|
| 344 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 345 | + $query = $qb->select('*') |
|
| 346 | + ->from('comments') |
|
| 347 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
| 348 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
| 349 | + ->orderBy('creation_timestamp', 'DESC') |
|
| 350 | + ->setParameter('type', $objectType) |
|
| 351 | + ->setParameter('id', $objectId); |
|
| 352 | + |
|
| 353 | + if ($limit > 0) { |
|
| 354 | + $query->setMaxResults($limit); |
|
| 355 | + } |
|
| 356 | + if ($offset > 0) { |
|
| 357 | + $query->setFirstResult($offset); |
|
| 358 | + } |
|
| 359 | + if (!is_null($notOlderThan)) { |
|
| 360 | + $query |
|
| 361 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
| 362 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
| 363 | + } |
|
| 364 | + |
|
| 365 | + $resultStatement = $query->execute(); |
|
| 366 | + while ($data = $resultStatement->fetch()) { |
|
| 367 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
| 368 | + $this->cache($comment); |
|
| 369 | + $comments[] = $comment; |
|
| 370 | + } |
|
| 371 | + $resultStatement->closeCursor(); |
|
| 372 | + |
|
| 373 | + return $comments; |
|
| 374 | + } |
|
| 375 | + |
|
| 376 | + /** |
|
| 377 | + * @param $objectType string the object type, e.g. 'files' |
|
| 378 | + * @param $objectId string the id of the object |
|
| 379 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
| 380 | + * that may be returned |
|
| 381 | + * @return Int |
|
| 382 | + * @since 9.0.0 |
|
| 383 | + */ |
|
| 384 | + public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
| 385 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 386 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
| 387 | + ->from('comments') |
|
| 388 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
| 389 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
| 390 | + ->setParameter('type', $objectType) |
|
| 391 | + ->setParameter('id', $objectId); |
|
| 392 | + |
|
| 393 | + if (!is_null($notOlderThan)) { |
|
| 394 | + $query |
|
| 395 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
| 396 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
| 397 | + } |
|
| 398 | + |
|
| 399 | + $resultStatement = $query->execute(); |
|
| 400 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
| 401 | + $resultStatement->closeCursor(); |
|
| 402 | + return intval($data[0]); |
|
| 403 | + } |
|
| 404 | + |
|
| 405 | + /** |
|
| 406 | + * Get the number of unread comments for all files in a folder |
|
| 407 | + * |
|
| 408 | + * @param int $folderId |
|
| 409 | + * @param IUser $user |
|
| 410 | + * @return array [$fileId => $unreadCount] |
|
| 411 | + */ |
|
| 412 | + public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
|
| 413 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 414 | + $query = $qb->select('f.fileid') |
|
| 415 | + ->selectAlias( |
|
| 416 | + $qb->createFunction('COUNT(' . $qb->getColumnName('c.id') . ')'), |
|
| 417 | + 'num_ids' |
|
| 418 | + ) |
|
| 419 | + ->from('comments', 'c') |
|
| 420 | + ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
|
| 421 | + $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
|
| 422 | + $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)) |
|
| 423 | + )) |
|
| 424 | + ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX( |
|
| 425 | + $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')), |
|
| 426 | + $qb->expr()->eq('m.object_id', 'c.object_id'), |
|
| 427 | + $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())) |
|
| 428 | + )) |
|
| 429 | + ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId))) |
|
| 430 | + ->andWhere($qb->expr()->orX( |
|
| 431 | + $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'), |
|
| 432 | + $qb->expr()->isNull('marker_datetime') |
|
| 433 | + )) |
|
| 434 | + ->groupBy('f.fileid'); |
|
| 435 | + |
|
| 436 | + $resultStatement = $query->execute(); |
|
| 437 | + |
|
| 438 | + $results = []; |
|
| 439 | + while ($row = $resultStatement->fetch()) { |
|
| 440 | + $results[$row['fileid']] = (int) $row['num_ids']; |
|
| 441 | + } |
|
| 442 | + $resultStatement->closeCursor(); |
|
| 443 | + return $results; |
|
| 444 | + } |
|
| 445 | + |
|
| 446 | + /** |
|
| 447 | + * creates a new comment and returns it. At this point of time, it is not |
|
| 448 | + * saved in the used data storage. Use save() after setting other fields |
|
| 449 | + * of the comment (e.g. message or verb). |
|
| 450 | + * |
|
| 451 | + * @param string $actorType the actor type (e.g. 'users') |
|
| 452 | + * @param string $actorId a user id |
|
| 453 | + * @param string $objectType the object type the comment is attached to |
|
| 454 | + * @param string $objectId the object id the comment is attached to |
|
| 455 | + * @return IComment |
|
| 456 | + * @since 9.0.0 |
|
| 457 | + */ |
|
| 458 | + public function create($actorType, $actorId, $objectType, $objectId) { |
|
| 459 | + $comment = new Comment(); |
|
| 460 | + $comment |
|
| 461 | + ->setActor($actorType, $actorId) |
|
| 462 | + ->setObject($objectType, $objectId); |
|
| 463 | + return $comment; |
|
| 464 | + } |
|
| 465 | + |
|
| 466 | + /** |
|
| 467 | + * permanently deletes the comment specified by the ID |
|
| 468 | + * |
|
| 469 | + * When the comment has child comments, their parent ID will be changed to |
|
| 470 | + * the parent ID of the item that is to be deleted. |
|
| 471 | + * |
|
| 472 | + * @param string $id |
|
| 473 | + * @return bool |
|
| 474 | + * @throws \InvalidArgumentException |
|
| 475 | + * @since 9.0.0 |
|
| 476 | + */ |
|
| 477 | + public function delete($id) { |
|
| 478 | + if (!is_string($id)) { |
|
| 479 | + throw new \InvalidArgumentException('Parameter must be string'); |
|
| 480 | + } |
|
| 481 | + |
|
| 482 | + try { |
|
| 483 | + $comment = $this->get($id); |
|
| 484 | + } catch (\Exception $e) { |
|
| 485 | + // Ignore exceptions, we just don't fire a hook then |
|
| 486 | + $comment = null; |
|
| 487 | + } |
|
| 488 | + |
|
| 489 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 490 | + $query = $qb->delete('comments') |
|
| 491 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
| 492 | + ->setParameter('id', $id); |
|
| 493 | + |
|
| 494 | + try { |
|
| 495 | + $affectedRows = $query->execute(); |
|
| 496 | + $this->uncache($id); |
|
| 497 | + } catch (DriverException $e) { |
|
| 498 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
| 499 | + return false; |
|
| 500 | + } |
|
| 501 | + |
|
| 502 | + if ($affectedRows > 0 && $comment instanceof IComment) { |
|
| 503 | + $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
| 504 | + } |
|
| 505 | + |
|
| 506 | + return ($affectedRows > 0); |
|
| 507 | + } |
|
| 508 | + |
|
| 509 | + /** |
|
| 510 | + * saves the comment permanently |
|
| 511 | + * |
|
| 512 | + * if the supplied comment has an empty ID, a new entry comment will be |
|
| 513 | + * saved and the instance updated with the new ID. |
|
| 514 | + * |
|
| 515 | + * Otherwise, an existing comment will be updated. |
|
| 516 | + * |
|
| 517 | + * Throws NotFoundException when a comment that is to be updated does not |
|
| 518 | + * exist anymore at this point of time. |
|
| 519 | + * |
|
| 520 | + * @param IComment $comment |
|
| 521 | + * @return bool |
|
| 522 | + * @throws NotFoundException |
|
| 523 | + * @since 9.0.0 |
|
| 524 | + */ |
|
| 525 | + public function save(IComment $comment) { |
|
| 526 | + if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
| 527 | + $result = $this->insert($comment); |
|
| 528 | + } else { |
|
| 529 | + $result = $this->update($comment); |
|
| 530 | + } |
|
| 531 | + |
|
| 532 | + if ($result && !!$comment->getParentId()) { |
|
| 533 | + $this->updateChildrenInformation( |
|
| 534 | + $comment->getParentId(), |
|
| 535 | + $comment->getCreationDateTime() |
|
| 536 | + ); |
|
| 537 | + $this->cache($comment); |
|
| 538 | + } |
|
| 539 | + |
|
| 540 | + return $result; |
|
| 541 | + } |
|
| 542 | + |
|
| 543 | + /** |
|
| 544 | + * inserts the provided comment in the database |
|
| 545 | + * |
|
| 546 | + * @param IComment $comment |
|
| 547 | + * @return bool |
|
| 548 | + */ |
|
| 549 | + protected function insert(IComment &$comment) { |
|
| 550 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 551 | + $affectedRows = $qb |
|
| 552 | + ->insert('comments') |
|
| 553 | + ->values([ |
|
| 554 | + 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
| 555 | + 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
| 556 | + 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
| 557 | + 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
| 558 | + 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
| 559 | + 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
| 560 | + 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
| 561 | + 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
| 562 | + 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
| 563 | + 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
| 564 | + 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
| 565 | + ]) |
|
| 566 | + ->execute(); |
|
| 567 | + |
|
| 568 | + if ($affectedRows > 0) { |
|
| 569 | + $comment->setId(strval($qb->getLastInsertId())); |
|
| 570 | + $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
| 571 | + } |
|
| 572 | + |
|
| 573 | + return $affectedRows > 0; |
|
| 574 | + } |
|
| 575 | + |
|
| 576 | + /** |
|
| 577 | + * updates a Comment data row |
|
| 578 | + * |
|
| 579 | + * @param IComment $comment |
|
| 580 | + * @return bool |
|
| 581 | + * @throws NotFoundException |
|
| 582 | + */ |
|
| 583 | + protected function update(IComment $comment) { |
|
| 584 | + // for properly working preUpdate Events we need the old comments as is |
|
| 585 | + // in the DB and overcome caching. Also avoid that outdated information stays. |
|
| 586 | + $this->uncache($comment->getId()); |
|
| 587 | + $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
| 588 | + $this->uncache($comment->getId()); |
|
| 589 | + |
|
| 590 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 591 | + $affectedRows = $qb |
|
| 592 | + ->update('comments') |
|
| 593 | + ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
| 594 | + ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
| 595 | + ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
| 596 | + ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
| 597 | + ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
| 598 | + ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
| 599 | + ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
| 600 | + ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
| 601 | + ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
| 602 | + ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
| 603 | + ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
| 604 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
| 605 | + ->setParameter('id', $comment->getId()) |
|
| 606 | + ->execute(); |
|
| 607 | + |
|
| 608 | + if ($affectedRows === 0) { |
|
| 609 | + throw new NotFoundException('Comment to update does ceased to exist'); |
|
| 610 | + } |
|
| 611 | + |
|
| 612 | + $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
| 613 | + |
|
| 614 | + return $affectedRows > 0; |
|
| 615 | + } |
|
| 616 | + |
|
| 617 | + /** |
|
| 618 | + * removes references to specific actor (e.g. on user delete) of a comment. |
|
| 619 | + * The comment itself must not get lost/deleted. |
|
| 620 | + * |
|
| 621 | + * @param string $actorType the actor type (e.g. 'users') |
|
| 622 | + * @param string $actorId a user id |
|
| 623 | + * @return boolean |
|
| 624 | + * @since 9.0.0 |
|
| 625 | + */ |
|
| 626 | + public function deleteReferencesOfActor($actorType, $actorId) { |
|
| 627 | + $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
| 628 | + |
|
| 629 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 630 | + $affectedRows = $qb |
|
| 631 | + ->update('comments') |
|
| 632 | + ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
| 633 | + ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
| 634 | + ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
| 635 | + ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
| 636 | + ->setParameter('type', $actorType) |
|
| 637 | + ->setParameter('id', $actorId) |
|
| 638 | + ->execute(); |
|
| 639 | + |
|
| 640 | + $this->commentsCache = []; |
|
| 641 | + |
|
| 642 | + return is_int($affectedRows); |
|
| 643 | + } |
|
| 644 | + |
|
| 645 | + /** |
|
| 646 | + * deletes all comments made of a specific object (e.g. on file delete) |
|
| 647 | + * |
|
| 648 | + * @param string $objectType the object type (e.g. 'files') |
|
| 649 | + * @param string $objectId e.g. the file id |
|
| 650 | + * @return boolean |
|
| 651 | + * @since 9.0.0 |
|
| 652 | + */ |
|
| 653 | + public function deleteCommentsAtObject($objectType, $objectId) { |
|
| 654 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
| 655 | + |
|
| 656 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 657 | + $affectedRows = $qb |
|
| 658 | + ->delete('comments') |
|
| 659 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
| 660 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
| 661 | + ->setParameter('type', $objectType) |
|
| 662 | + ->setParameter('id', $objectId) |
|
| 663 | + ->execute(); |
|
| 664 | + |
|
| 665 | + $this->commentsCache = []; |
|
| 666 | + |
|
| 667 | + return is_int($affectedRows); |
|
| 668 | + } |
|
| 669 | + |
|
| 670 | + /** |
|
| 671 | + * deletes the read markers for the specified user |
|
| 672 | + * |
|
| 673 | + * @param \OCP\IUser $user |
|
| 674 | + * @return bool |
|
| 675 | + * @since 9.0.0 |
|
| 676 | + */ |
|
| 677 | + public function deleteReadMarksFromUser(IUser $user) { |
|
| 678 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 679 | + $query = $qb->delete('comments_read_markers') |
|
| 680 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
| 681 | + ->setParameter('user_id', $user->getUID()); |
|
| 682 | + |
|
| 683 | + try { |
|
| 684 | + $affectedRows = $query->execute(); |
|
| 685 | + } catch (DriverException $e) { |
|
| 686 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
| 687 | + return false; |
|
| 688 | + } |
|
| 689 | + return ($affectedRows > 0); |
|
| 690 | + } |
|
| 691 | + |
|
| 692 | + /** |
|
| 693 | + * sets the read marker for a given file to the specified date for the |
|
| 694 | + * provided user |
|
| 695 | + * |
|
| 696 | + * @param string $objectType |
|
| 697 | + * @param string $objectId |
|
| 698 | + * @param \DateTime $dateTime |
|
| 699 | + * @param IUser $user |
|
| 700 | + * @since 9.0.0 |
|
| 701 | + * @suppress SqlInjectionChecker |
|
| 702 | + */ |
|
| 703 | + public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
| 704 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
| 705 | + |
|
| 706 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 707 | + $values = [ |
|
| 708 | + 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
| 709 | + 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
| 710 | + 'object_type' => $qb->createNamedParameter($objectType), |
|
| 711 | + 'object_id' => $qb->createNamedParameter($objectId), |
|
| 712 | + ]; |
|
| 713 | + |
|
| 714 | + // Strategy: try to update, if this does not return affected rows, do an insert. |
|
| 715 | + $affectedRows = $qb |
|
| 716 | + ->update('comments_read_markers') |
|
| 717 | + ->set('user_id', $values['user_id']) |
|
| 718 | + ->set('marker_datetime', $values['marker_datetime']) |
|
| 719 | + ->set('object_type', $values['object_type']) |
|
| 720 | + ->set('object_id', $values['object_id']) |
|
| 721 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
| 722 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
| 723 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
| 724 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
| 725 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
| 726 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
| 727 | + ->execute(); |
|
| 728 | + |
|
| 729 | + if ($affectedRows > 0) { |
|
| 730 | + return; |
|
| 731 | + } |
|
| 732 | + |
|
| 733 | + $qb->insert('comments_read_markers') |
|
| 734 | + ->values($values) |
|
| 735 | + ->execute(); |
|
| 736 | + } |
|
| 737 | + |
|
| 738 | + /** |
|
| 739 | + * returns the read marker for a given file to the specified date for the |
|
| 740 | + * provided user. It returns null, when the marker is not present, i.e. |
|
| 741 | + * no comments were marked as read. |
|
| 742 | + * |
|
| 743 | + * @param string $objectType |
|
| 744 | + * @param string $objectId |
|
| 745 | + * @param IUser $user |
|
| 746 | + * @return \DateTime|null |
|
| 747 | + * @since 9.0.0 |
|
| 748 | + */ |
|
| 749 | + public function getReadMark($objectType, $objectId, IUser $user) { |
|
| 750 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 751 | + $resultStatement = $qb->select('marker_datetime') |
|
| 752 | + ->from('comments_read_markers') |
|
| 753 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
| 754 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
| 755 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
| 756 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
| 757 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
| 758 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
| 759 | + ->execute(); |
|
| 760 | + |
|
| 761 | + $data = $resultStatement->fetch(); |
|
| 762 | + $resultStatement->closeCursor(); |
|
| 763 | + if (!$data || is_null($data['marker_datetime'])) { |
|
| 764 | + return null; |
|
| 765 | + } |
|
| 766 | + |
|
| 767 | + return new \DateTime($data['marker_datetime']); |
|
| 768 | + } |
|
| 769 | + |
|
| 770 | + /** |
|
| 771 | + * deletes the read markers on the specified object |
|
| 772 | + * |
|
| 773 | + * @param string $objectType |
|
| 774 | + * @param string $objectId |
|
| 775 | + * @return bool |
|
| 776 | + * @since 9.0.0 |
|
| 777 | + */ |
|
| 778 | + public function deleteReadMarksOnObject($objectType, $objectId) { |
|
| 779 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
| 780 | + |
|
| 781 | + $qb = $this->dbConn->getQueryBuilder(); |
|
| 782 | + $query = $qb->delete('comments_read_markers') |
|
| 783 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
| 784 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
| 785 | + ->setParameter('object_type', $objectType) |
|
| 786 | + ->setParameter('object_id', $objectId); |
|
| 787 | + |
|
| 788 | + try { |
|
| 789 | + $affectedRows = $query->execute(); |
|
| 790 | + } catch (DriverException $e) { |
|
| 791 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
| 792 | + return false; |
|
| 793 | + } |
|
| 794 | + return ($affectedRows > 0); |
|
| 795 | + } |
|
| 796 | + |
|
| 797 | + /** |
|
| 798 | + * registers an Entity to the manager, so event notifications can be send |
|
| 799 | + * to consumers of the comments infrastructure |
|
| 800 | + * |
|
| 801 | + * @param \Closure $closure |
|
| 802 | + */ |
|
| 803 | + public function registerEventHandler(\Closure $closure) { |
|
| 804 | + $this->eventHandlerClosures[] = $closure; |
|
| 805 | + $this->eventHandlers = []; |
|
| 806 | + } |
|
| 807 | + |
|
| 808 | + /** |
|
| 809 | + * registers a method that resolves an ID to a display name for a given type |
|
| 810 | + * |
|
| 811 | + * @param string $type |
|
| 812 | + * @param \Closure $closure |
|
| 813 | + * @throws \OutOfBoundsException |
|
| 814 | + * @since 11.0.0 |
|
| 815 | + * |
|
| 816 | + * Only one resolver shall be registered per type. Otherwise a |
|
| 817 | + * \OutOfBoundsException has to thrown. |
|
| 818 | + */ |
|
| 819 | + public function registerDisplayNameResolver($type, \Closure $closure) { |
|
| 820 | + if (!is_string($type)) { |
|
| 821 | + throw new \InvalidArgumentException('String expected.'); |
|
| 822 | + } |
|
| 823 | + if (isset($this->displayNameResolvers[$type])) { |
|
| 824 | + throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
| 825 | + } |
|
| 826 | + $this->displayNameResolvers[$type] = $closure; |
|
| 827 | + } |
|
| 828 | + |
|
| 829 | + /** |
|
| 830 | + * resolves a given ID of a given Type to a display name. |
|
| 831 | + * |
|
| 832 | + * @param string $type |
|
| 833 | + * @param string $id |
|
| 834 | + * @return string |
|
| 835 | + * @throws \OutOfBoundsException |
|
| 836 | + * @since 11.0.0 |
|
| 837 | + * |
|
| 838 | + * If a provided type was not registered, an \OutOfBoundsException shall |
|
| 839 | + * be thrown. It is upon the resolver discretion what to return of the |
|
| 840 | + * provided ID is unknown. It must be ensured that a string is returned. |
|
| 841 | + */ |
|
| 842 | + public function resolveDisplayName($type, $id) { |
|
| 843 | + if (!is_string($type)) { |
|
| 844 | + throw new \InvalidArgumentException('String expected.'); |
|
| 845 | + } |
|
| 846 | + if (!isset($this->displayNameResolvers[$type])) { |
|
| 847 | + throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
| 848 | + } |
|
| 849 | + return (string)$this->displayNameResolvers[$type]($id); |
|
| 850 | + } |
|
| 851 | + |
|
| 852 | + /** |
|
| 853 | + * returns valid, registered entities |
|
| 854 | + * |
|
| 855 | + * @return \OCP\Comments\ICommentsEventHandler[] |
|
| 856 | + */ |
|
| 857 | + private function getEventHandlers() { |
|
| 858 | + if (!empty($this->eventHandlers)) { |
|
| 859 | + return $this->eventHandlers; |
|
| 860 | + } |
|
| 861 | + |
|
| 862 | + $this->eventHandlers = []; |
|
| 863 | + foreach ($this->eventHandlerClosures as $name => $closure) { |
|
| 864 | + $entity = $closure(); |
|
| 865 | + if (!($entity instanceof ICommentsEventHandler)) { |
|
| 866 | + throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
| 867 | + } |
|
| 868 | + $this->eventHandlers[$name] = $entity; |
|
| 869 | + } |
|
| 870 | + |
|
| 871 | + return $this->eventHandlers; |
|
| 872 | + } |
|
| 873 | + |
|
| 874 | + /** |
|
| 875 | + * sends notifications to the registered entities |
|
| 876 | + * |
|
| 877 | + * @param $eventType |
|
| 878 | + * @param IComment $comment |
|
| 879 | + */ |
|
| 880 | + private function sendEvent($eventType, IComment $comment) { |
|
| 881 | + $entities = $this->getEventHandlers(); |
|
| 882 | + $event = new CommentsEvent($eventType, $comment); |
|
| 883 | + foreach ($entities as $entity) { |
|
| 884 | + $entity->handle($event); |
|
| 885 | + } |
|
| 886 | + } |
|
| 887 | 887 | } |
@@ -190,7 +190,7 @@ discard block |
||
| 190 | 190 | !is_string($type) || empty($type) |
| 191 | 191 | || !is_string($id) || empty($id) |
| 192 | 192 | ) { |
| 193 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
| 193 | + throw new \InvalidArgumentException($role.' parameters must be string and not empty'); |
|
| 194 | 194 | } |
| 195 | 195 | } |
| 196 | 196 | |
@@ -413,7 +413,7 @@ discard block |
||
| 413 | 413 | $qb = $this->dbConn->getQueryBuilder(); |
| 414 | 414 | $query = $qb->select('f.fileid') |
| 415 | 415 | ->selectAlias( |
| 416 | - $qb->createFunction('COUNT(' . $qb->getColumnName('c.id') . ')'), |
|
| 416 | + $qb->createFunction('COUNT('.$qb->getColumnName('c.id').')'), |
|
| 417 | 417 | 'num_ids' |
| 418 | 418 | ) |
| 419 | 419 | ->from('comments', 'c') |
@@ -546,7 +546,7 @@ discard block |
||
| 546 | 546 | * @param IComment $comment |
| 547 | 547 | * @return bool |
| 548 | 548 | */ |
| 549 | - protected function insert(IComment &$comment) { |
|
| 549 | + protected function insert(IComment & $comment) { |
|
| 550 | 550 | $qb = $this->dbConn->getQueryBuilder(); |
| 551 | 551 | $affectedRows = $qb |
| 552 | 552 | ->insert('comments') |
@@ -846,7 +846,7 @@ discard block |
||
| 846 | 846 | if (!isset($this->displayNameResolvers[$type])) { |
| 847 | 847 | throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
| 848 | 848 | } |
| 849 | - return (string)$this->displayNameResolvers[$type]($id); |
|
| 849 | + return (string) $this->displayNameResolvers[$type]($id); |
|
| 850 | 850 | } |
| 851 | 851 | |
| 852 | 852 | /** |
@@ -93,7 +93,7 @@ discard block |
||
| 93 | 93 | /** |
| 94 | 94 | * Formats the date of the given timestamp |
| 95 | 95 | * |
| 96 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 96 | + * @param integer $timestamp Either a Unix timestamp or DateTime object |
|
| 97 | 97 | * @param string $format Either 'full', 'long', 'medium' or 'short' |
| 98 | 98 | * full: e.g. 'EEEE, MMMM d, y' => 'Wednesday, August 20, 2014' |
| 99 | 99 | * long: e.g. 'MMMM d, y' => 'August 20, 2014' |
@@ -192,7 +192,7 @@ discard block |
||
| 192 | 192 | /** |
| 193 | 193 | * Gives the relative past time of the timestamp |
| 194 | 194 | * |
| 195 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 195 | + * @param integer $timestamp Either a Unix timestamp or DateTime object |
|
| 196 | 196 | * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time |
| 197 | 197 | * @return string Dates returned are: |
| 198 | 198 | * < 60 sec => seconds ago |
@@ -228,7 +228,7 @@ discard block |
||
| 228 | 228 | /** |
| 229 | 229 | * Formats the date and time of the given timestamp |
| 230 | 230 | * |
| 231 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 231 | + * @param integer $timestamp Either a Unix timestamp or DateTime object |
|
| 232 | 232 | * @param string $formatDate See formatDate() for description |
| 233 | 233 | * @param string $formatTime See formatTime() for description |
| 234 | 234 | * @param \DateTimeZone $timeZone The timezone to use |
@@ -237,7 +237,7 @@ discard block |
||
| 237 | 237 | * @return string Formatted date and time string |
| 238 | 238 | */ |
| 239 | 239 | public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
| 240 | - return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); |
|
| 240 | + return $this->format($timestamp, 'datetime', $formatDate.'|'.$formatTime, $timeZone, $l); |
|
| 241 | 241 | } |
| 242 | 242 | |
| 243 | 243 | /** |
@@ -256,7 +256,7 @@ discard block |
||
| 256 | 256 | $formatDate .= '^'; |
| 257 | 257 | } |
| 258 | 258 | |
| 259 | - return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); |
|
| 259 | + return $this->format($timestamp, 'datetime', $formatDate.'|'.$formatTime, $timeZone, $l); |
|
| 260 | 260 | } |
| 261 | 261 | |
| 262 | 262 | /** |
@@ -25,294 +25,294 @@ |
||
| 25 | 25 | namespace OC; |
| 26 | 26 | |
| 27 | 27 | class DateTimeFormatter implements \OCP\IDateTimeFormatter { |
| 28 | - /** @var \DateTimeZone */ |
|
| 29 | - protected $defaultTimeZone; |
|
| 28 | + /** @var \DateTimeZone */ |
|
| 29 | + protected $defaultTimeZone; |
|
| 30 | 30 | |
| 31 | - /** @var \OCP\IL10N */ |
|
| 32 | - protected $defaultL10N; |
|
| 31 | + /** @var \OCP\IL10N */ |
|
| 32 | + protected $defaultL10N; |
|
| 33 | 33 | |
| 34 | - /** |
|
| 35 | - * Constructor |
|
| 36 | - * |
|
| 37 | - * @param \DateTimeZone $defaultTimeZone Set the timezone for the format |
|
| 38 | - * @param \OCP\IL10N $defaultL10N Set the language for the format |
|
| 39 | - */ |
|
| 40 | - public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) { |
|
| 41 | - $this->defaultTimeZone = $defaultTimeZone; |
|
| 42 | - $this->defaultL10N = $defaultL10N; |
|
| 43 | - } |
|
| 34 | + /** |
|
| 35 | + * Constructor |
|
| 36 | + * |
|
| 37 | + * @param \DateTimeZone $defaultTimeZone Set the timezone for the format |
|
| 38 | + * @param \OCP\IL10N $defaultL10N Set the language for the format |
|
| 39 | + */ |
|
| 40 | + public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) { |
|
| 41 | + $this->defaultTimeZone = $defaultTimeZone; |
|
| 42 | + $this->defaultL10N = $defaultL10N; |
|
| 43 | + } |
|
| 44 | 44 | |
| 45 | - /** |
|
| 46 | - * Get TimeZone to use |
|
| 47 | - * |
|
| 48 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 49 | - * @return \DateTimeZone The timezone to use, falling back to the current user's timezone |
|
| 50 | - */ |
|
| 51 | - protected function getTimeZone($timeZone = null) { |
|
| 52 | - if ($timeZone === null) { |
|
| 53 | - $timeZone = $this->defaultTimeZone; |
|
| 54 | - } |
|
| 45 | + /** |
|
| 46 | + * Get TimeZone to use |
|
| 47 | + * |
|
| 48 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 49 | + * @return \DateTimeZone The timezone to use, falling back to the current user's timezone |
|
| 50 | + */ |
|
| 51 | + protected function getTimeZone($timeZone = null) { |
|
| 52 | + if ($timeZone === null) { |
|
| 53 | + $timeZone = $this->defaultTimeZone; |
|
| 54 | + } |
|
| 55 | 55 | |
| 56 | - return $timeZone; |
|
| 57 | - } |
|
| 56 | + return $timeZone; |
|
| 57 | + } |
|
| 58 | 58 | |
| 59 | - /** |
|
| 60 | - * Get \OCP\IL10N to use |
|
| 61 | - * |
|
| 62 | - * @param \OCP\IL10N $l The locale to use |
|
| 63 | - * @return \OCP\IL10N The locale to use, falling back to the current user's locale |
|
| 64 | - */ |
|
| 65 | - protected function getLocale($l = null) { |
|
| 66 | - if ($l === null) { |
|
| 67 | - $l = $this->defaultL10N; |
|
| 68 | - } |
|
| 59 | + /** |
|
| 60 | + * Get \OCP\IL10N to use |
|
| 61 | + * |
|
| 62 | + * @param \OCP\IL10N $l The locale to use |
|
| 63 | + * @return \OCP\IL10N The locale to use, falling back to the current user's locale |
|
| 64 | + */ |
|
| 65 | + protected function getLocale($l = null) { |
|
| 66 | + if ($l === null) { |
|
| 67 | + $l = $this->defaultL10N; |
|
| 68 | + } |
|
| 69 | 69 | |
| 70 | - return $l; |
|
| 71 | - } |
|
| 70 | + return $l; |
|
| 71 | + } |
|
| 72 | 72 | |
| 73 | - /** |
|
| 74 | - * Generates a DateTime object with the given timestamp and TimeZone |
|
| 75 | - * |
|
| 76 | - * @param mixed $timestamp |
|
| 77 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 78 | - * @return \DateTime |
|
| 79 | - */ |
|
| 80 | - protected function getDateTime($timestamp, \DateTimeZone $timeZone = null) { |
|
| 81 | - if ($timestamp === null) { |
|
| 82 | - return new \DateTime('now', $timeZone); |
|
| 83 | - } else if (!$timestamp instanceof \DateTime) { |
|
| 84 | - $dateTime = new \DateTime('now', $timeZone); |
|
| 85 | - $dateTime->setTimestamp($timestamp); |
|
| 86 | - return $dateTime; |
|
| 87 | - } |
|
| 88 | - if ($timeZone) { |
|
| 89 | - $timestamp->setTimezone($timeZone); |
|
| 90 | - } |
|
| 91 | - return $timestamp; |
|
| 92 | - } |
|
| 73 | + /** |
|
| 74 | + * Generates a DateTime object with the given timestamp and TimeZone |
|
| 75 | + * |
|
| 76 | + * @param mixed $timestamp |
|
| 77 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 78 | + * @return \DateTime |
|
| 79 | + */ |
|
| 80 | + protected function getDateTime($timestamp, \DateTimeZone $timeZone = null) { |
|
| 81 | + if ($timestamp === null) { |
|
| 82 | + return new \DateTime('now', $timeZone); |
|
| 83 | + } else if (!$timestamp instanceof \DateTime) { |
|
| 84 | + $dateTime = new \DateTime('now', $timeZone); |
|
| 85 | + $dateTime->setTimestamp($timestamp); |
|
| 86 | + return $dateTime; |
|
| 87 | + } |
|
| 88 | + if ($timeZone) { |
|
| 89 | + $timestamp->setTimezone($timeZone); |
|
| 90 | + } |
|
| 91 | + return $timestamp; |
|
| 92 | + } |
|
| 93 | 93 | |
| 94 | - /** |
|
| 95 | - * Formats the date of the given timestamp |
|
| 96 | - * |
|
| 97 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 98 | - * @param string $format Either 'full', 'long', 'medium' or 'short' |
|
| 99 | - * full: e.g. 'EEEE, MMMM d, y' => 'Wednesday, August 20, 2014' |
|
| 100 | - * long: e.g. 'MMMM d, y' => 'August 20, 2014' |
|
| 101 | - * medium: e.g. 'MMM d, y' => 'Aug 20, 2014' |
|
| 102 | - * short: e.g. 'M/d/yy' => '8/20/14' |
|
| 103 | - * The exact format is dependent on the language |
|
| 104 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 105 | - * @param \OCP\IL10N $l The locale to use |
|
| 106 | - * @return string Formatted date string |
|
| 107 | - */ |
|
| 108 | - public function formatDate($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 109 | - return $this->format($timestamp, 'date', $format, $timeZone, $l); |
|
| 110 | - } |
|
| 94 | + /** |
|
| 95 | + * Formats the date of the given timestamp |
|
| 96 | + * |
|
| 97 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 98 | + * @param string $format Either 'full', 'long', 'medium' or 'short' |
|
| 99 | + * full: e.g. 'EEEE, MMMM d, y' => 'Wednesday, August 20, 2014' |
|
| 100 | + * long: e.g. 'MMMM d, y' => 'August 20, 2014' |
|
| 101 | + * medium: e.g. 'MMM d, y' => 'Aug 20, 2014' |
|
| 102 | + * short: e.g. 'M/d/yy' => '8/20/14' |
|
| 103 | + * The exact format is dependent on the language |
|
| 104 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 105 | + * @param \OCP\IL10N $l The locale to use |
|
| 106 | + * @return string Formatted date string |
|
| 107 | + */ |
|
| 108 | + public function formatDate($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 109 | + return $this->format($timestamp, 'date', $format, $timeZone, $l); |
|
| 110 | + } |
|
| 111 | 111 | |
| 112 | - /** |
|
| 113 | - * Formats the date of the given timestamp |
|
| 114 | - * |
|
| 115 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 116 | - * @param string $format Either 'full', 'long', 'medium' or 'short' |
|
| 117 | - * full: e.g. 'EEEE, MMMM d, y' => 'Wednesday, August 20, 2014' |
|
| 118 | - * long: e.g. 'MMMM d, y' => 'August 20, 2014' |
|
| 119 | - * medium: e.g. 'MMM d, y' => 'Aug 20, 2014' |
|
| 120 | - * short: e.g. 'M/d/yy' => '8/20/14' |
|
| 121 | - * The exact format is dependent on the language |
|
| 122 | - * Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable |
|
| 123 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 124 | - * @param \OCP\IL10N $l The locale to use |
|
| 125 | - * @return string Formatted relative date string |
|
| 126 | - */ |
|
| 127 | - public function formatDateRelativeDay($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 128 | - if (substr($format, -1) !== '*' && substr($format, -1) !== '*') { |
|
| 129 | - $format .= '^'; |
|
| 130 | - } |
|
| 112 | + /** |
|
| 113 | + * Formats the date of the given timestamp |
|
| 114 | + * |
|
| 115 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 116 | + * @param string $format Either 'full', 'long', 'medium' or 'short' |
|
| 117 | + * full: e.g. 'EEEE, MMMM d, y' => 'Wednesday, August 20, 2014' |
|
| 118 | + * long: e.g. 'MMMM d, y' => 'August 20, 2014' |
|
| 119 | + * medium: e.g. 'MMM d, y' => 'Aug 20, 2014' |
|
| 120 | + * short: e.g. 'M/d/yy' => '8/20/14' |
|
| 121 | + * The exact format is dependent on the language |
|
| 122 | + * Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable |
|
| 123 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 124 | + * @param \OCP\IL10N $l The locale to use |
|
| 125 | + * @return string Formatted relative date string |
|
| 126 | + */ |
|
| 127 | + public function formatDateRelativeDay($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 128 | + if (substr($format, -1) !== '*' && substr($format, -1) !== '*') { |
|
| 129 | + $format .= '^'; |
|
| 130 | + } |
|
| 131 | 131 | |
| 132 | - return $this->format($timestamp, 'date', $format, $timeZone, $l); |
|
| 133 | - } |
|
| 132 | + return $this->format($timestamp, 'date', $format, $timeZone, $l); |
|
| 133 | + } |
|
| 134 | 134 | |
| 135 | - /** |
|
| 136 | - * Gives the relative date of the timestamp |
|
| 137 | - * Only works for past dates |
|
| 138 | - * |
|
| 139 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 140 | - * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time |
|
| 141 | - * @return string Dates returned are: |
|
| 142 | - * < 1 month => Today, Yesterday, n days ago |
|
| 143 | - * < 13 month => last month, n months ago |
|
| 144 | - * >= 13 month => last year, n years ago |
|
| 145 | - * @param \OCP\IL10N $l The locale to use |
|
| 146 | - * @return string Formatted date span |
|
| 147 | - */ |
|
| 148 | - public function formatDateSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) { |
|
| 149 | - $l = $this->getLocale($l); |
|
| 150 | - $timestamp = $this->getDateTime($timestamp); |
|
| 151 | - $timestamp->setTime(0, 0, 0); |
|
| 135 | + /** |
|
| 136 | + * Gives the relative date of the timestamp |
|
| 137 | + * Only works for past dates |
|
| 138 | + * |
|
| 139 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 140 | + * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time |
|
| 141 | + * @return string Dates returned are: |
|
| 142 | + * < 1 month => Today, Yesterday, n days ago |
|
| 143 | + * < 13 month => last month, n months ago |
|
| 144 | + * >= 13 month => last year, n years ago |
|
| 145 | + * @param \OCP\IL10N $l The locale to use |
|
| 146 | + * @return string Formatted date span |
|
| 147 | + */ |
|
| 148 | + public function formatDateSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) { |
|
| 149 | + $l = $this->getLocale($l); |
|
| 150 | + $timestamp = $this->getDateTime($timestamp); |
|
| 151 | + $timestamp->setTime(0, 0, 0); |
|
| 152 | 152 | |
| 153 | - if ($baseTimestamp === null) { |
|
| 154 | - $baseTimestamp = time(); |
|
| 155 | - } |
|
| 156 | - $baseTimestamp = $this->getDateTime($baseTimestamp); |
|
| 157 | - $baseTimestamp->setTime(0, 0, 0); |
|
| 158 | - $dateInterval = $timestamp->diff($baseTimestamp); |
|
| 153 | + if ($baseTimestamp === null) { |
|
| 154 | + $baseTimestamp = time(); |
|
| 155 | + } |
|
| 156 | + $baseTimestamp = $this->getDateTime($baseTimestamp); |
|
| 157 | + $baseTimestamp->setTime(0, 0, 0); |
|
| 158 | + $dateInterval = $timestamp->diff($baseTimestamp); |
|
| 159 | 159 | |
| 160 | - if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 0) { |
|
| 161 | - return $l->t('today'); |
|
| 162 | - } else if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 1) { |
|
| 163 | - if ($timestamp > $baseTimestamp) { |
|
| 164 | - return $l->t('tomorrow'); |
|
| 165 | - } else { |
|
| 166 | - return $l->t('yesterday'); |
|
| 167 | - } |
|
| 168 | - } else if ($dateInterval->y == 0 && $dateInterval->m == 0) { |
|
| 169 | - if ($timestamp > $baseTimestamp) { |
|
| 170 | - return $l->n('in %n day', 'in %n days', $dateInterval->d); |
|
| 171 | - } else { |
|
| 172 | - return $l->n('%n day ago', '%n days ago', $dateInterval->d); |
|
| 173 | - } |
|
| 174 | - } else if ($dateInterval->y == 0 && $dateInterval->m == 1) { |
|
| 175 | - if ($timestamp > $baseTimestamp) { |
|
| 176 | - return $l->t('next month'); |
|
| 177 | - } else { |
|
| 178 | - return $l->t('last month'); |
|
| 179 | - } |
|
| 180 | - } else if ($dateInterval->y == 0) { |
|
| 181 | - if ($timestamp > $baseTimestamp) { |
|
| 182 | - return $l->n('in %n month', 'in %n months', $dateInterval->m); |
|
| 183 | - } else { |
|
| 184 | - return $l->n('%n month ago', '%n months ago', $dateInterval->m); |
|
| 185 | - } |
|
| 186 | - } else if ($dateInterval->y == 1) { |
|
| 187 | - if ($timestamp > $baseTimestamp) { |
|
| 188 | - return $l->t('next year'); |
|
| 189 | - } else { |
|
| 190 | - return $l->t('last year'); |
|
| 191 | - } |
|
| 192 | - } |
|
| 193 | - if ($timestamp > $baseTimestamp) { |
|
| 194 | - return $l->n('in %n year', 'in %n years', $dateInterval->y); |
|
| 195 | - } else { |
|
| 196 | - return $l->n('%n year ago', '%n years ago', $dateInterval->y); |
|
| 197 | - } |
|
| 198 | - } |
|
| 160 | + if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 0) { |
|
| 161 | + return $l->t('today'); |
|
| 162 | + } else if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 1) { |
|
| 163 | + if ($timestamp > $baseTimestamp) { |
|
| 164 | + return $l->t('tomorrow'); |
|
| 165 | + } else { |
|
| 166 | + return $l->t('yesterday'); |
|
| 167 | + } |
|
| 168 | + } else if ($dateInterval->y == 0 && $dateInterval->m == 0) { |
|
| 169 | + if ($timestamp > $baseTimestamp) { |
|
| 170 | + return $l->n('in %n day', 'in %n days', $dateInterval->d); |
|
| 171 | + } else { |
|
| 172 | + return $l->n('%n day ago', '%n days ago', $dateInterval->d); |
|
| 173 | + } |
|
| 174 | + } else if ($dateInterval->y == 0 && $dateInterval->m == 1) { |
|
| 175 | + if ($timestamp > $baseTimestamp) { |
|
| 176 | + return $l->t('next month'); |
|
| 177 | + } else { |
|
| 178 | + return $l->t('last month'); |
|
| 179 | + } |
|
| 180 | + } else if ($dateInterval->y == 0) { |
|
| 181 | + if ($timestamp > $baseTimestamp) { |
|
| 182 | + return $l->n('in %n month', 'in %n months', $dateInterval->m); |
|
| 183 | + } else { |
|
| 184 | + return $l->n('%n month ago', '%n months ago', $dateInterval->m); |
|
| 185 | + } |
|
| 186 | + } else if ($dateInterval->y == 1) { |
|
| 187 | + if ($timestamp > $baseTimestamp) { |
|
| 188 | + return $l->t('next year'); |
|
| 189 | + } else { |
|
| 190 | + return $l->t('last year'); |
|
| 191 | + } |
|
| 192 | + } |
|
| 193 | + if ($timestamp > $baseTimestamp) { |
|
| 194 | + return $l->n('in %n year', 'in %n years', $dateInterval->y); |
|
| 195 | + } else { |
|
| 196 | + return $l->n('%n year ago', '%n years ago', $dateInterval->y); |
|
| 197 | + } |
|
| 198 | + } |
|
| 199 | 199 | |
| 200 | - /** |
|
| 201 | - * Formats the time of the given timestamp |
|
| 202 | - * |
|
| 203 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 204 | - * @param string $format Either 'full', 'long', 'medium' or 'short' |
|
| 205 | - * full: e.g. 'h:mm:ss a zzzz' => '11:42:13 AM GMT+0:00' |
|
| 206 | - * long: e.g. 'h:mm:ss a z' => '11:42:13 AM GMT' |
|
| 207 | - * medium: e.g. 'h:mm:ss a' => '11:42:13 AM' |
|
| 208 | - * short: e.g. 'h:mm a' => '11:42 AM' |
|
| 209 | - * The exact format is dependent on the language |
|
| 210 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 211 | - * @param \OCP\IL10N $l The locale to use |
|
| 212 | - * @return string Formatted time string |
|
| 213 | - */ |
|
| 214 | - public function formatTime($timestamp, $format = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 215 | - return $this->format($timestamp, 'time', $format, $timeZone, $l); |
|
| 216 | - } |
|
| 200 | + /** |
|
| 201 | + * Formats the time of the given timestamp |
|
| 202 | + * |
|
| 203 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 204 | + * @param string $format Either 'full', 'long', 'medium' or 'short' |
|
| 205 | + * full: e.g. 'h:mm:ss a zzzz' => '11:42:13 AM GMT+0:00' |
|
| 206 | + * long: e.g. 'h:mm:ss a z' => '11:42:13 AM GMT' |
|
| 207 | + * medium: e.g. 'h:mm:ss a' => '11:42:13 AM' |
|
| 208 | + * short: e.g. 'h:mm a' => '11:42 AM' |
|
| 209 | + * The exact format is dependent on the language |
|
| 210 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 211 | + * @param \OCP\IL10N $l The locale to use |
|
| 212 | + * @return string Formatted time string |
|
| 213 | + */ |
|
| 214 | + public function formatTime($timestamp, $format = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 215 | + return $this->format($timestamp, 'time', $format, $timeZone, $l); |
|
| 216 | + } |
|
| 217 | 217 | |
| 218 | - /** |
|
| 219 | - * Gives the relative past time of the timestamp |
|
| 220 | - * |
|
| 221 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 222 | - * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time |
|
| 223 | - * @return string Dates returned are: |
|
| 224 | - * < 60 sec => seconds ago |
|
| 225 | - * < 1 hour => n minutes ago |
|
| 226 | - * < 1 day => n hours ago |
|
| 227 | - * < 1 month => Yesterday, n days ago |
|
| 228 | - * < 13 month => last month, n months ago |
|
| 229 | - * >= 13 month => last year, n years ago |
|
| 230 | - * @param \OCP\IL10N $l The locale to use |
|
| 231 | - * @return string Formatted time span |
|
| 232 | - */ |
|
| 233 | - public function formatTimeSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) { |
|
| 234 | - $l = $this->getLocale($l); |
|
| 235 | - $timestamp = $this->getDateTime($timestamp); |
|
| 236 | - if ($baseTimestamp === null) { |
|
| 237 | - $baseTimestamp = time(); |
|
| 238 | - } |
|
| 239 | - $baseTimestamp = $this->getDateTime($baseTimestamp); |
|
| 218 | + /** |
|
| 219 | + * Gives the relative past time of the timestamp |
|
| 220 | + * |
|
| 221 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 222 | + * @param int|\DateTime $baseTimestamp Timestamp to compare $timestamp against, defaults to current time |
|
| 223 | + * @return string Dates returned are: |
|
| 224 | + * < 60 sec => seconds ago |
|
| 225 | + * < 1 hour => n minutes ago |
|
| 226 | + * < 1 day => n hours ago |
|
| 227 | + * < 1 month => Yesterday, n days ago |
|
| 228 | + * < 13 month => last month, n months ago |
|
| 229 | + * >= 13 month => last year, n years ago |
|
| 230 | + * @param \OCP\IL10N $l The locale to use |
|
| 231 | + * @return string Formatted time span |
|
| 232 | + */ |
|
| 233 | + public function formatTimeSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) { |
|
| 234 | + $l = $this->getLocale($l); |
|
| 235 | + $timestamp = $this->getDateTime($timestamp); |
|
| 236 | + if ($baseTimestamp === null) { |
|
| 237 | + $baseTimestamp = time(); |
|
| 238 | + } |
|
| 239 | + $baseTimestamp = $this->getDateTime($baseTimestamp); |
|
| 240 | 240 | |
| 241 | - $diff = $timestamp->diff($baseTimestamp); |
|
| 242 | - if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0) { |
|
| 243 | - return $this->formatDateSpan($timestamp, $baseTimestamp, $l); |
|
| 244 | - } |
|
| 241 | + $diff = $timestamp->diff($baseTimestamp); |
|
| 242 | + if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0) { |
|
| 243 | + return $this->formatDateSpan($timestamp, $baseTimestamp, $l); |
|
| 244 | + } |
|
| 245 | 245 | |
| 246 | - if ($diff->h > 0) { |
|
| 247 | - if ($timestamp > $baseTimestamp) { |
|
| 248 | - return $l->n('in %n hour', 'in %n hours', $diff->h); |
|
| 249 | - } else { |
|
| 250 | - return $l->n('%n hour ago', '%n hours ago', $diff->h); |
|
| 251 | - } |
|
| 252 | - } else if ($diff->i > 0) { |
|
| 253 | - if ($timestamp > $baseTimestamp) { |
|
| 254 | - return $l->n('in %n minute', 'in %n minutes', $diff->i); |
|
| 255 | - } else { |
|
| 256 | - return $l->n('%n minute ago', '%n minutes ago', $diff->i); |
|
| 257 | - } |
|
| 258 | - } |
|
| 259 | - if ($timestamp > $baseTimestamp) { |
|
| 260 | - return $l->t('in a few seconds'); |
|
| 261 | - } else { |
|
| 262 | - return $l->t('seconds ago'); |
|
| 263 | - } |
|
| 264 | - } |
|
| 246 | + if ($diff->h > 0) { |
|
| 247 | + if ($timestamp > $baseTimestamp) { |
|
| 248 | + return $l->n('in %n hour', 'in %n hours', $diff->h); |
|
| 249 | + } else { |
|
| 250 | + return $l->n('%n hour ago', '%n hours ago', $diff->h); |
|
| 251 | + } |
|
| 252 | + } else if ($diff->i > 0) { |
|
| 253 | + if ($timestamp > $baseTimestamp) { |
|
| 254 | + return $l->n('in %n minute', 'in %n minutes', $diff->i); |
|
| 255 | + } else { |
|
| 256 | + return $l->n('%n minute ago', '%n minutes ago', $diff->i); |
|
| 257 | + } |
|
| 258 | + } |
|
| 259 | + if ($timestamp > $baseTimestamp) { |
|
| 260 | + return $l->t('in a few seconds'); |
|
| 261 | + } else { |
|
| 262 | + return $l->t('seconds ago'); |
|
| 263 | + } |
|
| 264 | + } |
|
| 265 | 265 | |
| 266 | - /** |
|
| 267 | - * Formats the date and time of the given timestamp |
|
| 268 | - * |
|
| 269 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 270 | - * @param string $formatDate See formatDate() for description |
|
| 271 | - * @param string $formatTime See formatTime() for description |
|
| 272 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 273 | - * @param \OCP\IL10N $l The locale to use |
|
| 274 | - * @return string Formatted date and time string |
|
| 275 | - */ |
|
| 276 | - public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 277 | - return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); |
|
| 278 | - } |
|
| 266 | + /** |
|
| 267 | + * Formats the date and time of the given timestamp |
|
| 268 | + * |
|
| 269 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 270 | + * @param string $formatDate See formatDate() for description |
|
| 271 | + * @param string $formatTime See formatTime() for description |
|
| 272 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 273 | + * @param \OCP\IL10N $l The locale to use |
|
| 274 | + * @return string Formatted date and time string |
|
| 275 | + */ |
|
| 276 | + public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 277 | + return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); |
|
| 278 | + } |
|
| 279 | 279 | |
| 280 | - /** |
|
| 281 | - * Formats the date and time of the given timestamp |
|
| 282 | - * |
|
| 283 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 284 | - * @param string $formatDate See formatDate() for description |
|
| 285 | - * Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable |
|
| 286 | - * @param string $formatTime See formatTime() for description |
|
| 287 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 288 | - * @param \OCP\IL10N $l The locale to use |
|
| 289 | - * @return string Formatted relative date and time string |
|
| 290 | - */ |
|
| 291 | - public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 292 | - if (substr($formatDate, -1) !== '^' && substr($formatDate, -1) !== '*') { |
|
| 293 | - $formatDate .= '^'; |
|
| 294 | - } |
|
| 280 | + /** |
|
| 281 | + * Formats the date and time of the given timestamp |
|
| 282 | + * |
|
| 283 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 284 | + * @param string $formatDate See formatDate() for description |
|
| 285 | + * Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable |
|
| 286 | + * @param string $formatTime See formatTime() for description |
|
| 287 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 288 | + * @param \OCP\IL10N $l The locale to use |
|
| 289 | + * @return string Formatted relative date and time string |
|
| 290 | + */ |
|
| 291 | + public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 292 | + if (substr($formatDate, -1) !== '^' && substr($formatDate, -1) !== '*') { |
|
| 293 | + $formatDate .= '^'; |
|
| 294 | + } |
|
| 295 | 295 | |
| 296 | - return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); |
|
| 297 | - } |
|
| 296 | + return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l); |
|
| 297 | + } |
|
| 298 | 298 | |
| 299 | - /** |
|
| 300 | - * Formats the date and time of the given timestamp |
|
| 301 | - * |
|
| 302 | - * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 303 | - * @param string $type One of 'date', 'datetime' or 'time' |
|
| 304 | - * @param string $format Format string |
|
| 305 | - * @param \DateTimeZone $timeZone The timezone to use |
|
| 306 | - * @param \OCP\IL10N $l The locale to use |
|
| 307 | - * @return string Formatted date and time string |
|
| 308 | - */ |
|
| 309 | - protected function format($timestamp, $type, $format, \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 310 | - $l = $this->getLocale($l); |
|
| 311 | - $timeZone = $this->getTimeZone($timeZone); |
|
| 312 | - $timestamp = $this->getDateTime($timestamp, $timeZone); |
|
| 299 | + /** |
|
| 300 | + * Formats the date and time of the given timestamp |
|
| 301 | + * |
|
| 302 | + * @param int|\DateTime $timestamp Either a Unix timestamp or DateTime object |
|
| 303 | + * @param string $type One of 'date', 'datetime' or 'time' |
|
| 304 | + * @param string $format Format string |
|
| 305 | + * @param \DateTimeZone $timeZone The timezone to use |
|
| 306 | + * @param \OCP\IL10N $l The locale to use |
|
| 307 | + * @return string Formatted date and time string |
|
| 308 | + */ |
|
| 309 | + protected function format($timestamp, $type, $format, \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) { |
|
| 310 | + $l = $this->getLocale($l); |
|
| 311 | + $timeZone = $this->getTimeZone($timeZone); |
|
| 312 | + $timestamp = $this->getDateTime($timestamp, $timeZone); |
|
| 313 | 313 | |
| 314 | - return $l->l($type, $timestamp, array( |
|
| 315 | - 'width' => $format, |
|
| 316 | - )); |
|
| 317 | - } |
|
| 314 | + return $l->l($type, $timestamp, array( |
|
| 315 | + 'width' => $format, |
|
| 316 | + )); |
|
| 317 | + } |
|
| 318 | 318 | } |
@@ -173,7 +173,7 @@ discard block |
||
| 173 | 173 | * If an SQLLogger is configured, the execution is logged. |
| 174 | 174 | * |
| 175 | 175 | * @param string $query The SQL query to execute. |
| 176 | - * @param array $params The parameters to bind to the query, if any. |
|
| 176 | + * @param string[] $params The parameters to bind to the query, if any. |
|
| 177 | 177 | * @param array $types The types the previous parameters are in. |
| 178 | 178 | * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
| 179 | 179 | * |
@@ -218,7 +218,7 @@ discard block |
||
| 218 | 218 | * columns or sequences. |
| 219 | 219 | * |
| 220 | 220 | * @param string $seqName Name of the sequence object from which the ID should be returned. |
| 221 | - * @return string A string representation of the last inserted ID. |
|
| 221 | + * @return integer A string representation of the last inserted ID. |
|
| 222 | 222 | */ |
| 223 | 223 | public function lastInsertId($seqName = null) { |
| 224 | 224 | if ($seqName) { |
@@ -58,7 +58,7 @@ discard block |
||
| 58 | 58 | return parent::connect(); |
| 59 | 59 | } catch (DBALException $e) { |
| 60 | 60 | // throw a new exception to prevent leaking info from the stacktrace |
| 61 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
| 61 | + throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode()); |
|
| 62 | 62 | } |
| 63 | 63 | } |
| 64 | 64 | |
@@ -110,7 +110,7 @@ discard block |
||
| 110 | 110 | // 0 is the method where we use `getCallerBacktrace` |
| 111 | 111 | // 1 is the target method which uses the method we want to log |
| 112 | 112 | if (isset($traces[1])) { |
| 113 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
| 113 | + return $traces[1]['file'].':'.$traces[1]['line']; |
|
| 114 | 114 | } |
| 115 | 115 | |
| 116 | 116 | return ''; |
@@ -156,7 +156,7 @@ discard block |
||
| 156 | 156 | * @param int $offset |
| 157 | 157 | * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
| 158 | 158 | */ |
| 159 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
| 159 | + public function prepare($statement, $limit = null, $offset = null) { |
|
| 160 | 160 | if ($limit === -1) { |
| 161 | 161 | $limit = null; |
| 162 | 162 | } |
@@ -321,7 +321,7 @@ discard block |
||
| 321 | 321 | throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
| 322 | 322 | } |
| 323 | 323 | |
| 324 | - $tableName = $this->tablePrefix . $tableName; |
|
| 324 | + $tableName = $this->tablePrefix.$tableName; |
|
| 325 | 325 | $this->lockedTable = $tableName; |
| 326 | 326 | $this->adapter->lockTable($tableName); |
| 327 | 327 | } |
@@ -342,11 +342,11 @@ discard block |
||
| 342 | 342 | * @return string |
| 343 | 343 | */ |
| 344 | 344 | public function getError() { |
| 345 | - $msg = $this->errorCode() . ': '; |
|
| 345 | + $msg = $this->errorCode().': '; |
|
| 346 | 346 | $errorInfo = $this->errorInfo(); |
| 347 | 347 | if (is_array($errorInfo)) { |
| 348 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
| 349 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
| 348 | + $msg .= 'SQLSTATE = '.$errorInfo[0].', '; |
|
| 349 | + $msg .= 'Driver Code = '.$errorInfo[1].', '; |
|
| 350 | 350 | $msg .= 'Driver Message = '.$errorInfo[2]; |
| 351 | 351 | } |
| 352 | 352 | return $msg; |
@@ -358,9 +358,9 @@ discard block |
||
| 358 | 358 | * @param string $table table name without the prefix |
| 359 | 359 | */ |
| 360 | 360 | public function dropTable($table) { |
| 361 | - $table = $this->tablePrefix . trim($table); |
|
| 361 | + $table = $this->tablePrefix.trim($table); |
|
| 362 | 362 | $schema = $this->getSchemaManager(); |
| 363 | - if($schema->tablesExist(array($table))) { |
|
| 363 | + if ($schema->tablesExist(array($table))) { |
|
| 364 | 364 | $schema->dropTable($table); |
| 365 | 365 | } |
| 366 | 366 | } |
@@ -371,8 +371,8 @@ discard block |
||
| 371 | 371 | * @param string $table table name without the prefix |
| 372 | 372 | * @return bool |
| 373 | 373 | */ |
| 374 | - public function tableExists($table){ |
|
| 375 | - $table = $this->tablePrefix . trim($table); |
|
| 374 | + public function tableExists($table) { |
|
| 375 | + $table = $this->tablePrefix.trim($table); |
|
| 376 | 376 | $schema = $this->getSchemaManager(); |
| 377 | 377 | return $schema->tablesExist(array($table)); |
| 378 | 378 | } |
@@ -383,7 +383,7 @@ discard block |
||
| 383 | 383 | * @return string |
| 384 | 384 | */ |
| 385 | 385 | protected function replaceTablePrefix($statement) { |
| 386 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
| 386 | + return str_replace('*PREFIX*', $this->tablePrefix, $statement); |
|
| 387 | 387 | } |
| 388 | 388 | |
| 389 | 389 | /** |
@@ -42,405 +42,405 @@ |
||
| 42 | 42 | use OCP\PreConditionNotMetException; |
| 43 | 43 | |
| 44 | 44 | class Connection extends \Doctrine\DBAL\Connection implements IDBConnection { |
| 45 | - /** |
|
| 46 | - * @var string $tablePrefix |
|
| 47 | - */ |
|
| 48 | - protected $tablePrefix; |
|
| 49 | - |
|
| 50 | - /** |
|
| 51 | - * @var \OC\DB\Adapter $adapter |
|
| 52 | - */ |
|
| 53 | - protected $adapter; |
|
| 54 | - |
|
| 55 | - protected $lockedTable = null; |
|
| 56 | - |
|
| 57 | - public function connect() { |
|
| 58 | - try { |
|
| 59 | - return parent::connect(); |
|
| 60 | - } catch (DBALException $e) { |
|
| 61 | - // throw a new exception to prevent leaking info from the stacktrace |
|
| 62 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
| 63 | - } |
|
| 64 | - } |
|
| 65 | - |
|
| 66 | - /** |
|
| 67 | - * Returns a QueryBuilder for the connection. |
|
| 68 | - * |
|
| 69 | - * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
| 70 | - */ |
|
| 71 | - public function getQueryBuilder() { |
|
| 72 | - return new QueryBuilder( |
|
| 73 | - $this, |
|
| 74 | - \OC::$server->getSystemConfig(), |
|
| 75 | - \OC::$server->getLogger() |
|
| 76 | - ); |
|
| 77 | - } |
|
| 78 | - |
|
| 79 | - /** |
|
| 80 | - * Gets the QueryBuilder for the connection. |
|
| 81 | - * |
|
| 82 | - * @return \Doctrine\DBAL\Query\QueryBuilder |
|
| 83 | - * @deprecated please use $this->getQueryBuilder() instead |
|
| 84 | - */ |
|
| 85 | - public function createQueryBuilder() { |
|
| 86 | - $backtrace = $this->getCallerBacktrace(); |
|
| 87 | - \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
| 88 | - return parent::createQueryBuilder(); |
|
| 89 | - } |
|
| 90 | - |
|
| 91 | - /** |
|
| 92 | - * Gets the ExpressionBuilder for the connection. |
|
| 93 | - * |
|
| 94 | - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
| 95 | - * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
| 96 | - */ |
|
| 97 | - public function getExpressionBuilder() { |
|
| 98 | - $backtrace = $this->getCallerBacktrace(); |
|
| 99 | - \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
| 100 | - return parent::getExpressionBuilder(); |
|
| 101 | - } |
|
| 102 | - |
|
| 103 | - /** |
|
| 104 | - * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
| 105 | - * |
|
| 106 | - * @return string |
|
| 107 | - */ |
|
| 108 | - protected function getCallerBacktrace() { |
|
| 109 | - $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
| 110 | - |
|
| 111 | - // 0 is the method where we use `getCallerBacktrace` |
|
| 112 | - // 1 is the target method which uses the method we want to log |
|
| 113 | - if (isset($traces[1])) { |
|
| 114 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
| 115 | - } |
|
| 116 | - |
|
| 117 | - return ''; |
|
| 118 | - } |
|
| 119 | - |
|
| 120 | - /** |
|
| 121 | - * @return string |
|
| 122 | - */ |
|
| 123 | - public function getPrefix() { |
|
| 124 | - return $this->tablePrefix; |
|
| 125 | - } |
|
| 126 | - |
|
| 127 | - /** |
|
| 128 | - * Initializes a new instance of the Connection class. |
|
| 129 | - * |
|
| 130 | - * @param array $params The connection parameters. |
|
| 131 | - * @param \Doctrine\DBAL\Driver $driver |
|
| 132 | - * @param \Doctrine\DBAL\Configuration $config |
|
| 133 | - * @param \Doctrine\Common\EventManager $eventManager |
|
| 134 | - * @throws \Exception |
|
| 135 | - */ |
|
| 136 | - public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
| 137 | - EventManager $eventManager = null) |
|
| 138 | - { |
|
| 139 | - if (!isset($params['adapter'])) { |
|
| 140 | - throw new \Exception('adapter not set'); |
|
| 141 | - } |
|
| 142 | - if (!isset($params['tablePrefix'])) { |
|
| 143 | - throw new \Exception('tablePrefix not set'); |
|
| 144 | - } |
|
| 145 | - parent::__construct($params, $driver, $config, $eventManager); |
|
| 146 | - $this->adapter = new $params['adapter']($this); |
|
| 147 | - $this->tablePrefix = $params['tablePrefix']; |
|
| 148 | - |
|
| 149 | - parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
| 150 | - } |
|
| 151 | - |
|
| 152 | - /** |
|
| 153 | - * Prepares an SQL statement. |
|
| 154 | - * |
|
| 155 | - * @param string $statement The SQL statement to prepare. |
|
| 156 | - * @param int $limit |
|
| 157 | - * @param int $offset |
|
| 158 | - * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
| 159 | - */ |
|
| 160 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
| 161 | - if ($limit === -1) { |
|
| 162 | - $limit = null; |
|
| 163 | - } |
|
| 164 | - if (!is_null($limit)) { |
|
| 165 | - $platform = $this->getDatabasePlatform(); |
|
| 166 | - $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
| 167 | - } |
|
| 168 | - $statement = $this->replaceTablePrefix($statement); |
|
| 169 | - $statement = $this->adapter->fixupStatement($statement); |
|
| 170 | - |
|
| 171 | - return parent::prepare($statement); |
|
| 172 | - } |
|
| 173 | - |
|
| 174 | - /** |
|
| 175 | - * Executes an, optionally parametrized, SQL query. |
|
| 176 | - * |
|
| 177 | - * If the query is parametrized, a prepared statement is used. |
|
| 178 | - * If an SQLLogger is configured, the execution is logged. |
|
| 179 | - * |
|
| 180 | - * @param string $query The SQL query to execute. |
|
| 181 | - * @param array $params The parameters to bind to the query, if any. |
|
| 182 | - * @param array $types The types the previous parameters are in. |
|
| 183 | - * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
|
| 184 | - * |
|
| 185 | - * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
|
| 186 | - * |
|
| 187 | - * @throws \Doctrine\DBAL\DBALException |
|
| 188 | - */ |
|
| 189 | - public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) |
|
| 190 | - { |
|
| 191 | - $query = $this->replaceTablePrefix($query); |
|
| 192 | - $query = $this->adapter->fixupStatement($query); |
|
| 193 | - return parent::executeQuery($query, $params, $types, $qcp); |
|
| 194 | - } |
|
| 195 | - |
|
| 196 | - /** |
|
| 197 | - * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
|
| 198 | - * and returns the number of affected rows. |
|
| 199 | - * |
|
| 200 | - * This method supports PDO binding types as well as DBAL mapping types. |
|
| 201 | - * |
|
| 202 | - * @param string $query The SQL query. |
|
| 203 | - * @param array $params The query parameters. |
|
| 204 | - * @param array $types The parameter types. |
|
| 205 | - * |
|
| 206 | - * @return integer The number of affected rows. |
|
| 207 | - * |
|
| 208 | - * @throws \Doctrine\DBAL\DBALException |
|
| 209 | - */ |
|
| 210 | - public function executeUpdate($query, array $params = array(), array $types = array()) |
|
| 211 | - { |
|
| 212 | - $query = $this->replaceTablePrefix($query); |
|
| 213 | - $query = $this->adapter->fixupStatement($query); |
|
| 214 | - return parent::executeUpdate($query, $params, $types); |
|
| 215 | - } |
|
| 216 | - |
|
| 217 | - /** |
|
| 218 | - * Returns the ID of the last inserted row, or the last value from a sequence object, |
|
| 219 | - * depending on the underlying driver. |
|
| 220 | - * |
|
| 221 | - * Note: This method may not return a meaningful or consistent result across different drivers, |
|
| 222 | - * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
|
| 223 | - * columns or sequences. |
|
| 224 | - * |
|
| 225 | - * @param string $seqName Name of the sequence object from which the ID should be returned. |
|
| 226 | - * @return string A string representation of the last inserted ID. |
|
| 227 | - */ |
|
| 228 | - public function lastInsertId($seqName = null) { |
|
| 229 | - if ($seqName) { |
|
| 230 | - $seqName = $this->replaceTablePrefix($seqName); |
|
| 231 | - } |
|
| 232 | - return $this->adapter->lastInsertId($seqName); |
|
| 233 | - } |
|
| 234 | - |
|
| 235 | - // internal use |
|
| 236 | - public function realLastInsertId($seqName = null) { |
|
| 237 | - return parent::lastInsertId($seqName); |
|
| 238 | - } |
|
| 239 | - |
|
| 240 | - /** |
|
| 241 | - * Insert a row if the matching row does not exists. |
|
| 242 | - * |
|
| 243 | - * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
|
| 244 | - * @param array $input data that should be inserted into the table (column name => value) |
|
| 245 | - * @param array|null $compare List of values that should be checked for "if not exists" |
|
| 246 | - * If this is null or an empty array, all keys of $input will be compared |
|
| 247 | - * Please note: text fields (clob) must not be used in the compare array |
|
| 248 | - * @return int number of inserted rows |
|
| 249 | - * @throws \Doctrine\DBAL\DBALException |
|
| 250 | - */ |
|
| 251 | - public function insertIfNotExist($table, $input, array $compare = null) { |
|
| 252 | - return $this->adapter->insertIfNotExist($table, $input, $compare); |
|
| 253 | - } |
|
| 254 | - |
|
| 255 | - private function getType($value) { |
|
| 256 | - if (is_bool($value)) { |
|
| 257 | - return IQueryBuilder::PARAM_BOOL; |
|
| 258 | - } else if (is_int($value)) { |
|
| 259 | - return IQueryBuilder::PARAM_INT; |
|
| 260 | - } else { |
|
| 261 | - return IQueryBuilder::PARAM_STR; |
|
| 262 | - } |
|
| 263 | - } |
|
| 264 | - |
|
| 265 | - /** |
|
| 266 | - * Insert or update a row value |
|
| 267 | - * |
|
| 268 | - * @param string $table |
|
| 269 | - * @param array $keys (column name => value) |
|
| 270 | - * @param array $values (column name => value) |
|
| 271 | - * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
|
| 272 | - * @return int number of new rows |
|
| 273 | - * @throws \Doctrine\DBAL\DBALException |
|
| 274 | - * @throws PreConditionNotMetException |
|
| 275 | - * @suppress SqlInjectionChecker |
|
| 276 | - */ |
|
| 277 | - public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
| 278 | - try { |
|
| 279 | - $insertQb = $this->getQueryBuilder(); |
|
| 280 | - $insertQb->insert($table) |
|
| 281 | - ->values( |
|
| 282 | - array_map(function($value) use ($insertQb) { |
|
| 283 | - return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
| 284 | - }, array_merge($keys, $values)) |
|
| 285 | - ); |
|
| 286 | - return $insertQb->execute(); |
|
| 287 | - } catch (ConstraintViolationException $e) { |
|
| 288 | - // value already exists, try update |
|
| 289 | - $updateQb = $this->getQueryBuilder(); |
|
| 290 | - $updateQb->update($table); |
|
| 291 | - foreach ($values as $name => $value) { |
|
| 292 | - $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
| 293 | - } |
|
| 294 | - $where = $updateQb->expr()->andX(); |
|
| 295 | - $whereValues = array_merge($keys, $updatePreconditionValues); |
|
| 296 | - foreach ($whereValues as $name => $value) { |
|
| 297 | - $where->add($updateQb->expr()->eq( |
|
| 298 | - $name, |
|
| 299 | - $updateQb->createNamedParameter($value, $this->getType($value)), |
|
| 300 | - $this->getType($value) |
|
| 301 | - )); |
|
| 302 | - } |
|
| 303 | - $updateQb->where($where); |
|
| 304 | - $affected = $updateQb->execute(); |
|
| 305 | - |
|
| 306 | - if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
| 307 | - throw new PreConditionNotMetException(); |
|
| 308 | - } |
|
| 309 | - |
|
| 310 | - return 0; |
|
| 311 | - } |
|
| 312 | - } |
|
| 313 | - |
|
| 314 | - /** |
|
| 315 | - * Create an exclusive read+write lock on a table |
|
| 316 | - * |
|
| 317 | - * @param string $tableName |
|
| 318 | - * @throws \BadMethodCallException When trying to acquire a second lock |
|
| 319 | - * @since 9.1.0 |
|
| 320 | - */ |
|
| 321 | - public function lockTable($tableName) { |
|
| 322 | - if ($this->lockedTable !== null) { |
|
| 323 | - throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
| 324 | - } |
|
| 325 | - |
|
| 326 | - $tableName = $this->tablePrefix . $tableName; |
|
| 327 | - $this->lockedTable = $tableName; |
|
| 328 | - $this->adapter->lockTable($tableName); |
|
| 329 | - } |
|
| 330 | - |
|
| 331 | - /** |
|
| 332 | - * Release a previous acquired lock again |
|
| 333 | - * |
|
| 334 | - * @since 9.1.0 |
|
| 335 | - */ |
|
| 336 | - public function unlockTable() { |
|
| 337 | - $this->adapter->unlockTable(); |
|
| 338 | - $this->lockedTable = null; |
|
| 339 | - } |
|
| 340 | - |
|
| 341 | - /** |
|
| 342 | - * returns the error code and message as a string for logging |
|
| 343 | - * works with DoctrineException |
|
| 344 | - * @return string |
|
| 345 | - */ |
|
| 346 | - public function getError() { |
|
| 347 | - $msg = $this->errorCode() . ': '; |
|
| 348 | - $errorInfo = $this->errorInfo(); |
|
| 349 | - if (is_array($errorInfo)) { |
|
| 350 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
| 351 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
| 352 | - $msg .= 'Driver Message = '.$errorInfo[2]; |
|
| 353 | - } |
|
| 354 | - return $msg; |
|
| 355 | - } |
|
| 356 | - |
|
| 357 | - /** |
|
| 358 | - * Drop a table from the database if it exists |
|
| 359 | - * |
|
| 360 | - * @param string $table table name without the prefix |
|
| 361 | - */ |
|
| 362 | - public function dropTable($table) { |
|
| 363 | - $table = $this->tablePrefix . trim($table); |
|
| 364 | - $schema = $this->getSchemaManager(); |
|
| 365 | - if($schema->tablesExist(array($table))) { |
|
| 366 | - $schema->dropTable($table); |
|
| 367 | - } |
|
| 368 | - } |
|
| 369 | - |
|
| 370 | - /** |
|
| 371 | - * Check if a table exists |
|
| 372 | - * |
|
| 373 | - * @param string $table table name without the prefix |
|
| 374 | - * @return bool |
|
| 375 | - */ |
|
| 376 | - public function tableExists($table){ |
|
| 377 | - $table = $this->tablePrefix . trim($table); |
|
| 378 | - $schema = $this->getSchemaManager(); |
|
| 379 | - return $schema->tablesExist(array($table)); |
|
| 380 | - } |
|
| 381 | - |
|
| 382 | - // internal use |
|
| 383 | - /** |
|
| 384 | - * @param string $statement |
|
| 385 | - * @return string |
|
| 386 | - */ |
|
| 387 | - protected function replaceTablePrefix($statement) { |
|
| 388 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
| 389 | - } |
|
| 390 | - |
|
| 391 | - /** |
|
| 392 | - * Check if a transaction is active |
|
| 393 | - * |
|
| 394 | - * @return bool |
|
| 395 | - * @since 8.2.0 |
|
| 396 | - */ |
|
| 397 | - public function inTransaction() { |
|
| 398 | - return $this->getTransactionNestingLevel() > 0; |
|
| 399 | - } |
|
| 400 | - |
|
| 401 | - /** |
|
| 402 | - * Espace a parameter to be used in a LIKE query |
|
| 403 | - * |
|
| 404 | - * @param string $param |
|
| 405 | - * @return string |
|
| 406 | - */ |
|
| 407 | - public function escapeLikeParameter($param) { |
|
| 408 | - return addcslashes($param, '\\_%'); |
|
| 409 | - } |
|
| 410 | - |
|
| 411 | - /** |
|
| 412 | - * Check whether or not the current database support 4byte wide unicode |
|
| 413 | - * |
|
| 414 | - * @return bool |
|
| 415 | - * @since 11.0.0 |
|
| 416 | - */ |
|
| 417 | - public function supports4ByteText() { |
|
| 418 | - if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
| 419 | - return true; |
|
| 420 | - } |
|
| 421 | - return $this->getParams()['charset'] === 'utf8mb4'; |
|
| 422 | - } |
|
| 423 | - |
|
| 424 | - |
|
| 425 | - /** |
|
| 426 | - * Create the schema of the connected database |
|
| 427 | - * |
|
| 428 | - * @return Schema |
|
| 429 | - */ |
|
| 430 | - public function createSchema() { |
|
| 431 | - $schemaManager = new MDB2SchemaManager($this); |
|
| 432 | - $migrator = $schemaManager->getMigrator(); |
|
| 433 | - return $migrator->createSchema(); |
|
| 434 | - } |
|
| 435 | - |
|
| 436 | - /** |
|
| 437 | - * Migrate the database to the given schema |
|
| 438 | - * |
|
| 439 | - * @param Schema $toSchema |
|
| 440 | - */ |
|
| 441 | - public function migrateToSchema(Schema $toSchema) { |
|
| 442 | - $schemaManager = new MDB2SchemaManager($this); |
|
| 443 | - $migrator = $schemaManager->getMigrator(); |
|
| 444 | - $migrator->migrate($toSchema); |
|
| 445 | - } |
|
| 45 | + /** |
|
| 46 | + * @var string $tablePrefix |
|
| 47 | + */ |
|
| 48 | + protected $tablePrefix; |
|
| 49 | + |
|
| 50 | + /** |
|
| 51 | + * @var \OC\DB\Adapter $adapter |
|
| 52 | + */ |
|
| 53 | + protected $adapter; |
|
| 54 | + |
|
| 55 | + protected $lockedTable = null; |
|
| 56 | + |
|
| 57 | + public function connect() { |
|
| 58 | + try { |
|
| 59 | + return parent::connect(); |
|
| 60 | + } catch (DBALException $e) { |
|
| 61 | + // throw a new exception to prevent leaking info from the stacktrace |
|
| 62 | + throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
| 63 | + } |
|
| 64 | + } |
|
| 65 | + |
|
| 66 | + /** |
|
| 67 | + * Returns a QueryBuilder for the connection. |
|
| 68 | + * |
|
| 69 | + * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
| 70 | + */ |
|
| 71 | + public function getQueryBuilder() { |
|
| 72 | + return new QueryBuilder( |
|
| 73 | + $this, |
|
| 74 | + \OC::$server->getSystemConfig(), |
|
| 75 | + \OC::$server->getLogger() |
|
| 76 | + ); |
|
| 77 | + } |
|
| 78 | + |
|
| 79 | + /** |
|
| 80 | + * Gets the QueryBuilder for the connection. |
|
| 81 | + * |
|
| 82 | + * @return \Doctrine\DBAL\Query\QueryBuilder |
|
| 83 | + * @deprecated please use $this->getQueryBuilder() instead |
|
| 84 | + */ |
|
| 85 | + public function createQueryBuilder() { |
|
| 86 | + $backtrace = $this->getCallerBacktrace(); |
|
| 87 | + \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
| 88 | + return parent::createQueryBuilder(); |
|
| 89 | + } |
|
| 90 | + |
|
| 91 | + /** |
|
| 92 | + * Gets the ExpressionBuilder for the connection. |
|
| 93 | + * |
|
| 94 | + * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
| 95 | + * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
| 96 | + */ |
|
| 97 | + public function getExpressionBuilder() { |
|
| 98 | + $backtrace = $this->getCallerBacktrace(); |
|
| 99 | + \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
| 100 | + return parent::getExpressionBuilder(); |
|
| 101 | + } |
|
| 102 | + |
|
| 103 | + /** |
|
| 104 | + * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
| 105 | + * |
|
| 106 | + * @return string |
|
| 107 | + */ |
|
| 108 | + protected function getCallerBacktrace() { |
|
| 109 | + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
| 110 | + |
|
| 111 | + // 0 is the method where we use `getCallerBacktrace` |
|
| 112 | + // 1 is the target method which uses the method we want to log |
|
| 113 | + if (isset($traces[1])) { |
|
| 114 | + return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
| 115 | + } |
|
| 116 | + |
|
| 117 | + return ''; |
|
| 118 | + } |
|
| 119 | + |
|
| 120 | + /** |
|
| 121 | + * @return string |
|
| 122 | + */ |
|
| 123 | + public function getPrefix() { |
|
| 124 | + return $this->tablePrefix; |
|
| 125 | + } |
|
| 126 | + |
|
| 127 | + /** |
|
| 128 | + * Initializes a new instance of the Connection class. |
|
| 129 | + * |
|
| 130 | + * @param array $params The connection parameters. |
|
| 131 | + * @param \Doctrine\DBAL\Driver $driver |
|
| 132 | + * @param \Doctrine\DBAL\Configuration $config |
|
| 133 | + * @param \Doctrine\Common\EventManager $eventManager |
|
| 134 | + * @throws \Exception |
|
| 135 | + */ |
|
| 136 | + public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
| 137 | + EventManager $eventManager = null) |
|
| 138 | + { |
|
| 139 | + if (!isset($params['adapter'])) { |
|
| 140 | + throw new \Exception('adapter not set'); |
|
| 141 | + } |
|
| 142 | + if (!isset($params['tablePrefix'])) { |
|
| 143 | + throw new \Exception('tablePrefix not set'); |
|
| 144 | + } |
|
| 145 | + parent::__construct($params, $driver, $config, $eventManager); |
|
| 146 | + $this->adapter = new $params['adapter']($this); |
|
| 147 | + $this->tablePrefix = $params['tablePrefix']; |
|
| 148 | + |
|
| 149 | + parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
| 150 | + } |
|
| 151 | + |
|
| 152 | + /** |
|
| 153 | + * Prepares an SQL statement. |
|
| 154 | + * |
|
| 155 | + * @param string $statement The SQL statement to prepare. |
|
| 156 | + * @param int $limit |
|
| 157 | + * @param int $offset |
|
| 158 | + * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
| 159 | + */ |
|
| 160 | + public function prepare( $statement, $limit=null, $offset=null ) { |
|
| 161 | + if ($limit === -1) { |
|
| 162 | + $limit = null; |
|
| 163 | + } |
|
| 164 | + if (!is_null($limit)) { |
|
| 165 | + $platform = $this->getDatabasePlatform(); |
|
| 166 | + $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
| 167 | + } |
|
| 168 | + $statement = $this->replaceTablePrefix($statement); |
|
| 169 | + $statement = $this->adapter->fixupStatement($statement); |
|
| 170 | + |
|
| 171 | + return parent::prepare($statement); |
|
| 172 | + } |
|
| 173 | + |
|
| 174 | + /** |
|
| 175 | + * Executes an, optionally parametrized, SQL query. |
|
| 176 | + * |
|
| 177 | + * If the query is parametrized, a prepared statement is used. |
|
| 178 | + * If an SQLLogger is configured, the execution is logged. |
|
| 179 | + * |
|
| 180 | + * @param string $query The SQL query to execute. |
|
| 181 | + * @param array $params The parameters to bind to the query, if any. |
|
| 182 | + * @param array $types The types the previous parameters are in. |
|
| 183 | + * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
|
| 184 | + * |
|
| 185 | + * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
|
| 186 | + * |
|
| 187 | + * @throws \Doctrine\DBAL\DBALException |
|
| 188 | + */ |
|
| 189 | + public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) |
|
| 190 | + { |
|
| 191 | + $query = $this->replaceTablePrefix($query); |
|
| 192 | + $query = $this->adapter->fixupStatement($query); |
|
| 193 | + return parent::executeQuery($query, $params, $types, $qcp); |
|
| 194 | + } |
|
| 195 | + |
|
| 196 | + /** |
|
| 197 | + * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
|
| 198 | + * and returns the number of affected rows. |
|
| 199 | + * |
|
| 200 | + * This method supports PDO binding types as well as DBAL mapping types. |
|
| 201 | + * |
|
| 202 | + * @param string $query The SQL query. |
|
| 203 | + * @param array $params The query parameters. |
|
| 204 | + * @param array $types The parameter types. |
|
| 205 | + * |
|
| 206 | + * @return integer The number of affected rows. |
|
| 207 | + * |
|
| 208 | + * @throws \Doctrine\DBAL\DBALException |
|
| 209 | + */ |
|
| 210 | + public function executeUpdate($query, array $params = array(), array $types = array()) |
|
| 211 | + { |
|
| 212 | + $query = $this->replaceTablePrefix($query); |
|
| 213 | + $query = $this->adapter->fixupStatement($query); |
|
| 214 | + return parent::executeUpdate($query, $params, $types); |
|
| 215 | + } |
|
| 216 | + |
|
| 217 | + /** |
|
| 218 | + * Returns the ID of the last inserted row, or the last value from a sequence object, |
|
| 219 | + * depending on the underlying driver. |
|
| 220 | + * |
|
| 221 | + * Note: This method may not return a meaningful or consistent result across different drivers, |
|
| 222 | + * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
|
| 223 | + * columns or sequences. |
|
| 224 | + * |
|
| 225 | + * @param string $seqName Name of the sequence object from which the ID should be returned. |
|
| 226 | + * @return string A string representation of the last inserted ID. |
|
| 227 | + */ |
|
| 228 | + public function lastInsertId($seqName = null) { |
|
| 229 | + if ($seqName) { |
|
| 230 | + $seqName = $this->replaceTablePrefix($seqName); |
|
| 231 | + } |
|
| 232 | + return $this->adapter->lastInsertId($seqName); |
|
| 233 | + } |
|
| 234 | + |
|
| 235 | + // internal use |
|
| 236 | + public function realLastInsertId($seqName = null) { |
|
| 237 | + return parent::lastInsertId($seqName); |
|
| 238 | + } |
|
| 239 | + |
|
| 240 | + /** |
|
| 241 | + * Insert a row if the matching row does not exists. |
|
| 242 | + * |
|
| 243 | + * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
|
| 244 | + * @param array $input data that should be inserted into the table (column name => value) |
|
| 245 | + * @param array|null $compare List of values that should be checked for "if not exists" |
|
| 246 | + * If this is null or an empty array, all keys of $input will be compared |
|
| 247 | + * Please note: text fields (clob) must not be used in the compare array |
|
| 248 | + * @return int number of inserted rows |
|
| 249 | + * @throws \Doctrine\DBAL\DBALException |
|
| 250 | + */ |
|
| 251 | + public function insertIfNotExist($table, $input, array $compare = null) { |
|
| 252 | + return $this->adapter->insertIfNotExist($table, $input, $compare); |
|
| 253 | + } |
|
| 254 | + |
|
| 255 | + private function getType($value) { |
|
| 256 | + if (is_bool($value)) { |
|
| 257 | + return IQueryBuilder::PARAM_BOOL; |
|
| 258 | + } else if (is_int($value)) { |
|
| 259 | + return IQueryBuilder::PARAM_INT; |
|
| 260 | + } else { |
|
| 261 | + return IQueryBuilder::PARAM_STR; |
|
| 262 | + } |
|
| 263 | + } |
|
| 264 | + |
|
| 265 | + /** |
|
| 266 | + * Insert or update a row value |
|
| 267 | + * |
|
| 268 | + * @param string $table |
|
| 269 | + * @param array $keys (column name => value) |
|
| 270 | + * @param array $values (column name => value) |
|
| 271 | + * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
|
| 272 | + * @return int number of new rows |
|
| 273 | + * @throws \Doctrine\DBAL\DBALException |
|
| 274 | + * @throws PreConditionNotMetException |
|
| 275 | + * @suppress SqlInjectionChecker |
|
| 276 | + */ |
|
| 277 | + public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
| 278 | + try { |
|
| 279 | + $insertQb = $this->getQueryBuilder(); |
|
| 280 | + $insertQb->insert($table) |
|
| 281 | + ->values( |
|
| 282 | + array_map(function($value) use ($insertQb) { |
|
| 283 | + return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
| 284 | + }, array_merge($keys, $values)) |
|
| 285 | + ); |
|
| 286 | + return $insertQb->execute(); |
|
| 287 | + } catch (ConstraintViolationException $e) { |
|
| 288 | + // value already exists, try update |
|
| 289 | + $updateQb = $this->getQueryBuilder(); |
|
| 290 | + $updateQb->update($table); |
|
| 291 | + foreach ($values as $name => $value) { |
|
| 292 | + $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
| 293 | + } |
|
| 294 | + $where = $updateQb->expr()->andX(); |
|
| 295 | + $whereValues = array_merge($keys, $updatePreconditionValues); |
|
| 296 | + foreach ($whereValues as $name => $value) { |
|
| 297 | + $where->add($updateQb->expr()->eq( |
|
| 298 | + $name, |
|
| 299 | + $updateQb->createNamedParameter($value, $this->getType($value)), |
|
| 300 | + $this->getType($value) |
|
| 301 | + )); |
|
| 302 | + } |
|
| 303 | + $updateQb->where($where); |
|
| 304 | + $affected = $updateQb->execute(); |
|
| 305 | + |
|
| 306 | + if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
| 307 | + throw new PreConditionNotMetException(); |
|
| 308 | + } |
|
| 309 | + |
|
| 310 | + return 0; |
|
| 311 | + } |
|
| 312 | + } |
|
| 313 | + |
|
| 314 | + /** |
|
| 315 | + * Create an exclusive read+write lock on a table |
|
| 316 | + * |
|
| 317 | + * @param string $tableName |
|
| 318 | + * @throws \BadMethodCallException When trying to acquire a second lock |
|
| 319 | + * @since 9.1.0 |
|
| 320 | + */ |
|
| 321 | + public function lockTable($tableName) { |
|
| 322 | + if ($this->lockedTable !== null) { |
|
| 323 | + throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
| 324 | + } |
|
| 325 | + |
|
| 326 | + $tableName = $this->tablePrefix . $tableName; |
|
| 327 | + $this->lockedTable = $tableName; |
|
| 328 | + $this->adapter->lockTable($tableName); |
|
| 329 | + } |
|
| 330 | + |
|
| 331 | + /** |
|
| 332 | + * Release a previous acquired lock again |
|
| 333 | + * |
|
| 334 | + * @since 9.1.0 |
|
| 335 | + */ |
|
| 336 | + public function unlockTable() { |
|
| 337 | + $this->adapter->unlockTable(); |
|
| 338 | + $this->lockedTable = null; |
|
| 339 | + } |
|
| 340 | + |
|
| 341 | + /** |
|
| 342 | + * returns the error code and message as a string for logging |
|
| 343 | + * works with DoctrineException |
|
| 344 | + * @return string |
|
| 345 | + */ |
|
| 346 | + public function getError() { |
|
| 347 | + $msg = $this->errorCode() . ': '; |
|
| 348 | + $errorInfo = $this->errorInfo(); |
|
| 349 | + if (is_array($errorInfo)) { |
|
| 350 | + $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
| 351 | + $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
| 352 | + $msg .= 'Driver Message = '.$errorInfo[2]; |
|
| 353 | + } |
|
| 354 | + return $msg; |
|
| 355 | + } |
|
| 356 | + |
|
| 357 | + /** |
|
| 358 | + * Drop a table from the database if it exists |
|
| 359 | + * |
|
| 360 | + * @param string $table table name without the prefix |
|
| 361 | + */ |
|
| 362 | + public function dropTable($table) { |
|
| 363 | + $table = $this->tablePrefix . trim($table); |
|
| 364 | + $schema = $this->getSchemaManager(); |
|
| 365 | + if($schema->tablesExist(array($table))) { |
|
| 366 | + $schema->dropTable($table); |
|
| 367 | + } |
|
| 368 | + } |
|
| 369 | + |
|
| 370 | + /** |
|
| 371 | + * Check if a table exists |
|
| 372 | + * |
|
| 373 | + * @param string $table table name without the prefix |
|
| 374 | + * @return bool |
|
| 375 | + */ |
|
| 376 | + public function tableExists($table){ |
|
| 377 | + $table = $this->tablePrefix . trim($table); |
|
| 378 | + $schema = $this->getSchemaManager(); |
|
| 379 | + return $schema->tablesExist(array($table)); |
|
| 380 | + } |
|
| 381 | + |
|
| 382 | + // internal use |
|
| 383 | + /** |
|
| 384 | + * @param string $statement |
|
| 385 | + * @return string |
|
| 386 | + */ |
|
| 387 | + protected function replaceTablePrefix($statement) { |
|
| 388 | + return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
| 389 | + } |
|
| 390 | + |
|
| 391 | + /** |
|
| 392 | + * Check if a transaction is active |
|
| 393 | + * |
|
| 394 | + * @return bool |
|
| 395 | + * @since 8.2.0 |
|
| 396 | + */ |
|
| 397 | + public function inTransaction() { |
|
| 398 | + return $this->getTransactionNestingLevel() > 0; |
|
| 399 | + } |
|
| 400 | + |
|
| 401 | + /** |
|
| 402 | + * Espace a parameter to be used in a LIKE query |
|
| 403 | + * |
|
| 404 | + * @param string $param |
|
| 405 | + * @return string |
|
| 406 | + */ |
|
| 407 | + public function escapeLikeParameter($param) { |
|
| 408 | + return addcslashes($param, '\\_%'); |
|
| 409 | + } |
|
| 410 | + |
|
| 411 | + /** |
|
| 412 | + * Check whether or not the current database support 4byte wide unicode |
|
| 413 | + * |
|
| 414 | + * @return bool |
|
| 415 | + * @since 11.0.0 |
|
| 416 | + */ |
|
| 417 | + public function supports4ByteText() { |
|
| 418 | + if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
| 419 | + return true; |
|
| 420 | + } |
|
| 421 | + return $this->getParams()['charset'] === 'utf8mb4'; |
|
| 422 | + } |
|
| 423 | + |
|
| 424 | + |
|
| 425 | + /** |
|
| 426 | + * Create the schema of the connected database |
|
| 427 | + * |
|
| 428 | + * @return Schema |
|
| 429 | + */ |
|
| 430 | + public function createSchema() { |
|
| 431 | + $schemaManager = new MDB2SchemaManager($this); |
|
| 432 | + $migrator = $schemaManager->getMigrator(); |
|
| 433 | + return $migrator->createSchema(); |
|
| 434 | + } |
|
| 435 | + |
|
| 436 | + /** |
|
| 437 | + * Migrate the database to the given schema |
|
| 438 | + * |
|
| 439 | + * @param Schema $toSchema |
|
| 440 | + */ |
|
| 441 | + public function migrateToSchema(Schema $toSchema) { |
|
| 442 | + $schemaManager = new MDB2SchemaManager($this); |
|
| 443 | + $migrator = $schemaManager->getMigrator(); |
|
| 444 | + $migrator->migrate($toSchema); |
|
| 445 | + } |
|
| 446 | 446 | } |