diff --git a/apps/accessibility/lib/AccessibilityProvider.php b/apps/accessibility/lib/AccessibilityProvider.php index ef8571528bb..1325c731662 100644 --- a/apps/accessibility/lib/AccessibilityProvider.php +++ b/apps/accessibility/lib/AccessibilityProvider.php @@ -91,5 +91,4 @@ class AccessibilityProvider { ] ]; } - } diff --git a/apps/accessibility/lib/Controller/ConfigController.php b/apps/accessibility/lib/Controller/ConfigController.php index 726cca31076..65173ccacea 100644 --- a/apps/accessibility/lib/Controller/ConfigController.php +++ b/apps/accessibility/lib/Controller/ConfigController.php @@ -107,7 +107,6 @@ class ConfigController extends OCSController { */ public function setConfig(string $key, $value): DataResponse { if ($key === 'theme' || $key === 'font' || $key === 'highcontrast') { - if ($value === false || $value === '') { throw new OCSBadRequestException('Invalid value: ' . $value); } @@ -142,7 +141,6 @@ class ConfigController extends OCSController { */ public function deleteConfig(string $key): DataResponse { if ($key === 'theme' || $key === 'font' || $key === 'highcontrast') { - $this->config->deleteUserValue($this->userId, $this->appName, $key); $userValues = $this->config->getUserKeys($this->userId, $this->appName); @@ -156,5 +154,4 @@ class ConfigController extends OCSController { throw new OCSBadRequestException('Invalid key: ' . $key); } - } diff --git a/apps/accessibility/lib/Migration/RepairUserConfig.php b/apps/accessibility/lib/Migration/RepairUserConfig.php index a479afaf052..49f22860ac1 100644 --- a/apps/accessibility/lib/Migration/RepairUserConfig.php +++ b/apps/accessibility/lib/Migration/RepairUserConfig.php @@ -86,5 +86,4 @@ class RepairUserConfig implements IRepairStep { }); $output->finishProgress(); } - } diff --git a/apps/admin_audit/lib/Actions/Action.php b/apps/admin_audit/lib/Actions/Action.php index 16b2fd759c8..3d8d39f0ce0 100644 --- a/apps/admin_audit/lib/Actions/Action.php +++ b/apps/admin_audit/lib/Actions/Action.php @@ -53,8 +53,8 @@ class Action { array $params, array $elements, bool $obfuscateParameters = false) { - foreach($elements as $element) { - if(!isset($params[$element])) { + foreach ($elements as $element) { + if (!isset($params[$element])) { if ($obfuscateParameters) { $this->logger->critical( '$params["'.$element.'"] was missing.', @@ -74,8 +74,8 @@ class Action { } $replaceArray = []; - foreach($elements as $element) { - if($params[$element] instanceof \DateTime) { + foreach ($elements as $element) { + if ($params[$element] instanceof \DateTime) { $params[$element] = $params[$element]->format('Y-m-d H:i:s'); } $replaceArray[] = $params[$element]; diff --git a/apps/admin_audit/lib/Actions/Sharing.php b/apps/admin_audit/lib/Actions/Sharing.php index fef112e77d3..4359360908e 100644 --- a/apps/admin_audit/lib/Actions/Sharing.php +++ b/apps/admin_audit/lib/Actions/Sharing.php @@ -43,7 +43,7 @@ class Sharing extends Action { * @param array $params */ public function shared(array $params) { - if($params['shareType'] === Share::SHARE_TYPE_LINK) { + if ($params['shareType'] === Share::SHARE_TYPE_LINK) { $this->log( 'The %s "%s" with ID "%s" has been shared via link with permissions "%s" (Share ID: %s)', $params, @@ -55,7 +55,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_USER) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_USER) { $this->log( 'The %s "%s" with ID "%s" has been shared to the user "%s" with permissions "%s" (Share ID: %s)', $params, @@ -68,7 +68,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_GROUP) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_GROUP) { $this->log( 'The %s "%s" with ID "%s" has been shared to the group "%s" with permissions "%s" (Share ID: %s)', $params, @@ -81,7 +81,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_ROOM) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_ROOM) { $this->log( 'The %s "%s" with ID "%s" has been shared to the room "%s" with permissions "%s" (Share ID: %s)', $params, @@ -94,7 +94,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_EMAIL) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_EMAIL) { $this->log( 'The %s "%s" with ID "%s" has been shared to the email recipient "%s" with permissions "%s" (Share ID: %s)', $params, @@ -107,7 +107,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_CIRCLE) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_CIRCLE) { $this->log( 'The %s "%s" with ID "%s" has been shared to the circle "%s" with permissions "%s" (Share ID: %s)', $params, @@ -120,7 +120,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_REMOTE) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_REMOTE) { $this->log( 'The %s "%s" with ID "%s" has been shared to the remote user "%s" with permissions "%s" (Share ID: %s)', $params, @@ -133,7 +133,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_REMOTE_GROUP) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_REMOTE_GROUP) { $this->log( 'The %s "%s" with ID "%s" has been shared to the remote group "%s" with permissions "%s" (Share ID: %s)', $params, @@ -155,7 +155,7 @@ class Sharing extends Action { * @param array $params */ public function unshare(array $params) { - if($params['shareType'] === Share::SHARE_TYPE_LINK) { + if ($params['shareType'] === Share::SHARE_TYPE_LINK) { $this->log( 'The %s "%s" with ID "%s" has been unshared (Share ID: %s)', $params, @@ -166,7 +166,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_USER) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_USER) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the user "%s" (Share ID: %s)', $params, @@ -178,7 +178,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_GROUP) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_GROUP) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the group "%s" (Share ID: %s)', $params, @@ -190,7 +190,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_ROOM) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_ROOM) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the room "%s" (Share ID: %s)', $params, @@ -202,7 +202,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_EMAIL) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_EMAIL) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the email recipient "%s" (Share ID: %s)', $params, @@ -214,7 +214,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_CIRCLE) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_CIRCLE) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the circle "%s" (Share ID: %s)', $params, @@ -226,7 +226,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_REMOTE) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_REMOTE) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the remote user "%s" (Share ID: %s)', $params, @@ -238,7 +238,7 @@ class Sharing extends Action { 'id', ] ); - } elseif($params['shareType'] === Share::SHARE_TYPE_REMOTE_GROUP) { + } elseif ($params['shareType'] === Share::SHARE_TYPE_REMOTE_GROUP) { $this->log( 'The %s "%s" with ID "%s" has been unshared from the remote group "%s" (Share ID: %s)', $params, diff --git a/apps/admin_audit/lib/Actions/Trashbin.php b/apps/admin_audit/lib/Actions/Trashbin.php index 50a3d28a8ad..a3e050a29f5 100644 --- a/apps/admin_audit/lib/Actions/Trashbin.php +++ b/apps/admin_audit/lib/Actions/Trashbin.php @@ -29,7 +29,6 @@ declare(strict_types=1); namespace OCA\AdminAudit\Actions; class Trashbin extends Action { - public function delete(array $params) { $this->log('File "%s" deleted from trash bin.', ['path' => $params['path']], ['path'] @@ -41,5 +40,4 @@ class Trashbin extends Action { ['path' => $params['filePath']], ['path'] ); } - } diff --git a/apps/admin_audit/lib/Actions/UserManagement.php b/apps/admin_audit/lib/Actions/UserManagement.php index ab231a796c7..2bc733b5e1f 100644 --- a/apps/admin_audit/lib/Actions/UserManagement.php +++ b/apps/admin_audit/lib/Actions/UserManagement.php @@ -100,7 +100,7 @@ class UserManagement extends Action { * @param array $params */ public function change(array $params) { - switch($params['feature']) { + switch ($params['feature']) { case 'enabled': $this->log( $params['value'] === true @@ -130,7 +130,7 @@ class UserManagement extends Action { * @param IUser $user */ public function setPassword(IUser $user) { - if($user->getBackendClassName() === 'Database') { + if ($user->getBackendClassName() === 'Database') { $this->log( 'Password of user "%s" has been changed', [ diff --git a/apps/admin_audit/lib/Actions/Versions.php b/apps/admin_audit/lib/Actions/Versions.php index 612e5a8abd2..8594d781d74 100644 --- a/apps/admin_audit/lib/Actions/Versions.php +++ b/apps/admin_audit/lib/Actions/Versions.php @@ -29,7 +29,6 @@ declare(strict_types=1); namespace OCA\AdminAudit\Actions; class Versions extends Action { - public function rollback(array $params) { $this->log('Version "%s" of "%s" was restored.', [ @@ -46,5 +45,4 @@ class Versions extends Action { ['path'] ); } - } diff --git a/apps/admin_audit/lib/AppInfo/Application.php b/apps/admin_audit/lib/AppInfo/Application.php index 7e6c5410f6e..34c432a078e 100644 --- a/apps/admin_audit/lib/AppInfo/Application.php +++ b/apps/admin_audit/lib/AppInfo/Application.php @@ -74,12 +74,11 @@ class Application extends App { $default = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/audit.log'; $logFile = $config->getAppValue('admin_audit', 'logfile', $default); - if($logFile === null) { + if ($logFile === null) { $this->logger = $c->getLogger(); return; } $this->logger = $c->getLogFactory()->getCustomLogger($logFile); - } public function register() { @@ -152,7 +151,6 @@ class Application extends App { } protected function appHooks() { - $eventDispatcher = $this->getContainer()->getServer()->getEventDispatcher(); $eventDispatcher->addListener(ManagerEvent::EVENT_APP_ENABLE, function (ManagerEvent $event) { $appActions = new AppManagement($this->logger); @@ -166,7 +164,6 @@ class Application extends App { $appActions = new AppManagement($this->logger); $appActions->disableApp($event->getAppID()); }); - } protected function consoleHooks() { diff --git a/apps/admin_audit/lib/BackgroundJobs/Rotate.php b/apps/admin_audit/lib/BackgroundJobs/Rotate.php index 566b11cf375..f6e8f6d875b 100644 --- a/apps/admin_audit/lib/BackgroundJobs/Rotate.php +++ b/apps/admin_audit/lib/BackgroundJobs/Rotate.php @@ -38,14 +38,14 @@ class Rotate extends TimedJob { $default = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/audit.log'; $this->filePath = $config->getAppValue('admin_audit', 'logfile', $default); - if($this->filePath === '') { + if ($this->filePath === '') { // default log file, nothing to do return; } $this->maxSize = $config->getSystemValue('log_rotate_size', 100 * 1024 * 1024); - if($this->shouldRotateBySize()) { + if ($this->shouldRotateBySize()) { $this->rotate(); } } diff --git a/apps/admin_audit/tests/Actions/SecurityTest.php b/apps/admin_audit/tests/Actions/SecurityTest.php index 2d7560fac09..63453ca0ea0 100644 --- a/apps/admin_audit/tests/Actions/SecurityTest.php +++ b/apps/admin_audit/tests/Actions/SecurityTest.php @@ -73,5 +73,4 @@ class SecurityTest extends TestCase { $this->security->twofactorSuccess($this->user, ['provider' => 'myprovider']); } - } diff --git a/apps/cloud_federation_api/lib/AppInfo/Application.php b/apps/cloud_federation_api/lib/AppInfo/Application.php index 0f808a88c04..0082217acc0 100644 --- a/apps/cloud_federation_api/lib/AppInfo/Application.php +++ b/apps/cloud_federation_api/lib/AppInfo/Application.php @@ -27,7 +27,6 @@ use OCA\CloudFederationAPI\Capabilities; use OCP\AppFramework\App; class Application extends App { - public function __construct() { parent::__construct('cloud_federation_api'); diff --git a/apps/cloud_federation_api/lib/Config.php b/apps/cloud_federation_api/lib/Config.php index 6553ae7d9b2..86f39f7f177 100644 --- a/apps/cloud_federation_api/lib/Config.php +++ b/apps/cloud_federation_api/lib/Config.php @@ -55,5 +55,4 @@ class Config { return []; } } - } diff --git a/apps/cloud_federation_api/lib/Controller/RequestHandlerController.php b/apps/cloud_federation_api/lib/Controller/RequestHandlerController.php index 3b8b29a49cd..17d2bea323f 100644 --- a/apps/cloud_federation_api/lib/Controller/RequestHandlerController.php +++ b/apps/cloud_federation_api/lib/Controller/RequestHandlerController.php @@ -166,7 +166,7 @@ class RequestHandlerController extends Controller { } if ($shareType === 'group') { - if(!$this->groupManager->groupExists($shareWith)) { + if (!$this->groupManager->groupExists($shareWith)) { return new JSONResponse( ['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()], Http::STATUS_BAD_REQUEST @@ -208,14 +208,13 @@ class RequestHandlerController extends Controller { $user = $this->userManager->get($shareWith); $recipientDisplayName = ''; - if($user) { + if ($user) { $recipientDisplayName = $user->getDisplayName(); } return new JSONResponse( ['recipientDisplayName' => $recipientDisplayName], Http::STATUS_CREATED); - } /** @@ -267,8 +266,7 @@ class RequestHandlerController extends Controller { return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST); } catch (AuthenticationFailedException $e) { return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN); - } - catch (\Exception $e) { + } catch (\Exception $e) { return new JSONResponse( ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()], Http::STATUS_BAD_REQUEST @@ -276,7 +274,6 @@ class RequestHandlerController extends Controller { } return new JSONResponse($result,Http::STATUS_CREATED); - } /** @@ -297,5 +294,4 @@ class RequestHandlerController extends Controller { return $uid; } - } diff --git a/apps/comments/lib/AppInfo/Application.php b/apps/comments/lib/AppInfo/Application.php index a4c01f3f620..9168948d7c8 100644 --- a/apps/comments/lib/AppInfo/Application.php +++ b/apps/comments/lib/AppInfo/Application.php @@ -42,7 +42,6 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Util; class Application extends App { - const APP_ID = 'comments'; public function __construct(array $urlParams = []) { diff --git a/apps/comments/lib/Collaboration/CommentersSorter.php b/apps/comments/lib/Collaboration/CommentersSorter.php index 0db043f918b..80f263acb0c 100644 --- a/apps/comments/lib/Collaboration/CommentersSorter.php +++ b/apps/comments/lib/Collaboration/CommentersSorter.php @@ -48,12 +48,12 @@ class CommentersSorter implements ISorter { */ public function sort(array &$sortArray, array $context) { $commenters = $this->retrieveCommentsInformation($context['itemType'], $context['itemId']); - if(count($commenters) === 0) { + if (count($commenters) === 0) { return; } foreach ($sortArray as $type => &$byType) { - if(!isset($commenters[$type])) { + if (!isset($commenters[$type])) { continue; } @@ -66,7 +66,7 @@ class CommentersSorter implements ISorter { usort($workArray, function ($a, $b) use ($commenters, $type) { $r = $this->compare($a[1], $b[1], $commenters[$type]); - if($r === 0) { + if ($r === 0) { $r = $a[0] - $b[0]; } return $r; @@ -84,16 +84,16 @@ class CommentersSorter implements ISorter { */ protected function retrieveCommentsInformation($type, $id) { $comments = $this->commentsManager->getForObject($type, $id); - if(count($comments) === 0) { + if (count($comments) === 0) { return []; } $actors = []; foreach ($comments as $comment) { - if(!isset($actors[$comment->getActorType()])) { + if (!isset($actors[$comment->getActorType()])) { $actors[$comment->getActorType()] = []; } - if(!isset($actors[$comment->getActorType()][$comment->getActorId()])) { + if (!isset($actors[$comment->getActorType()][$comment->getActorId()])) { $actors[$comment->getActorType()][$comment->getActorId()] = 1; } else { $actors[$comment->getActorType()][$comment->getActorId()]++; diff --git a/apps/comments/lib/Controller/Notifications.php b/apps/comments/lib/Controller/Notifications.php index 6610b56b689..030a221a03c 100644 --- a/apps/comments/lib/Controller/Notifications.php +++ b/apps/comments/lib/Controller/Notifications.php @@ -108,7 +108,7 @@ class Notifications extends Controller { try { $comment = $this->commentsManager->get($id); - if($comment->getObjectType() !== 'files') { + if ($comment->getObjectType() !== 'files') { return new NotFoundResponse(); } $userFolder = $this->rootFolder->getUserFolder($currentUser->getUID()); diff --git a/apps/comments/lib/EventHandler.php b/apps/comments/lib/EventHandler.php index 4364550a222..3d78ad43129 100644 --- a/apps/comments/lib/EventHandler.php +++ b/apps/comments/lib/EventHandler.php @@ -49,13 +49,13 @@ class EventHandler implements ICommentsEventHandler { * @param CommentsEvent $event */ public function handle(CommentsEvent $event) { - if($event->getComment()->getObjectType() !== 'files') { + if ($event->getComment()->getObjectType() !== 'files') { // this is a 'files'-specific Handler return; } $eventType = $event->getEvent(); - if($eventType === CommentsEvent::EVENT_ADD + if ($eventType === CommentsEvent::EVENT_ADD ) { $this->notificationHandler($event); $this->activityHandler($event); @@ -67,7 +67,7 @@ class EventHandler implements ICommentsEventHandler { CommentsEvent::EVENT_UPDATE, CommentsEvent::EVENT_DELETE, ]; - if(in_array($eventType, $applicableEvents)) { + if (in_array($eventType, $applicableEvents)) { $this->notificationHandler($event); return; } diff --git a/apps/comments/lib/Listener/LoadAdditionalScripts.php b/apps/comments/lib/Listener/LoadAdditionalScripts.php index ddaf288394b..2ab67a45ab5 100644 --- a/apps/comments/lib/Listener/LoadAdditionalScripts.php +++ b/apps/comments/lib/Listener/LoadAdditionalScripts.php @@ -43,5 +43,4 @@ class LoadAdditionalScripts implements IEventListener { // we properly split it between files list and sidebar Util::addScript(Application::APP_ID, 'comments'); } - } diff --git a/apps/comments/lib/Listener/LoadSidebarScripts.php b/apps/comments/lib/Listener/LoadSidebarScripts.php index 209c62dc406..29d1f2eb394 100644 --- a/apps/comments/lib/Listener/LoadSidebarScripts.php +++ b/apps/comments/lib/Listener/LoadSidebarScripts.php @@ -42,5 +42,4 @@ class LoadSidebarScripts implements IEventListener { // we properly split it between files list and sidebar Util::addScript(Application::APP_ID, 'comments'); } - } diff --git a/apps/comments/lib/Notification/Listener.php b/apps/comments/lib/Notification/Listener.php index ba645ac5779..f157dd4cd31 100644 --- a/apps/comments/lib/Notification/Listener.php +++ b/apps/comments/lib/Notification/Listener.php @@ -45,7 +45,6 @@ class Listener { IManager $notificationManager, IUserManager $userManager ) { - $this->notificationManager = $notificationManager; $this->userManager = $userManager; } @@ -57,15 +56,15 @@ class Listener { $comment = $event->getComment(); $mentions = $this->extractMentions($comment->getMentions()); - if(empty($mentions)) { + if (empty($mentions)) { // no one to notify return; } $notification = $this->instantiateNotification($comment); - foreach($mentions as $uid) { - if(($comment->getActorType() === 'users' && $uid === $comment->getActorId()) + foreach ($mentions as $uid) { + if (($comment->getActorType() === 'users' && $uid === $comment->getActorId()) || !$this->userManager->userExists($uid) ) { // do not notify unknown users or yourself @@ -73,9 +72,8 @@ class Listener { } $notification->setUser($uid); - if($event->getEvent() === CommentsEvent::EVENT_DELETE - || $event->getEvent() === CommentsEvent::EVENT_PRE_UPDATE) - { + if ($event->getEvent() === CommentsEvent::EVENT_DELETE + || $event->getEvent() === CommentsEvent::EVENT_PRE_UPDATE) { $this->notificationManager->markProcessed($notification); } else { $this->notificationManager->notify($notification); @@ -107,12 +105,12 @@ class Listener { * @return string[] containing the mentions, e.g. ['alice', 'bob'] */ public function extractMentions(array $mentions) { - if(empty($mentions)) { + if (empty($mentions)) { return []; } $uids = []; - foreach($mentions as $mention) { - if($mention['type'] === 'user') { + foreach ($mentions as $mention) { + if ($mention['type'] === 'user') { $uids[] = $mention['id']; } } diff --git a/apps/comments/lib/Notification/Notifier.php b/apps/comments/lib/Notification/Notifier.php index 3b502c0c504..01a003eb8dc 100644 --- a/apps/comments/lib/Notification/Notifier.php +++ b/apps/comments/lib/Notification/Notifier.php @@ -96,12 +96,12 @@ class Notifier implements INotifier { * @since 9.0.0 */ public function prepare(INotification $notification, string $languageCode): INotification { - if($notification->getApp() !== 'comments') { + if ($notification->getApp() !== 'comments') { throw new \InvalidArgumentException(); } try { $comment = $this->commentsManager->get($notification->getObjectId()); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { // needs to be converted to InvalidArgumentException, otherwise none Notifications will be shown at all throw new \InvalidArgumentException('Comment not found', 0, $e); } @@ -118,12 +118,12 @@ class Notifier implements INotifier { switch ($notification->getSubject()) { case 'mention': $parameters = $notification->getSubjectParameters(); - if($parameters[0] !== 'files') { + if ($parameters[0] !== 'files') { throw new \InvalidArgumentException('Unsupported comment object'); } $userFolder = $this->rootFolder->getUserFolder($notification->getUser()); $nodes = $userFolder->getById((int)$parameters[1]); - if(empty($nodes)) { + if (empty($nodes)) { throw new AlreadyProcessedException(); } $node = $nodes[0]; diff --git a/apps/comments/lib/Search/Result.php b/apps/comments/lib/Search/Result.php index 36b0303fc4e..9f0e6936320 100644 --- a/apps/comments/lib/Search/Result.php +++ b/apps/comments/lib/Search/Result.php @@ -29,7 +29,6 @@ use OCP\Files\NotFoundException; use OCP\Search\Result as BaseResult; class Result extends BaseResult { - public $type = 'comment'; public $comment; public $authorId; @@ -108,5 +107,4 @@ class Result extends BaseResult { return $prefix . mb_substr($message, $start, $end - $start) . $suffix; } - } diff --git a/apps/comments/tests/Unit/AppInfo/ApplicationTest.php b/apps/comments/tests/Unit/AppInfo/ApplicationTest.php index d6dd02da24f..dcf17896e49 100644 --- a/apps/comments/tests/Unit/AppInfo/ApplicationTest.php +++ b/apps/comments/tests/Unit/AppInfo/ApplicationTest.php @@ -64,7 +64,7 @@ class ApplicationTest extends TestCase { Notifier::class, ]; - foreach($services as $service) { + foreach ($services as $service) { $s = $c->query($service); $this->assertInstanceOf($service, $s); } diff --git a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php index 82df3dce5e0..f94d935e773 100644 --- a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php +++ b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php @@ -49,9 +49,9 @@ class CommentersSorterTest extends TestCase { */ public function testSort($data) { $commentMocks = []; - foreach($data['actors'] as $actorType => $actors) { + foreach ($data['actors'] as $actorType => $actors) { foreach ($actors as $actorId => $noOfComments) { - for($i=0;$i<$noOfComments;$i++) { + for ($i=0;$i<$noOfComments;$i++) { $mock = $this->createMock(IComment::class); $mock->expects($this->atLeastOnce()) ->method('getActorType') diff --git a/apps/comments/tests/Unit/EventHandlerTest.php b/apps/comments/tests/Unit/EventHandlerTest.php index 3dd5d3d68a2..bb1d660af1e 100644 --- a/apps/comments/tests/Unit/EventHandlerTest.php +++ b/apps/comments/tests/Unit/EventHandlerTest.php @@ -116,5 +116,4 @@ class EventHandlerTest extends TestCase { $this->eventHandler->handle($event); } - } diff --git a/apps/comments/tests/Unit/Notification/NotifierTest.php b/apps/comments/tests/Unit/Notification/NotifierTest.php index 390624c2c85..dbb79176320 100644 --- a/apps/comments/tests/Unit/Notification/NotifierTest.php +++ b/apps/comments/tests/Unit/Notification/NotifierTest.php @@ -616,5 +616,4 @@ class NotifierTest extends TestCase { $this->notifier->prepare($this->notification, $this->lc); } - } diff --git a/apps/contactsinteraction/lib/AddressBook.php b/apps/contactsinteraction/lib/AddressBook.php index 6e015780378..ac433c7ce73 100644 --- a/apps/contactsinteraction/lib/AddressBook.php +++ b/apps/contactsinteraction/lib/AddressBook.php @@ -40,7 +40,6 @@ use Sabre\DAVACL\ACLTrait; use Sabre\DAVACL\IACL; class AddressBook extends ExternalAddressBook implements IACL { - public const URI = 'recent'; use ACLTrait; @@ -174,5 +173,4 @@ class AddressBook extends ExternalAddressBook implements IACL { list(, $uid) = \Sabre\Uri\split($this->principalUri); return $uid; } - } diff --git a/apps/contactsinteraction/lib/AddressBookProvider.php b/apps/contactsinteraction/lib/AddressBookProvider.php index 6d16d1da0a5..4a4d5235a33 100644 --- a/apps/contactsinteraction/lib/AddressBookProvider.php +++ b/apps/contactsinteraction/lib/AddressBookProvider.php @@ -77,5 +77,4 @@ class AddressBookProvider implements IAddressBookProvider { return null; } - } diff --git a/apps/contactsinteraction/lib/AppInfo/Application.php b/apps/contactsinteraction/lib/AppInfo/Application.php index 3a7e0111f6c..a3cb74f408b 100644 --- a/apps/contactsinteraction/lib/AppInfo/Application.php +++ b/apps/contactsinteraction/lib/AppInfo/Application.php @@ -31,7 +31,6 @@ use OCP\Contacts\Events\ContactInteractedWithEvent; use OCP\EventDispatcher\IEventDispatcher; class Application extends App { - public const APP_ID = 'contactsinteraction'; public function __construct() { @@ -43,5 +42,4 @@ class Application extends App { private function registerListeners(IEventDispatcher $dispatcher): void { $dispatcher->addServiceListener(ContactInteractedWithEvent::class, ContactInteractionListener::class); } - } diff --git a/apps/contactsinteraction/lib/BackgroundJob/CleanupJob.php b/apps/contactsinteraction/lib/BackgroundJob/CleanupJob.php index 0efc9d54e81..9e3ab5bf3ca 100644 --- a/apps/contactsinteraction/lib/BackgroundJob/CleanupJob.php +++ b/apps/contactsinteraction/lib/BackgroundJob/CleanupJob.php @@ -48,5 +48,4 @@ class CleanupJob extends TimedJob { $time->modify('-7days'); $this->mapper->cleanUp($time->getTimestamp()); } - } diff --git a/apps/contactsinteraction/lib/Card.php b/apps/contactsinteraction/lib/Card.php index 264f0ebe96f..56dca77b011 100644 --- a/apps/contactsinteraction/lib/Card.php +++ b/apps/contactsinteraction/lib/Card.php @@ -32,7 +32,6 @@ use Sabre\DAVACL\ACLTrait; use Sabre\DAVACL\IACL; class Card implements ICard, IACL { - use ACLTrait; /** @var RecentContact */ @@ -133,5 +132,4 @@ class Card implements ICard, IACL { function getLastModified(): ?int { return $this->contact->getLastContact(); } - } diff --git a/apps/contactsinteraction/lib/Db/CardSearchDao.php b/apps/contactsinteraction/lib/Db/CardSearchDao.php index 8370203bb9e..391dca60fab 100644 --- a/apps/contactsinteraction/lib/Db/CardSearchDao.php +++ b/apps/contactsinteraction/lib/Db/CardSearchDao.php @@ -88,5 +88,4 @@ class CardSearchDao { return $card; } - } diff --git a/apps/contactsinteraction/lib/Db/RecentContact.php b/apps/contactsinteraction/lib/Db/RecentContact.php index 71b58353efb..475de093419 100644 --- a/apps/contactsinteraction/lib/Db/RecentContact.php +++ b/apps/contactsinteraction/lib/Db/RecentContact.php @@ -69,5 +69,4 @@ class RecentContact extends Entity { $this->addType('card', 'string'); $this->addType('lastContact', 'int'); } - } diff --git a/apps/contactsinteraction/lib/Db/RecentContactMapper.php b/apps/contactsinteraction/lib/Db/RecentContactMapper.php index 7fe98e6e4ec..18a5bf6cedc 100644 --- a/apps/contactsinteraction/lib/Db/RecentContactMapper.php +++ b/apps/contactsinteraction/lib/Db/RecentContactMapper.php @@ -31,7 +31,6 @@ use OCP\IDBConnection; use OCP\IUser; class RecentContactMapper extends QBMapper { - public const TABLE_NAME = 'recent_contact'; public function __construct(IDBConnection $db) { @@ -114,5 +113,4 @@ class RecentContactMapper extends QBMapper { $delete->execute(); } - } diff --git a/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php b/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php index 8e801f2e76e..2c1aced82e1 100644 --- a/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php +++ b/apps/contactsinteraction/lib/Listeners/ContactInteractionListener.php @@ -167,5 +167,4 @@ class ContactInteractionListener implements IEventListener { return (new VCard($props))->serialize(); } - } diff --git a/apps/contactsinteraction/lib/Migration/Version010000Date20200304152605.php b/apps/contactsinteraction/lib/Migration/Version010000Date20200304152605.php index fea763106ae..a2f01480562 100644 --- a/apps/contactsinteraction/lib/Migration/Version010000Date20200304152605.php +++ b/apps/contactsinteraction/lib/Migration/Version010000Date20200304152605.php @@ -89,5 +89,4 @@ class Version010000Date20200304152605 extends SimpleMigrationStep { return $schema; } - } diff --git a/apps/dav/appinfo/app.php b/apps/dav/appinfo/app.php index ff5a324946b..5e2d5c5327d 100644 --- a/apps/dav/appinfo/app.php +++ b/apps/dav/appinfo/app.php @@ -97,7 +97,7 @@ $eventHandler = function () use ($app) { $job = $app->getContainer()->query(\OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob::class); $job->run([]); $app->getContainer()->getServer()->getJobList()->setLastRun($job); - } catch(\Exception $ex) { + } catch (\Exception $ex) { $app->getContainer()->getServer()->getLogger()->logException($ex); } }; diff --git a/apps/dav/bin/chunkperf.php b/apps/dav/bin/chunkperf.php index 588fb3258d5..bbb8e6de7ff 100644 --- a/apps/dav/bin/chunkperf.php +++ b/apps/dav/bin/chunkperf.php @@ -65,7 +65,7 @@ $size = filesize($file); $stream = fopen($file, 'r'); $index = 0; -while(!feof($stream)) { +while (!feof($stream)) { request($client, 'PUT', "$uploadUrl/$index", fread($stream, $chunkSize)); $index++; } diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index caad7bf040b..7a80c9b2152 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -53,7 +53,6 @@ use OCP\IUser; use Symfony\Component\EventDispatcher\GenericEvent; class Application extends App { - const APP_ID = 'dav'; /** @@ -265,9 +264,8 @@ class Application extends App { $notificationProviderManager->registerProvider(AudioProvider::class); $notificationProviderManager->registerProvider(EmailProvider::class); $notificationProviderManager->registerProvider(PushProvider::class); - } catch(\Exception $ex) { + } catch (\Exception $ex) { $this->getContainer()->getServer()->getLogger()->logException($ex); } } - } diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index 21ff40ba6b8..79bd07e0835 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -303,5 +303,4 @@ class PluginManager { $this->calendarPlugins[] = $instantiatedCalendarPlugin; } } - } diff --git a/apps/dav/lib/Avatars/AvatarHome.php b/apps/dav/lib/Avatars/AvatarHome.php index 8ee43281b62..73d417dee90 100644 --- a/apps/dav/lib/Avatars/AvatarHome.php +++ b/apps/dav/lib/Avatars/AvatarHome.php @@ -79,7 +79,7 @@ class AvatarHome implements ICollection { return [ $this->getChild('96.jpeg') ]; - } catch(NotFound $exception) { + } catch (NotFound $exception) { return []; } } @@ -116,6 +116,4 @@ class AvatarHome implements ICollection { public function getLastModified() { return null; } - - } diff --git a/apps/dav/lib/Avatars/AvatarNode.php b/apps/dav/lib/Avatars/AvatarNode.php index af3486c4368..a577a591616 100644 --- a/apps/dav/lib/Avatars/AvatarNode.php +++ b/apps/dav/lib/Avatars/AvatarNode.php @@ -93,6 +93,5 @@ class AvatarNode extends File { return (int)$timestamp; } return $timestamp; - } } diff --git a/apps/dav/lib/Avatars/RootCollection.php b/apps/dav/lib/Avatars/RootCollection.php index 6047d1b285e..01f270362b7 100644 --- a/apps/dav/lib/Avatars/RootCollection.php +++ b/apps/dav/lib/Avatars/RootCollection.php @@ -47,5 +47,4 @@ class RootCollection extends AbstractPrincipalCollection { public function getName() { return 'avatars'; } - } diff --git a/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php b/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php index 5d0b25d747b..ad5bf7736ab 100644 --- a/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php @@ -117,7 +117,7 @@ class BuildReminderIndexBackgroundJob extends QueuedJob { ->orderBy('id', 'ASC'); $stmt = $query->execute(); - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $offset = $row['id']; if (is_resource($row['calendardata'])) { $row['calendardata'] = stream_get_contents($row['calendardata']); @@ -126,7 +126,7 @@ class BuildReminderIndexBackgroundJob extends QueuedJob { try { $this->reminderService->onTouchCalendarObject('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $row); - } catch(\Exception $ex) { + } catch (\Exception $ex) { $this->logger->logException($ex); } diff --git a/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php b/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php index d815b999c87..60eae25fdcc 100644 --- a/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php +++ b/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php @@ -48,5 +48,4 @@ class CleanupDirectLinksJob extends TimedJob { // Delete all shares expired 24 hours ago $this->mapper->deleteExpired($this->timeFactory->getTime() - 60*60*24); } - } diff --git a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php index f1d56775903..72401d0f7d1 100644 --- a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php +++ b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php @@ -92,7 +92,7 @@ class RefreshWebcalJob extends Job { try { /** @var DateInterval $dateInterval */ $dateInterval = DateTimeParser::parseDuration($refreshRate); - } catch(InvalidDataException $ex) { + } catch (InvalidDataException $ex) { $this->logger->logException($ex); $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid"); return; @@ -142,7 +142,7 @@ class RefreshWebcalJob extends Job { RefreshWebcalService::STRIP_TODOS, ]; - foreach($forceInt as $column) { + foreach ($forceInt as $column) { if (isset($row[$column])) { $row[$column] = (int) $row[$column]; } diff --git a/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php b/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php index 8396bfb9a5a..d0427b6c5c3 100644 --- a/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php +++ b/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php @@ -64,5 +64,4 @@ class RegisterRegenerateBirthdayCalendars extends QueuedJob { ]); }); } - } diff --git a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php index 7fe107e0004..cd01e7ae94d 100644 --- a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php @@ -106,7 +106,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { string $principalPrefix):void { $backends = $backendManager->getBackends(); - foreach($backends as $backend) { + foreach ($backends as $backend) { $backendId = $backend->getBackendIdentifier(); try { @@ -115,7 +115,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { } else { $list = $backend->listAllRooms(); } - } catch(BackendTemporarilyUnavailableException $ex) { + } catch (BackendTemporarilyUnavailableException $ex) { continue; } @@ -124,7 +124,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { $deletedIds = array_diff($cachedList, $list); $editedIds = array_intersect($list, $cachedList); - foreach($newIds as $newId) { + foreach ($newIds as $newId) { try { if ($backend instanceof IResourceBackend) { $resource = $backend->getResource($newId); @@ -136,7 +136,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { if ($resource instanceof IMetadataProvider) { $metadata = $this->getAllMetadataOfBackend($resource); } - } catch(BackendTemporarilyUnavailableException $ex) { + } catch (BackendTemporarilyUnavailableException $ex) { continue; } @@ -146,7 +146,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { // when an event is actually scheduled with this resource / room } - foreach($deletedIds as $deletedId) { + foreach ($deletedIds as $deletedId) { $id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId); $this->deleteFromCache($dbTable, $id); $this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id); @@ -155,7 +155,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { $this->deleteCalendarDataForResource($principalPrefix, $principalName); } - foreach($editedIds as $editedId) { + foreach ($editedIds as $editedId) { $id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId); try { @@ -169,7 +169,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { if ($resource instanceof IMetadataProvider) { $metadata = $this->getAllMetadataOfBackend($resource); } - } catch(BackendTemporarilyUnavailableException $ex) { + } catch (BackendTemporarilyUnavailableException $ex) { continue; } @@ -220,7 +220,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { string $foreignKey, int $foreignId, array $metadata):void { - foreach($metadata as $key => $value) { + foreach ($metadata as $key => $value) { $query = $this->dbConnection->getQueryBuilder(); $query->insert($table) ->values([ @@ -308,7 +308,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { ->execute(); } - foreach($deletedMetadata as $key => $value) { + foreach ($deletedMetadata as $key => $value) { $query = $this->dbConnection->getQueryBuilder(); $query->delete($dbTable) ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id))) @@ -317,7 +317,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { } $existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata)); - foreach($existingKeys as $existingKey) { + foreach ($existingKeys as $existingKey) { if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) { $query = $this->dbConnection->getQueryBuilder(); $query->update($dbTable) @@ -352,7 +352,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { $keys = $resource->getAllAvailableMetadataKeys(); $metadata = []; - foreach($keys as $key) { + foreach ($keys as $key) { $metadata[$key] = $resource->getMetadataForKey($key); } @@ -376,7 +376,7 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $metadata = []; - foreach($rows as $row) { + foreach ($rows as $row) { $metadata[$row['key']] = $row['value']; } diff --git a/apps/dav/lib/BackgroundJob/UploadCleanup.php b/apps/dav/lib/BackgroundJob/UploadCleanup.php index f5863ddeafe..71b0b515872 100644 --- a/apps/dav/lib/BackgroundJob/UploadCleanup.php +++ b/apps/dav/lib/BackgroundJob/UploadCleanup.php @@ -86,5 +86,4 @@ class UploadCleanup extends TimedJob { $this->jobList->remove(self::class, $argument); } } - } diff --git a/apps/dav/lib/CalDAV/Activity/Backend.php b/apps/dav/lib/CalDAV/Activity/Backend.php index 804b88d0322..4ca5ad17aeb 100644 --- a/apps/dav/lib/CalDAV/Activity/Backend.php +++ b/apps/dav/lib/CalDAV/Activity/Backend.php @@ -469,7 +469,7 @@ class Backend { protected function getObjectNameAndType(array $objectData) { $vObject = Reader::read($objectData['calendardata']); $component = $componentType = null; - foreach($vObject->getComponents() as $component) { + foreach ($vObject->getComponents() as $component) { if (in_array($component->name, ['VEVENT', 'VTODO'])) { $componentType = $component->name; break; diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php b/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php index 0a070810bdb..42b70f0a928 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php @@ -36,7 +36,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory; class Calendar extends Base { - const SUBJECT_ADD = 'calendar_add'; const SUBJECT_UPDATE = 'calendar_update'; const SUBJECT_DELETE = 'calendar_delete'; @@ -111,12 +110,10 @@ class Calendar extends Base { $subject = $this->l->t('{actor} updated calendar {calendar}'); } elseif ($event->getSubject() === self::SUBJECT_UPDATE . '_self') { $subject = $this->l->t('You updated calendar {calendar}'); - } elseif ($event->getSubject() === self::SUBJECT_PUBLISH . '_self') { $subject = $this->l->t('You shared calendar {calendar} as public link'); } elseif ($event->getSubject() === self::SUBJECT_UNPUBLISH . '_self') { $subject = $this->l->t('You removed public link for calendar {calendar}'); - } elseif ($event->getSubject() === self::SUBJECT_SHARE_USER) { $subject = $this->l->t('{actor} shared calendar {calendar} with you'); } elseif ($event->getSubject() === self::SUBJECT_SHARE_USER . '_you') { @@ -131,7 +128,6 @@ class Calendar extends Base { $subject = $this->l->t('{actor} unshared calendar {calendar} from {user}'); } elseif ($event->getSubject() === self::SUBJECT_UNSHARE_USER . '_self') { $subject = $this->l->t('{actor} unshared calendar {calendar} from themselves'); - } elseif ($event->getSubject() === self::SUBJECT_SHARE_GROUP . '_you') { $subject = $this->l->t('You shared calendar {calendar} with group {group}'); } elseif ($event->getSubject() === self::SUBJECT_SHARE_GROUP . '_by') { diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Event.php b/apps/dav/lib/CalDAV/Activity/Provider/Event.php index 9a71553fd31..f044c2f8208 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Event.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Event.php @@ -34,7 +34,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory; class Event extends Base { - const SUBJECT_OBJECT_ADD = 'object_add'; const SUBJECT_OBJECT_UPDATE = 'object_update'; const SUBJECT_OBJECT_DELETE = 'object_delete'; diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Todo.php b/apps/dav/lib/CalDAV/Activity/Provider/Todo.php index 54339566823..dcdc3577233 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Todo.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Todo.php @@ -60,7 +60,6 @@ class Todo extends Event { $subject = $this->l->t('{actor} updated todo {todo} in list {calendar}'); } elseif ($event->getSubject() === self::SUBJECT_OBJECT_UPDATE . '_todo_self') { $subject = $this->l->t('You updated todo {todo} in list {calendar}'); - } elseif ($event->getSubject() === self::SUBJECT_OBJECT_UPDATE . '_todo_completed') { $subject = $this->l->t('{actor} solved todo {todo} in list {calendar}'); } elseif ($event->getSubject() === self::SUBJECT_OBJECT_UPDATE . '_todo_completed_self') { diff --git a/apps/dav/lib/CalDAV/BirthdayService.php b/apps/dav/lib/CalDAV/BirthdayService.php index 208b923f531..2969e5f3ead 100644 --- a/apps/dav/lib/CalDAV/BirthdayService.php +++ b/apps/dav/lib/CalDAV/BirthdayService.php @@ -49,7 +49,6 @@ use Sabre\VObject\Reader; * @package OCA\DAV\CalDAV */ class BirthdayService { - const BIRTHDAY_CALENDAR_URI = 'contact_birthdays'; /** @var GroupPrincipalBackend */ @@ -298,7 +297,7 @@ class BirthdayService { $calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI); $calendarObjects = $this->calDavBackEnd->getCalendarObjects($calendar['id'], CalDavBackend::CALENDAR_TYPE_CALENDAR); - foreach($calendarObjects as $calendarObject) { + foreach ($calendarObjects as $calendarObject) { $this->calDavBackEnd->deleteCalendarObject($calendar['id'], $calendarObject['uri'], CalDavBackend::CALENDAR_TYPE_CALENDAR); } } @@ -311,9 +310,9 @@ class BirthdayService { $principal = 'principals/users/'.$user; $this->ensureCalendarExists($principal); $books = $this->cardDavBackEnd->getAddressBooksForUser($principal); - foreach($books as $book) { + foreach ($books as $book) { $cards = $this->cardDavBackEnd->getCards($book['id']); - foreach($cards as $card) { + foreach ($cards as $card) { $this->onCardChanged((int) $book['id'], $card['uri'], $card['carddata']); } } @@ -455,7 +454,7 @@ class BirthdayService { return ''; } } else { - switch($field) { + switch ($field) { case 'BDAY': return implode('', [ $name, diff --git a/apps/dav/lib/CalDAV/CachedSubscription.php b/apps/dav/lib/CalDAV/CachedSubscription.php index 093a86dcad0..7f81617b9a4 100644 --- a/apps/dav/lib/CalDAV/CachedSubscription.php +++ b/apps/dav/lib/CalDAV/CachedSubscription.php @@ -136,7 +136,6 @@ class CachedSubscription extends \Sabre\CalDAV\Calendar { $obj['acl'] = $this->getChildACL(); return new CachedSubscriptionObject($this->caldavBackend, $this->calendarInfo, $obj); - } /** @@ -146,7 +145,7 @@ class CachedSubscription extends \Sabre\CalDAV\Calendar { $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); $children = []; - foreach($objs as $obj) { + foreach ($objs as $obj) { $children[] = new CachedSubscriptionObject($this->caldavBackend, $this->calendarInfo, $obj); } @@ -161,7 +160,7 @@ class CachedSubscription extends \Sabre\CalDAV\Calendar { $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); $children = []; - foreach($objs as $obj) { + foreach ($objs as $obj) { $children[] = new CachedSubscriptionObject($this->caldavBackend, $this->calendarInfo, $obj); } diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 9b96a4cfaaa..dd3cb048483 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -77,7 +77,6 @@ use Symfony\Component\EventDispatcher\GenericEvent; * @package OCA\DAV\CalDAV */ class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport { - const CALENDAR_TYPE_CALENDAR = 0; const CALENDAR_TYPE_SUBSCRIPTION = 1; @@ -273,8 +272,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt = $query->execute(); $calendars = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { - + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $components = []; if ($row['components']) { $components = explode(',',$row['components']); @@ -291,7 +289,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint), ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } @@ -332,7 +330,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ->execute(); $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { if ($row['principaluri'] === $principalUri) { continue; } @@ -369,7 +367,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $readOnlyPropertyName => $readOnly, ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } @@ -402,7 +400,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ->orderBy('calendarorder', 'ASC'); $stmt = $query->execute(); $calendars = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $components = []; if ($row['components']) { $components = explode(',',$row['components']); @@ -416,7 +414,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components), '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'), ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } @@ -471,7 +469,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar'))) ->execute(); - while($row = $result->fetch()) { + while ($row = $result->fetch()) { list(, $name) = Uri\split($row['principaluri']); $row['displayname'] = $row['displayname'] . "($name)"; $components = []; @@ -491,7 +489,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC, ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } @@ -557,14 +555,13 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC, ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } $this->addOwnerPrincipal($calendar); return $calendar; - } /** @@ -610,7 +607,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'), ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } @@ -660,7 +657,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'), ]; - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { $calendar[$xmlName] = $row[$dbName]; } @@ -704,7 +701,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0', ]; - foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) { + foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) { if (!is_null($row[$dbName])) { $subscription[$xmlName] = $row[$dbName]; } @@ -753,7 +750,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent'); } - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName=>$dbName) { if (isset($properties[$xmlName])) { $values[$dbName] = $properties[$xmlName]; } @@ -761,7 +758,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $query = $this->db->getQueryBuilder(); $query->insert('calendars'); - foreach($values as $column => $value) { + foreach ($values as $column => $value) { $query->setValue($column, $query->createNamedParameter($value)); } $query->execute(); @@ -803,7 +800,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) { $newValues = []; foreach ($mutations as $propertyName => $propertyValue) { - switch ($propertyName) { case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp': $fieldName = 'transparent'; @@ -814,7 +810,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $newValues[$fieldName] = $propertyValue; break; } - } $query = $this->db->getQueryBuilder(); $query->update('calendars'); @@ -923,7 +918,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt = $query->execute(); $result = []; - foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { + foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { $result[] = [ 'id' => $row['id'], 'uri' => $row['uri'], @@ -966,7 +961,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt = $query->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } @@ -1326,7 +1321,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $requirePostFilter = false; } } - } $columns = ['uri']; if ($requirePostFilter) { @@ -1352,13 +1346,13 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt = $query->execute(); $result = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if ($requirePostFilter) { // validateFilterForObject will parse the calendar data // catch parsing errors try { $matches = $this->validateFilterForObject($row, $filters); - } catch(ParseException $ex) { + } catch (ParseException $ex) { $this->logger->logException($ex, [ 'app' => 'dav', 'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri'] @@ -1400,7 +1394,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $uriMapper = []; - foreach($calendars as $calendar) { + foreach ($calendars as $calendar) { if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) { $ownCalendars[] = $calendar['id']; } else { @@ -1415,14 +1409,14 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $query = $this->db->getQueryBuilder(); // Calendar id expressions $calendarExpressions = []; - foreach($ownCalendars as $id) { + foreach ($ownCalendars as $id) { $calendarExpressions[] = $query->expr()->andX( $query->expr()->eq('c.calendarid', $query->createNamedParameter($id)), $query->expr()->eq('c.calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR))); } - foreach($sharedCalendars as $id) { + foreach ($sharedCalendars as $id) { $calendarExpressions[] = $query->expr()->andX( $query->expr()->eq('c.calendarid', $query->createNamedParameter($id)), @@ -1440,7 +1434,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription // Component expressions $compExpressions = []; - foreach($filters['comps'] as $comp) { + foreach ($filters['comps'] as $comp) { $compExpressions[] = $query->expr() ->eq('c.componenttype', $query->createNamedParameter($comp)); } @@ -1459,13 +1453,13 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription } $propParamExpressions = []; - foreach($filters['props'] as $prop) { + foreach ($filters['props'] as $prop) { $propParamExpressions[] = $query->expr()->andX( $query->expr()->eq('i.name', $query->createNamedParameter($prop)), $query->expr()->isNull('i.parameter') ); } - foreach($filters['params'] as $param) { + foreach ($filters['params'] as $param) { $propParamExpressions[] = $query->expr()->andX( $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])), $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter'])) @@ -1497,7 +1491,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt = $query->execute(); $result = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $path = $uriMapper[$row['calendarid']] . '/' . $row['uri']; if (!in_array($path, $result)) { $result[] = $path; @@ -1538,7 +1532,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription } $or = $innerQuery->expr()->orX(); - foreach($searchProperties as $searchProperty) { + foreach ($searchProperties as $searchProperty) { $or->add($innerQuery->expr()->eq('op.name', $outerQuery->createNamedParameter($searchProperty))); } @@ -1557,7 +1551,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) { $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence', $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()))); - } if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) { $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence', @@ -1567,7 +1560,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription if (isset($options['types'])) { $or = $outerQuery->expr()->orX(); - foreach($options['types'] as $type) { + foreach ($options['types'] as $type) { $or->add($outerQuery->expr()->eq('componenttype', $outerQuery->createNamedParameter($type))); } @@ -1592,7 +1585,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $comps = $calendarData->getComponents(); $objects = []; $timezones = []; - foreach($comps as $comp) { + foreach ($comps as $comp) { if ($comp instanceof VTimeZone) { $timezones[] = $comp; } else { @@ -1629,7 +1622,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription }); $validationRules = $comp->getValidationRules(); - foreach($subComponents as $subComponent) { + foreach ($subComponents as $subComponent) { $name = $subComponent->name; if (!isset($data[$name])) { $data[$name] = []; @@ -1637,7 +1630,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $data[$name][] = $this->transformSearchData($subComponent); } - foreach($properties as $property) { + foreach ($properties as $property) { $name = $property->name; if (!isset($validationRules[$name])) { $validationRules[$name] = '*'; @@ -1696,7 +1689,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @return string|null */ function getCalendarObjectByUID($principalUri, $uid) { - $query = $this->db->getQueryBuilder(); $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi') ->from('calendarobjects', 'co') @@ -1789,7 +1781,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ]; if ($syncToken) { - $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`"; if ($limit>0) { $query.= " LIMIT " . (int)$limit; @@ -1803,15 +1794,12 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription // This loop ensures that any duplicates are overwritten, only the // last change on a node is relevant. - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { - + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $changes[$row['uri']] = $row['operation']; - } - foreach($changes as $uri => $operation) { - - switch($operation) { + foreach ($changes as $uri => $operation) { + switch ($operation) { case 1: $result['added'][] = $uri; break; @@ -1822,7 +1810,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $result['deleted'][] = $uri; break; } - } } else { // No synctoken supplied, this is the initial sync. @@ -1833,7 +1820,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN); } return $result; - } /** @@ -1885,8 +1871,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt =$query->execute(); $subscriptions = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { - + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $subscription = [ 'id' => $row['id'], 'uri' => $row['uri'], @@ -1898,14 +1883,13 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0', ]; - foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) { + foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) { if (!is_null($row[$dbName])) { $subscription[$xmlName] = $row[$dbName]; } } $subscriptions[] = $subscription; - } return $subscriptions; @@ -1923,7 +1907,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @return mixed */ function createSubscription($principalUri, $uri, array $properties) { - if (!isset($properties['{http://calendarserver.org/ns/}source'])) { throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions'); } @@ -1937,11 +1920,11 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments']; - foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) { + foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) { if (array_key_exists($xmlName, $properties)) { - $values[$dbName] = $properties[$xmlName]; - if (in_array($dbName, $propertiesBoolean)) { - $values[$dbName] = true; + $values[$dbName] = $properties[$xmlName]; + if (in_array($dbName, $propertiesBoolean)) { + $values[$dbName] = true; } } } @@ -1994,10 +1977,9 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @suppress SqlInjectionChecker */ $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) { - $newValues = []; - foreach($mutations as $propertyName=>$propertyValue) { + foreach ($mutations as $propertyName=>$propertyValue) { if ($propertyName === '{http://calendarserver.org/ns/}source') { $newValues['source'] = $propertyValue->getHref(); } else { @@ -2009,7 +1991,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $query = $this->db->getQueryBuilder(); $query->update('calendarsubscriptions') ->set('lastmodified', $query->createNamedParameter(time())); - foreach($newValues as $fieldName=>$value) { + foreach ($newValues as $fieldName=>$value) { $query->set($fieldName, $query->createNamedParameter($value)); } $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId))) @@ -2024,7 +2006,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ])); return true; - }); } @@ -2090,7 +2071,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } @@ -2122,7 +2103,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ->execute(); $result = []; - foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { + foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { $result[] = [ 'calendardata' => $row['calendardata'], 'uri' => $row['uri'], @@ -2205,7 +2186,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt->execute([ $calendarId ]); - } /** @@ -2224,7 +2204,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @return array */ public function getDenormalizedData($calendarData) { - $vObject = Reader::read($calendarData); $componentType = null; $component = null; @@ -2232,7 +2211,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $lastOccurrence = null; $uid = null; $classification = self::CLASSIFICATION_PUBLIC; - foreach($vObject->getComponents() as $component) { + foreach ($vObject->getComponents() as $component) { if ($component->name!=='VTIMEZONE') { $componentType = $component->name; $uid = (string)$component->UID; @@ -2266,14 +2245,12 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $lastOccurrence = $maxDate->getTimestamp(); } else { $end = $it->getDtEnd(); - while($it->valid() && $end < $maxDate) { + while ($it->valid() && $end < $maxDate) { $end = $it->getDtEnd(); $it->next(); - } $lastOccurrence = $end->getTimestamp(); } - } } @@ -2297,7 +2274,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription 'uid' => $uid, 'classification' => $classification ]; - } /** @@ -2346,7 +2322,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @return string|null */ public function setPublishStatus($value, $calendar) { - $calendarId = $calendar->getResourceId(); $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent( '\OCA\DAV\CalDAV\CalDavBackend::updateShares', @@ -2490,7 +2465,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ->execute(); $ids = $result->fetchAll(); - foreach($ids as $id) { + foreach ($ids as $id) { $this->deleteCalendar($id['id']); } } @@ -2507,7 +2482,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription $stmt = $query->execute(); $uris = []; - foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { + foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { $uris[] = $row['uri']; } $stmt->closeCursor(); @@ -2528,7 +2503,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION))) ->execute(); - foreach($uris as $uri) { + foreach ($uris as $uri) { $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION); } } @@ -2540,8 +2515,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @param string $uriOrigin * @param string $uriDestination */ - public function moveCalendar($uriName, $uriOrigin, $uriDestination) - { + public function moveCalendar($uriName, $uriOrigin, $uriDestination) { $query = $this->db->getQueryBuilder(); $query->update('calendars') ->set('principaluri', $query->createNamedParameter($uriDestination)) diff --git a/apps/dav/lib/CalDAV/Calendar.php b/apps/dav/lib/CalDAV/Calendar.php index 1c7e0106fb6..11b4bfe2c1d 100644 --- a/apps/dav/lib/CalDAV/Calendar.php +++ b/apps/dav/lib/CalDAV/Calendar.php @@ -280,7 +280,6 @@ class Calendar extends \Sabre\CalDAV\Calendar implements IShareable { } public function getChild($name) { - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); if (!$obj) { @@ -294,11 +293,9 @@ class Calendar extends \Sabre\CalDAV\Calendar implements IShareable { $obj['acl'] = $this->getChildACL(); return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj); - } public function getChildren() { - $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); $children = []; foreach ($objs as $obj) { @@ -309,11 +306,9 @@ class Calendar extends \Sabre\CalDAV\Calendar implements IShareable { $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj); } return $children; - } public function getMultipleChildren(array $paths) { - $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths); $children = []; foreach ($objs as $obj) { @@ -324,7 +319,6 @@ class Calendar extends \Sabre\CalDAV\Calendar implements IShareable { $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj); } return $children; - } public function childExists($name) { @@ -340,7 +334,6 @@ class Calendar extends \Sabre\CalDAV\Calendar implements IShareable { } public function calendarQuery(array $filters) { - $uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters); if ($this->isShared()) { return array_filter($uris, function ($uri) { diff --git a/apps/dav/lib/CalDAV/CalendarImpl.php b/apps/dav/lib/CalDAV/CalendarImpl.php index 24121e4fff5..9c7521cb6ba 100644 --- a/apps/dav/lib/CalDAV/CalendarImpl.php +++ b/apps/dav/lib/CalDAV/CalendarImpl.php @@ -101,7 +101,7 @@ class CalendarImpl implements ICalendar { $permissions = $this->calendar->getACL(); $result = 0; foreach ($permissions as $permission) { - switch($permission['privilege']) { + switch ($permission['privilege']) { case '{DAV:}read': $result |= Constants::PERMISSION_READ; break; diff --git a/apps/dav/lib/CalDAV/CalendarManager.php b/apps/dav/lib/CalDAV/CalendarManager.php index b7fff47347f..5b237b0f060 100644 --- a/apps/dav/lib/CalDAV/CalendarManager.php +++ b/apps/dav/lib/CalDAV/CalendarManager.php @@ -66,7 +66,7 @@ class CalendarManager { * @param array $calendars */ private function register(IManager $cm, array $calendars) { - foreach($calendars as $calendarInfo) { + foreach ($calendars as $calendarInfo) { $calendar = new Calendar($this->backend, $calendarInfo, $this->l10n, $this->config); $cm->registerCalendar(new CalendarImpl( $calendar, diff --git a/apps/dav/lib/CalDAV/CalendarObject.php b/apps/dav/lib/CalDAV/CalendarObject.php index 9a402d3bf2c..8bdde256628 100644 --- a/apps/dav/lib/CalDAV/CalendarObject.php +++ b/apps/dav/lib/CalDAV/CalendarObject.php @@ -96,19 +96,19 @@ class CalendarObject extends \Sabre\CalDAV\CalendarObject { private function createConfidentialObject(Component\VCalendar $vObject) { /** @var Component $vElement */ $vElement = null; - if(isset($vObject->VEVENT)) { + if (isset($vObject->VEVENT)) { $vElement = $vObject->VEVENT; } - if(isset($vObject->VJOURNAL)) { + if (isset($vObject->VJOURNAL)) { $vElement = $vObject->VJOURNAL; } - if(isset($vObject->VTODO)) { + if (isset($vObject->VTODO)) { $vElement = $vObject->VTODO; } - if(!is_null($vElement)) { + if (!is_null($vElement)) { foreach ($vElement->children() as &$property) { /** @var Property $property */ - switch($property->name) { + switch ($property->name) { case 'CREATED': case 'DTSTART': case 'RRULE': @@ -136,7 +136,7 @@ class CalendarObject extends \Sabre\CalDAV\CalendarObject { private function removeVAlarms(Component\VCalendar $vObject) { $subcomponents = $vObject->getComponents(); - foreach($subcomponents as $subcomponent) { + foreach ($subcomponents as $subcomponent) { unset($subcomponent->VALARM); } } diff --git a/apps/dav/lib/CalDAV/CalendarRoot.php b/apps/dav/lib/CalDAV/CalendarRoot.php index b7cceec5bd1..ace8482d9c7 100644 --- a/apps/dav/lib/CalDAV/CalendarRoot.php +++ b/apps/dav/lib/CalDAV/CalendarRoot.php @@ -26,7 +26,6 @@ namespace OCA\DAV\CalDAV; class CalendarRoot extends \Sabre\CalDAV\CalendarRoot { - function getChildForPrincipal(array $principal) { return new CalendarHome($this->caldavBackend, $principal); } diff --git a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php index 9f4a84e24c5..52e9c330b2f 100644 --- a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php +++ b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php @@ -93,5 +93,4 @@ class ICSExportPlugin extends \Sabre\CalDAV\ICSExportPlugin { return $vcalendar; } - } diff --git a/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php b/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php index 88d43f0bb55..a42c704f53c 100644 --- a/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php +++ b/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php @@ -89,7 +89,6 @@ abstract class ExternalCalendar implements CalDAV\ICalendar, DAV\IProperties { */ final public function createDirectory($name) { throw new DAV\Exception\MethodNotAllowed('Creating collections in calendar objects is not allowed'); - } /** diff --git a/apps/dav/lib/CalDAV/Integration/ICalendarProvider.php b/apps/dav/lib/CalDAV/Integration/ICalendarProvider.php index b15468e460d..298d877f5da 100644 --- a/apps/dav/lib/CalDAV/Integration/ICalendarProvider.php +++ b/apps/dav/lib/CalDAV/Integration/ICalendarProvider.php @@ -67,5 +67,4 @@ interface ICalendarProvider { * @return ExternalCalendar|null Calendar if it exists, null otherwise */ public function getCalendarInCalendarHome(string $principalUri, string $calendarUri): ?ExternalCalendar; - } diff --git a/apps/dav/lib/CalDAV/Plugin.php b/apps/dav/lib/CalDAV/Plugin.php index b7569cac8a4..6d88244bbf1 100644 --- a/apps/dav/lib/CalDAV/Plugin.php +++ b/apps/dav/lib/CalDAV/Plugin.php @@ -25,7 +25,6 @@ namespace OCA\DAV\CalDAV; class Plugin extends \Sabre\CalDAV\Plugin { - const SYSTEM_CALENDAR_ROOT = 'system-calendars'; /** @@ -52,5 +51,4 @@ class Plugin extends \Sabre\CalDAV\Plugin { return self::SYSTEM_CALENDAR_ROOT . '/calendar-rooms/' . $principalId; } } - } diff --git a/apps/dav/lib/CalDAV/Principal/Collection.php b/apps/dav/lib/CalDAV/Principal/Collection.php index fe345d24801..6e7e20223c8 100644 --- a/apps/dav/lib/CalDAV/Principal/Collection.php +++ b/apps/dav/lib/CalDAV/Principal/Collection.php @@ -39,5 +39,4 @@ class Collection extends \Sabre\CalDAV\Principal\Collection { function getChildForPrincipal(array $principalInfo) { return new User($this->principalBackend, $principalInfo); } - } diff --git a/apps/dav/lib/CalDAV/Principal/User.php b/apps/dav/lib/CalDAV/Principal/User.php index 916dc17ec61..f10773769ca 100644 --- a/apps/dav/lib/CalDAV/Principal/User.php +++ b/apps/dav/lib/CalDAV/Principal/User.php @@ -51,5 +51,4 @@ class User extends \Sabre\CalDAV\Principal\User { ]; return $acl; } - } diff --git a/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php b/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php index df48b9127cc..bc13efc1e5a 100644 --- a/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php +++ b/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php @@ -36,7 +36,6 @@ use OCP\IDBConnection; * @package OCA\DAV\CalDAV\Proxy */ class ProxyMapper extends QBMapper { - const PERMISSION_READ = 1; const PERMISSION_WRITE = 2; diff --git a/apps/dav/lib/CalDAV/PublicCalendarRoot.php b/apps/dav/lib/CalDAV/PublicCalendarRoot.php index 17d0d06711c..a79fffa598a 100644 --- a/apps/dav/lib/CalDAV/PublicCalendarRoot.php +++ b/apps/dav/lib/CalDAV/PublicCalendarRoot.php @@ -53,7 +53,6 @@ class PublicCalendarRoot extends Collection { $this->caldavBackend = $caldavBackend; $this->l10n = $l10n; $this->config = $config; - } /** diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php index 61373327c6c..00dee6b0907 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php @@ -44,7 +44,7 @@ use Sabre\VObject\Property; * * @package OCA\DAV\CalDAV\Reminder\NotificationProvider */ -abstract class AbstractProvider implements INotificationProvider { +abstract class AbstractProvider implements INotificationProvider { /** @var string */ public const NOTIFICATION_TYPE = ''; diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php index 3893d24d802..b675b09e427 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php @@ -99,7 +99,7 @@ class EmailProvider extends AbstractProvider { $sortedByLanguage = $this->sortEMailAddressesByLanguage($emailAddresses, $fallbackLanguage); $organizer = $this->getOrganizerEMailAndNameFromEvent($vevent); - foreach($sortedByLanguage as $lang => $emailAddresses) { + foreach ($sortedByLanguage as $lang => $emailAddresses) { if (!$this->hasL10NForLang($lang)) { $lang = $fallbackLanguage; } @@ -212,7 +212,7 @@ class EmailProvider extends AbstractProvider { string $defaultLanguage):array { $sortedByLanguage = []; - foreach($emails as $emailAddress => $parameters) { + foreach ($emails as $emailAddress => $parameters) { if (isset($parameters['LANG'])) { $lang = $parameters['LANG']; } else { @@ -260,7 +260,7 @@ class EmailProvider extends AbstractProvider { } $emailAddressesOfDelegates = $delegates->getParts(); - foreach($emailAddressesOfDelegates as $addressesOfDelegate) { + foreach ($emailAddressesOfDelegates as $addressesOfDelegate) { if (strcasecmp($addressesOfDelegate, 'mailto:') === 0) { $emailAddresses[substr($addressesOfDelegate, 7)] = []; } @@ -345,7 +345,7 @@ class EmailProvider extends AbstractProvider { private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $users):array { $emailAddresses = []; - foreach($users as $user) { + foreach ($users as $user) { $emailAddress = $user->getEMailAddress(); if ($emailAddress) { $lang = $this->getLangForUser($user); diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/ProviderNotAvailableException.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/ProviderNotAvailableException.php index c83865d1eea..e6c41d02ac4 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/ProviderNotAvailableException.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/ProviderNotAvailableException.php @@ -39,5 +39,4 @@ class ProviderNotAvailableException extends \Exception { public function __construct(string $type) { parent::__construct("No notification provider for type $type available"); } - } diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php index 0074b5c201c..f3da0c03a68 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php @@ -97,7 +97,7 @@ class PushProvider extends AbstractProvider { // Empty Notification ObjectId will be catched by OC\Notification\Notification $eventUUIDHash = $eventUUID ? hash('sha256', $eventUUID, false) : ''; - foreach($users as $user) { + foreach ($users as $user) { /** @var INotification $notification */ $notification = $this->manager->createNotification(); $notification->setApp(Application::APP_ID) diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationTypeDoesNotExistException.php b/apps/dav/lib/CalDAV/Reminder/NotificationTypeDoesNotExistException.php index 2f182937a93..1b144fdbbf0 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationTypeDoesNotExistException.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationTypeDoesNotExistException.php @@ -38,5 +38,4 @@ class NotificationTypeDoesNotExistException extends \Exception { public function __construct(string $type) { parent::__construct("Type $type is not an accepted type of notification"); } - } diff --git a/apps/dav/lib/CalDAV/Reminder/Notifier.php b/apps/dav/lib/CalDAV/Reminder/Notifier.php index c436d4fc329..93390f537ef 100644 --- a/apps/dav/lib/CalDAV/Reminder/Notifier.php +++ b/apps/dav/lib/CalDAV/Reminder/Notifier.php @@ -110,7 +110,7 @@ class Notifier implements INotifier { $this->l10n = $this->l10nFactory->get('dav', $languageCode); // Handle notifier subjects - switch($notification->getSubject()) { + switch ($notification->getSubject()) { case 'calendar_reminder': return $this->prepareReminderNotification($notification); diff --git a/apps/dav/lib/CalDAV/Reminder/ReminderService.php b/apps/dav/lib/CalDAV/Reminder/ReminderService.php index 48feaa0c589..7cf2d52768d 100644 --- a/apps/dav/lib/CalDAV/Reminder/ReminderService.php +++ b/apps/dav/lib/CalDAV/Reminder/ReminderService.php @@ -111,7 +111,7 @@ class ReminderService { public function processReminders():void { $reminders = $this->backend->getRemindersToProcess(); - foreach($reminders as $reminder) { + foreach ($reminders as $reminder) { $calendarData = is_resource($reminder['calendardata']) ? stream_get_contents($reminder['calendardata']) : $reminder['calendardata']; @@ -163,7 +163,7 @@ class ReminderService { return; } - switch($action) { + switch ($action) { case '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject': $this->onCalendarObjectCreate($objectData); break; @@ -206,14 +206,14 @@ class ReminderService { $now = $this->timeFactory->getDateTime(); $isRecurring = $masterItem ? $this->isRecurring($masterItem) : false; - foreach($recurrenceExceptions as $recurrenceException) { + foreach ($recurrenceExceptions as $recurrenceException) { $eventHash = $this->getEventHash($recurrenceException); if (!isset($recurrenceException->VALARM)) { continue; } - foreach($recurrenceException->VALARM as $valarm) { + foreach ($recurrenceException->VALARM as $valarm) { /** @var VAlarm $valarm */ $alarmHash = $this->getAlarmHash($valarm); $triggerTime = $valarm->getEffectiveTriggerTime(); @@ -237,7 +237,7 @@ class ReminderService { return; } - foreach($masterItem->VALARM as $valarm) { + foreach ($masterItem->VALARM as $valarm) { $masterAlarms[] = $this->getAlarmHash($valarm); } @@ -250,7 +250,7 @@ class ReminderService { return; } - while($iterator->valid() && count($processedAlarms) < count($masterAlarms)) { + while ($iterator->valid() && count($processedAlarms) < count($masterAlarms)) { $event = $iterator->getEventObject(); // Recurrence-exceptions are handled separately, so just ignore them here @@ -259,7 +259,7 @@ class ReminderService { continue; } - foreach($event->VALARM as $valarm) { + foreach ($event->VALARM as $valarm) { /** @var VAlarm $valarm */ $alarmHash = $this->getAlarmHash($valarm); if (\in_array($alarmHash, $processedAlarms, true)) { @@ -365,7 +365,7 @@ class ReminderService { ]; $repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0; - for($i = 0; $i < $repeat; $i++) { + for ($i = 0; $i < $repeat; $i++) { if ($valarm->DURATION === null) { continue; } @@ -394,7 +394,7 @@ class ReminderService { * @param array $reminders */ private function writeRemindersToDatabase(array $reminders): void { - foreach($reminders as $reminder) { + foreach ($reminders as $reminder) { $this->backend->insertReminder( (int) $reminder['calendar_id'], (int) $reminder['object_id'], @@ -422,7 +422,6 @@ class ReminderService { !$reminder['is_recurring'] || !$reminder['is_relative'] || $reminder['is_recurrence_exception']) { - $this->backend->removeReminder($reminder['id']); return; } @@ -440,7 +439,7 @@ class ReminderService { return; } - while($iterator->valid()) { + while ($iterator->valid()) { $event = $iterator->getEventObject(); // Recurrence-exceptions are handled separately, so just ignore them here @@ -455,7 +454,7 @@ class ReminderService { continue; } - foreach($event->VALARM as $valarm) { + foreach ($event->VALARM as $valarm) { /** @var VAlarm $valarm */ $alarmHash = $this->getAlarmHash($valarm); if ($alarmHash !== $reminder['alarm_hash']) { @@ -608,7 +607,7 @@ class ReminderService { // Handle recurrence-exceptions first, because recurrence-expansion is expensive if ($isRecurrenceException) { - foreach($recurrenceExceptions as $recurrenceException) { + foreach ($recurrenceExceptions as $recurrenceException) { if ($this->getEffectiveRecurrenceIdOfVEvent($recurrenceException) === $recurrenceId) { return $recurrenceException; } @@ -678,7 +677,7 @@ class ReminderService { try { return VObject\Reader::read($calendarData, VObject\Reader::OPTION_FORGIVING); - } catch(ParseException $ex) { + } catch (ParseException $ex) { return null; } } @@ -707,7 +706,7 @@ class ReminderService { private function getAllVEventsFromVCalendar(VObject\Component\VCalendar $vcalendar):array { $vevents = []; - foreach($vcalendar->children() as $child) { + foreach ($vcalendar->children() as $child) { if (!($child instanceof VObject\Component)) { continue; } diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php index 96b4371bd7c..2a28c9fc02c 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php @@ -125,7 +125,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); $metaDataById = []; - foreach($metaDataRows as $metaDataRow) { + foreach ($metaDataRows as $metaDataRow) { if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) { $metaDataById[$metaDataRow[$this->dbForeignKeyName]] = []; } @@ -134,7 +134,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $metaDataRow['value']; } - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $id = $row['id']; if (isset($metaDataById[$id])) { @@ -142,7 +142,6 @@ abstract class AbstractPrincipalBackend implements BackendInterface { } else { $principals[] = $this->rowToPrincipal($row); } - } $stmt->closeCursor(); @@ -175,7 +174,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } @@ -187,7 +186,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); $metadata = []; - foreach($metaDataRows as $metaDataRow) { + foreach ($metaDataRows as $metaDataRow) { $metadata[$metaDataRow['key']] = $metaDataRow['value']; } @@ -206,7 +205,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } @@ -218,7 +217,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); $metadata = []; - foreach($metaDataRows as $metaDataRow) { + foreach ($metaDataRows as $metaDataRow) { $metadata[$metaDataRow['key']] = $metaDataRow['value']; } @@ -265,7 +264,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $principals = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if (!$this->isAllowedToAccessResource($row, $usersGroups)) { continue; } @@ -284,7 +283,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $principals = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if (!$this->isAllowedToAccessResource($row, $usersGroups)) { continue; } @@ -352,7 +351,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $rows = []; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $id = $row[$this->dbForeignKeyName]; $principalRow = $this->getPrincipalById($id); @@ -388,7 +387,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } if (!$this->isAllowedToAccessResource($row, $usersGroups)) { @@ -415,7 +414,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { $stmt = $query->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } if (!$this->isAllowedToAccessResource($row, $usersGroups)) { diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index 1e7d66d0772..15228f9bc3d 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -316,7 +316,7 @@ class IMipPlugin extends SabreIMipPlugin { $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } - } catch(\Exception $ex) { + } catch (\Exception $ex) { $this->logger->logException($ex, ['app' => 'dav']); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } @@ -358,10 +358,9 @@ class IMipPlugin extends SabreIMipPlugin { $lastOccurrence = $maxDate->getTimestamp(); } else { $end = $it->getDtEnd(); - while($it->valid() && $end < $maxDate) { + while ($it->valid() && $end < $maxDate) { $end = $it->getDtEnd(); $it->next(); - } $lastOccurrence = $end->getTimestamp(); } diff --git a/apps/dav/lib/CalDAV/Search/SearchPlugin.php b/apps/dav/lib/CalDAV/Search/SearchPlugin.php index 86aef36482b..dc3cbdf06ba 100644 --- a/apps/dav/lib/CalDAV/Search/SearchPlugin.php +++ b/apps/dav/lib/CalDAV/Search/SearchPlugin.php @@ -142,7 +142,6 @@ class SearchPlugin extends ServerPlugin { // If we're dealing with the calendar home, the calendar home itself is // responsible for the calendar-query if ($node instanceof CalendarHome && $depth === 2) { - $nodePaths = $node->calendarSearch($report->filters, $report->limit, $report->offset); foreach ($nodePaths as $path) { diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php index ac26e9f94c8..10b065fc426 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php @@ -45,7 +45,6 @@ class ParamFilter implements XmlDeserializable { if (!is_string($property)) { throw new BadRequest('The {' . SearchPlugin::NS_Nextcloud . '}param-filter requires a valid property attribute'); - } if (!is_string($parameter)) { throw new BadRequest('The {' . SearchPlugin::NS_Nextcloud . '}param-filter requires a valid parameter attribute'); diff --git a/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php b/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php index 783c73968be..2cfeb1108f1 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php @@ -111,7 +111,7 @@ class Plugin extends ServerPlugin { } $calendarHome->enableCachedSubscriptionsForThisRequest(); - } catch(NotFound $ex) { + } catch (NotFound $ex) { return; } } diff --git a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php index d00e0886b61..fadf61fd7de 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php @@ -137,7 +137,7 @@ class RefreshWebcalService { $calendarData = $vObject->serialize(); try { $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); - } catch(BadRequest $ex) { + } catch (BadRequest $ex) { $this->logger->logException($ex); } } @@ -148,7 +148,7 @@ class RefreshWebcalService { } $this->updateSubscription($subscription, $mutations); - } catch(ParseException $ex) { + } catch (ParseException $ex) { $subscriptionId = $subscription['id']; $this->logger->logException($ex); @@ -274,11 +274,11 @@ class RefreshWebcalService { $contentType = $response->getHeader('Content-Type'); $contentType = explode(';', $contentType, 2)[0]; - switch($contentType) { + switch ($contentType) { case 'application/calendar+json': try { $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING); - } catch(Exception $ex) { + } catch (Exception $ex) { // In case of a parsing error return null $this->logger->debug("Subscription $subscriptionId could not be parsed"); return null; @@ -288,7 +288,7 @@ class RefreshWebcalService { case 'application/calendar+xml': try { $xCalendar = Reader::readXML($body); - } catch(Exception $ex) { + } catch (Exception $ex) { // In case of a parsing error return null $this->logger->debug("Subscription $subscriptionId could not be parsed"); return null; @@ -299,14 +299,14 @@ class RefreshWebcalService { default: try { $vCalendar = Reader::read($body); - } catch(Exception $ex) { + } catch (Exception $ex) { // In case of a parsing error return null $this->logger->debug("Subscription $subscriptionId could not be parsed"); return null; } return $vCalendar->serialize(); } - } catch(Exception $ex) { + } catch (Exception $ex) { $this->logger->logException($ex); $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error"); @@ -349,7 +349,7 @@ class RefreshWebcalService { // check if new refresh rate is even valid try { DateTimeParser::parseDuration($newRefreshRate); - } catch(InvalidDataException $ex) { + } catch (InvalidDataException $ex) { return null; } diff --git a/apps/dav/lib/Capabilities.php b/apps/dav/lib/Capabilities.php index cd803abcdd3..2ab06117c38 100644 --- a/apps/dav/lib/Capabilities.php +++ b/apps/dav/lib/Capabilities.php @@ -25,7 +25,6 @@ namespace OCA\DAV; use OCP\Capabilities\ICapability; class Capabilities implements ICapability { - public function getCapabilities() { return [ 'dav' => [ diff --git a/apps/dav/lib/CardDAV/AddressBook.php b/apps/dav/lib/CardDAV/AddressBook.php index 010e98d18e7..4a9df56e6b4 100644 --- a/apps/dav/lib/CardDAV/AddressBook.php +++ b/apps/dav/lib/CardDAV/AddressBook.php @@ -155,14 +155,12 @@ class AddressBook extends \Sabre\CardDAV\AddressBook implements IShareable { } public function getChild($name) { - $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'], $name); if (!$obj) { throw new NotFound('Card not found'); } $obj['acl'] = $this->getChildACL(); return new Card($this->carddavBackend, $this->addressBookInfo, $obj); - } /** diff --git a/apps/dav/lib/CardDAV/AddressBookImpl.php b/apps/dav/lib/CardDAV/AddressBookImpl.php index 01ebdcd7019..c63955202f4 100644 --- a/apps/dav/lib/CardDAV/AddressBookImpl.php +++ b/apps/dav/lib/CardDAV/AddressBookImpl.php @@ -65,7 +65,6 @@ class AddressBookImpl implements IAddressBook { array $addressBookInfo, CardDavBackend $backend, IURLGenerator $urlGenerator) { - $this->addressBook = $addressBook; $this->addressBookInfo = $addressBookInfo; $this->backend = $backend; @@ -156,7 +155,6 @@ class AddressBookImpl implements IAddressBook { } return $this->vCard2Array($uri, $vCard); - } /** @@ -167,7 +165,7 @@ class AddressBookImpl implements IAddressBook { $permissions = $this->addressBook->getACL(); $result = 0; foreach ($permissions as $permission) { - switch($permission['privilege']) { + switch ($permission['privilege']) { case '{DAV:}read': $result |= Constants::PERMISSION_READ; break; @@ -261,7 +259,6 @@ class AddressBookImpl implements IAddressBook { ]) . '?photo'; $result['PHOTO'] = 'VALUE=uri:' . $url; - } elseif ($property->name === 'X-SOCIALPROFILE') { $type = $this->getTypeFromProperty($property); @@ -273,7 +270,7 @@ class AddressBookImpl implements IAddressBook { $result[$property->name][$type] = $property->getValue(); } - // The following properties can be set multiple times + // The following properties can be set multiple times } elseif (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL', 'X-ADDRESSBOOKSERVER-MEMBER'])) { if (!isset($result[$property->name])) { $result[$property->name] = []; @@ -288,8 +285,6 @@ class AddressBookImpl implements IAddressBook { } else { $result[$property->name][] = $property->getValue(); } - - } else { $result[$property->name] = $property->getValue(); } diff --git a/apps/dav/lib/CardDAV/AddressBookRoot.php b/apps/dav/lib/CardDAV/AddressBookRoot.php index 254f3e0a8e9..771e44b7d32 100644 --- a/apps/dav/lib/CardDAV/AddressBookRoot.php +++ b/apps/dav/lib/CardDAV/AddressBookRoot.php @@ -61,7 +61,6 @@ class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot { } function getName() { - if ($this->principalPrefix === 'principals') { return parent::getName(); } @@ -70,7 +69,5 @@ class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot { // We are only interested in the second part. return $parts[1]; - } - } diff --git a/apps/dav/lib/CardDAV/CardDavBackend.php b/apps/dav/lib/CardDAV/CardDavBackend.php index 54427404db5..47551c8f170 100644 --- a/apps/dav/lib/CardDAV/CardDavBackend.php +++ b/apps/dav/lib/CardDAV/CardDavBackend.php @@ -55,7 +55,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; class CardDavBackend implements BackendInterface, SyncSupport { - const PERSONAL_ADDRESSBOOK_URI = 'contacts'; const PERSONAL_ADDRESSBOOK_NAME = 'Contacts'; @@ -155,7 +154,7 @@ class CardDavBackend implements BackendInterface, SyncSupport { $addressBooks = []; $result = $query->execute(); - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $addressBooks[$row['id']] = [ 'id' => $row['id'], 'uri' => $row['uri'], @@ -190,7 +189,7 @@ class CardDavBackend implements BackendInterface, SyncSupport { ->execute(); $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { if ($row['principaluri'] === $principalUri) { continue; } @@ -241,7 +240,7 @@ class CardDavBackend implements BackendInterface, SyncSupport { $addressBooks = []; $result = $query->execute(); - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $addressBooks[$row['id']] = [ 'id' => $row['id'], 'uri' => $row['uri'], @@ -364,11 +363,9 @@ class CardDavBackend implements BackendInterface, SyncSupport { * @suppress SqlInjectionChecker */ $propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) { - $updates = []; - foreach($mutations as $property=>$newValue) { - - switch($property) { + foreach ($mutations as $property=>$newValue) { + switch ($property) { case '{DAV:}displayname': $updates['displayname'] = $newValue; break; @@ -380,7 +377,7 @@ class CardDavBackend implements BackendInterface, SyncSupport { $query = $this->db->getQueryBuilder(); $query->update('addressbooks'); - foreach($updates as $key=>$value) { + foreach ($updates as $key=>$value) { $query->set($key, $query->createNamedParameter($value)); } $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId))) @@ -389,7 +386,6 @@ class CardDavBackend implements BackendInterface, SyncSupport { $this->addChange($addressBookId, "", 2); return true; - }); } @@ -411,9 +407,8 @@ class CardDavBackend implements BackendInterface, SyncSupport { 'synctoken' => 1 ]; - foreach($properties as $property=>$newValue) { - - switch($property) { + foreach ($properties as $property=>$newValue) { + switch ($property) { case '{DAV:}displayname': $values['displayname'] = $newValue; break; @@ -423,12 +418,11 @@ class CardDavBackend implements BackendInterface, SyncSupport { default: throw new BadRequest('Unknown property: ' . $property); } - } // Fallback to make sure the displayname is set. Some clients may refuse // to work with addressbooks not having a displayname. - if(is_null($values['displayname'])) { + if (is_null($values['displayname'])) { $values['displayname'] = $url; } @@ -475,7 +469,6 @@ class CardDavBackend implements BackendInterface, SyncSupport { $query->delete($this->dbCardsPropertiesTable) ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))) ->execute(); - } /** @@ -506,7 +499,7 @@ class CardDavBackend implements BackendInterface, SyncSupport { $cards = []; $result = $query->execute(); - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $row['etag'] = '"' . $row['etag'] . '"'; $row['carddata'] = $this->readBlob($row['carddata']); $cards[] = $row; @@ -680,7 +673,6 @@ class CardDavBackend implements BackendInterface, SyncSupport { * @return string */ function updateCard($addressBookId, $cardUri, $cardData) { - $uid = $this->getUID($cardData); $etag = md5($cardData); $query = $this->db->getQueryBuilder(); @@ -804,7 +796,9 @@ class CardDavBackend implements BackendInterface, SyncSupport { $stmt->execute([ $addressBookId ]); $currentToken = $stmt->fetchColumn(0); - if (is_null($currentToken)) return null; + if (is_null($currentToken)) { + return null; + } $result = [ 'syncToken' => $currentToken, @@ -814,7 +808,6 @@ class CardDavBackend implements BackendInterface, SyncSupport { ]; if ($syncToken) { - $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`"; if ($limit>0) { $query .= " LIMIT " . (int)$limit; @@ -828,15 +821,12 @@ class CardDavBackend implements BackendInterface, SyncSupport { // This loop ensures that any duplicates are overwritten, only the // last change on a node is relevant. - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { - + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $changes[$row['uri']] = $row['operation']; - } - foreach($changes as $uri => $operation) { - - switch($operation) { + foreach ($changes as $uri => $operation) { + switch ($operation) { case 1: $result['added'][] = $uri; break; @@ -847,7 +837,6 @@ class CardDavBackend implements BackendInterface, SyncSupport { $result['deleted'][] = $uri; break; } - } } else { // No synctoken supplied, this is the initial sync. @@ -924,7 +913,7 @@ class CardDavBackend implements BackendInterface, SyncSupport { // No need for like when the pattern is empty if ('' !== $pattern) { - if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) { + if (\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) { $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern))); } else { $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))); @@ -1053,11 +1042,11 @@ class CardDavBackend implements BackendInterface, SyncSupport { ); foreach ($vCard->children() as $property) { - if(!in_array($property->name, self::$indexProperties)) { + if (!in_array($property->name, self::$indexProperties)) { continue; } $preferred = 0; - foreach($property->parameters as $parameter) { + foreach ($property->parameters as $parameter) { if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') { $preferred = 1; break; diff --git a/apps/dav/lib/CardDAV/ContactsManager.php b/apps/dav/lib/CardDAV/ContactsManager.php index ae4906c7d15..20616a65edc 100644 --- a/apps/dav/lib/CardDAV/ContactsManager.php +++ b/apps/dav/lib/CardDAV/ContactsManager.php @@ -86,5 +86,4 @@ class ContactsManager { ); } } - } diff --git a/apps/dav/lib/CardDAV/Converter.php b/apps/dav/lib/CardDAV/Converter.php index f3b55ac4a30..8dea77bd0a6 100644 --- a/apps/dav/lib/CardDAV/Converter.php +++ b/apps/dav/lib/CardDAV/Converter.php @@ -50,7 +50,6 @@ class Converter { * @return VCard|null */ public function createCardFromUser(IUser $user) { - $userData = $this->accountManager->getUser($user); $uid = $user->getUID(); @@ -68,7 +67,6 @@ class Converter { } foreach ($userData as $property => $value) { - $shareWithTrustedServers = $value['scope'] === AccountManager::VISIBILITY_CONTACTS_ONLY || $value['scope'] === AccountManager::VISIBILITY_PUBLIC; @@ -150,5 +148,4 @@ class Converter { return null; } } - } diff --git a/apps/dav/lib/CardDAV/HasPhotoPlugin.php b/apps/dav/lib/CardDAV/HasPhotoPlugin.php index 4d4af47f812..3cf9e0f9a61 100644 --- a/apps/dav/lib/CardDAV/HasPhotoPlugin.php +++ b/apps/dav/lib/CardDAV/HasPhotoPlugin.php @@ -57,7 +57,6 @@ class HasPhotoPlugin extends ServerPlugin { * @return void */ function propFind(PropFind $propFind, INode $node) { - $ns = '{http://nextcloud.com/ns}'; if ($node instanceof Card) { @@ -96,7 +95,5 @@ class HasPhotoPlugin extends ServerPlugin { 'name' => $this->getPluginName(), 'description' => 'Return a boolean stating if the vcard have a photo property set or not.' ]; - } - } diff --git a/apps/dav/lib/CardDAV/ImageExportPlugin.php b/apps/dav/lib/CardDAV/ImageExportPlugin.php index 74faa5d7df9..097f52f9576 100644 --- a/apps/dav/lib/CardDAV/ImageExportPlugin.php +++ b/apps/dav/lib/CardDAV/ImageExportPlugin.php @@ -65,7 +65,6 @@ class ImageExportPlugin extends ServerPlugin { * @return bool */ public function httpGet(RequestInterface $request, ResponseInterface $response) { - $queryParams = $request->getQueryParameters(); // TODO: in addition to photo we should also add logo some point in time if (!array_key_exists('photo', $queryParams)) { diff --git a/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php b/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php index 1bcd3fbe419..0bd01184eba 100644 --- a/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php +++ b/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php @@ -87,7 +87,6 @@ abstract class ExternalAddressBook implements IAddressBook, DAV\IProperties { */ final public function createDirectory($name) { throw new DAV\Exception\MethodNotAllowed('Creating collections in address book objects is not allowed'); - } /** @@ -130,5 +129,4 @@ abstract class ExternalAddressBook implements IAddressBook, DAV\IProperties { public static function doesViolateReservedName(string $uri): bool { return strpos($uri, self::PREFIX) === 0; } - } diff --git a/apps/dav/lib/CardDAV/Integration/IAddressBookProvider.php b/apps/dav/lib/CardDAV/Integration/IAddressBookProvider.php index 6542db23650..4fb3ccf5337 100644 --- a/apps/dav/lib/CardDAV/Integration/IAddressBookProvider.php +++ b/apps/dav/lib/CardDAV/Integration/IAddressBookProvider.php @@ -68,5 +68,4 @@ interface IAddressBookProvider { *@since 19.0.0 */ public function getAddressBookInAddressBookHome(string $principalUri, string $uri): ?ExternalAddressBook; - } diff --git a/apps/dav/lib/CardDAV/MultiGetExportPlugin.php b/apps/dav/lib/CardDAV/MultiGetExportPlugin.php index 1a1900b2633..bb911ffc033 100644 --- a/apps/dav/lib/CardDAV/MultiGetExportPlugin.php +++ b/apps/dav/lib/CardDAV/MultiGetExportPlugin.php @@ -55,7 +55,6 @@ class MultiGetExportPlugin extends DAV\ServerPlugin { * @return bool */ public function httpReport(RequestInterface $request, ResponseInterface $response) { - $queryParams = $request->getQueryParameters(); if (!array_key_exists('export', $queryParams)) { return; @@ -118,7 +117,5 @@ class MultiGetExportPlugin extends DAV\ServerPlugin { 'name' => $this->getPluginName(), 'description' => 'Intercept a multi-get request and return a single vcf file instead.' ]; - } - } diff --git a/apps/dav/lib/CardDAV/PhotoCache.php b/apps/dav/lib/CardDAV/PhotoCache.php index 2244e99170c..81067f15b17 100644 --- a/apps/dav/lib/CardDAV/PhotoCache.php +++ b/apps/dav/lib/CardDAV/PhotoCache.php @@ -164,7 +164,6 @@ class PhotoCache { $file = $folder->newFile($path); $file->putContent($photo->data()); } catch (NotPermittedException $e) { - } } @@ -180,7 +179,7 @@ class PhotoCache { try { return $this->appData->getFolder($hash); } catch (NotFoundException $e) { - if($createIfNotExists) { + if ($createIfNotExists) { return $this->appData->newFolder($hash); } else { throw $e; diff --git a/apps/dav/lib/CardDAV/Plugin.php b/apps/dav/lib/CardDAV/Plugin.php index 1d615a13ced..430fda4578d 100644 --- a/apps/dav/lib/CardDAV/Plugin.php +++ b/apps/dav/lib/CardDAV/Plugin.php @@ -30,7 +30,6 @@ use Sabre\DAV\PropFind; use Sabre\DAV\Server; class Plugin extends \Sabre\CardDAV\Plugin { - function initialize(Server $server) { $server->on('propFind', [$this, 'propFind']); parent::initialize($server); @@ -65,11 +64,9 @@ class Plugin extends \Sabre\CardDAV\Plugin { * @return void */ function propFind(PropFind $propFind, INode $node) { - $ns = '{http://owncloud.org/ns}'; if ($node instanceof AddressBook) { - $propFind->handle($ns . 'groups', function () use ($node) { return new Groups($node->getContactsGroups()); }); diff --git a/apps/dav/lib/CardDAV/SyncService.php b/apps/dav/lib/CardDAV/SyncService.php index c0241de2076..daced49373e 100644 --- a/apps/dav/lib/CardDAV/SyncService.php +++ b/apps/dav/lib/CardDAV/SyncService.php @@ -196,17 +196,17 @@ class SyncService { * @param string $syncToken * @return array */ - protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) { - $client = $this->getClient($url, $userName, $sharedSecret); + protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) { + $client = $this->getClient($url, $userName, $sharedSecret); - $body = $this->buildSyncCollectionRequestBody($syncToken); + $body = $this->buildSyncCollectionRequestBody($syncToken); - $response = $client->request('REPORT', $addressBookUrl, $body, [ - 'Content-Type' => 'application/xml' - ]); + $response = $client->request('REPORT', $addressBookUrl, $body, [ + 'Content-Type' => 'application/xml' + ]); - return $this->parseMultiStatus($response['body']); - } + return $this->parseMultiStatus($response['body']); + } /** * @param string $url @@ -225,7 +225,6 @@ class SyncService { * @return string */ private function buildSyncCollectionRequestBody($syncToken) { - $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $root = $dom->createElementNS('DAV:', 'd:sync-collection'); @@ -297,7 +296,7 @@ class SyncService { */ public function deleteUser($userOrCardId) { $systemAddressBook = $this->getLocalSystemAddressBook(); - if ($userOrCardId instanceof IUser){ + if ($userOrCardId instanceof IUser) { $name = $userOrCardId->getBackendClassName(); $userId = $userOrCardId->getUID(); @@ -331,7 +330,7 @@ class SyncService { // remove no longer existing $allCards = $this->backend->getCards($systemAddressBook['id']); - foreach($allCards as $card) { + foreach ($allCards as $card) { $vCard = Reader::read($card['carddata']); $uid = $vCard->UID->getValue(); // load backend and see if user exists @@ -340,6 +339,4 @@ class SyncService { } } } - - } diff --git a/apps/dav/lib/CardDAV/UserAddressBooks.php b/apps/dav/lib/CardDAV/UserAddressBooks.php index 7ebe3b03d11..18fc286fdd9 100644 --- a/apps/dav/lib/CardDAV/UserAddressBooks.php +++ b/apps/dav/lib/CardDAV/UserAddressBooks.php @@ -108,7 +108,6 @@ class UserAddressBooks extends \Sabre\CardDAV\AddressBookHome { * @return array */ function getACL() { - $acl = parent::getACL(); if ($this->principalUri === 'principals/system/system') { $acl[] = [ @@ -120,5 +119,4 @@ class UserAddressBooks extends \Sabre\CardDAV\AddressBookHome { return $acl; } - } diff --git a/apps/dav/lib/Command/ListCalendars.php b/apps/dav/lib/Command/ListCalendars.php index 00f14605eca..e63fbd2066e 100644 --- a/apps/dav/lib/Command/ListCalendars.php +++ b/apps/dav/lib/Command/ListCalendars.php @@ -70,7 +70,7 @@ class ListCalendars extends Command { $calendars = $this->caldav->getCalendarsForUser("principals/users/$user"); $calendarTableData = []; - foreach($calendars as $calendar) { + foreach ($calendars as $calendar) { // skip birthday calendar if ($calendar['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI) { continue; @@ -101,5 +101,4 @@ class ListCalendars extends Command { $output->writeln("User <$user> has no calendars"); } } - } diff --git a/apps/dav/lib/Command/MoveCalendar.php b/apps/dav/lib/Command/MoveCalendar.php index 8399fb5ed32..845e8970698 100644 --- a/apps/dav/lib/Command/MoveCalendar.php +++ b/apps/dav/lib/Command/MoveCalendar.php @@ -146,8 +146,7 @@ class MoveCalendar extends Command { * @param string $userDestination * @param bool $force */ - private function checkShares(array $calendar, string $userOrigin, string $userDestination, bool $force = false) - { + private function checkShares(array $calendar, string $userOrigin, string $userDestination, bool $force = false) { $shares = $this->calDav->getShares($calendar['id']); foreach ($shares as $share) { list(, $prefix, $userOrGroup) = explode('/', $share['href'], 3); diff --git a/apps/dav/lib/Command/RemoveInvalidShares.php b/apps/dav/lib/Command/RemoveInvalidShares.php index 9e3aecc60ed..b72396c96cd 100644 --- a/apps/dav/lib/Command/RemoveInvalidShares.php +++ b/apps/dav/lib/Command/RemoveInvalidShares.php @@ -62,7 +62,7 @@ class RemoveInvalidShares extends Command { ->from('dav_shares') ->execute(); - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $principaluri = $row['principaluri']; $p = $this->principalBackend->getPrincipalByPath($principaluri); if ($p === null) { diff --git a/apps/dav/lib/Comments/CommentNode.php b/apps/dav/lib/Comments/CommentNode.php index d24c41409ba..e02eef1cd51 100644 --- a/apps/dav/lib/Comments/CommentNode.php +++ b/apps/dav/lib/Comments/CommentNode.php @@ -88,8 +88,8 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { $methods = array_filter($methods, function ($name) { return strpos($name, 'get') === 0; }); - foreach($methods as $getter) { - if($getter === 'getMentions') { + foreach ($methods as $getter) { + if ($getter === 'getMentions') { continue; // special treatment } $name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3)); @@ -131,7 +131,7 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { protected function checkWriteAccessOnComment() { $user = $this->userSession->getUser(); - if($this->comment->getActorType() !== 'users' + if ($this->comment->getActorType() !== 'users' || is_null($user) || $this->comment->getActorId() !== $user->getUID() ) { @@ -195,7 +195,7 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { return true; } catch (\Exception $e) { $this->logger->logException($e, ['app' => 'dav/comments']); - if($e instanceof MessageTooLongException) { + if ($e instanceof MessageTooLongException) { $msg = 'Message exceeds allowed character limit of '; throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e); } @@ -239,14 +239,14 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { $properties = array_keys($this->properties); $result = []; - foreach($properties as $property) { + foreach ($properties as $property) { $getter = $this->properties[$property]; - if(method_exists($this->comment, $getter)) { + if (method_exists($this->comment, $getter)) { $result[$property] = $this->comment->$getter(); } } - if($this->comment->getActorType() === 'users') { + if ($this->comment->getActorType() === 'users') { $user = $this->userManager->get($this->comment->getActorId()); $displayName = is_null($user) ? null : $user->getDisplayName(); $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName; @@ -256,13 +256,13 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { $unread = null; $user = $this->userSession->getUser(); - if(!is_null($user)) { + if (!is_null($user)) { $readUntil = $this->commentsManager->getReadMark( $this->comment->getObjectType(), $this->comment->getObjectId(), $user ); - if(is_null($readUntil)) { + if (is_null($readUntil)) { $unread = 'true'; } else { $unread = $this->comment->getCreationDateTime() > $readUntil; diff --git a/apps/dav/lib/Comments/CommentsPlugin.php b/apps/dav/lib/Comments/CommentsPlugin.php index 55b0bdd4b40..ebdf3fde318 100644 --- a/apps/dav/lib/Comments/CommentsPlugin.php +++ b/apps/dav/lib/Comments/CommentsPlugin.php @@ -85,7 +85,7 @@ class CommentsPlugin extends ServerPlugin { */ function initialize(Server $server) { $this->server = $server; - if(strpos($this->server->getRequestUri(), 'comments/') !== 0) { + if (strpos($this->server->getRequestUri(), 'comments/') !== 0) { return; } @@ -158,7 +158,7 @@ class CommentsPlugin extends ServerPlugin { */ public function onReport($reportName, $report, $uri) { $node = $this->server->tree->getNodeForPath($uri); - if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) { + if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) { throw new ReportNotSupported(); } $args = ['limit' => 0, 'offset' => 0, 'datetime' => null]; @@ -168,31 +168,30 @@ class CommentsPlugin extends ServerPlugin { $this::REPORT_PARAM_TIMESTAMP ]; $ns = '{' . $this::NS_OWNCLOUD . '}'; - foreach($report as $parameter) { - if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) { + foreach ($report as $parameter) { + if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) { continue; } $args[str_replace($ns, '', $parameter['name'])] = $parameter['value']; } - if(!is_null($args['datetime'])) { + if (!is_null($args['datetime'])) { $args['datetime'] = new \DateTime($args['datetime']); } $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']); $responses = []; - foreach($results as $node) { + foreach ($results as $node) { $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId(); $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames()); - if(isset($resultSet[0]) && isset($resultSet[0][200])) { + if (isset($resultSet[0]) && isset($resultSet[0][200])) { $responses[] = new Response( $this->server->getBaseUri() . $nodePath, [200 => $resultSet[0][200]], 200 ); } - } $xml = $this->server->xml->write( @@ -228,13 +227,13 @@ class CommentsPlugin extends ServerPlugin { $actorType = $data['actorType']; $actorId = null; - if($actorType === 'users') { + if ($actorType === 'users') { $user = $this->userSession->getUser(); - if(!is_null($user)) { + if (!is_null($user)) { $actorId = $user->getUID(); } } - if(is_null($actorId)) { + if (is_null($actorId)) { throw new BadRequest('Invalid actor "' . $actorType .'"'); } @@ -251,7 +250,4 @@ class CommentsPlugin extends ServerPlugin { throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); } } - - - } diff --git a/apps/dav/lib/Comments/EntityCollection.php b/apps/dav/lib/Comments/EntityCollection.php index fadf83df063..94ee3d2a250 100644 --- a/apps/dav/lib/Comments/EntityCollection.php +++ b/apps/dav/lib/Comments/EntityCollection.php @@ -65,9 +65,9 @@ class EntityCollection extends RootCollection implements IProperties { IUserSession $userSession, ILogger $logger ) { - foreach(['id', 'name'] as $property) { + foreach (['id', 'name'] as $property) { $$property = trim($$property); - if(empty($$property) || !is_string($$property)) { + if (empty($$property) || !is_string($$property)) { throw new \InvalidArgumentException('"' . $property . '" parameter must be non-empty string'); } } @@ -134,7 +134,7 @@ class EntityCollection extends RootCollection implements IProperties { function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null) { $comments = $this->commentsManager->getForObject($this->name, $this->id, $limit, $offset, $datetime); $result = []; - foreach($comments as $comment) { + foreach ($comments as $comment) { $result[] = new CommentNode( $this->commentsManager, $comment, @@ -187,7 +187,7 @@ class EntityCollection extends RootCollection implements IProperties { function getProperties($properties) { $marker = null; $user = $this->userSession->getUser(); - if(!is_null($user)) { + if (!is_null($user)) { $marker = $this->commentsManager->getReadMark($this->name, $this->id, $user); } return [self::PROPERTY_NAME_READ_MARKER => $marker]; diff --git a/apps/dav/lib/Comments/EntityTypeCollection.php b/apps/dav/lib/Comments/EntityTypeCollection.php index 4d282b21184..275b41c87e0 100644 --- a/apps/dav/lib/Comments/EntityTypeCollection.php +++ b/apps/dav/lib/Comments/EntityTypeCollection.php @@ -69,7 +69,7 @@ class EntityTypeCollection extends RootCollection { \Closure $childExistsFunction ) { $name = trim($name); - if(empty($name) || !is_string($name)) { + if (empty($name) || !is_string($name)) { throw new \InvalidArgumentException('"name" parameter must be non-empty string'); } $this->name = $name; @@ -91,7 +91,7 @@ class EntityTypeCollection extends RootCollection { * @throws NotFound */ function getChild($name) { - if(!$this->childExists($name)) { + if (!$this->childExists($name)) { throw new NotFound('Entity does not exist or is not available'); } return new EntityCollection( @@ -123,5 +123,4 @@ class EntityTypeCollection extends RootCollection { function childExists($name) { return call_user_func($this->childExistsFunction, $name); } - } diff --git a/apps/dav/lib/Comments/RootCollection.php b/apps/dav/lib/Comments/RootCollection.php index 1a4cfbedb9e..b6703a13a11 100644 --- a/apps/dav/lib/Comments/RootCollection.php +++ b/apps/dav/lib/Comments/RootCollection.php @@ -70,8 +70,7 @@ class RootCollection implements ICollection { IUserManager $userManager, IUserSession $userSession, EventDispatcherInterface $dispatcher, - ILogger $logger) - { + ILogger $logger) { $this->commentsManager = $commentsManager; $this->logger = $logger; $this->userManager = $userManager; @@ -87,11 +86,11 @@ class RootCollection implements ICollection { * @throws NotAuthenticated */ protected function initCollections() { - if($this->entityTypeCollections !== null) { + if ($this->entityTypeCollections !== null) { return; } $user = $this->userSession->getUser(); - if(is_null($user)) { + if (is_null($user)) { throw new NotAuthenticated(); } @@ -145,7 +144,7 @@ class RootCollection implements ICollection { */ function getChild($name) { $this->initCollections(); - if(isset($this->entityTypeCollections[$name])) { + if (isset($this->entityTypeCollections[$name])) { return $this->entityTypeCollections[$name]; } throw new NotFound('Entity type "' . $name . '" not found."'); diff --git a/apps/dav/lib/Connector/LegacyDAVACL.php b/apps/dav/lib/Connector/LegacyDAVACL.php index d763c4b4a68..8a892a01203 100644 --- a/apps/dav/lib/Connector/LegacyDAVACL.php +++ b/apps/dav/lib/Connector/LegacyDAVACL.php @@ -38,7 +38,9 @@ class LegacyDAVACL extends DavAclPlugin { public function getCurrentUserPrincipals() { $principalV2 = $this->getCurrentUserPrincipal(); - if (is_null($principalV2)) return []; + if (is_null($principalV2)) { + return []; + } $principalV1 = $this->convertPrincipal($principalV2, false); return array_merge( diff --git a/apps/dav/lib/Connector/PublicAuth.php b/apps/dav/lib/Connector/PublicAuth.php index 59c5c0a38e6..cffc295d46d 100644 --- a/apps/dav/lib/Connector/PublicAuth.php +++ b/apps/dav/lib/Connector/PublicAuth.php @@ -98,7 +98,6 @@ class PublicAuth extends AbstractBasic { // check if the share is password protected if ($share->getPassword() !== null) { - if ($share->getShareType() === IShare::TYPE_LINK || $share->getShareType() === IShare::TYPE_EMAIL || $share->getShareType() === IShare::TYPE_CIRCLE) { diff --git a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php index ee15d137b63..28264b05057 100644 --- a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php @@ -72,7 +72,6 @@ class AppEnabledPlugin extends ServerPlugin { * @return void */ public function initialize(\Sabre\DAV\Server $server) { - $this->server = $server; $this->server->on('beforeMethod:*', [$this, 'checkAppEnabled'], 30); } diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index 15ea9447ffd..8457670be6b 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -50,8 +50,6 @@ use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; class Auth extends AbstractBasic { - - const DAV_AUTHENTICATED = 'AUTHENTICATED_TO_DAV_BACKEND'; /** @var ISession */ @@ -173,12 +171,12 @@ class Auth extends AbstractBasic { */ private function requiresCSRFCheck() { // GET requires no check at all - if($this->request->getMethod() === 'GET') { + if ($this->request->getMethod() === 'GET') { return false; } // Official Nextcloud clients require no checks - if($this->request->isUserAgent([ + if ($this->request->isUserAgent([ IRequest::USER_AGENT_CLIENT_DESKTOP, IRequest::USER_AGENT_CLIENT_ANDROID, IRequest::USER_AGENT_CLIENT_IOS, @@ -187,17 +185,17 @@ class Auth extends AbstractBasic { } // If not logged-in no check is required - if(!$this->userSession->isLoggedIn()) { + if (!$this->userSession->isLoggedIn()) { return false; } // POST always requires a check - if($this->request->getMethod() === 'POST') { + if ($this->request->getMethod() === 'POST') { return true; } // If logged-in AND DAV authenticated no check is required - if($this->userSession->isLoggedIn() && + if ($this->userSession->isLoggedIn() && $this->isDavAuthenticated($this->userSession->getUser()->getUID())) { return false; } @@ -214,10 +212,10 @@ class Auth extends AbstractBasic { private function auth(RequestInterface $request, ResponseInterface $response) { $forcedLogout = false; - if(!$this->request->passesCSRFCheck() && + if (!$this->request->passesCSRFCheck() && $this->requiresCSRFCheck()) { // In case of a fail with POST we need to recheck the credentials - if($this->request->getMethod() === 'POST') { + if ($this->request->getMethod() === 'POST') { $forcedLogout = true; } else { $response->setStatus(401); @@ -225,10 +223,10 @@ class Auth extends AbstractBasic { } } - if($forcedLogout) { + if ($forcedLogout) { $this->userSession->logout(); } else { - if($this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) { + if ($this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) { throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.'); } if ( @@ -254,7 +252,7 @@ class Auth extends AbstractBasic { } $data = parent::check($request, $response); - if($data[0] === true) { + if ($data[0] === true) { $startPos = strrpos($data[1], '/') + 1; $user = $this->userSession->getUser()->getUID(); $data[1] = substr_replace($data[1], $user, $startPos); diff --git a/apps/dav/lib/Connector/Sabre/BearerAuth.php b/apps/dav/lib/Connector/Sabre/BearerAuth.php index 61945a51d7b..cc01874e541 100644 --- a/apps/dav/lib/Connector/Sabre/BearerAuth.php +++ b/apps/dav/lib/Connector/Sabre/BearerAuth.php @@ -72,10 +72,10 @@ class BearerAuth extends AbstractBearer { public function validateBearerToken($bearerToken) { \OC_Util::setupFS(); - if(!$this->userSession->isLoggedIn()) { + if (!$this->userSession->isLoggedIn()) { $this->userSession->tryTokenLogin($this->request); } - if($this->userSession->isLoggedIn()) { + if ($this->userSession->isLoggedIn()) { return $this->setupUserFs($this->userSession->getUser()->getUID()); } diff --git a/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php b/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php index 1ddebe06ee1..b64feb22f48 100644 --- a/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php +++ b/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php @@ -65,7 +65,7 @@ class BlockLegacyClientPlugin extends ServerPlugin { */ public function beforeHandler(RequestInterface $request) { $userAgent = $request->getHeader('User-Agent'); - if($userAgent === null) { + if ($userAgent === null) { return; } @@ -74,7 +74,7 @@ class BlockLegacyClientPlugin extends ServerPlugin { // Match on the mirall version which is in scheme "Mozilla/5.0 (%1) mirall/%2" or // "mirall/%1" for older releases preg_match("/(?:mirall\\/)([\d.]+)/i", $userAgent, $versionMatches); - if(isset($versionMatches[1]) && + if (isset($versionMatches[1]) && version_compare($versionMatches[1], $minimumSupportedDesktopVersion) === -1) { throw new \Sabre\DAV\Exception\Forbidden('Unsupported client version.'); } diff --git a/apps/dav/lib/Connector/Sabre/ChecksumList.php b/apps/dav/lib/Connector/Sabre/ChecksumList.php index 2fb8a0293e7..f5c0a3d9b01 100644 --- a/apps/dav/lib/Connector/Sabre/ChecksumList.php +++ b/apps/dav/lib/Connector/Sabre/ChecksumList.php @@ -64,7 +64,6 @@ class ChecksumList implements XmlSerializable { * @return void */ function xmlSerialize(Writer $writer) { - foreach ($this->checksums as $checksum) { $writer->writeElement('{' . self::NS_OWNCLOUD . '}checksum', $checksum); } diff --git a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php index 51d453e3f2a..31ea282308e 100644 --- a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php @@ -32,7 +32,6 @@ use Sabre\DAV\PropFind; use Sabre\DAV\ServerPlugin; class CommentPropertiesPlugin extends ServerPlugin { - const PROPERTY_NAME_HREF = '{http://owncloud.org/ns}comments-href'; const PROPERTY_NAME_COUNT = '{http://owncloud.org/ns}comments-count'; const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}comments-unread'; @@ -134,7 +133,7 @@ class CommentPropertiesPlugin extends ServerPlugin { public function getCommentsLink(Node $node) { $href = $this->server->getBaseUri(); $entryPoint = strpos($href, '/remote.php/'); - if($entryPoint === false) { + if ($entryPoint === false) { // in case we end up somewhere else, unexpectedly. return null; } @@ -152,7 +151,7 @@ class CommentPropertiesPlugin extends ServerPlugin { */ public function getUnreadCount(Node $node) { $user = $this->userSession->getUser(); - if(is_null($user)) { + if (is_null($user)) { return null; } @@ -160,5 +159,4 @@ class CommentPropertiesPlugin extends ServerPlugin { return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId(), $lastRead); } - } diff --git a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php index ebe6d4cefab..67be788eb04 100644 --- a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php +++ b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php @@ -50,11 +50,11 @@ class DavAclPlugin extends \Sabre\DAVACL\Plugin { function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) { $access = parent::checkPrivileges($uri, $privileges, $recursion, false); - if($access === false && $throwExceptions) { + if ($access === false && $throwExceptions) { /** @var INode $node */ $node = $this->server->tree->getNodeForPath($uri); - switch(get_class($node)) { + switch (get_class($node)) { case AddressBook::class: $type = 'Addressbook'; break; @@ -77,7 +77,7 @@ class DavAclPlugin extends \Sabre\DAVACL\Plugin { public function propFind(PropFind $propFind, INode $node) { // If the node is neither readable nor writable then fail unless its of // the standard user-principal - if(!($node instanceof User)) { + if (!($node instanceof User)) { $path = $propFind->getPath(); $readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false); $writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false); diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index 71b7e33d284..0e4ddd1f232 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -118,7 +118,6 @@ class Directory extends \OCA\DAV\Connector\Sabre\Node * @throws \Sabre\DAV\Exception\ServiceUnavailable */ public function createFile($name, $data = null) { - try { // for chunked upload also updating a existing file is a "createFile" // because we create all the chunks before re-assemble them to the existing file. @@ -131,7 +130,6 @@ class Directory extends \OCA\DAV\Connector\Sabre\Node ) { throw new \Sabre\DAV\Exception\Forbidden(); } - } else { // For non-chunked upload it is enough to check if we can create a new file if (!$this->fileView->isCreatable($this->path)) { @@ -293,7 +291,6 @@ class Directory extends \OCA\DAV\Connector\Sabre\Node // TODO: resolve chunk file name here and implement "updateFile" $path = $this->path . '/' . $name; return $this->fileView->file_exists($path); - } /** @@ -304,7 +301,6 @@ class Directory extends \OCA\DAV\Connector\Sabre\Node * @throws \Sabre\DAV\Exception\Forbidden */ public function delete() { - if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) { throw new \Sabre\DAV\Exception\Forbidden(); } diff --git a/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php b/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php index 970524dca1c..36b114b88fb 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php +++ b/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php @@ -39,9 +39,6 @@ class EntityTooLarge extends \Sabre\DAV\Exception { * @return int */ public function getHTTPCode() { - return 413; - } - } diff --git a/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php b/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php index 13af4d888bb..2db4faf50d7 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php +++ b/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php @@ -29,9 +29,8 @@ namespace OCA\DAV\Connector\Sabre\Exception; use Exception; class FileLocked extends \Sabre\DAV\Exception { - public function __construct($message = "", $code = 0, Exception $previous = null) { - if($previous instanceof \OCP\Files\LockNotAcquiredException) { + if ($previous instanceof \OCP\Files\LockNotAcquiredException) { $message = sprintf('Target file %s is locked by another process.', $previous->path); } parent::__construct($message, $code, $previous); @@ -43,7 +42,6 @@ class FileLocked extends \Sabre\DAV\Exception { * @return int */ public function getHTTPCode() { - return 423; } } diff --git a/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php b/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php index 94ff9a05123..46659737e87 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php +++ b/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php @@ -23,7 +23,6 @@ namespace OCA\DAV\Connector\Sabre\Exception; class Forbidden extends \Sabre\DAV\Exception\Forbidden { - const NS_OWNCLOUD = 'http://owncloud.org/ns'; /** diff --git a/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php b/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php index a330653e05c..2871fd83e09 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php +++ b/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php @@ -26,7 +26,6 @@ namespace OCA\DAV\Connector\Sabre\Exception; use Sabre\DAV\Exception; class InvalidPath extends Exception { - const NS_OWNCLOUD = 'http://owncloud.org/ns'; /** @@ -50,9 +49,7 @@ class InvalidPath extends Exception { * @return int */ public function getHTTPCode() { - return 400; - } /** @@ -76,5 +73,4 @@ class InvalidPath extends Exception { $error = $errorNode->ownerDocument->createElementNS('o:','o:reason', $this->getMessage()); $errorNode->appendChild($error); } - } diff --git a/apps/dav/lib/Connector/Sabre/Exception/PasswordLoginForbidden.php b/apps/dav/lib/Connector/Sabre/Exception/PasswordLoginForbidden.php index 5851ed8158a..c3e417b20ad 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/PasswordLoginForbidden.php +++ b/apps/dav/lib/Connector/Sabre/Exception/PasswordLoginForbidden.php @@ -29,7 +29,6 @@ use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Server; class PasswordLoginForbidden extends NotAuthenticated { - const NS_OWNCLOUD = 'http://owncloud.org/ns'; public function getHTTPCode() { @@ -52,5 +51,4 @@ class PasswordLoginForbidden extends NotAuthenticated { $error = $errorNode->ownerDocument->createElementNS('o:', 'o:hint', 'password login forbidden'); $errorNode->appendChild($error); } - } diff --git a/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php b/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php index cb39b3ca423..700625a2299 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php +++ b/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php @@ -39,9 +39,6 @@ class UnsupportedMediaType extends \Sabre\DAV\Exception { * @return int */ public function getHTTPCode() { - return 415; - } - } diff --git a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php index dc65837c746..9a6b19ea3fa 100644 --- a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php @@ -103,7 +103,6 @@ class ExceptionLoggerPlugin extends \Sabre\DAV\ServerPlugin { * @return void */ public function initialize(\Sabre\DAV\Server $server) { - $server->on('exception', [$this, 'logException'], 10); } diff --git a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php index 62c9915cc4e..bca15e15688 100644 --- a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php @@ -104,11 +104,11 @@ class FakeLockerPlugin extends ServerPlugin { * @param array $conditions */ public function validateTokens(RequestInterface $request, &$conditions) { - foreach($conditions as &$fileCondition) { - if(isset($fileCondition['tokens'])) { - foreach($fileCondition['tokens'] as &$token) { - if(isset($token['token'])) { - if(substr($token['token'], 0, 16) === 'opaquelocktoken:') { + foreach ($conditions as &$fileCondition) { + if (isset($fileCondition['tokens'])) { + foreach ($fileCondition['tokens'] as &$token) { + if (isset($token['token'])) { + if (substr($token['token'], 0, 16) === 'opaquelocktoken:') { $token['validToken'] = true; } } @@ -126,7 +126,6 @@ class FakeLockerPlugin extends ServerPlugin { */ public function fakeLockProvider(RequestInterface $request, ResponseInterface $response) { - $lockInfo = new LockInfo(); $lockInfo->token = md5($request->getPath()); $lockInfo->uri = $request->getPath(); diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index d025ba2aaca..2c108819e9f 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -70,7 +70,6 @@ use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\IFile; class File extends Node implements IFile { - protected $request; /** @@ -175,7 +174,6 @@ class File extends Node implements IFile { } if ($partStorage->instanceOfStorage(Storage\IWriteStreamStorage::class)) { - if (!is_resource($data)) { $tmpData = fopen('php://temp', 'r+'); if ($data !== null) { @@ -199,7 +197,6 @@ class File extends Node implements IFile { $result = feof($wrappedData); } } - } else { $target = $partStorage->fopen($internalPartPath, 'wb'); if ($target === false) { @@ -230,7 +227,6 @@ class File extends Node implements IFile { throw new BadRequest('Expected filesize of ' . $expected . ' bytes but read (from Nextcloud client) and wrote (to Nextcloud storage) ' . $count . ' bytes. Could either be a network problem on the sending side or a problem writing to the storage on the server side.'); } } - } catch (\Exception $e) { $context = []; @@ -332,7 +328,6 @@ class File extends Node implements IFile { $this->fileView->putFileInfo($this->path, ['checksum' => '']); $this->refreshInfo(); } - } catch (StorageNotAvailableException $e) { throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage(), 0, $e); } diff --git a/apps/dav/lib/Connector/Sabre/FilesPlugin.php b/apps/dav/lib/Connector/Sabre/FilesPlugin.php index 890e65a7fa5..5f2bbdd12e3 100644 --- a/apps/dav/lib/Connector/Sabre/FilesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesPlugin.php @@ -252,7 +252,9 @@ class FilesPlugin extends ServerPlugin { function httpGet(RequestInterface $request, ResponseInterface $response) { // Only handle valid files $node = $this->tree->getNodeForPath($request->getPath()); - if (!($node instanceof IFile)) return; + if (!($node instanceof IFile)) { + return; + } // adds a 'Content-Disposition: attachment' header in case no disposition // header has been set before @@ -290,7 +292,6 @@ class FilesPlugin extends ServerPlugin { * @return void */ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) { - $httpRequest = $this->server->httpRequest; if ($node instanceof \OCA\DAV\Connector\Sabre\Node) { @@ -412,7 +413,6 @@ class FilesPlugin extends ServerPlugin { $propFind->handle(self::UPLOAD_TIME_PROPERTYNAME, function () use ($node) { return $node->getFileInfo()->getUploadTime(); }); - } if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) { @@ -433,7 +433,6 @@ class FilesPlugin extends ServerPlugin { * @return array */ protected function ncPermissions2ocmPermissions($ncPermissions) { - $ocmPermissions = []; if ($ncPermissions & Constants::PERMISSION_SHARE) { @@ -450,7 +449,6 @@ class FilesPlugin extends ServerPlugin { } return $ocmPermissions; - } /** diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 4c7c689bde3..617847626cc 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -151,7 +151,6 @@ class FilesReportPlugin extends ServerPlugin { * @return void */ public function initialize(\Sabre\DAV\Server $server) { - $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; $this->server = $server; @@ -282,7 +281,6 @@ class FilesReportPlugin extends ServerPlugin { if ($filterRule['name'] === $ns . 'favorite') { $favoriteFilter = true; } - } if ($favoriteFilter !== null) { diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php index 1dd209a8303..83f90fa4ba2 100644 --- a/apps/dav/lib/Connector/Sabre/Node.php +++ b/apps/dav/lib/Connector/Sabre/Node.php @@ -323,7 +323,7 @@ abstract class Node implements \Sabre\DAV\INode { $shares = $this->shareManager->getSharedWith($user, $shareType, $this, -1); foreach ($shares as $share) { $note = $share->getNote(); - if($share->getShareOwner() !== $user && !empty($note)) { + if ($share->getShareOwner() !== $user && !empty($note)) { return $note; } } @@ -416,5 +416,4 @@ abstract class Node implements \Sabre\DAV\INode { return (int)$mtimeFromRequest; } - } diff --git a/apps/dav/lib/Connector/Sabre/ObjectTree.php b/apps/dav/lib/Connector/Sabre/ObjectTree.php index e3a7dccffdc..e292744cd2f 100644 --- a/apps/dav/lib/Connector/Sabre/ObjectTree.php +++ b/apps/dav/lib/Connector/Sabre/ObjectTree.php @@ -181,7 +181,6 @@ class ObjectTree extends CachingTree { $this->cache[$path] = $node; return $node; - } /** diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 2acc783eecf..b6a96053cb3 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -132,7 +132,7 @@ class Principal implements BackendInterface { $principals = []; if ($prefixPath === $this->principalPrefix) { - foreach($this->userManager->search('') as $user) { + foreach ($this->userManager->search('') as $user) { $principals[] = $this->userToPrincipal($user); } } @@ -206,7 +206,7 @@ class Principal implements BackendInterface { if ($this->hasGroups || $needGroups) { $userGroups = $this->groupManager->getUserGroups($user); - foreach($userGroups as $userGroup) { + foreach ($userGroups as $userGroup) { $groups[] = 'principals/groups/' . urlencode($userGroup->getGID()); } } @@ -477,9 +477,9 @@ class Principal implements BackendInterface { try { $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true); - } catch(QueryException $ex) { + } catch (QueryException $ex) { return null; - } catch(CircleDoesNotExistException $ex) { + } catch (CircleDoesNotExistException $ex) { return null; } diff --git a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php index f6da755aaf7..92187b92daf 100644 --- a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php +++ b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php @@ -72,7 +72,6 @@ class QuotaPlugin extends \Sabre\DAV\ServerPlugin { * @return void */ public function initialize(\Sabre\DAV\Server $server) { - $this->server = $server; $server->on('beforeWriteContent', [$this, 'beforeWriteContent'], 10); @@ -153,7 +152,7 @@ class QuotaPlugin extends \Sabre\DAV\ServerPlugin { if ($length) { list($parentPath, $newName) = \Sabre\Uri\split($path); - if(is_null($parentPath)) { + if (is_null($parentPath)) { $parentPath = ''; } $req = $this->server->httpRequest; diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index f740284f271..0f7f753b86f 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -128,7 +128,7 @@ class ServerFactory { $server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin()); // Some WebDAV clients do require Class 2 WebDAV support (locking), since // we do not provide locking we emulate it using a fake locking plugin. - if($this->request->isUserAgent([ + if ($this->request->isUserAgent([ '/WebDAVFS/', '/OneNote/', '/Microsoft-WebDAV-MiniRedir/', @@ -173,7 +173,7 @@ class ServerFactory { ); $server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view, true)); - if($this->userSession->isLoggedIn()) { + if ($this->userSession->isLoggedIn()) { $server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager)); $server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin( $objectTree, @@ -216,7 +216,6 @@ class ServerFactory { foreach ($pluginManager->getAppPlugins() as $appPlugin) { $server->addPlugin($appPlugin); } - }, 30); // priority 30: after auth (10) and acl(20), before lock(50) and handling the request return $server; } diff --git a/apps/dav/lib/Connector/Sabre/SharesPlugin.php b/apps/dav/lib/Connector/Sabre/SharesPlugin.php index ef1e7236c9b..ee4246011bf 100644 --- a/apps/dav/lib/Connector/Sabre/SharesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/SharesPlugin.php @@ -35,7 +35,6 @@ use Sabre\DAV\PropFind; * Sabre Plugin to provide share-related properties */ class SharesPlugin extends \Sabre\DAV\ServerPlugin { - const NS_OWNCLOUD = 'http://owncloud.org/ns'; const NS_NEXTCLOUD = 'http://nextcloud.org/ns'; const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types'; diff --git a/apps/dav/lib/Connector/Sabre/TagList.php b/apps/dav/lib/Connector/Sabre/TagList.php index e3f248ee3e2..72c3fb31b07 100644 --- a/apps/dav/lib/Connector/Sabre/TagList.php +++ b/apps/dav/lib/Connector/Sabre/TagList.php @@ -56,9 +56,7 @@ class TagList implements Element { * @return array */ public function getTags() { - return $this->tags; - } /** @@ -117,7 +115,6 @@ class TagList implements Element { * @return void */ function xmlSerialize(Writer $writer) { - foreach ($this->tags as $tag) { $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag); } diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index 83995a31e57..33698810cfb 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -52,8 +52,7 @@ namespace OCA\DAV\Connector\Sabre; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; -class TagsPlugin extends \Sabre\DAV\ServerPlugin -{ +class TagsPlugin extends \Sabre\DAV\ServerPlugin { // namespace const NS_OWNCLOUD = 'http://owncloud.org/ns'; @@ -114,7 +113,6 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin * @return void */ public function initialize(\Sabre\DAV\Server $server) { - $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; $server->xml->elementMap[self::TAGS_PROPERTYNAME] = TagList::class; diff --git a/apps/dav/lib/Controller/InvitationResponseController.php b/apps/dav/lib/Controller/InvitationResponseController.php index adf139a3fd3..aeb7350336b 100644 --- a/apps/dav/lib/Controller/InvitationResponseController.php +++ b/apps/dav/lib/Controller/InvitationResponseController.php @@ -172,7 +172,7 @@ class InvitationResponseController extends Controller { $stmt = $query->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) { + if (!$row) { return null; } diff --git a/apps/dav/lib/DAV/CustomPropertiesBackend.php b/apps/dav/lib/DAV/CustomPropertiesBackend.php index a50f171f6f3..b25c33add82 100644 --- a/apps/dav/lib/DAV/CustomPropertiesBackend.php +++ b/apps/dav/lib/DAV/CustomPropertiesBackend.php @@ -236,7 +236,6 @@ class CustomPropertiesBackend implements BackendInterface { * @return bool */ private function updateProperties(string $path, array $properties) { - $deleteStatement = 'DELETE FROM `*PREFIX*properties`' . ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; diff --git a/apps/dav/lib/DAV/GroupPrincipalBackend.php b/apps/dav/lib/DAV/GroupPrincipalBackend.php index 04fe0223607..f03c7cc2bdd 100644 --- a/apps/dav/lib/DAV/GroupPrincipalBackend.php +++ b/apps/dav/lib/DAV/GroupPrincipalBackend.php @@ -36,7 +36,6 @@ use Sabre\DAV\PropPatch; use Sabre\DAVACL\PrincipalBackend\BackendInterface; class GroupPrincipalBackend implements BackendInterface { - const PRINCIPAL_PREFIX = 'principals/groups'; /** @var IGroupManager */ @@ -78,7 +77,7 @@ class GroupPrincipalBackend implements BackendInterface { $principals = []; if ($prefixPath === self::PRINCIPAL_PREFIX) { - foreach($this->groupManager->search('') as $user) { + foreach ($this->groupManager->search('') as $user) { $principals[] = $this->groupToPrincipal($user); } } diff --git a/apps/dav/lib/DAV/PublicAuth.php b/apps/dav/lib/DAV/PublicAuth.php index ad917fb4b76..407f1a2853f 100644 --- a/apps/dav/lib/DAV/PublicAuth.php +++ b/apps/dav/lib/DAV/PublicAuth.php @@ -68,7 +68,6 @@ class PublicAuth implements BackendInterface { * @return array */ function check(RequestInterface $request, ResponseInterface $response) { - if ($this->isRequestPublic($request)) { return [true, "principals/system/public"]; } diff --git a/apps/dav/lib/DAV/Sharing/Backend.php b/apps/dav/lib/DAV/Sharing/Backend.php index bb04918716e..ae69e33387c 100644 --- a/apps/dav/lib/DAV/Sharing/Backend.php +++ b/apps/dav/lib/DAV/Sharing/Backend.php @@ -70,13 +70,13 @@ class Backend { * @param string[] $remove */ public function updateShares(IShareable $shareable, array $add, array $remove) { - foreach($add as $element) { + foreach ($add as $element) { $principal = $this->principalBackend->findByUri($element['href'], ''); if ($principal !== '') { $this->shareWith($shareable, $element); } } - foreach($remove as $element) { + foreach ($remove as $element) { $principal = $this->principalBackend->findByUri($element, ''); if ($principal !== '') { $this->unshare($shareable, $element); @@ -195,7 +195,7 @@ class Backend { ->execute(); $shares = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $p = $this->principalBackend->getPrincipalByPath($row['principaluri']); $shares[]= [ 'href' => "principal:${row['principaluri']}", @@ -218,7 +218,6 @@ class Backend { * @return array */ public function applyShareAcl($resourceId, $acl) { - $shares = $this->getShares($resourceId); foreach ($shares as $share) { $acl[] = [ diff --git a/apps/dav/lib/DAV/Sharing/IShareable.php b/apps/dav/lib/DAV/Sharing/IShareable.php index 7da6549ee4f..1293721040a 100644 --- a/apps/dav/lib/DAV/Sharing/IShareable.php +++ b/apps/dav/lib/DAV/Sharing/IShareable.php @@ -74,5 +74,4 @@ interface IShareable extends INode { * @return string */ public function getOwner(); - } diff --git a/apps/dav/lib/DAV/Sharing/Plugin.php b/apps/dav/lib/DAV/Sharing/Plugin.php index f0c2b82ccbf..67eed9c9b4a 100644 --- a/apps/dav/lib/DAV/Sharing/Plugin.php +++ b/apps/dav/lib/DAV/Sharing/Plugin.php @@ -37,7 +37,6 @@ use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; class Plugin extends ServerPlugin { - const NS_OWNCLOUD = 'http://owncloud.org/ns'; const NS_NEXTCLOUD = 'http://nextcloud.com/ns'; @@ -117,13 +116,13 @@ class Plugin extends ServerPlugin { * @return null|false */ function httpPost(RequestInterface $request, ResponseInterface $response) { - $path = $request->getPath(); // Only handling xml $contentType = $request->getHeader('Content-Type'); - if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) + if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) { return; + } // Making sure the node exists try { @@ -191,14 +190,11 @@ class Plugin extends ServerPlugin { */ function propFind(PropFind $propFind, INode $node) { if ($node instanceof IShareable) { - $propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function () use ($node) { return new Invite( $node->getShares() ); }); - } } - } diff --git a/apps/dav/lib/DAV/Sharing/Xml/Invite.php b/apps/dav/lib/DAV/Sharing/Xml/Invite.php index 7852fa8431b..68aab171ab7 100644 --- a/apps/dav/lib/DAV/Sharing/Xml/Invite.php +++ b/apps/dav/lib/DAV/Sharing/Xml/Invite.php @@ -85,10 +85,8 @@ class Invite implements XmlSerializable { * @param array $users */ function __construct(array $users, array $organizer = null) { - $this->users = $users; $this->organizer = $organizer; - } /** @@ -97,9 +95,7 @@ class Invite implements XmlSerializable { * @return array */ function getValue() { - return $this->users; - } /** @@ -122,11 +118,9 @@ class Invite implements XmlSerializable { * @return void */ function xmlSerialize(Writer $writer) { - $cs = '{' . Plugin::NS_OWNCLOUD . '}'; if (!is_null($this->organizer)) { - $writer->startElement($cs . 'organizer'); $writer->writeElement('{DAV:}href', $this->organizer['href']); @@ -140,11 +134,9 @@ class Invite implements XmlSerializable { $writer->writeElement($cs . 'last-name', $this->organizer['lastName']); } $writer->endElement(); // organizer - } foreach ($this->users as $user) { - $writer->startElement($cs . 'user'); $writer->writeElement('{DAV:}href', $user['href']); if (isset($user['commonName']) && $user['commonName']) { @@ -165,8 +157,6 @@ class Invite implements XmlSerializable { } $writer->endElement(); //user - } - } } diff --git a/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php b/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php index c63bb4fe1d1..d76e65aa232 100644 --- a/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php +++ b/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php @@ -28,7 +28,6 @@ use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; class ShareRequest implements XmlDeserializable { - public $set = []; public $remove = []; @@ -40,14 +39,11 @@ class ShareRequest implements XmlDeserializable { * @param array $remove */ function __construct(array $set, array $remove) { - $this->set = $set; $this->remove = $remove; - } static function xmlDeserialize(Reader $reader) { - $elements = $reader->parseInnerTree([ '{' . Plugin::NS_OWNCLOUD. '}set' => 'Sabre\\Xml\\Element\\KeyValue', '{' . Plugin::NS_OWNCLOUD . '}remove' => 'Sabre\\Xml\\Element\\KeyValue', @@ -81,7 +77,5 @@ class ShareRequest implements XmlDeserializable { } return new self($set, $remove); - } - } diff --git a/apps/dav/lib/DAV/SystemPrincipalBackend.php b/apps/dav/lib/DAV/SystemPrincipalBackend.php index 6c1c5a932fb..c369f4da375 100644 --- a/apps/dav/lib/DAV/SystemPrincipalBackend.php +++ b/apps/dav/lib/DAV/SystemPrincipalBackend.php @@ -69,7 +69,6 @@ class SystemPrincipalBackend extends AbstractBackend { * @return array */ function getPrincipalByPath($path) { - if ($path === 'principals/system/system') { $principal = [ 'uri' => 'principals/system/system', diff --git a/apps/dav/lib/Db/DirectMapper.php b/apps/dav/lib/Db/DirectMapper.php index 3c8198c5390..f088011d1dc 100644 --- a/apps/dav/lib/Db/DirectMapper.php +++ b/apps/dav/lib/Db/DirectMapper.php @@ -31,7 +31,6 @@ use OCP\AppFramework\Db\Mapper; use OCP\IDBConnection; class DirectMapper extends Mapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'directlink', Direct::class); } diff --git a/apps/dav/lib/Direct/DirectFile.php b/apps/dav/lib/Direct/DirectFile.php index 69ee9d9d883..f9b29d0af6e 100644 --- a/apps/dav/lib/Direct/DirectFile.php +++ b/apps/dav/lib/Direct/DirectFile.php @@ -108,5 +108,4 @@ class DirectFile implements IFile { return $this->file; } - } diff --git a/apps/dav/lib/Direct/DirectHome.php b/apps/dav/lib/Direct/DirectHome.php index c383e0220f8..8fc85be3bf1 100644 --- a/apps/dav/lib/Direct/DirectHome.php +++ b/apps/dav/lib/Direct/DirectHome.php @@ -116,5 +116,4 @@ class DirectHome implements ICollection { public function getLastModified(): int { return 0; } - } diff --git a/apps/dav/lib/Direct/ServerFactory.php b/apps/dav/lib/Direct/ServerFactory.php index 9c4045708d2..f0f56921bdc 100644 --- a/apps/dav/lib/Direct/ServerFactory.php +++ b/apps/dav/lib/Direct/ServerFactory.php @@ -57,7 +57,5 @@ class ServerFactory { $server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin($this->config)); return $server; - - } } diff --git a/apps/dav/lib/Files/BrowserErrorPagePlugin.php b/apps/dav/lib/Files/BrowserErrorPagePlugin.php index 9589ea11e0e..47de5020d56 100644 --- a/apps/dav/lib/Files/BrowserErrorPagePlugin.php +++ b/apps/dav/lib/Files/BrowserErrorPagePlugin.php @@ -98,7 +98,7 @@ class BrowserErrorPagePlugin extends ServerPlugin { $request = \OC::$server->getRequest(); $templateName = 'exception'; - if($httpCode === 403 || $httpCode === 404) { + if ($httpCode === 403 || $httpCode === 404) { $templateName = (string)$httpCode; } diff --git a/apps/dav/lib/Files/FileSearchBackend.php b/apps/dav/lib/Files/FileSearchBackend.php index 751580eabfc..fd951961623 100644 --- a/apps/dav/lib/Files/FileSearchBackend.php +++ b/apps/dav/lib/Files/FileSearchBackend.php @@ -419,7 +419,7 @@ class FileSearchBackend implements ISearchBackend { } else { throw new \InvalidArgumentException("searching by '$propertyName' is only allowed with a literal value"); } - } else{ + } else { throw new \InvalidArgumentException("searching by '$propertyName' is not allowed inside a '{DAV:}or' or '{DAV:}not'"); } } else { diff --git a/apps/dav/lib/Files/LazySearchBackend.php b/apps/dav/lib/Files/LazySearchBackend.php index 992205da72b..2ec41ccfd12 100644 --- a/apps/dav/lib/Files/LazySearchBackend.php +++ b/apps/dav/lib/Files/LazySearchBackend.php @@ -67,6 +67,4 @@ class LazySearchBackend implements ISearchBackend { return []; } } - - } diff --git a/apps/dav/lib/Files/RootCollection.php b/apps/dav/lib/Files/RootCollection.php index 6e2b7ef09d2..22142b46e1c 100644 --- a/apps/dav/lib/Files/RootCollection.php +++ b/apps/dav/lib/Files/RootCollection.php @@ -61,5 +61,4 @@ class RootCollection extends AbstractPrincipalCollection { function getName() { return 'files'; } - } diff --git a/apps/dav/lib/Files/Sharing/FilesDropPlugin.php b/apps/dav/lib/Files/Sharing/FilesDropPlugin.php index 6dbdeaa6fd9..b4201ef80c1 100644 --- a/apps/dav/lib/Files/Sharing/FilesDropPlugin.php +++ b/apps/dav/lib/Files/Sharing/FilesDropPlugin.php @@ -67,7 +67,6 @@ class FilesDropPlugin extends ServerPlugin { } public function beforeMethod(RequestInterface $request, ResponseInterface $response) { - if (!$this->enabled) { return; } diff --git a/apps/dav/lib/HookManager.php b/apps/dav/lib/HookManager.php index 72d20eb2813..558aad72c03 100644 --- a/apps/dav/lib/HookManager.php +++ b/apps/dav/lib/HookManager.php @@ -123,7 +123,7 @@ class HookManager { public function postDeleteUser($params) { $uid = $params['uid']; - if (isset($this->usersToDelete[$uid])){ + if (isset($this->usersToDelete[$uid])) { $this->syncService->deleteUser($this->usersToDelete[$uid]); } @@ -138,7 +138,7 @@ class HookManager { } public function postUnassignedUserId($uid) { - if (isset($this->usersToDelete[$uid])){ + if (isset($this->usersToDelete[$uid])) { $this->syncService->deleteUser($this->usersToDelete[$uid]); } } diff --git a/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php b/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php index c482de5b6df..ef608a8f1be 100644 --- a/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php @@ -102,7 +102,7 @@ class BuildCalendarSearchIndexBackgroundJob extends QueuedJob { ->orderBy('id', 'ASC'); $stmt = $query->execute(); - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $offset = $row['id']; $calendarData = $row['calendardata']; diff --git a/apps/dav/lib/Migration/ChunkCleanup.php b/apps/dav/lib/Migration/ChunkCleanup.php index e691314b34a..90d3b569591 100644 --- a/apps/dav/lib/Migration/ChunkCleanup.php +++ b/apps/dav/lib/Migration/ChunkCleanup.php @@ -93,5 +93,4 @@ class ChunkCleanup implements IRepairStep { $this->config->setAppValue('dav', 'chunks_migrated', '1'); } - } diff --git a/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php b/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php index 6f32978d3d8..618fb674ca3 100644 --- a/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php +++ b/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php @@ -68,7 +68,7 @@ class RefreshWebcalJobRegistrar implements IRepairStep { $stmt = $query->execute(); $count = 0; - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $args = [ 'principaluri' => $row['principaluri'], 'uri' => $row['uri'], diff --git a/apps/dav/lib/Migration/Version1004Date20170919104507.php b/apps/dav/lib/Migration/Version1004Date20170919104507.php index a71688777a0..a581978868c 100644 --- a/apps/dav/lib/Migration/Version1004Date20170919104507.php +++ b/apps/dav/lib/Migration/Version1004Date20170919104507.php @@ -56,5 +56,4 @@ class Version1004Date20170919104507 extends SimpleMigrationStep { return $schema; } - } diff --git a/apps/dav/lib/Migration/Version1004Date20170926103422.php b/apps/dav/lib/Migration/Version1004Date20170926103422.php index ce76d929d8b..3881e922935 100644 --- a/apps/dav/lib/Migration/Version1004Date20170926103422.php +++ b/apps/dav/lib/Migration/Version1004Date20170926103422.php @@ -52,5 +52,4 @@ class Version1004Date20170926103422 extends BigIntMigration { 'schedulingobjects' => ['id'], ]; } - } diff --git a/apps/dav/lib/Migration/Version1005Date20180530124431.php b/apps/dav/lib/Migration/Version1005Date20180530124431.php index 655f8165a23..8642294e6bc 100644 --- a/apps/dav/lib/Migration/Version1005Date20180530124431.php +++ b/apps/dav/lib/Migration/Version1005Date20180530124431.php @@ -44,7 +44,7 @@ class Version1005Date20180530124431 extends SimpleMigrationStep { $schema = $schemaClosure(); $types = ['resources', 'rooms']; - foreach($types as $type) { + foreach ($types as $type) { if (!$schema->hasTable('calendar_' . $type)) { $table = $schema->createTable('calendar_' . $type); diff --git a/apps/dav/lib/Migration/Version1008Date20181105110300.php b/apps/dav/lib/Migration/Version1008Date20181105110300.php index ec556ed281d..e36ec34dd8d 100644 --- a/apps/dav/lib/Migration/Version1008Date20181105110300.php +++ b/apps/dav/lib/Migration/Version1008Date20181105110300.php @@ -76,5 +76,4 @@ class Version1008Date20181105110300 extends SimpleMigrationStep { ->set('source', 'source_copy') ->execute(); } - } diff --git a/apps/dav/lib/Migration/Version1011Date20190725113607.php b/apps/dav/lib/Migration/Version1011Date20190725113607.php index c2604c8e274..4163d0d0ec6 100644 --- a/apps/dav/lib/Migration/Version1011Date20190725113607.php +++ b/apps/dav/lib/Migration/Version1011Date20190725113607.php @@ -49,7 +49,7 @@ class Version1011Date20190725113607 extends SimpleMigrationStep { $schema = $schemaClosure(); $types = ['resource', 'room']; - foreach($types as $type) { + foreach ($types as $type) { if (!$schema->hasTable($this->getMetadataTableName($type))) { $table = $schema->createTable($this->getMetadataTableName($type)); diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php index c7a3f4f60f1..98c9ce0b6e1 100644 --- a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php @@ -30,7 +30,6 @@ use Sabre\DAV\IProperties; use Sabre\DAV\PropPatch; class AppleProvisioningNode implements INode, IProperties { - const FILENAME = 'apple-provisioning.mobileconfig'; protected $timeFactory; diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php index e4feaf5d42f..7b00532495e 100644 --- a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php @@ -157,28 +157,28 @@ class AppleProvisioningPlugin extends ServerPlugin { $xmlSkeleton = $this->getTemplate(); $body = vsprintf($xmlSkeleton, array_map(function ($v) { - return \htmlspecialchars($v, ENT_XML1, 'UTF-8'); - }, [ - $description, - $server_url, - $userId, - $serverPort, - $caldavDescription, - $caldavDisplayname, - $caldavIdentifier, - $caldavUUID, - $description, - $server_url, - $userId, - $serverPort, - $carddavDescription, - $carddavDisplayname, - $carddavIdentifier, - $carddavUUID, - $description, - $profileIdentifier, - $profileUUID - ] + return \htmlspecialchars($v, ENT_XML1, 'UTF-8'); + }, [ + $description, + $server_url, + $userId, + $serverPort, + $caldavDescription, + $caldavDisplayname, + $caldavIdentifier, + $caldavUUID, + $description, + $server_url, + $userId, + $serverPort, + $carddavDescription, + $carddavDisplayname, + $carddavIdentifier, + $carddavUUID, + $description, + $profileIdentifier, + $profileUUID + ] )); $response->setStatus(200); diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index e50c2a882ca..53cba3eefa0 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -48,7 +48,6 @@ use OCP\AppFramework\Utility\ITimeFactory; use Sabre\DAV\SimpleCollection; class RootCollection extends SimpleCollection { - public function __construct() { $config = \OC::$server->getConfig(); $l10n = \OC::$server->getL10N('dav'); @@ -176,5 +175,4 @@ class RootCollection extends SimpleCollection { parent::__construct('root', $children); } - } diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index 1a432008a3a..b71c16e2319 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -126,7 +126,7 @@ class Server { $authPlugin->addBackend($authBackend); // debugging - if(\OC::$server->getConfig()->getSystemValue('debug', false)) { + if (\OC::$server->getConfig()->getSystemValue('debug', false)) { $this->server->addPlugin(new \Sabre\DAV\Browser\Plugin()); } else { $this->server->addPlugin(new DummyGetResponsePlugin()); @@ -201,7 +201,7 @@ class Server { // Some WebDAV clients do require Class 2 WebDAV support (locking), since // we do not provide locking we emulate it using a fake locking plugin. - if($request->isUserAgent([ + if ($request->isUserAgent([ '/WebDAVFS/', '/OneNote/', '/^Microsoft-WebDAV/',// Microsoft-WebDAV-MiniRedir/6.1.7601 diff --git a/apps/dav/lib/SystemTag/SystemTagPlugin.php b/apps/dav/lib/SystemTag/SystemTagPlugin.php index 4ca7b041884..b05ba07ead2 100644 --- a/apps/dav/lib/SystemTag/SystemTagPlugin.php +++ b/apps/dav/lib/SystemTag/SystemTagPlugin.php @@ -103,7 +103,6 @@ class SystemTagPlugin extends \Sabre\DAV\ServerPlugin { * @return void */ public function initialize(\Sabre\DAV\Server $server) { - $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; $server->protectedProperties[] = self::ID_PROPERTYNAME; @@ -194,8 +193,8 @@ class SystemTagPlugin extends \Sabre\DAV\ServerPlugin { } } - if($userVisible === false || $userAssignable === false || !empty($groups)) { - if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) { + if ($userVisible === false || $userAssignable === false || !empty($groups)) { + if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) { throw new BadRequest('Not sufficient permissions'); } } @@ -323,6 +322,5 @@ class SystemTagPlugin extends \Sabre\DAV\ServerPlugin { return true; }); - } } diff --git a/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php b/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php index ff0409c7ea0..80741342991 100644 --- a/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php @@ -120,7 +120,7 @@ class SystemTagsObjectTypeCollection implements ICollection { */ function getChild($objectId) { // make sure the object exists and is reachable - if(!$this->childExists($objectId)) { + if (!$this->childExists($objectId)) { throw new NotFound('Entity does not exist or is not available'); } return new SystemTagsObjectMappingCollection( diff --git a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php index e85480d4a2f..bc4e6a8c4c4 100644 --- a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php @@ -91,5 +91,4 @@ class SystemTagsRelationsCollection extends SimpleCollection { function setName($name) { throw new Forbidden('Permission denied to rename this collection'); } - } diff --git a/apps/dav/lib/Traits/PrincipalProxyTrait.php b/apps/dav/lib/Traits/PrincipalProxyTrait.php index ee8ac58e3c6..b47b462a450 100644 --- a/apps/dav/lib/Traits/PrincipalProxyTrait.php +++ b/apps/dav/lib/Traits/PrincipalProxyTrait.php @@ -193,7 +193,6 @@ trait PrincipalProxyTrait { return $proxy === 'calendar-proxy-read' || $proxy === 'calendar-proxy-write'; - } /** diff --git a/apps/dav/lib/Upload/AssemblyStream.php b/apps/dav/lib/Upload/AssemblyStream.php index 560fc7c07bc..6421abec3d5 100644 --- a/apps/dav/lib/Upload/AssemblyStream.php +++ b/apps/dav/lib/Upload/AssemblyStream.php @@ -115,7 +115,7 @@ class AssemblyStream implements \Icewind\Streams\File { $stream = $this->getStream($this->nodes[$nodeIndex]); $nodeOffset = $offset - $nodeStart; - if(fseek($stream, $nodeOffset) === -1) { + if (fseek($stream, $nodeOffset) === -1) { return false; } $this->currentNode = $nodeIndex; diff --git a/apps/dav/lib/Upload/RootCollection.php b/apps/dav/lib/Upload/RootCollection.php index ce18b5277ec..3dfddf5c0a4 100644 --- a/apps/dav/lib/Upload/RootCollection.php +++ b/apps/dav/lib/Upload/RootCollection.php @@ -55,5 +55,4 @@ class RootCollection extends AbstractPrincipalCollection { public function getName(): string { return 'uploads'; } - } diff --git a/apps/dav/templates/schedule-response-error.php b/apps/dav/templates/schedule-response-error.php index c65875f3b0b..010ea2ed6cb 100644 --- a/apps/dav/templates/schedule-response-error.php +++ b/apps/dav/templates/schedule-response-error.php @@ -1,7 +1,7 @@

t('There was an error updating your attendance status.'));?>

t('Please contact the organizer directly.'));?>

- +

diff --git a/apps/dav/tests/unit/Avatars/AvatarHomeTest.php b/apps/dav/tests/unit/Avatars/AvatarHomeTest.php index 59edfed267e..cce30d75fd2 100644 --- a/apps/dav/tests/unit/Avatars/AvatarHomeTest.php +++ b/apps/dav/tests/unit/Avatars/AvatarHomeTest.php @@ -121,5 +121,4 @@ class AvatarHomeTest extends TestCase { public function testGetLastModified() { self::assertNull($this->home->getLastModified()); } - } diff --git a/apps/dav/tests/unit/Avatars/AvatarNodeTest.php b/apps/dav/tests/unit/Avatars/AvatarNodeTest.php index d93e8422884..de81e903667 100644 --- a/apps/dav/tests/unit/Avatars/AvatarNodeTest.php +++ b/apps/dav/tests/unit/Avatars/AvatarNodeTest.php @@ -27,7 +27,6 @@ use OCP\IAvatar; use Test\TestCase; class AvatarNodeTest extends TestCase { - public function testGetName() { /** @var IAvatar | \PHPUnit_Framework_MockObject_MockObject $a */ $a = $this->createMock(IAvatar::class); diff --git a/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php b/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php index 0704bf1e9d6..b19c78d83c4 100644 --- a/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php @@ -53,8 +53,7 @@ class EventReminderJobTest extends TestCase { $this->backgroundJob = new EventReminderJob($this->reminderService, $this->config); } - public function data(): array - { + public function data(): array { return [ [true, true, true], [true, false, false], @@ -81,7 +80,6 @@ class EventReminderJobTest extends TestCase { ->method('getAppValue') ->with('dav', 'sendEventRemindersMode', 'backgroundjob') ->willReturn($sendEventRemindersMode ? 'backgroundjob' : 'cron'); - } if ($expectCall) { diff --git a/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php b/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php index d260ed352e6..cc960b4e5d2 100644 --- a/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php @@ -147,7 +147,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $res6->method('getAllAvailableMetadataKeys')->willReturn(['meta99', 'meta123']); $res6->method('getMetadataForKey')->willReturnCallback(function ($key) { - switch($key) { + switch ($key) { case 'meta99': return 'value99-new'; @@ -166,7 +166,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $res7->method('getBackend')->willReturn($backend3); $res7->method('getAllAvailableMetadataKeys')->willReturn(['meta1']); $res7->method('getMetadataForKey')->willReturnCallback(function ($key) { - switch($key) { + switch ($key) { case 'meta1': return 'value1'; @@ -182,7 +182,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $res8->method('getBackend')->willReturn($backend4); $res8->method('getAllAvailableMetadataKeys')->willReturn(['meta2']); $res8->method('getMetadataForKey')->willReturnCallback(function ($key) { - switch($key) { + switch ($key) { case 'meta2': return 'value2'; @@ -218,7 +218,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $rows = []; $ids = []; $stmt = $query->execute(); - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $ids[$row['backend_id'] . '::' . $row['resource_id']] = $row['id']; unset($row['id']); $rows[] = $row; @@ -288,7 +288,7 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { $rows2 = []; $stmt = $query2->execute(); - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { unset($row['id']); $rows2[] = $row; } diff --git a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php index db823598c3d..ff62bdaa6d2 100644 --- a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php +++ b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php @@ -172,7 +172,6 @@ abstract class AbstractCalDavBackend extends TestCase { } protected function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z') { - $randomPart = self::getUniqueID(); $calData = <<addToAssertionCount(1); return; @@ -213,7 +212,7 @@ EOD; } protected function assertNotAcl($principal, $privilege, $acl) { - foreach($acl as $a) { + foreach ($acl as $a) { if ($a['principal'] === $principal && $a['privilege'] === $privilege) { $this->fail("ACL contains $principal / $privilege"); return; diff --git a/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php b/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php index 4574a0e9aa2..7cc02ee008c 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php @@ -33,7 +33,6 @@ use Test\TestCase; * @group DB */ class GenericTest extends TestCase { - public function dataFilters() { return [ [Calendar::class], diff --git a/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php b/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php index 1f1a4429598..44c05e8b0a5 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php @@ -31,7 +31,6 @@ use OCP\Activity\ISetting; use Test\TestCase; class GenericTest extends TestCase { - public function dataSettings() { return [ [Calendar::class], diff --git a/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php b/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php index bb0e9aa22c4..51acfae8204 100644 --- a/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php +++ b/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php @@ -29,7 +29,6 @@ use OCA\DAV\CalDAV\CachedSubscriptionObject; use OCA\DAV\CalDAV\CalDavBackend; class CachedSubscriptionObjectTest extends \Test\TestCase { - public function testGet() { $backend = $this->createMock(CalDavBackend::class); $calendarInfo = [ @@ -92,5 +91,4 @@ class CachedSubscriptionObjectTest extends \Test\TestCase { $calendarObject = new CachedSubscriptionObject($backend, $calendarInfo, $objectData); $calendarObject->delete(); } - } diff --git a/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php b/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php index d0df178cc79..bc6942062b0 100644 --- a/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php +++ b/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php @@ -31,7 +31,6 @@ use OCA\DAV\CalDAV\CalDavBackend; use Sabre\DAV\PropPatch; class CachedSubscriptionTest extends \Test\TestCase { - public function testGetACL() { $backend = $this->createMock(CalDavBackend::class); $calendarInfo = [ diff --git a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php index 8cb6b9fbf10..76335f00bfe 100644 --- a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php @@ -49,9 +49,7 @@ use Sabre\DAVACL\IACL; * @package OCA\DAV\Tests\unit\CalDAV */ class CalDavBackendTest extends AbstractCalDavBackend { - public function testCalendarOperations() { - $calendarId = $this->createTestCalendar(); // update it's display name @@ -206,7 +204,6 @@ EOD; } public function testCalendarObjectsOperations() { - $calendarId = $this->createTestCalendar(); // create a card @@ -313,7 +310,6 @@ EOD; } public function testMultiCalendarObjects() { - $calendarId = $this->createTestCalendar(); // create an event @@ -392,7 +388,7 @@ EOD; // get the cards $calendarObjects = $this->backend->getMultipleCalendarObjects($calendarId, [$uri1, $uri2]); $this->assertCount(2, $calendarObjects); - foreach($calendarObjects as $card) { + foreach ($calendarObjects as $card) { $this->assertArrayHasKey('id', $card); $this->assertArrayHasKey('uri', $card); $this->assertArrayHasKey('lastmodified', $card); @@ -988,8 +984,7 @@ EOD; $this->assertEquals(null, $this->backend->getCalendarObject($subscriptionId, $uri, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION)); } - public function testCalendarMovement() - { + public function testCalendarMovement() { $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', []); $this->assertCount(1, $this->backend->getCalendarsForUser(self::UNIT_TEST_USER)); diff --git a/apps/dav/tests/unit/CalDAV/CalendarTest.php b/apps/dav/tests/unit/CalDAV/CalendarTest.php index 534661af6c6..da3a6f9e55c 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarTest.php @@ -296,7 +296,6 @@ class CalendarTest extends TestCase { * @param bool $isShared */ public function testPrivateClassification($expectedChildren, $isShared) { - $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC]; $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL]; $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE]; @@ -323,7 +322,6 @@ class CalendarTest extends TestCase { if ($isShared) { $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1'; - } $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config); $children = $c->getChildren(); @@ -570,7 +568,7 @@ EOD; $backend->expects($this->any()) ->method('getCalendarObject') ->willReturnCallback(function ($cId, $uri) use ($publicObject, $confidentialObject) { - switch($uri) { + switch ($uri) { case 'event-0': return $publicObject; @@ -633,7 +631,6 @@ EOD; $this->assertEquals( $this->fixLinebreak($roCalendar->getChild('event-1')->get()), $this->fixLinebreak($confidentialObjectCleaned)); - } private function fixLinebreak($str) { diff --git a/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php b/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php index a6698087155..8d2fab953a7 100644 --- a/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/Integration/ExternalCalendarTest.php @@ -27,7 +27,6 @@ use OCA\DAV\CalDAV\Integration\ExternalCalendar; use Test\TestCase; class ExternalCalendarTest extends TestCase { - private $abstractExternalCalendar; protected function setUp(): void { diff --git a/apps/dav/tests/unit/CalDAV/PluginTest.php b/apps/dav/tests/unit/CalDAV/PluginTest.php index 6a7d6f78850..2068c0c57fe 100644 --- a/apps/dav/tests/unit/CalDAV/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/PluginTest.php @@ -28,7 +28,7 @@ namespace OCA\DAV\Tests\unit\CalDAV; use OCA\DAV\CalDAV\Plugin; use Test\TestCase; -class PluginTest extends TestCase { +class PluginTest extends TestCase { /** @var Plugin */ private $plugin; diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php index 2560fec9815..0e58c36b39d 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php @@ -52,7 +52,6 @@ use Test\TestCase; * @package OCA\DAV\Tests\unit\CalDAV */ class PublicCalendarRootTest extends TestCase { - const UNIT_TEST_USER = ''; /** @var CalDavBackend */ private $backend; @@ -136,7 +135,6 @@ class PublicCalendarRootTest extends TestCase { } public function testGetChild() { - $calendar = $this->createPublicCalendar(); $publicCalendars = $this->backend->getPublicCalendars(); @@ -170,5 +168,4 @@ class PublicCalendarRootTest extends TestCase { return $calendar; } - } diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php index 1ef3287f15d..5710a1793c6 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php @@ -38,7 +38,6 @@ class PublicCalendarTest extends CalendarTest { * @param bool $isShared */ public function testPrivateClassification($expectedChildren, $isShared) { - $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC]; $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL]; $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE]; diff --git a/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php b/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php index 1e3ccc80750..7a555220d85 100644 --- a/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php +++ b/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php @@ -31,7 +31,6 @@ use Sabre\Xml\Writer; use Test\TestCase; class PublisherTest extends TestCase { - const NS_CALENDARSERVER = 'http://calendarserver.org/ns/'; public function testSerializePublished() { diff --git a/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php b/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php index 12278a80544..cf30df723cf 100644 --- a/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php +++ b/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php @@ -79,7 +79,6 @@ class PluginTest extends TestCase { } public function testPublishing() { - $this->book->expects($this->once())->method('setPublishStatus')->with(true); // setup request @@ -91,7 +90,6 @@ class PluginTest extends TestCase { } public function testUnPublishing() { - $this->book->expects($this->once())->method('setPublishStatus')->with(false); // setup request diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AudioProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AudioProviderTest.php index 5e18be27422..9004a42f98d 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AudioProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AudioProviderTest.php @@ -30,9 +30,7 @@ namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\AudioProvider; class AudioProviderTest extends PushProviderTest { - public function testNotificationType():void { $this->assertEquals(AudioProvider::NOTIFICATION_TYPE, 'AUDIO'); } - } diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php index 796ac38e1b2..cd111c44ae4 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php @@ -43,7 +43,6 @@ use OCP\Mail\IMessage; use Sabre\VObject\Component\VCalendar; class EmailProviderTest extends AbstractNotificationProviderTest { - const USER_EMAIL = 'frodo@hobb.it'; /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php index 568a65b77d3..eb4e3310aab 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php @@ -103,8 +103,7 @@ class NotifierTest extends TestCase { } - public function testPrepareWrongApp(): void - { + public function testPrepareWrongApp(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Notification not from this app'); @@ -138,8 +137,7 @@ class NotifierTest extends TestCase { $this->notifier->prepare($notification, 'en'); } - public function dataPrepare(): array - { + public function dataPrepare(): array { return [ [ 'calendar_reminder', @@ -176,8 +174,7 @@ class NotifierTest extends TestCase { * @param string $message * @throws \Exception */ - public function testPrepare(string $subjectType, array $subjectParams, string $subject, array $messageParams, string $message): void - { + public function testPrepare(string $subjectType, array $subjectParams, string $subject, array $messageParams, string $message): void { /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ $notification = $this->createMock(INotification::class); diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php index 1dbd45ea4ca..e614da37f4c 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php @@ -130,7 +130,6 @@ abstract class AbstractPrincipalBackendTest extends TestCase { '{http://nextcloud.com/ns}meta99' => 'value99' ] ], $actual); - } public function testGetNoPrincipalsByPrefixForWrongPrincipalPrefix() { @@ -586,5 +585,4 @@ abstract class AbstractPrincipalBackendTest extends TestCase { ]) ->execute(); } - } diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php index a666aec95a7..a9946d7454b 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php @@ -54,33 +54,33 @@ use Test\TestCase; class IMipPluginTest extends TestCase { /** @var IMessage|MockObject */ - private $mailMessage; + private $mailMessage; - /** @var IMailer|MockObject */ - private $mailer; + /** @var IMailer|MockObject */ + private $mailer; - /** @var IEMailTemplate|MockObject */ - private $emailTemplate; + /** @var IEMailTemplate|MockObject */ + private $emailTemplate; - /** @var IAttachment|MockObject */ - private $emailAttachment; + /** @var IAttachment|MockObject */ + private $emailAttachment; - /** @var ITimeFactory|MockObject */ - private $timeFactory; + /** @var ITimeFactory|MockObject */ + private $timeFactory; - /** @var IConfig|MockObject */ - private $config; + /** @var IConfig|MockObject */ + private $config; - /** @var IUserManager|MockObject */ - private $userManager; + /** @var IUserManager|MockObject */ + private $userManager; - /** @var IQueryBuilder|MockObject */ - private $queryBuilder; + /** @var IQueryBuilder|MockObject */ + private $queryBuilder; - /** @var IMipPlugin */ - private $plugin; + /** @var IMipPlugin */ + private $plugin; - protected function setUp(): void { + protected function setUp(): void { $this->mailMessage = $this->createMock(IMessage::class); $this->mailMessage->method('setFrom')->willReturn($this->mailMessage); $this->mailMessage->method('setReplyTo')->willReturn($this->mailMessage); @@ -186,7 +186,6 @@ class IMipPluginTest extends TestCase { * @dataProvider dataNoMessageSendForPastEvents */ public function testNoMessageSendForPastEvents(array $veventParams, bool $expectsMail) { - $this->config ->method('getAppValue') ->with('dav', 'invitation_link_recipients', 'yes') @@ -319,8 +318,7 @@ class IMipPluginTest extends TestCase { ->willReturn($this->queryBuilder); $this->queryBuilder->expects($this->at(9)) ->method('execute'); - } - else { + } else { $this->queryBuilder->expects($this->never()) ->method('insert') ->with('calendar_invitations'); diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php index 97d4e552fa4..859dccbe489 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php @@ -32,7 +32,7 @@ use Sabre\VObject\Parameter; use Sabre\VObject\Property\ICalendar\CalAddress; use Test\TestCase; -class PluginTest extends TestCase { +class PluginTest extends TestCase { /** @var Plugin */ private $plugin; /** @var Server|\PHPUnit_Framework_MockObject_MockObject */ diff --git a/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php b/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php index 178a05f112c..5211df8867a 100644 --- a/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php +++ b/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php @@ -30,7 +30,6 @@ use Sabre\Xml\Reader; use Test\TestCase; class CalendarSearchReportTest extends TestCase { - private $elementMap = [ '{http://nextcloud.com/ns}calendar-search' => 'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport', diff --git a/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php b/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php index a789753065b..c6c468b9d62 100644 --- a/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php @@ -32,7 +32,6 @@ use Sabre\Xml\Service; use Test\TestCase; class SearchPluginTest extends TestCase { - protected $server; /** @var \OCA\DAV\CalDAV\Search\SearchPlugin $plugin */ diff --git a/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php b/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php index 82c84423243..2d57ad3b7d5 100644 --- a/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php @@ -28,7 +28,6 @@ use OCA\DAV\CalDAV\WebcalCaching\Plugin; use OCP\IRequest; class PluginTest extends \Test\TestCase { - public function testDisabled() { $request = $this->createMock(IRequest::class); $request->expects($this->at(0)) diff --git a/apps/dav/tests/unit/CapabilitiesTest.php b/apps/dav/tests/unit/CapabilitiesTest.php index 1e9c4bdf836..720d91fc17e 100644 --- a/apps/dav/tests/unit/CapabilitiesTest.php +++ b/apps/dav/tests/unit/CapabilitiesTest.php @@ -29,7 +29,7 @@ use Test\TestCase; /** * @package OCA\DAV\Tests\unit */ -class CapabilitiesTest extends TestCase { +class CapabilitiesTest extends TestCase { public function testGetCapabilities() { $capabilities = new Capabilities(); $expected = [ diff --git a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php index 326e77a58be..e4e2d4aef8e 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php @@ -134,7 +134,6 @@ class AddressBookImplTest extends TestCase { * @param array $properties */ public function testCreate($properties) { - $uid = 'uid'; /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ @@ -173,7 +172,6 @@ class AddressBookImplTest extends TestCase { } public function testUpdate() { - $uid = 'uid'; $uri = 'bla.vcf'; $properties = ['URI' => $uri, 'UID' => $uid, 'FN' => 'John Doe']; @@ -288,7 +286,6 @@ class AddressBookImplTest extends TestCase { $this->assertSame('uid1', $this->invokePrivate($addressBookImpl, 'createUid', []) ); - } public function testCreateEmptyVCard() { diff --git a/apps/dav/tests/unit/CardDAV/AddressBookTest.php b/apps/dav/tests/unit/CardDAV/AddressBookTest.php index c7557c29476..0edc130c904 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookTest.php @@ -32,7 +32,6 @@ use Sabre\DAV\PropPatch; use Test\TestCase; class AddressBookTest extends TestCase { - public function testDelete() { /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); @@ -152,4 +151,5 @@ class AddressBookTest extends TestCase { 'read-only property is false and no owner' => [true, false, false], 'read-only property is true and no owner' => [false, true, false], ]; - }} + } +} diff --git a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php index 9d23280f607..e7d2197a6ee 100644 --- a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php +++ b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php @@ -206,7 +206,6 @@ class CardDavBackendTest extends TestCase { } public function testAddressBookSharing() { - $this->userManager->expects($this->any()) ->method('userExists') ->willReturn(true); @@ -333,7 +332,9 @@ class CardDavBackendTest extends TestCase { // get all the cards $cards = $this->backend->getCards($bookId); $this->assertEquals(3, count($cards)); - usort($cards, function ($a, $b) { return $a['id'] < $b['id'] ? -1 : 1; }); + usort($cards, function ($a, $b) { + return $a['id'] < $b['id'] ? -1 : 1; + }); $this->assertEquals($this->vcardTest0, $cards[0]['carddata']); $this->assertEquals($this->vcardTest1, $cards[1]['carddata']); @@ -342,8 +343,10 @@ class CardDavBackendTest extends TestCase { // get the cards 1 & 2 (not 0) $cards = $this->backend->getMultipleCards($bookId, [$uri1, $uri2]); $this->assertEquals(2, count($cards)); - usort($cards, function ($a, $b) { return $a['id'] < $b['id'] ? -1 : 1; }); - foreach($cards as $index => $card) { + usort($cards, function ($a, $b) { + return $a['id'] < $b['id'] ? -1 : 1; + }); + foreach ($cards as $index => $card) { $this->assertArrayHasKey('id', $card); $this->assertArrayHasKey('uri', $card); $this->assertArrayHasKey('lastmodified', $card); @@ -361,7 +364,6 @@ class CardDavBackendTest extends TestCase { } public function testMultipleUIDOnDifferentAddressbooks() { - $this->backend = $this->getMockBuilder(CardDavBackend::class) ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher]) ->setMethods(['updateProperties'])->getMock(); @@ -486,7 +488,6 @@ class CardDavBackendTest extends TestCase { } public function testSharing() { - $this->userManager->expects($this->any()) ->method('userExists') ->willReturn(true); @@ -525,7 +526,6 @@ class CardDavBackendTest extends TestCase { } public function testUpdateProperties() { - $bookId = 42; $cardUri = 'card-uri'; $cardId = 2; @@ -574,7 +574,6 @@ class CardDavBackendTest extends TestCase { } public function testPurgeProperties() { - $query = $this->db->getQueryBuilder(); $query->insert('cards_properties') ->values( @@ -608,7 +607,6 @@ class CardDavBackendTest extends TestCase { $this->assertSame(1, count($result)); $this->assertSame(1 ,(int)$result[0]['addressbookid']); $this->assertSame(2 ,(int)$result[0]['cardid']); - } public function testGetCardId() { @@ -664,7 +662,7 @@ class CardDavBackendTest extends TestCase { $vCardIds = []; $query = $this->db->getQueryBuilder(); - for($i=0; $i < 3; $i++) { + for ($i=0; $i < 3; $i++) { $query->insert($this->dbCardsTable) ->values( [ @@ -794,7 +792,7 @@ class CardDavBackendTest extends TestCase { public function testGetContact() { $query = $this->db->getQueryBuilder(); - for($i=0; $i<2; $i++) { + for ($i=0; $i<2; $i++) { $query->insert($this->dbCardsTable) ->values( [ diff --git a/apps/dav/tests/unit/CardDAV/ConverterTest.php b/apps/dav/tests/unit/CardDAV/ConverterTest.php index 7e93c05a3fc..da2255a7172 100644 --- a/apps/dav/tests/unit/CardDAV/ConverterTest.php +++ b/apps/dav/tests/unit/CardDAV/ConverterTest.php @@ -103,23 +103,23 @@ class ConverterTest extends TestCase { $this->assertInstanceOf('Sabre\VObject\Component\VCard', $vCard); $cardData = $vCard->jsonSerialize(); $this->compareData($expectedVCard, $cardData); - } else { $this->assertSame($expectedVCard, $vCard); } - } protected function compareData($expected, $data) { foreach ($expected as $key => $value) { $found = false; foreach ($data[1] as $d) { - if($d[0] === $key && $d[3] === $value) { + if ($d[0] === $key && $d[3] === $value) { $found = true; break; } } - if (!$found) $this->assertTrue(false, 'Expected data: ' . $key . ' not found.'); + if (!$found) { + $this->assertTrue(false, 'Expected data: ' . $key . ' not found.'); + } } } @@ -183,7 +183,6 @@ class ConverterTest extends TestCase { * @param $fullName */ public function testNameSplitter($expected, $fullName) { - $converter = new Converter($this->accountManager); $r = $converter->splitFullName($fullName); $r = implode(';', $r); diff --git a/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php b/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php index 6cdfe04e8a9..076c9119cd7 100644 --- a/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php +++ b/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php @@ -185,7 +185,6 @@ class ImageExportPluginTest extends TestCase { $this->response->expects($this->once()) ->method('setBody') ->with('imgdata'); - } else { $this->cache->method('get') ->with(1, 'card', $size, $card) diff --git a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php index e0abbf7857d..647af7db69b 100644 --- a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php +++ b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php @@ -66,7 +66,6 @@ class PluginTest extends TestCase { } public function testSharing() { - $this->book->expects($this->once())->method('updateShares')->with([[ 'href' => 'principal:principals/admin', 'commonName' => null, diff --git a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php index 9015528763f..f3dc3f95fa5 100644 --- a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php +++ b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php @@ -216,5 +216,4 @@ class SyncServiceTest extends TestCase { $ss->method('getCertPath')->willReturn(''); return $ss; } - } diff --git a/apps/dav/tests/unit/Command/ListCalendarsTest.php b/apps/dav/tests/unit/Command/ListCalendarsTest.php index 72c76ecc7a6..8960a9d7721 100644 --- a/apps/dav/tests/unit/Command/ListCalendarsTest.php +++ b/apps/dav/tests/unit/Command/ListCalendarsTest.php @@ -63,8 +63,7 @@ class ListCalendarsTest extends TestCase { } - public function testWithBadUser() - { + public function testWithBadUser() { $this->expectException(\InvalidArgumentException::class); $this->userManager->expects($this->once()) @@ -79,8 +78,7 @@ class ListCalendarsTest extends TestCase { $this->assertContains("User <" . self::USERNAME . "> in unknown", $commandTester->getDisplay()); } - public function testWithCorrectUserWithNoCalendars() - { + public function testWithCorrectUserWithNoCalendars() { $this->userManager->expects($this->once()) ->method('userExists') ->with(self::USERNAME) @@ -98,8 +96,7 @@ class ListCalendarsTest extends TestCase { $this->assertContains("User <" . self::USERNAME . "> has no calendars\n", $commandTester->getDisplay()); } - public function dataExecute() - { + public function dataExecute() { return [ [false, '✓'], [true, 'x'] @@ -109,8 +106,7 @@ class ListCalendarsTest extends TestCase { /** * @dataProvider dataExecute */ - public function testWithCorrectUser(bool $readOnly, string $output) - { + public function testWithCorrectUser(bool $readOnly, string $output) { $this->userManager->expects($this->once()) ->method('userExists') ->with(self::USERNAME) diff --git a/apps/dav/tests/unit/Command/MoveCalendarTest.php b/apps/dav/tests/unit/Command/MoveCalendarTest.php index 36553ff65a2..156043411da 100644 --- a/apps/dav/tests/unit/Command/MoveCalendarTest.php +++ b/apps/dav/tests/unit/Command/MoveCalendarTest.php @@ -97,8 +97,7 @@ class MoveCalendarTest extends TestCase { * @param $userOriginExists * @param $userDestinationExists */ - public function testWithBadUserOrigin($userOriginExists, $userDestinationExists) - { + public function testWithBadUserOrigin($userOriginExists, $userDestinationExists) { $this->expectException(\InvalidArgumentException::class); $this->userManager->expects($this->at(0)) @@ -122,8 +121,7 @@ class MoveCalendarTest extends TestCase { } - public function testMoveWithInexistantCalendar() - { + public function testMoveWithInexistantCalendar() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('User has no calendar named . You can run occ dav:list-calendars to list calendars URIs for this user.'); @@ -150,8 +148,7 @@ class MoveCalendarTest extends TestCase { } - public function testMoveWithExistingDestinationCalendar() - { + public function testMoveWithExistingDestinationCalendar() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('User already has a calendar named .'); @@ -171,7 +168,7 @@ class MoveCalendarTest extends TestCase { 'id' => 1234, ]); - $this->calDav->expects($this->at(1))->method('getCalendarByUri') + $this->calDav->expects($this->at(1))->method('getCalendarByUri') ->with('principals/users/user2', 'personal') ->willReturn([ 'id' => 1234, @@ -185,8 +182,7 @@ class MoveCalendarTest extends TestCase { ]); } - public function testMove() - { + public function testMove() { $this->userManager->expects($this->at(0)) ->method('userExists') ->with('user') @@ -221,8 +217,7 @@ class MoveCalendarTest extends TestCase { $this->assertContains("[OK] Calendar was moved from user to ", $commandTester->getDisplay()); } - public function dataTestMoveWithDestinationNotPartOfGroup(): array - { + public function dataTestMoveWithDestinationNotPartOfGroup(): array { return [ [true], [false] @@ -232,8 +227,7 @@ class MoveCalendarTest extends TestCase { /** * @dataProvider dataTestMoveWithDestinationNotPartOfGroup */ - public function testMoveWithDestinationNotPartOfGroup(bool $shareWithGroupMembersOnly) - { + public function testMoveWithDestinationNotPartOfGroup(bool $shareWithGroupMembersOnly) { $this->userManager->expects($this->at(0)) ->method('userExists') ->with('user') @@ -276,8 +270,7 @@ class MoveCalendarTest extends TestCase { ]); } - public function testMoveWithDestinationPartOfGroup() - { + public function testMoveWithDestinationPartOfGroup() { $this->userManager->expects($this->at(0)) ->method('userExists') ->with('user') @@ -322,8 +315,7 @@ class MoveCalendarTest extends TestCase { $this->assertContains("[OK] Calendar was moved from user to ", $commandTester->getDisplay()); } - public function testMoveWithDestinationNotPartOfGroupAndForce() - { + public function testMoveWithDestinationNotPartOfGroupAndForce() { $this->userManager->expects($this->at(0)) ->method('userExists') ->with('user') @@ -370,8 +362,7 @@ class MoveCalendarTest extends TestCase { $this->assertContains("[OK] Calendar was moved from user to ", $commandTester->getDisplay()); } - public function dataTestMoveWithCalendarAlreadySharedToDestination(): array - { + public function dataTestMoveWithCalendarAlreadySharedToDestination(): array { return [ [true], [false] @@ -381,8 +372,7 @@ class MoveCalendarTest extends TestCase { /** * @dataProvider dataTestMoveWithCalendarAlreadySharedToDestination */ - public function testMoveWithCalendarAlreadySharedToDestination(bool $force) - { + public function testMoveWithCalendarAlreadySharedToDestination(bool $force) { $this->userManager->expects($this->at(0)) ->method('userExists') ->with('user') diff --git a/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php b/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php index ce830e3f699..2416ec6978f 100644 --- a/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php +++ b/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php @@ -36,7 +36,6 @@ use Test\TestCase; * @group DB */ class RemoveInvalidSharesTest extends TestCase { - protected function setUp(): void { parent::setUp(); $db = \OC::$server->getDatabaseConnection(); diff --git a/apps/dav/tests/unit/Comments/CommentsNodeTest.php b/apps/dav/tests/unit/Comments/CommentsNodeTest.php index a219b0a5c74..6bb0033ecb8 100644 --- a/apps/dav/tests/unit/Comments/CommentsNodeTest.php +++ b/apps/dav/tests/unit/Comments/CommentsNodeTest.php @@ -488,7 +488,7 @@ class CommentsNodeTest extends \Test\TestCase { $properties = $this->node->getProperties(null); - foreach($properties as $name => $value) { + foreach ($properties as $name => $value) { $this->assertArrayHasKey($name, $expected); $this->assertSame($expected[$name], $value); unset($expected[$name]); @@ -499,8 +499,10 @@ class CommentsNodeTest extends \Test\TestCase { public function readCommentProvider() { $creationDT = new \DateTime('2016-01-19 18:48:00'); $diff = new \DateInterval('PT2H'); - $readDT1 = clone $creationDT; $readDT1->sub($diff); - $readDT2 = clone $creationDT; $readDT2->add($diff); + $readDT1 = clone $creationDT; + $readDT1->sub($diff); + $readDT2 = clone $creationDT; + $readDT2->add($diff); return [ [$creationDT, $readDT1, 'true'], [$creationDT, $readDT2, 'false'], diff --git a/apps/dav/tests/unit/Comments/CommentsPluginTest.php b/apps/dav/tests/unit/Comments/CommentsPluginTest.php index 7210e96b122..c2234f116fc 100644 --- a/apps/dav/tests/unit/Comments/CommentsPluginTest.php +++ b/apps/dav/tests/unit/Comments/CommentsPluginTest.php @@ -772,7 +772,4 @@ class CommentsPluginTest extends \Test\TestCase { $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, $parameters, '/' . $path); } - - - } diff --git a/apps/dav/tests/unit/Comments/RootCollectionTest.php b/apps/dav/tests/unit/Comments/RootCollectionTest.php index f039c0d6ea3..68098f2aebc 100644 --- a/apps/dav/tests/unit/Comments/RootCollectionTest.php +++ b/apps/dav/tests/unit/Comments/RootCollectionTest.php @@ -146,7 +146,7 @@ class RootCollectionTest extends \Test\TestCase { $this->prepareForInitCollections(); $children = $this->collection->getChildren(); $this->assertFalse(empty($children)); - foreach($children as $child) { + foreach ($children as $child) { $this->assertTrue($child instanceof EntityTypeCollectionImplementation); } } diff --git a/apps/dav/tests/unit/Connector/PublicAuthTest.php b/apps/dav/tests/unit/Connector/PublicAuthTest.php index ccf7d503205..bcec84d414c 100644 --- a/apps/dav/tests/unit/Connector/PublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/PublicAuthTest.php @@ -267,5 +267,4 @@ class PublicAuthTest extends \Test\TestCase { $this->assertFalse($result); } - } diff --git a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php index 37663ebc0dc..d2f2d8f2d4c 100644 --- a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php @@ -135,5 +135,4 @@ class BlockLegacyClientPluginTest extends TestCase { ->willReturn(null); $this->blockLegacyClientVersionPlugin->beforeHandler($request); } - } diff --git a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php index c5150d8a586..9585fae9cf8 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php @@ -61,7 +61,7 @@ class CommentsPropertiesPluginTest extends \Test\TestCase { public function nodeProvider() { $mocks = []; - foreach(['\OCA\DAV\Connector\Sabre\File', '\OCA\DAV\Connector\Sabre\Directory', '\Sabre\DAV\INode'] as $class) { + foreach (['\OCA\DAV\Connector\Sabre\File', '\OCA\DAV\Connector\Sabre\Directory', '\Sabre\DAV\INode'] as $class) { $mocks[] = $this->getMockBuilder($class) ->disableOriginalConstructor() ->getMock(); @@ -84,7 +84,7 @@ class CommentsPropertiesPluginTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); - if($expectedSuccessful) { + if ($expectedSuccessful) { $propFind->expects($this->exactly(3)) ->method('handle'); } else { @@ -157,11 +157,10 @@ class CommentsPropertiesPluginTest extends \Test\TestCase { ->willReturn(42); $unread = $this->plugin->getUnreadCount($node); - if(is_null($user)) { + if (is_null($user)) { $this->assertNull($unread); } else { $this->assertSame($unread, 42); } } - } diff --git a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php index 94ef048eb57..d3d17eefec1 100644 --- a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php @@ -34,7 +34,6 @@ use OCA\DAV\Connector\Sabre\Directory; use OCP\Files\ForbiddenException; class TestViewDirectory extends \OC\Files\View { - private $updatables; private $deletables; private $canRename; diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php index 1b48ccf77f7..1f6a80f3882 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php @@ -26,7 +26,6 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre\Exception; use OCA\DAV\Connector\Sabre\Exception\Forbidden; class ForbiddenTest extends \Test\TestCase { - public function testSerialization() { // create xml doc diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php index abe1d2e2858..bb3b421f630 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php @@ -27,7 +27,6 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre\Exception; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; class InvalidPathTest extends \Test\TestCase { - public function testSerialization() { // create xml doc diff --git a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php index ff9fac3ff18..468624ce8ac 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php @@ -97,5 +97,4 @@ class ExceptionLoggerPluginTest extends TestCase { [4, 'This path leads to nowhere', new InvalidPath('This path leads to nowhere')] ]; } - } diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index d366726e919..52b94f63811 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -1080,7 +1080,7 @@ class FileTest extends TestCase { } $files = []; list($storage, $internalPath) = $userView->resolvePath($path); - if($storage instanceof Local) { + if ($storage instanceof Local) { $realPath = $storage->getSourcePath($internalPath); $dh = opendir($realPath); while (($file = readdir($dh)) !== false) { diff --git a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php index be14400fad8..5a4424cb327 100644 --- a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php @@ -61,5 +61,4 @@ class MaintenancePluginTest extends TestCase { $this->maintenancePlugin->checkMaintenanceMode(); } - } diff --git a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php index bc49fb442a2..c6d0a6a340f 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php @@ -44,7 +44,6 @@ use OCA\DAV\Connector\Sabre\ObjectTree; * @package OCA\DAV\Tests\Unit\Connector\Sabre */ class ObjectTreeTest extends \Test\TestCase { - public function copyDataProvider() { return [ // copy into same dir @@ -152,7 +151,6 @@ class ObjectTreeTest extends \Test\TestCase { $type, $enableChunkingHeader ) { - if ($enableChunkingHeader) { $_SERVER['HTTP_OC_CHUNKED'] = true; } @@ -284,8 +282,8 @@ class ObjectTreeTest extends \Test\TestCase { $view->expects($this->once()) ->method('resolvePath') ->willReturnCallback(function ($path) use ($storage) { - return [$storage, ltrim($path, '/')]; - }); + return [$storage, ltrim($path, '/')]; + }); $rootNode = $this->getMockBuilder(Directory::class) ->disableOriginalConstructor() diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index 93cae17d539..0f2305be23b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -759,41 +759,41 @@ class PrincipalTest extends TestCase { ->method('shareApiEnabled') ->willReturn(true); - $this->shareManager->expects($this->once()) + $this->shareManager->expects($this->once()) ->method('shareWithGroupMembersOnly') ->willReturn(true); - $user = $this->createMock(IUser::class); - $this->userSession->expects($this->once()) + $user = $this->createMock(IUser::class); + $this->userSession->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->groupManager->expects($this->at(0)) + $this->groupManager->expects($this->at(0)) ->method('getUserGroupIds') ->with($user) ->willReturn(['group1', 'group2']); - $user2 = $this->createMock(IUser::class); - $user2->method('getUID')->willReturn('user2'); - $user3 = $this->createMock(IUser::class); - $user3->method('getUID')->willReturn('user3'); + $user2 = $this->createMock(IUser::class); + $user2->method('getUID')->willReturn('user2'); + $user3 = $this->createMock(IUser::class); + $user3->method('getUID')->willReturn('user3'); - $this->userManager->expects($this->once()) + $this->userManager->expects($this->once()) ->method('getByEmail') ->with($email) ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); - if ($email === 'user2@foo.bar') { - $this->groupManager->expects($this->at(1)) + if ($email === 'user2@foo.bar') { + $this->groupManager->expects($this->at(1)) ->method('getUserGroupIds') ->with($user2) ->willReturn(['group1', 'group3']); - } else { - $this->groupManager->expects($this->at(1)) + } else { + $this->groupManager->expects($this->at(1)) ->method('getUserGroupIds') ->with($user3) ->willReturn(['group3', 'group3']); - } + } $this->assertEquals($expects, $this->connector->findByUri($uri, 'principals/users')); } @@ -813,16 +813,16 @@ class PrincipalTest extends TestCase { ->method('shareApiEnabled') ->willReturn(true); - $this->shareManager->expects($this->once()) + $this->shareManager->expects($this->once()) ->method('shareWithGroupMembersOnly') ->willReturn(false); - $user2 = $this->createMock(IUser::class); - $user2->method('getUID')->willReturn('user2'); - $user3 = $this->createMock(IUser::class); - $user3->method('getUID')->willReturn('user3'); + $user2 = $this->createMock(IUser::class); + $user2->method('getUID')->willReturn('user2'); + $user3 = $this->createMock(IUser::class); + $user3->method('getUID')->willReturn('user3'); - $this->userManager->expects($this->once()) + $this->userManager->expects($this->once()) ->method('getByEmail') ->with($email) ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); diff --git a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php index e83aec4d198..dd1cc70046d 100644 --- a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php @@ -40,7 +40,6 @@ use OCP\Share\IShare; use Sabre\DAV\Tree; class SharesPluginTest extends \Test\TestCase { - const SHARETYPES_PROPERTYNAME = \OCA\DAV\Connector\Sabre\SharesPlugin::SHARETYPES_PROPERTYNAME; /** diff --git a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php index 37dd72ab884..0cfa9c5229c 100644 --- a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php @@ -41,7 +41,6 @@ use Sabre\DAV\Tree; * See the COPYING-README file. */ class TagsPluginTest extends \Test\TestCase { - const TAGS_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::TAGS_PROPERTYNAME; const FAVORITE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::FAVORITE_PROPERTYNAME; const TAG_FAVORITE = \OCA\DAV\Connector\Sabre\TagsPlugin::TAG_FAVORITE; @@ -430,5 +429,4 @@ class TagsPluginTest extends \Test\TestCase { $this->assertFalse(false, isset($result[self::TAGS_PROPERTYNAME])); $this->assertEquals(200, isset($result[self::FAVORITE_PROPERTYNAME])); } - } diff --git a/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php b/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php index 18f73d9685e..1e2cef4e37b 100644 --- a/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php +++ b/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php @@ -122,5 +122,4 @@ class BirthdayCalendarControllerTest extends TestCase { $response = $this->controller->disable(); $this->assertInstanceOf('OCP\AppFramework\Http\JSONResponse', $response); } - } diff --git a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php index 721c2c4b074..cd7f4c24340 100644 --- a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php +++ b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php @@ -88,7 +88,5 @@ class SapiMock extends Sapi { * @return void */ static function sendResponse(ResponseInterface $response) { - } - } diff --git a/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php b/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php index 42c38cf5ce7..da812016f21 100644 --- a/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php @@ -66,7 +66,6 @@ class CustomPropertiesBackendTest extends TestCase { $this->dbConnection, $this->user ); - } protected function tearDown(): void { diff --git a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php index 07a9e2ce9f5..56d0867f015 100644 --- a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php +++ b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php @@ -68,7 +68,6 @@ class PluginTest extends TestCase { } public function testSharing() { - $this->book->expects($this->once())->method('updateShares')->with([[ 'href' => 'principal:principals/admin', 'commonName' => null, diff --git a/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php b/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php index 698e39a5218..1bb1f6d8380 100644 --- a/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php +++ b/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php @@ -137,6 +137,4 @@ class SystemPrincipalBackendTest extends TestCase { $result = $backend->getGroupMembership('principals/system/system'); $this->assertEquals([], $result); } - - } diff --git a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php index dcc79d71ce0..6279583350b 100644 --- a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php +++ b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php @@ -37,7 +37,7 @@ use Test\TestCase; * @package OCA\DAV\Tests\Unit\DAV\Migration * @group DB */ -class CalDAVRemoveEmptyValueTest extends TestCase { +class CalDAVRemoveEmptyValueTest extends TestCase { /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */ private $logger; diff --git a/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php b/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php index 84dbe56a761..6856915961f 100644 --- a/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php +++ b/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php @@ -145,5 +145,4 @@ class RefreshWebcalJobRegistrarTest extends TestCase { $this->migration->run($output); } - } diff --git a/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php b/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php index 85a34d25694..ef7f2580941 100644 --- a/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php +++ b/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php @@ -98,6 +98,4 @@ class RegenerateBirthdayCalendarsTest extends TestCase { $this->migration->run($output); } - - } diff --git a/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php b/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php index 1b09c96c940..1c39f30527a 100644 --- a/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php +++ b/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php @@ -92,7 +92,8 @@ class AppleProvisioningPluginTest extends TestCase { $plugin = new AppleProvisioningPlugin($this->userSession, $this->urlGenerator, $this->themingDefaults, $this->request, $this->l10n, - function () {}); + function () { + }); $server->expects($this->at(0)) ->method('on') @@ -266,5 +267,4 @@ EOF $this->assertFalse($returnValue); } - } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php index ec80d916b58..dc47c20f345 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php @@ -43,7 +43,6 @@ use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; class SystemTagPluginTest extends \Test\TestCase { - const ID_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::ID_PROPERTYNAME; const DISPLAYNAME_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::DISPLAYNAME_PROPERTYNAME; const USERVISIBLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERVISIBLE_PROPERTYNAME; @@ -748,5 +747,4 @@ class SystemTagPluginTest extends \Test\TestCase { $this->plugin->httpPost($request, $response); } - } diff --git a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php index 2a4c832c71c..f7b34315106 100644 --- a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php +++ b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php @@ -64,7 +64,7 @@ class AssemblyStreamTest extends \Test\TestCase { $stream = \OCA\DAV\Upload\AssemblyStream::wrap($nodes); $offset = floor(strlen($expected) * 0.6); - if(fseek($stream, $offset) === -1) { + if (fseek($stream, $offset) === -1) { $this->fail('fseek failed'); } diff --git a/apps/dav/tests/unit/Upload/ChunkingPluginTest.php b/apps/dav/tests/unit/Upload/ChunkingPluginTest.php index f4f91c0e760..abbded089db 100644 --- a/apps/dav/tests/unit/Upload/ChunkingPluginTest.php +++ b/apps/dav/tests/unit/Upload/ChunkingPluginTest.php @@ -164,5 +164,4 @@ class ChunkingPluginTest extends TestCase { $this->assertFalse($this->plugin->beforeMove('source', 'target')); } - } diff --git a/apps/dav/tests/unit/Upload/FutureFileTest.php b/apps/dav/tests/unit/Upload/FutureFileTest.php index 248d4c826ae..793241cda72 100644 --- a/apps/dav/tests/unit/Upload/FutureFileTest.php +++ b/apps/dav/tests/unit/Upload/FutureFileTest.php @@ -29,7 +29,6 @@ namespace OCA\DAV\Tests\unit\Upload; use OCA\DAV\Connector\Sabre\Directory; class FutureFileTest extends \Test\TestCase { - public function testGetContentType() { $f = $this->mockFutureFile(); $this->assertEquals('application/octet-stream', $f->getContentType()); diff --git a/apps/encryption/lib/AppInfo/Application.php b/apps/encryption/lib/AppInfo/Application.php index fcd7ef569b9..688564887d3 100644 --- a/apps/encryption/lib/AppInfo/Application.php +++ b/apps/encryption/lib/AppInfo/Application.php @@ -78,7 +78,6 @@ class Application extends \OCP\AppFramework\App { */ public function registerHooks() { if (!$this->config->getSystemValueBool('maintenance')) { - $container = $this->getContainer(); $server = $container->getServer(); // Register our hooks and fire them. @@ -97,7 +96,6 @@ class Application extends \OCP\AppFramework\App { ]); $hookManager->fireHooks(); - } else { // Logout user if we are in maintenance to force re-login $this->getContainer()->getServer()->getUserSession()->logout(); @@ -112,8 +110,7 @@ class Application extends \OCP\AppFramework\App { Encryption::ID, Encryption::DISPLAY_NAME, function () use ($container) { - - return new Encryption( + return new Encryption( $container->query('Crypt'), $container->query('KeyManager'), $container->query('Util'), @@ -123,8 +120,7 @@ class Application extends \OCP\AppFramework\App { $container->getServer()->getLogger(), $container->getServer()->getL10N($container->getAppName()) ); - }); - + }); } public function registerServices() { @@ -261,6 +257,5 @@ class Application extends \OCP\AppFramework\App { ); } ); - } } diff --git a/apps/encryption/lib/Command/DisableMasterKey.php b/apps/encryption/lib/Command/DisableMasterKey.php index 18bf0b3903d..d59e3b586c8 100644 --- a/apps/encryption/lib/Command/DisableMasterKey.php +++ b/apps/encryption/lib/Command/DisableMasterKey.php @@ -50,7 +50,6 @@ class DisableMasterKey extends Command { public function __construct(Util $util, IConfig $config, QuestionHelper $questionHelper) { - $this->util = $util; $this->config = $config; $this->questionHelper = $questionHelper; @@ -64,10 +63,9 @@ class DisableMasterKey extends Command { } protected function execute(InputInterface $input, OutputInterface $output) { - $isMasterKeyEnabled = $this->util->isMasterKeyEnabled(); - if(!$isMasterKeyEnabled) { + if (!$isMasterKeyEnabled) { $output->writeln('Master key already disabled'); } else { $question = new ConfirmationQuestion( @@ -83,7 +81,5 @@ class DisableMasterKey extends Command { $output->writeln('aborted.'); } } - } - } diff --git a/apps/encryption/lib/Command/EnableMasterKey.php b/apps/encryption/lib/Command/EnableMasterKey.php index d1148c88ccd..6c4645e7212 100644 --- a/apps/encryption/lib/Command/EnableMasterKey.php +++ b/apps/encryption/lib/Command/EnableMasterKey.php @@ -49,7 +49,6 @@ class EnableMasterKey extends Command { public function __construct(Util $util, IConfig $config, QuestionHelper $questionHelper) { - $this->util = $util; $this->config = $config; $this->questionHelper = $questionHelper; @@ -63,10 +62,9 @@ class EnableMasterKey extends Command { } protected function execute(InputInterface $input, OutputInterface $output) { - $isAlreadyEnabled = $this->util->isMasterKeyEnabled(); - if($isAlreadyEnabled) { + if ($isAlreadyEnabled) { $output->writeln('Master key already enabled'); } else { $question = new ConfirmationQuestion( @@ -79,7 +77,5 @@ class EnableMasterKey extends Command { $output->writeln('aborted.'); } } - } - } diff --git a/apps/encryption/lib/Command/RecoverUser.php b/apps/encryption/lib/Command/RecoverUser.php index 9d98b38de47..a4d7b2407d6 100644 --- a/apps/encryption/lib/Command/RecoverUser.php +++ b/apps/encryption/lib/Command/RecoverUser.php @@ -54,7 +54,6 @@ class RecoverUser extends Command { IConfig $config, IUserManager $userManager, QuestionHelper $questionHelper) { - $this->util = $util; $this->questionHelper = $questionHelper; $this->userManager = $userManager; @@ -74,10 +73,9 @@ class RecoverUser extends Command { } protected function execute(InputInterface $input, OutputInterface $output) { - $isMasterKeyEnabled = $this->util->isMasterKeyEnabled(); - if($isMasterKeyEnabled) { + if ($isMasterKeyEnabled) { $output->writeln('You use the master key, no individual user recovery needed.'); return; } @@ -90,7 +88,7 @@ class RecoverUser extends Command { } $recoveryKeyEnabled = $this->util->isRecoveryEnabledForUser($uid); - if($recoveryKeyEnabled === false) { + if ($recoveryKeyEnabled === false) { $output->writeln('Recovery key is not enabled for: ' . $uid); return; } @@ -108,7 +106,5 @@ class RecoverUser extends Command { $output->write('Start to recover users files... This can take some time...'); $this->userManager->get($uid)->setPassword($newLoginPassword, $recoveryPassword); $output->writeln('Done.'); - } - } diff --git a/apps/encryption/lib/Controller/RecoveryController.php b/apps/encryption/lib/Controller/RecoveryController.php index 534e00e1b2e..509ff2a0391 100644 --- a/apps/encryption/lib/Controller/RecoveryController.php +++ b/apps/encryption/lib/Controller/RecoveryController.php @@ -161,7 +161,6 @@ class RecoveryController extends Controller { */ public function userSetRecovery($userEnableRecovery) { if ($userEnableRecovery === '0' || $userEnableRecovery === '1') { - $result = $this->recovery->setRecoveryForUser($userEnableRecovery); if ($result) { @@ -180,7 +179,6 @@ class RecoveryController extends Controller { ] ); } - } return new DataResponse( [ @@ -189,5 +187,4 @@ class RecoveryController extends Controller { ] ], Http::STATUS_BAD_REQUEST); } - } diff --git a/apps/encryption/lib/Controller/SettingsController.php b/apps/encryption/lib/Controller/SettingsController.php index 545f544625b..f918f176767 100644 --- a/apps/encryption/lib/Controller/SettingsController.php +++ b/apps/encryption/lib/Controller/SettingsController.php @@ -150,7 +150,6 @@ class SettingsController extends Controller { Http::STATUS_BAD_REQUEST ); } - } /** diff --git a/apps/encryption/lib/Controller/StatusController.php b/apps/encryption/lib/Controller/StatusController.php index d3925e4482a..40159627b00 100644 --- a/apps/encryption/lib/Controller/StatusController.php +++ b/apps/encryption/lib/Controller/StatusController.php @@ -67,10 +67,9 @@ class StatusController extends Controller { * @return DataResponse */ public function getStatus() { - $status = 'error'; $message = 'no valid init status'; - switch($this->session->getStatus()) { + switch ($this->session->getStatus()) { case Session::INIT_EXECUTED: $status = 'interactionNeeded'; $message = (string)$this->l->t( @@ -102,5 +101,4 @@ class StatusController extends Controller { ] ); } - } diff --git a/apps/encryption/lib/Crypto/Crypt.php b/apps/encryption/lib/Crypto/Crypt.php index b8e7ebab85b..24b1f21ecd0 100644 --- a/apps/encryption/lib/Crypto/Crypt.php +++ b/apps/encryption/lib/Crypto/Crypt.php @@ -54,7 +54,6 @@ use OCP\IUserSession; * @package OCA\Encryption\Crypto */ class Crypt { - const DEFAULT_CIPHER = 'AES-256-CTR'; // default cipher from old Nextcloud versions const LEGACY_CIPHER = 'AES-128-CFB'; @@ -109,7 +108,6 @@ class Crypt { * @return array|bool */ public function createKeyPair() { - $log = $this->logger; $res = $this->getOpenSSLPKey(); @@ -176,7 +174,6 @@ class Crypt { * @throws EncryptionFailedException */ public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) { - if (!$plainContent) { $this->logger->error('Encryption Library, symmetrical encryption failed no content given', ['app' => 'encryption']); @@ -207,7 +204,6 @@ class Crypt { * @throws \InvalidArgumentException */ public function generateHeader($keyFormat = 'hash') { - if (in_array($keyFormat, $this->supportedKeyFormats, true) === false) { throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported'); } @@ -267,8 +263,8 @@ class Crypt { } // Workaround for OpenSSL 0.9.8. Fallback to an old cipher that should work. - if(OPENSSL_VERSION_NUMBER < 0x1000101f) { - if($cipher === 'AES-256-CTR' || $cipher === 'AES-128-CTR') { + if (OPENSSL_VERSION_NUMBER < 0x1000101f) { + if ($cipher === 'AES-256-CTR' || $cipher === 'AES-128-CTR') { $cipher = self::LEGACY_CIPHER; } } @@ -284,7 +280,7 @@ class Crypt { * @throws \InvalidArgumentException */ protected function getKeySize($cipher) { - if(isset($this->supportedCiphersAndKeySize[$cipher])) { + if (isset($this->supportedCiphersAndKeySize[$cipher])) { return $this->supportedCiphersAndKeySize[$cipher]; } @@ -389,7 +385,6 @@ class Crypt { * @return false|string */ public function decryptPrivateKey($privateKey, $password = '', $uid = '') { - $header = $this->parseHeader($privateKey); if (isset($header['cipher'])) { diff --git a/apps/encryption/lib/Crypto/DecryptAll.php b/apps/encryption/lib/Crypto/DecryptAll.php index a488c726523..ed43bc75457 100644 --- a/apps/encryption/lib/Crypto/DecryptAll.php +++ b/apps/encryption/lib/Crypto/DecryptAll.php @@ -78,10 +78,9 @@ class DecryptAll { * @return bool */ public function prepare(InputInterface $input, OutputInterface $output, $user) { - $question = new Question('Please enter the recovery key password: '); - if($this->util->isMasterKeyEnabled()) { + if ($this->util->isMasterKeyEnabled()) { $output->writeln('Use master key to decrypt all files'); $user = $this->keyManager->getMasterKeyId(); $password =$this->keyManager->getMasterKeyPassword(); diff --git a/apps/encryption/lib/Crypto/EncryptAll.php b/apps/encryption/lib/Crypto/EncryptAll.php index d0aaafd0617..8fa2214234e 100644 --- a/apps/encryption/lib/Crypto/EncryptAll.php +++ b/apps/encryption/lib/Crypto/EncryptAll.php @@ -131,7 +131,6 @@ class EncryptAll { * @param OutputInterface $output */ public function encryptAll(InputInterface $input, OutputInterface $output) { - $this->input = $input; $this->output = $output; @@ -184,7 +183,7 @@ class EncryptAll { $progress->setFormat(" %message% \n [%bar%]"); $progress->start(); - foreach($this->userManager->getBackends() as $backend) { + foreach ($this->userManager->getBackends() as $backend) { $limit = 500; $offset = 0; do { @@ -203,7 +202,7 @@ class EncryptAll { } } $offset += $limit; - } while(count($users) >= $limit); + } while (count($users) >= $limit); } $progress->setMessage('Key-pair created for all users'); @@ -231,7 +230,6 @@ class EncryptAll { } $progress->setMessage("all files encrypted"); $progress->finish(); - } /** @@ -241,7 +239,7 @@ class EncryptAll { */ protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) { $userNo = 1; - foreach($this->userManager->getBackends() as $backend) { + foreach ($this->userManager->getBackends() as $backend) { $limit = 500; $offset = 0; do { @@ -252,7 +250,7 @@ class EncryptAll { $userNo++; } $offset += $limit; - } while(count($users) >= $limit); + } while (count($users) >= $limit); } } @@ -264,12 +262,11 @@ class EncryptAll { * @param string $userCount */ protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) { - $this->setupUserFS($uid); $directories = []; $directories[] = '/' . $uid . '/files'; - while($root = array_pop($directories)) { + while ($root = array_pop($directories)) { $content = $this->rootView->getDirectoryContent($root); foreach ($content as $file) { $path = $root . '/' . $file['name']; @@ -279,7 +276,7 @@ class EncryptAll { } else { $progress->setMessage("encrypt files for user $userCount: $path"); $progress->advance(); - if($this->encryptFile($path) === false) { + if ($this->encryptFile($path) === false) { $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)"); $progress->advance(); } @@ -461,7 +458,6 @@ class EncryptAll { $table->setRows($rows); $table->render(); } - } /** @@ -471,7 +467,6 @@ class EncryptAll { * @return array an array of the html mail body and the plain text mail body */ protected function createMailBody($password) { - $html = new \OC_Template("encryption", "mail", ""); $html->assign('password', $password); $htmlMail = $html->fetchPage(); @@ -482,5 +477,4 @@ class EncryptAll { return [$htmlMail, $plainTextMail]; } - } diff --git a/apps/encryption/lib/Crypto/Encryption.php b/apps/encryption/lib/Crypto/Encryption.php index f976a0815db..57cf4e2edac 100644 --- a/apps/encryption/lib/Crypto/Encryption.php +++ b/apps/encryption/lib/Crypto/Encryption.php @@ -45,7 +45,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class Encryption implements IEncryptionModule { - const ID = 'OC_DEFAULT_MODULE'; const DISPLAY_NAME = 'Default encryption module'; @@ -184,7 +183,7 @@ class Encryption implements IEncryptionModule { $this->isWriteOperation = false; $this->writeCache = ''; - if($this->session->isReady() === false) { + if ($this->session->isReady() === false) { // if the master key is enabled we can initialize encryption // with a empty password and user name if ($this->util->isMasterKeyEnabled()) { @@ -221,7 +220,7 @@ class Encryption implements IEncryptionModule { // if we read a part file we need to increase the version by 1 // because the version number was also increased by writing // the part file - if(Scanner::isPartialFile($path)) { + if (Scanner::isPartialFile($path)) { $this->version = $this->version + 1; } } @@ -313,7 +312,6 @@ class Encryption implements IEncryptionModule { // Clear the write cache, ready for reuse - it has been // flushed and its old contents processed $this->writeCache = ''; - } $encrypted = ''; @@ -340,7 +338,6 @@ class Encryption implements IEncryptionModule { // Clear $data ready for next round $data = ''; - } else { // Read the chunk from the start of $data @@ -352,9 +349,7 @@ class Encryption implements IEncryptionModule { // $data, leaving only unprocessed data in $data // var, for handling on the next round $data = substr($data, $this->unencryptedBlockSizeSigned); - } - } return $encrypted; @@ -389,7 +384,6 @@ class Encryption implements IEncryptionModule { * @return boolean */ public function update($path, $uid, array $accessList) { - if (empty($accessList)) { if (isset(self::$rememberVersion[$path])) { $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View()); @@ -401,7 +395,6 @@ class Encryption implements IEncryptionModule { $fileKey = $this->keyManager->getFileKey($path, $uid); if (!empty($fileKey)) { - $publicKeys = []; if ($this->useMasterPassword === true) { $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); @@ -422,7 +415,6 @@ class Encryption implements IEncryptionModule { $this->keyManager->deleteAllFileKeys($path); $this->keyManager->setAllFileKeys($path, $encryptedFileKey); - } else { $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', ['file' => $path, 'app' => 'encryption']); diff --git a/apps/encryption/lib/Exceptions/MultiKeyDecryptException.php b/apps/encryption/lib/Exceptions/MultiKeyDecryptException.php index 9bb01249d94..79ec2c3c822 100644 --- a/apps/encryption/lib/Exceptions/MultiKeyDecryptException.php +++ b/apps/encryption/lib/Exceptions/MultiKeyDecryptException.php @@ -26,5 +26,4 @@ namespace OCA\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class MultiKeyDecryptException extends GenericEncryptionException { - } diff --git a/apps/encryption/lib/Exceptions/MultiKeyEncryptException.php b/apps/encryption/lib/Exceptions/MultiKeyEncryptException.php index f4a03d259ca..4916a4ceba5 100644 --- a/apps/encryption/lib/Exceptions/MultiKeyEncryptException.php +++ b/apps/encryption/lib/Exceptions/MultiKeyEncryptException.php @@ -26,5 +26,4 @@ namespace OCA\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class MultiKeyEncryptException extends GenericEncryptionException { - } diff --git a/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php b/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php index f7014fa2701..4d14b191ddc 100644 --- a/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php +++ b/apps/encryption/lib/Exceptions/PrivateKeyMissingException.php @@ -32,10 +32,9 @@ class PrivateKeyMissingException extends GenericEncryptionException { * @param string $userId */ public function __construct($userId) { - if(empty($userId)) { + if (empty($userId)) { $userId = ""; } parent::__construct("Private Key missing for user: $userId"); } - } diff --git a/apps/encryption/lib/Exceptions/PublicKeyMissingException.php b/apps/encryption/lib/Exceptions/PublicKeyMissingException.php index d6f12b3669e..e0667d42a20 100644 --- a/apps/encryption/lib/Exceptions/PublicKeyMissingException.php +++ b/apps/encryption/lib/Exceptions/PublicKeyMissingException.php @@ -31,10 +31,9 @@ class PublicKeyMissingException extends GenericEncryptionException { * @param string $userId */ public function __construct($userId) { - if(empty($userId)) { + if (empty($userId)) { $userId = ""; } parent::__construct("Public Key missing for user: $userId"); } - } diff --git a/apps/encryption/lib/HookManager.php b/apps/encryption/lib/HookManager.php index a40f56fa373..324c0d718da 100644 --- a/apps/encryption/lib/HookManager.php +++ b/apps/encryption/lib/HookManager.php @@ -26,7 +26,6 @@ namespace OCA\Encryption; use OCA\Encryption\Hooks\Contracts\IHook; class HookManager { - private $hookInstances = []; /** @@ -42,7 +41,6 @@ class HookManager { } $this->hookInstances[] = $instance; } - } elseif ($instances instanceof IHook) { $this->hookInstances[] = $instances; } @@ -58,7 +56,5 @@ class HookManager { */ $instance->addHooks(); } - } - } diff --git a/apps/encryption/lib/Hooks/UserHooks.php b/apps/encryption/lib/Hooks/UserHooks.php index 16655dfe689..399e2865d03 100644 --- a/apps/encryption/lib/Hooks/UserHooks.php +++ b/apps/encryption/lib/Hooks/UserHooks.php @@ -109,7 +109,6 @@ class UserHooks implements IHook { Session $session, Crypt $crypt, Recovery $recovery) { - $this->keyManager = $keyManager; $this->userManager = $userManager; $this->logger = $logger; @@ -258,7 +257,6 @@ class UserHooks implements IHook { // current logged in user changes his own password if ($user && $params['uid'] === $user->getUID()) { - $privateKey = $this->session->getPrivateKey(); // Encrypt private key with new user pwd as passphrase diff --git a/apps/encryption/lib/KeyManager.php b/apps/encryption/lib/KeyManager.php index 8b286e00942..a62a4ca27f8 100644 --- a/apps/encryption/lib/KeyManager.php +++ b/apps/encryption/lib/KeyManager.php @@ -120,7 +120,6 @@ class KeyManager { ILogger $log, Util $util ) { - $this->util = $util; $this->session = $session; $this->keyStorage = $keyStorage; @@ -179,7 +178,6 @@ class KeyManager { * check if a key pair for the master key exists, if not we create one */ public function validateMasterKey() { - if ($this->util->isMasterKeyEnabled() === false) { return; } @@ -358,11 +356,10 @@ class KeyManager { * @return boolean */ public function init($uid, $passPhrase) { - $this->session->setStatus(Session::INIT_EXECUTED); try { - if($this->util->isMasterKeyEnabled()) { + if ($this->util->isMasterKeyEnabled()) { $uid = $this->getMasterKeyId(); $passPhrase = $this->getMasterKeyPassword(); $privateKey = $this->getSystemPrivateKey($uid); @@ -462,7 +459,7 @@ class KeyManager { */ public function getVersion($path, View $view) { $fileInfo = $view->getFileInfo($path); - if($fileInfo === false) { + if ($fileInfo === false) { return 0; } return $fileInfo->getEncryptedVersion(); @@ -478,7 +475,7 @@ class KeyManager { public function setVersion($path, $version, View $view) { $fileInfo= $view->getFileInfo($path); - if($fileInfo !== false) { + if ($fileInfo !== false) { $cache = $fileInfo->getStorage()->getCache(); $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]); } @@ -642,7 +639,6 @@ class KeyManager { } return $keys; - } /** @@ -685,7 +681,6 @@ class KeyManager { if ($this->recoveryKeyExists() && $this->util->isRecoveryEnabledForUser($uid)) { - $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey(); } @@ -700,7 +695,7 @@ class KeyManager { */ public function getMasterKeyPassword() { $password = $this->config->getSystemValue('secret'); - if (empty($password)){ + if (empty($password)) { throw new \Exception('Can not get secret from Nextcloud instance'); } diff --git a/apps/encryption/lib/Migration/SetMasterKeyStatus.php b/apps/encryption/lib/Migration/SetMasterKeyStatus.php index ade393cede1..322b991ae97 100644 --- a/apps/encryption/lib/Migration/SetMasterKeyStatus.php +++ b/apps/encryption/lib/Migration/SetMasterKeyStatus.php @@ -73,5 +73,4 @@ class SetMasterKeyStatus implements IRepairStep { $appVersion = $this->config->getAppValue('encryption', 'installed_version', '0.0.0'); return version_compare($appVersion, '2.0.0', '<'); } - } diff --git a/apps/encryption/lib/Recovery.php b/apps/encryption/lib/Recovery.php index 657d41b61dd..7d7132999ea 100644 --- a/apps/encryption/lib/Recovery.php +++ b/apps/encryption/lib/Recovery.php @@ -95,7 +95,7 @@ class Recovery { if (!$keyManager->recoveryKeyExists()) { $keyPair = $this->crypt->createKeyPair(); - if(!is_array($keyPair)) { + if (!is_array($keyPair)) { return false; } @@ -120,7 +120,7 @@ class Recovery { public function changeRecoveryKeyPassword($newPassword, $oldPassword) { $recoveryKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId()); $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $oldPassword); - if($decryptedRecoveryKey === false) { + if ($decryptedRecoveryKey === false) { return false; } $encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword); @@ -180,7 +180,6 @@ class Recovery { * @return bool */ public function setRecoveryForUser($value) { - try { $this->config->setUserValue($this->user->getUID(), 'encryption', @@ -253,7 +252,7 @@ class Recovery { $encryptedKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId()); $privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword); - if($privateKey !== false) { + if ($privateKey !== false) { $this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user); } } @@ -277,7 +276,6 @@ class Recovery { $this->recoverFile($filePath, $privateKey, $uid); } } - } /** @@ -309,8 +307,5 @@ class Recovery { $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); $this->keyManager->setAllFileKeys($path, $encryptedKeyfiles); } - } - - } diff --git a/apps/encryption/lib/Session.php b/apps/encryption/lib/Session.php index 58357b2efe1..4398f9c4e0a 100644 --- a/apps/encryption/lib/Session.php +++ b/apps/encryption/lib/Session.php @@ -184,5 +184,4 @@ class Session { $this->session->remove('decryptAllKey'); $this->session->remove('decryptAllUid'); } - } diff --git a/apps/encryption/lib/Settings/Admin.php b/apps/encryption/lib/Settings/Admin.php index 91ce234ef58..d3b64bee4ee 100644 --- a/apps/encryption/lib/Settings/Admin.php +++ b/apps/encryption/lib/Settings/Admin.php @@ -125,5 +125,4 @@ class Admin implements ISettings { public function getPriority() { return 11; } - } diff --git a/apps/encryption/lib/Util.php b/apps/encryption/lib/Util.php index 681f025417b..2b11b8151c0 100644 --- a/apps/encryption/lib/Util.php +++ b/apps/encryption/lib/Util.php @@ -182,7 +182,6 @@ class Util { throw new \BadMethodCallException('Unknown user: ' . 'method expects path to a user folder relative to the data folder'); } - } return $owner; @@ -197,5 +196,4 @@ class Util { public function getStorage($path) { return $this->files->getMount($path)->getStorage(); } - } diff --git a/apps/encryption/templates/settings-admin.php b/apps/encryption/templates/settings-admin.php index 48cc4d40da8..1ae93dfb0e2 100644 --- a/apps/encryption/templates/settings-admin.php +++ b/apps/encryption/templates/settings-admin.php @@ -6,17 +6,19 @@ style('encryption', 'settings-admin'); ?>

t("Default encryption module")); ?>

- + t("Encryption app is enabled but your keys are not initialized, please log-out and log-in again")); ?>

/> + value="1" />
t("Enabling this option encrypts all files stored on the main storage, otherwise only files on external storage will be encrypted")); ?>


- +

t("Enable recovery key")) : p($l->t("Disable recovery key")); ?> @@ -41,7 +43,9 @@ style('encryption', 'settings-admin');



-

> +

> t("Change recovery key password:")); ?>
diff --git a/apps/encryption/tests/Command/TestEnableMasterKey.php b/apps/encryption/tests/Command/TestEnableMasterKey.php index f8cbd790adb..b8db72938a5 100644 --- a/apps/encryption/tests/Command/TestEnableMasterKey.php +++ b/apps/encryption/tests/Command/TestEnableMasterKey.php @@ -77,7 +77,6 @@ class TestEnableMasterKey extends TestCase { * @param string $answer */ public function testExecute($isAlreadyEnabled, $answer) { - $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn($isAlreadyEnabled); @@ -92,7 +91,6 @@ class TestEnableMasterKey extends TestCase { } else { $this->questionHelper->expects($this->once())->method('ask')->willReturn(false); $this->config->expects($this->never())->method('setAppValue'); - } } diff --git a/apps/encryption/tests/Controller/RecoveryControllerTest.php b/apps/encryption/tests/Controller/RecoveryControllerTest.php index 5f69f11d2f7..27d67a12dfa 100644 --- a/apps/encryption/tests/Controller/RecoveryControllerTest.php +++ b/apps/encryption/tests/Controller/RecoveryControllerTest.php @@ -65,8 +65,6 @@ class RecoveryControllerTest extends TestCase { * @param $expectedStatus */ public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus) { - - $this->recoveryMock->expects($this->any()) ->method('enableAdminRecovery') ->willReturn(true); @@ -82,8 +80,6 @@ class RecoveryControllerTest extends TestCase { $this->assertEquals($expectedMessage, $response->getData()['data']['message']); $this->assertEquals($expectedStatus, $response->getStatus()); - - } public function changeRecoveryPasswordProvider() { @@ -119,8 +115,6 @@ class RecoveryControllerTest extends TestCase { $this->assertEquals($expectedMessage, $response->getData()['data']['message']); $this->assertEquals($expectedStatus, $response->getStatus()); - - } public function userSetRecoveryProvider() { @@ -150,7 +144,6 @@ class RecoveryControllerTest extends TestCase { $this->assertEquals($expectedMessage, $response->getData()['data']['message']); $this->assertEquals($expectedStatus, $response->getStatus()); - } protected function setUp(): void { @@ -183,5 +176,4 @@ class RecoveryControllerTest extends TestCase { $this->l10nMock, $this->recoveryMock); } - } diff --git a/apps/encryption/tests/Controller/SettingsControllerTest.php b/apps/encryption/tests/Controller/SettingsControllerTest.php index 160c9794613..0cd69c8c1c4 100644 --- a/apps/encryption/tests/Controller/SettingsControllerTest.php +++ b/apps/encryption/tests/Controller/SettingsControllerTest.php @@ -76,7 +76,6 @@ class SettingsControllerTest extends TestCase { private $utilMock; protected function setUp(): void { - parent::setUp(); $this->requestMock = $this->createMock(IRequest::class); @@ -136,7 +135,6 @@ class SettingsControllerTest extends TestCase { * test updatePrivateKeyPassword() if wrong new password was entered */ public function testUpdatePrivateKeyPasswordWrongNewPassword() { - $oldPassword = 'old'; $newPassword = 'new'; @@ -162,7 +160,6 @@ class SettingsControllerTest extends TestCase { * test updatePrivateKeyPassword() if wrong old password was entered */ public function testUpdatePrivateKeyPasswordWrongOldPassword() { - $oldPassword = 'old'; $newPassword = 'new'; @@ -189,7 +186,6 @@ class SettingsControllerTest extends TestCase { * test updatePrivateKeyPassword() with the correct old and new password */ public function testUpdatePrivateKeyPassword() { - $oldPassword = 'old'; $newPassword = 'new'; @@ -254,5 +250,4 @@ class SettingsControllerTest extends TestCase { $this->utilMock->expects($this->once())->method('setEncryptHomeStorage')->with($value); $this->controller->setEncryptHomeStorage($value); } - } diff --git a/apps/encryption/tests/Controller/StatusControllerTest.php b/apps/encryption/tests/Controller/StatusControllerTest.php index fe2616f9c54..5028fefbbe0 100644 --- a/apps/encryption/tests/Controller/StatusControllerTest.php +++ b/apps/encryption/tests/Controller/StatusControllerTest.php @@ -52,7 +52,6 @@ class StatusControllerTest extends TestCase { protected $controller; protected function setUp(): void { - parent::setUp(); $this->sessionMock = $this->getMockBuilder(Session::class) @@ -73,7 +72,6 @@ class StatusControllerTest extends TestCase { $this->l10nMock, $this->sessionMock, $this->encryptionManagerMock); - } /** diff --git a/apps/encryption/tests/Crypto/CryptTest.php b/apps/encryption/tests/Crypto/CryptTest.php index dd892616d0f..6f7b0cc2765 100644 --- a/apps/encryption/tests/Crypto/CryptTest.php +++ b/apps/encryption/tests/Crypto/CryptTest.php @@ -76,7 +76,6 @@ class CryptTest extends TestCase { * test getOpenSSLConfig without any additional parameters */ public function testGetOpenSSLConfigBasic() { - $this->config->expects($this->once()) ->method('getSystemValue') ->with($this->equalTo('openssl'), $this->equalTo([])) @@ -92,7 +91,6 @@ class CryptTest extends TestCase { * test getOpenSSLConfig with additional parameters defined in config.php */ public function testGetOpenSSLConfig() { - $this->config->expects($this->once()) ->method('getSystemValue') ->with($this->equalTo('openssl'), $this->equalTo([])) @@ -113,7 +111,6 @@ class CryptTest extends TestCase { * @dataProvider dataTestGenerateHeader */ public function testGenerateHeader($keyFormat, $expected) { - $this->config->expects($this->once()) ->method('getSystemValue') ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) @@ -176,7 +173,6 @@ class CryptTest extends TestCase { $this->assertSame($expected, $this->crypt->getCipher() ); - } /** @@ -199,7 +195,6 @@ class CryptTest extends TestCase { * test concatIV() */ public function testConcatIV() { - $result = self::invokePrivate( $this->crypt, 'concatIV', @@ -305,7 +300,6 @@ class CryptTest extends TestCase { * test parseHeader() */ public function testParseHeader() { - $header= 'HBEGIN:foo:bar:cipher:AES-256-CFB:HEND'; $result = self::invokePrivate($this->crypt, 'parseHeader', [$header]); @@ -323,7 +317,6 @@ class CryptTest extends TestCase { * @return string */ public function testEncrypt() { - $decrypted = 'content'; $password = 'password'; $iv = self::invokePrivate($this->crypt, 'generateIv'); @@ -340,7 +333,6 @@ class CryptTest extends TestCase { 'iv' => $iv, 'encrypted' => $result, 'decrypted' => $decrypted]; - } /** @@ -349,14 +341,12 @@ class CryptTest extends TestCase { * @depends testEncrypt */ public function testDecrypt($data) { - $result = self::invokePrivate( $this->crypt, 'decrypt', [$data['encrypted'], $data['iv'], $data['password']]); $this->assertSame($data['decrypted'], $result); - } /** @@ -461,5 +451,4 @@ class CryptTest extends TestCase { $this->invokePrivate($this->crypt, 'isValidPrivateKey', ['foo']) ); } - } diff --git a/apps/encryption/tests/Crypto/DecryptAllTest.php b/apps/encryption/tests/Crypto/DecryptAllTest.php index be980149145..b4d846bfd5a 100644 --- a/apps/encryption/tests/Crypto/DecryptAllTest.php +++ b/apps/encryption/tests/Crypto/DecryptAllTest.php @@ -110,7 +110,6 @@ class DecryptAllTest extends TestCase { $this->keyManager->expects($this->never())->method('getPrivateKey'); $this->crypt->expects($this->once())->method('decryptPrivateKey') ->with($masterKey, $password, $masterKeyId)->willReturn($unencryptedKey); - } else { $this->keyManager->expects($this->never())->method('getSystemPrivateKey'); $this->keyManager->expects($this->once())->method('getPrivateKey') @@ -131,5 +130,4 @@ class DecryptAllTest extends TestCase { ['masterKeyId', 'masterKeyId', 'masterKeyId'] ]; } - } diff --git a/apps/encryption/tests/Crypto/EncryptAllTest.php b/apps/encryption/tests/Crypto/EncryptAllTest.php index f5fd3d2287f..3041c27dee7 100644 --- a/apps/encryption/tests/Crypto/EncryptAllTest.php +++ b/apps/encryption/tests/Crypto/EncryptAllTest.php @@ -168,7 +168,6 @@ class EncryptAllTest extends TestCase { $encryptAll->expects($this->at(2))->method('encryptAllUsersFiles')->with(); $encryptAll->encryptAll($this->inputInterface, $this->outputInterface); - } public function testEncryptAllWithMasterKey() { @@ -198,7 +197,6 @@ class EncryptAllTest extends TestCase { $encryptAll->expects($this->never())->method('outputPasswords'); $encryptAll->encryptAll($this->inputInterface, $this->outputInterface); - } public function testCreateKeyPairs() { @@ -280,7 +278,6 @@ class EncryptAllTest extends TestCase { $encryptAll->expects($this->at(1))->method('encryptUsersFiles')->with('user2'); $this->invokePrivate($encryptAll, 'encryptAllUsersFiles'); - } public function testEncryptUsersFiles() { @@ -339,7 +336,6 @@ class EncryptAllTest extends TestCase { $progressBar = new ProgressBar($this->outputInterface); $this->invokePrivate($encryptAll, 'encryptUsersFiles', ['user1', $progressBar, '']); - } public function testGenerateOneTimePassword() { @@ -364,7 +360,7 @@ class EncryptAllTest extends TestCase { ->willReturn($fileInfo); - if($isEncrypted) { + if ($isEncrypted) { $this->view->expects($this->never())->method('copy'); $this->view->expects($this->never())->method('rename'); } else { @@ -383,5 +379,4 @@ class EncryptAllTest extends TestCase { [false], ]; } - } diff --git a/apps/encryption/tests/Crypto/EncryptionTest.php b/apps/encryption/tests/Crypto/EncryptionTest.php index 1e4cfad5e30..dee1118a992 100644 --- a/apps/encryption/tests/Crypto/EncryptionTest.php +++ b/apps/encryption/tests/Crypto/EncryptionTest.php @@ -118,7 +118,6 @@ class EncryptionTest extends TestCase { $this->loggerMock, $this->l10nMock ); - } /** @@ -200,7 +199,6 @@ class EncryptionTest extends TestCase { * @dataProvider dataTestBegin */ public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected) { - $this->sessionMock->expects($this->once()) ->method('decryptAllModeActivated') ->willReturn(false); @@ -255,7 +253,6 @@ class EncryptionTest extends TestCase { * test begin() if decryptAll mode was activated */ public function testBeginDecryptAll() { - $path = '/user/files/foo.txt'; $recoveryKeyId = 'recoveryKeyId'; $recoveryShareKey = 'recoveryShareKey'; @@ -299,7 +296,6 @@ class EncryptionTest extends TestCase { * and continue */ public function testBeginInitMasterKey() { - $this->sessionMock->expects($this->once())->method('isReady')->willReturn(false); $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); @@ -343,7 +339,6 @@ class EncryptionTest extends TestCase { } public function testUpdateNoUsers() { - $this->invokePrivate($this->instance, 'rememberVersion', [['path' => 2]]); $this->keyManagerMock->expects($this->never())->method('getFileKey'); @@ -452,5 +447,4 @@ class EncryptionTest extends TestCase { $this->instance->prepareDecryptAll($input, $output, 'user'); } - } diff --git a/apps/encryption/tests/HookManagerTest.php b/apps/encryption/tests/HookManagerTest.php index c49938f4f3f..d1b6a4466af 100644 --- a/apps/encryption/tests/HookManagerTest.php +++ b/apps/encryption/tests/HookManagerTest.php @@ -56,7 +56,6 @@ class HookManagerTest extends TestCase { parent::setUpBeforeClass(); // have to make instance static to preserve data between tests self::$instance = new HookManager(); - } @@ -67,7 +66,5 @@ class HookManagerTest extends TestCase { $hookInstances = self::invokePrivate(self::$instance, 'hookInstances'); $this->assertCount(3, $hookInstances); - } - } diff --git a/apps/encryption/tests/Hooks/UserHooksTest.php b/apps/encryption/tests/Hooks/UserHooksTest.php index c676acb1e90..dcd82fe7e0f 100644 --- a/apps/encryption/tests/Hooks/UserHooksTest.php +++ b/apps/encryption/tests/Hooks/UserHooksTest.php @@ -155,7 +155,6 @@ class UserHooksTest extends TestCase { $this->instance->postPasswordReset($params); $passwordResetUsers = $this->invokePrivate($this->instance, 'passwordResetUsers'); $this->assertEmpty($passwordResetUsers); - } /** @@ -302,7 +301,6 @@ class UserHooksTest extends TestCase { } public function XtestSetPasswordNoUser() { - $userSessionMock = $this->getMockBuilder(IUserSession::class) ->disableOriginalConstructor() ->getMock(); @@ -390,7 +388,5 @@ class UserHooksTest extends TestCase { $this->recoveryMock ] )->setMethods(['setupFS'])->getMock(); - } - } diff --git a/apps/encryption/tests/KeyManagerTest.php b/apps/encryption/tests/KeyManagerTest.php index 02ab30f998c..da5777d75ab 100644 --- a/apps/encryption/tests/KeyManagerTest.php +++ b/apps/encryption/tests/KeyManagerTest.php @@ -250,7 +250,6 @@ class KeyManagerTest extends TestCase { }); $this->instance->userHasKeys($this->userId); - } /** @@ -286,7 +285,7 @@ class KeyManagerTest extends TestCase { $instance->expects($this->any())->method('getSystemPrivateKey')->with('masterKeyId')->willReturn('privateMasterKey'); $instance->expects($this->any())->method('getPrivateKey')->with($this->userId)->willReturn('privateUserKey'); - if($useMasterKey) { + if ($useMasterKey) { $this->cryptMock->expects($this->once())->method('decryptPrivateKey') ->with('privateMasterKey', 'masterKeyPassword', 'masterKeyId') ->willReturn('key'); @@ -381,7 +380,6 @@ class KeyManagerTest extends TestCase { * @param $expected */ public function testGetFileKey($uid, $isMasterKeyEnabled, $privateKey, $expected) { - $path = '/foo.txt'; if ($isMasterKeyEnabled) { @@ -422,7 +420,7 @@ class KeyManagerTest extends TestCase { $this->sessionMock->expects($this->once())->method('getPrivateKey')->willReturn($privateKey); } - if($privateKey) { + if ($privateKey) { $this->cryptMock->expects($this->once()) ->method('multiKeyDecrypt') ->willReturn(true); @@ -434,7 +432,6 @@ class KeyManagerTest extends TestCase { $this->assertSame($expected, $this->instance->getFileKey($path, $uid) ); - } public function testDeletePrivateKey() { @@ -467,7 +464,6 @@ class KeyManagerTest extends TestCase { * @param array $expectedKeys */ public function testAddSystemKeys($accessList, $publicKeys, $uid, $expectedKeys) { - $publicShareKeyId = 'publicShareKey'; $recoveryKeyId = 'recoveryKey'; @@ -574,7 +570,7 @@ class KeyManagerTest extends TestCase { $instance->expects($this->any())->method('getMasterKeyPassword')->willReturn('masterKeyPassword'); $this->cryptMock->expects($this->any())->method('generateHeader')->willReturn('header'); - if(empty($masterKey)) { + if (empty($masterKey)) { $this->cryptMock->expects($this->once())->method('createKeyPair') ->willReturn(['publicKey' => 'public', 'privateKey' => 'private']); $this->keyStorageMock->expects($this->once())->method('setSystemUserKey') @@ -677,5 +673,4 @@ class KeyManagerTest extends TestCase { ->with('OC_DEFAULT_MODULE', 'test', 'user1'); $this->instance->backupUserKeys('test', 'user1'); } - } diff --git a/apps/encryption/tests/RecoveryTest.php b/apps/encryption/tests/RecoveryTest.php index 5139e492f26..df5dc3241c0 100644 --- a/apps/encryption/tests/RecoveryTest.php +++ b/apps/encryption/tests/RecoveryTest.php @@ -172,7 +172,6 @@ class RecoveryTest extends TestCase { } public function testDisableAdminRecovery() { - $this->keyManagerMock->expects($this->exactly(2)) ->method('checkRecoveryPassword') ->willReturnOnConsecutiveCalls(true, false); @@ -185,7 +184,6 @@ class RecoveryTest extends TestCase { } public function testIsRecoveryEnabledForUser() { - $this->configMock->expects($this->exactly(2)) ->method('getUserValue') ->willReturnOnConsecutiveCalls('1', '0'); @@ -323,6 +321,4 @@ class RecoveryTest extends TestCase { } return null; } - - } diff --git a/apps/encryption/tests/SessionTest.php b/apps/encryption/tests/SessionTest.php index 279111e3c3b..19425cc8531 100644 --- a/apps/encryption/tests/SessionTest.php +++ b/apps/encryption/tests/SessionTest.php @@ -54,7 +54,6 @@ class SessionTest extends TestCase { public function testSetAndGetPrivateKey() { $this->instance->setPrivateKey('dummyPrivateKey'); $this->assertEquals('dummyPrivateKey', $this->instance->getPrivateKey()); - } /** diff --git a/apps/encryption/tests/Users/SetupTest.php b/apps/encryption/tests/Users/SetupTest.php index a580ca68e05..44bb2e55e86 100644 --- a/apps/encryption/tests/Users/SetupTest.php +++ b/apps/encryption/tests/Users/SetupTest.php @@ -84,7 +84,6 @@ class SetupTest extends TestCase { * @param bool $expected */ public function testSetupUser($hasKeys, $expected) { - $this->keyManagerMock->expects($this->once())->method('userHasKeys') ->with('uid')->willReturn($hasKeys); @@ -107,5 +106,4 @@ class SetupTest extends TestCase { [false, true] ]; } - } diff --git a/apps/encryption/tests/UtilTest.php b/apps/encryption/tests/UtilTest.php index d433826cb76..27c1469b031 100644 --- a/apps/encryption/tests/UtilTest.php +++ b/apps/encryption/tests/UtilTest.php @@ -216,5 +216,4 @@ class UtilTest extends TestCase { $this->assertEquals($return, $this->instance->getStorage($path)); } - } diff --git a/apps/federatedfilesharing/lib/AddressHandler.php b/apps/federatedfilesharing/lib/AddressHandler.php index 7ea3f304664..3a48e2adc86 100644 --- a/apps/federatedfilesharing/lib/AddressHandler.php +++ b/apps/federatedfilesharing/lib/AddressHandler.php @@ -149,7 +149,6 @@ class AddressHandler { public function urlContainProtocol($url) { if (strpos($url, 'https://') === 0 || strpos($url, 'http://') === 0) { - return true; } diff --git a/apps/federatedfilesharing/lib/AppInfo/Application.php b/apps/federatedfilesharing/lib/AppInfo/Application.php index 34666a62027..6dcb937605d 100644 --- a/apps/federatedfilesharing/lib/AppInfo/Application.php +++ b/apps/federatedfilesharing/lib/AppInfo/Application.php @@ -117,7 +117,6 @@ class Application extends App { } } ); - } /** @@ -170,5 +169,4 @@ class Application extends App { ); } - } diff --git a/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php b/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php index ebbff7b9c34..8af2d587fae 100644 --- a/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php +++ b/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php @@ -79,7 +79,6 @@ class RetryJob extends Job { \OC::$server->getCloudFederationFactory() ); } - } /** @@ -89,7 +88,6 @@ class RetryJob extends Job { * @param ILogger|null $logger */ public function execute($jobList, ILogger $logger = null) { - if ($this->shouldRun($this->argument)) { parent::execute($jobList, $logger); $jobList->remove($this, $this->argument); @@ -144,5 +142,4 @@ class RetryJob extends Job { $lastRun = (int)$argument['lastRun']; return ((time() - $lastRun) > $this->interval); } - } diff --git a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php index b46fab19449..64e12fcd251 100644 --- a/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php +++ b/apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php @@ -127,7 +127,6 @@ class MountPublicLinkController extends Controller { * @return JSONResponse */ public function createFederatedShare($shareWith, $token, $password = '') { - if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) { return new JSONResponse( ['message' => 'This server doesn\'t support outgoing federated shares'], diff --git a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php index e772d088f24..fe0f1b45e53 100644 --- a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php +++ b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php @@ -136,7 +136,6 @@ class RequestHandlerController extends OCSController { * @throws OCSException */ public function createShare() { - $remote = isset($_POST['remote']) ? $_POST['remote'] : null; $token = isset($_POST['token']) ? $_POST['token'] : null; $name = isset($_POST['name']) ? $_POST['name'] : null; @@ -197,7 +196,6 @@ class RequestHandlerController extends OCSController { * @throws OCSForbiddenException */ public function reShare($id) { - $token = $this->request->getParam('token', null); $shareWith = $this->request->getParam('shareWith', null); $permission = (int)$this->request->getParam('permission', null); @@ -251,7 +249,6 @@ class RequestHandlerController extends OCSController { * @throws \OC\HintException */ public function acceptShare($id) { - $token = isset($_POST['token']) ? $_POST['token'] : null; $notification = [ @@ -284,7 +281,6 @@ class RequestHandlerController extends OCSController { * @throws OCSException */ public function declineShare($id) { - $token = isset($_POST['token']) ? $_POST['token'] : null; $notification = [ @@ -317,7 +313,6 @@ class RequestHandlerController extends OCSController { * @throws OCSException */ public function unshare($id) { - if (!$this->isS2SEnabled()) { throw new OCSException('Server does not support federated cloud sharing', 503); } @@ -353,7 +348,6 @@ class RequestHandlerController extends OCSController { * @throws OCSBadRequestException */ public function revoke($id) { - $token = $this->request->getParam('token'); try { @@ -364,7 +358,6 @@ class RequestHandlerController extends OCSController { } catch (\Exception $e) { throw new OCSBadRequestException(); } - } /** @@ -374,7 +367,6 @@ class RequestHandlerController extends OCSController { * @return bool */ private function isS2SEnabled($incoming = false) { - $result = \OCP\App::isEnabled('files_sharing'); if ($incoming) { @@ -420,7 +412,6 @@ class RequestHandlerController extends OCSController { * @return array */ protected function ncPermissions2ocmPermissions($ncPermissions) { - $ocmPermissions = []; if ($ncPermissions & Constants::PERMISSION_SHARE) { @@ -437,7 +428,6 @@ class RequestHandlerController extends OCSController { } return $ocmPermissions; - } /** @@ -452,7 +442,6 @@ class RequestHandlerController extends OCSController { * @throws OCSException */ public function move($id) { - if (!$this->isS2SEnabled()) { throw new OCSException('Server does not support federated cloud sharing', 503); } diff --git a/apps/federatedfilesharing/lib/FederatedShareProvider.php b/apps/federatedfilesharing/lib/FederatedShareProvider.php index e1392b7a83a..aaa3e27cfd2 100644 --- a/apps/federatedfilesharing/lib/FederatedShareProvider.php +++ b/apps/federatedfilesharing/lib/FederatedShareProvider.php @@ -58,7 +58,6 @@ use OCP\Share\IShareProvider; * @package OCA\FederatedFileSharing */ class FederatedShareProvider implements IShareProvider { - const SHARE_TYPE_REMOTE = 6; /** @var IDBConnection */ @@ -165,7 +164,6 @@ class FederatedShareProvider implements IShareProvider { * @throws \Exception */ public function create(IShare $share) { - $shareWith = $share->getSharedWith(); $itemSource = $share->getNodeId(); $itemType = $share->getNodeType(); @@ -237,7 +235,6 @@ class FederatedShareProvider implements IShareProvider { $message_t = $this->l->t('File is already shared with %s', [$shareWith]); throw new \Exception($message_t); } - } else { $shareId = $this->createFederatedShare($share); } @@ -300,7 +297,7 @@ class FederatedShareProvider implements IShareProvider { $failure = true; } - if($failure) { + if ($failure) { $this->removeShareFromTableById($shareId); $message_t = $this->l->t('Sharing %1$s failed, could not find %2$s, maybe the server is currently unreachable or uses a self-signed certificate.', [$share->getNode()->getName(), $share->getSharedWith()]); @@ -308,7 +305,6 @@ class FederatedShareProvider implements IShareProvider { } return $shareId; - } /** @@ -319,7 +315,6 @@ class FederatedShareProvider implements IShareProvider { * @throws \Exception */ protected function askOwnerToReShare($shareWith, IShare $share, $shareId) { - $remoteShare = $this->getShareFromExternalShareTable($share); $token = $remoteShare['share_token']; $remoteId = $remoteShare['remote_id']; @@ -409,7 +404,7 @@ class FederatedShareProvider implements IShareProvider { * We allow updating the permissions of federated shares */ $qb = $this->dbConnection->getQueryBuilder(); - $qb->update('share') + $qb->update('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) ->set('permissions', $qb->createNamedParameter($share->getPermissions())) ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner())) @@ -523,7 +518,7 @@ class FederatedShareProvider implements IShareProvider { ->orderBy('id'); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $children[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -539,7 +534,6 @@ class FederatedShareProvider implements IShareProvider { * @throws \OC\HintException */ public function delete(IShare $share) { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith()); // if the local user is the owner we can send the unShare request directly... @@ -714,7 +708,7 @@ class FederatedShareProvider implements IShareProvider { $cursor = $qb->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -767,7 +761,7 @@ class FederatedShareProvider implements IShareProvider { ->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -806,7 +800,7 @@ class FederatedShareProvider implements IShareProvider { $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -881,7 +875,6 @@ class FederatedShareProvider implements IShareProvider { * @throws ShareNotFound */ private function createShareObject($data) { - $share = new Share($this->rootFolder, $this->userManager); $share->setId((int)$data['id']) ->setShareType((int)$data['share_type']) @@ -1119,7 +1112,7 @@ class FederatedShareProvider implements IShareProvider { ); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { try { $share = $this->createShareObject($data); } catch (InvalidShare $e) { diff --git a/apps/federatedfilesharing/lib/Notifications.php b/apps/federatedfilesharing/lib/Notifications.php index a70e947e3c1..6d11ea65096 100644 --- a/apps/federatedfilesharing/lib/Notifications.php +++ b/apps/federatedfilesharing/lib/Notifications.php @@ -94,7 +94,6 @@ class Notifications { * @throws \OC\ServerNotAvailableException */ public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) { - list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith); if ($user && $remote) { @@ -123,7 +122,6 @@ class Notifications { \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]); return true; } - } return false; @@ -144,7 +142,6 @@ class Notifications { * @throws \OC\ServerNotAvailableException */ public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) { - $fields = [ 'shareWith' => $shareWith, 'token' => $token, @@ -251,7 +248,6 @@ class Notifications { * @return boolean */ public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) { - $fields = [ 'token' => $token, 'remoteId' => $remoteId @@ -309,7 +305,6 @@ class Notifications { * @throws \Exception */ protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") { - if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) { $remoteDomain = 'https://' . $remoteDomain; } @@ -341,7 +336,6 @@ class Notifications { * @throws \Exception */ protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) { - $result = [ 'success' => false, 'result' => '', @@ -369,7 +363,6 @@ class Notifications { } return $result; - } /** @@ -440,6 +433,5 @@ class Notifications { } return false; - } } diff --git a/apps/federatedfilesharing/lib/Settings/Admin.php b/apps/federatedfilesharing/lib/Settings/Admin.php index 821421294e5..eb7423a4964 100644 --- a/apps/federatedfilesharing/lib/Settings/Admin.php +++ b/apps/federatedfilesharing/lib/Settings/Admin.php @@ -53,7 +53,6 @@ class Admin implements ISettings { * @return TemplateResponse */ public function getForm() { - $parameters = [ 'internalOnly' => $this->gsConfig->onlyInternalFederation(), 'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(), @@ -85,5 +84,4 @@ class Admin implements ISettings { public function getPriority() { return 20; } - } diff --git a/apps/federatedfilesharing/lib/TokenHandler.php b/apps/federatedfilesharing/lib/TokenHandler.php index 0e3fe7a049d..3922765aeba 100644 --- a/apps/federatedfilesharing/lib/TokenHandler.php +++ b/apps/federatedfilesharing/lib/TokenHandler.php @@ -30,7 +30,6 @@ use OCP\Security\ISecureRandom; * @package OCA\FederatedFileSharing */ class TokenHandler { - const TOKEN_LENGTH = 15; /** @var ISecureRandom */ @@ -56,5 +55,4 @@ class TokenHandler { ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS); return $token; } - } diff --git a/apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php b/apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php index 8af95e888b4..0e9b9dbed62 100644 --- a/apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php +++ b/apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php @@ -170,7 +170,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @since 14.0.0 */ public function shareReceived(ICloudFederationShare $share) { - if (!$this->isS2SEnabled(true)) { throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE); } @@ -205,7 +204,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { } if ($remote && $token && $name && $owner && $remoteId && $shareWith) { - if (!Util::isValidFileName($name)) { throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST); } @@ -283,7 +281,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { } throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST); - } /** @@ -301,7 +298,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @since 14.0.0 */ public function notificationReceived($notificationType, $providerId, array $notification) { - switch ($notificationType) { case 'SHARE_ACCEPTED': return $this->shareAccepted($providerId, $notification); @@ -378,7 +374,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @throws \OC\HintException */ private function shareAccepted($id, array $notification) { - if (!$this->isS2SEnabled()) { throw new ActionNotSupportedException('Server does not support federated cloud sharing'); } @@ -408,7 +403,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { ); $this->cloudFederationProviderManager->sendNotification($remote, $notification); - } return []; @@ -450,7 +444,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * */ protected function shareDeclined($id, array $notification) { - if (!$this->isS2SEnabled()) { throw new ActionNotSupportedException('Server does not support federated cloud sharing'); } @@ -485,7 +478,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { $this->executeDeclineShare($share); return []; - } /** @@ -512,7 +504,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { ->setObject('files', $fileId, $file) ->setLink($link); $this->activityManager->publish($event); - } /** @@ -547,7 +538,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @throws BadRequestException */ private function unshare($id, array $notification) { - if (!$this->isS2SEnabled(true)) { throw new ActionNotSupportedException("incoming shares disabled!"); } @@ -572,7 +562,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { $result->closeCursor(); if ($token && $id && !empty($share)) { - $remote = $this->cleanupRemote($share['remote']); $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote); @@ -639,7 +628,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @throws ShareNotFound */ protected function reshareRequested($id, array $notification) { - if (!isset($notification['sharedSecret'])) { throw new BadRequestException(['sharedSecret']); } @@ -681,7 +669,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { } else { throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id); } - } /** @@ -695,7 +682,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @throws BadRequestException */ protected function updateResharePermissions($id, array $notification) { - if (!isset($notification['sharedSecret'])) { throw new BadRequestException(['sharedSecret']); } @@ -725,7 +711,7 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { */ protected function ocmPermissions2ncPermissions(array $ocmPermissions) { $ncPermissions = 0; - foreach($ocmPermissions as $permission) { + foreach ($ocmPermissions as $permission) { switch (strtolower($permission)) { case 'read': $ncPermissions += Constants::PERMISSION_READ; @@ -739,7 +725,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { default: throw new BadRequestException(['permission']); } - } return $ncPermissions; @@ -779,7 +764,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { $link = Util::linkToAbsolute('files', 'index.php', $args); return [$file, $link]; - } /** @@ -836,7 +820,6 @@ class CloudFederationProviderFiles implements ICloudFederationProvider { * @return bool */ private function isS2SEnabled($incoming = false) { - $result = $this->appManager->isEnabledForUser('files_sharing'); if ($incoming) { diff --git a/apps/federatedfilesharing/templates/settings-admin.php b/apps/federatedfilesharing/templates/settings-admin.php index fbbeecd88bf..a7041d90821 100644 --- a/apps/federatedfilesharing/templates/settings-admin.php +++ b/apps/federatedfilesharing/templates/settings-admin.php @@ -5,7 +5,7 @@ script('federatedfilesharing', 'settings-admin'); style('federatedfilesharing', 'settings-admin'); ?> - +

@@ -19,29 +19,37 @@ style('federatedfilesharing', 'settings-admin');

/> + value="1" />

/> + value="1" />

- +

/> + value="1" />

/> + value="1" />
@@ -49,14 +57,18 @@ style('federatedfilesharing', 'settings-admin');

/> + value="1" />

/> + value="1" />
diff --git a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php index 123f669e74e..e6b4c09ccc5 100644 --- a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php @@ -135,7 +135,6 @@ class MountPublicLinkControllerTest extends \Test\TestCase { $createSuccessful, $expectedReturnData ) { - $this->federatedShareProvider->expects($this->any()) ->method('isOutgoingServer2serverShareEnabled') ->willReturn($outgoingSharesAllowed); @@ -188,9 +187,7 @@ class MountPublicLinkControllerTest extends \Test\TestCase { $this->assertSame(Http::STATUS_OK, $result->getStatus()); $this->assertTrue(isset($result->getData()['remoteUrl'])); $this->assertSame($expectedReturnData, $result->getData()['remoteUrl']); - } - } public function dataTestCreateFederatedShare() { @@ -207,5 +204,4 @@ class MountPublicLinkControllerTest extends \Test\TestCase { ['user@server', false, true, 'token', true, true, 'This server doesn\'t support outgoing federated shares'], ]; } - } diff --git a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php index f8de6919be6..df138333de6 100644 --- a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php @@ -48,7 +48,6 @@ use OCP\Share\IShare; * @group DB */ class RequestHandlerControllerTest extends \Test\TestCase { - private $owner = 'owner'; private $user1 = 'user1'; private $user2 = 'user2'; @@ -102,7 +101,6 @@ class RequestHandlerControllerTest extends \Test\TestCase { private $cloudFederationShare; protected function setUp(): void { - $this->share = $this->getMockBuilder(IShare::class)->getMock(); $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') ->disableOriginalConstructor()->getMock(); @@ -144,7 +142,6 @@ class RequestHandlerControllerTest extends \Test\TestCase { $this->cloudFederationFactory, $this->cloudFederationProviderManager ); - } function testCreateShare() { @@ -186,11 +183,9 @@ class RequestHandlerControllerTest extends \Test\TestCase { $result = $this->requestHandler->createShare(); $this->assertInstanceOf(DataResponse::class, $result); - } function testDeclineShare() { - $id = 42; $_POST['token'] = 'token'; @@ -211,12 +206,10 @@ class RequestHandlerControllerTest extends \Test\TestCase { $result = $this->requestHandler->declineShare($id); $this->assertInstanceOf(DataResponse::class, $result); - } function testAcceptShare() { - $id = 42; $_POST['token'] = 'token'; @@ -237,8 +230,5 @@ class RequestHandlerControllerTest extends \Test\TestCase { $result = $this->requestHandler->acceptShare($id); $this->assertInstanceOf(DataResponse::class, $result); - } - - } diff --git a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php index 1c82c310c1f..825b8382d1e 100644 --- a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php +++ b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php @@ -415,7 +415,6 @@ class FederatedShareProviderTest extends \Test\TestCase { * */ public function testUpdate($owner, $sharedBy) { - $this->provider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') ->setConstructorArgs( [ @@ -468,7 +467,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $sharedBy . '@http://localhost/' )->willReturn(true); - if($owner === $sharedBy) { + if ($owner === $sharedBy) { $this->provider->expects($this->never())->method('sendPermissionUpdate'); } else { $this->provider->expects($this->once())->method('sendPermissionUpdate'); @@ -631,7 +630,7 @@ class FederatedShareProviderTest extends \Test\TestCase { return ['user', 'server.com']; } return ['user2', 'server.com']; - }); + }); $this->tokenHandler->method('generateToken')->willReturn('token'); $this->notifications diff --git a/apps/federatedfilesharing/tests/NotificationsTest.php b/apps/federatedfilesharing/tests/NotificationsTest.php index a835709c978..af48b594380 100644 --- a/apps/federatedfilesharing/tests/NotificationsTest.php +++ b/apps/federatedfilesharing/tests/NotificationsTest.php @@ -62,7 +62,6 @@ class NotificationsTest extends \Test\TestCase { ->disableOriginalConstructor()->getMock(); $this->cloudFederationProviderManager = $this->createMock(ICloudFederationProviderManager::class); $this->cloudFederationFactory = $this->createMock(ICloudFederationFactory::class); - } /** @@ -142,7 +141,6 @@ class NotificationsTest extends \Test\TestCase { $this->assertSame($expected, $instance->sendUpdateToRemote($remote, $id, $token, $action, ['data1Key' => 'data1Value'], $try) ); - } @@ -162,5 +160,4 @@ class NotificationsTest extends \Test\TestCase { [0, ['success' => false, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 400]]])], false], ]; } - } diff --git a/apps/federatedfilesharing/tests/TestCase.php b/apps/federatedfilesharing/tests/TestCase.php index 83393af69f6..813c3c8a15f 100644 --- a/apps/federatedfilesharing/tests/TestCase.php +++ b/apps/federatedfilesharing/tests/TestCase.php @@ -36,7 +36,6 @@ use OC\Group\Database; * Base class for sharing tests. */ abstract class TestCase extends \Test\TestCase { - const TEST_FILES_SHARING_API_USER1 = "test-share-user1"; const TEST_FILES_SHARING_API_USER2 = "test-share-user2"; @@ -91,7 +90,6 @@ abstract class TestCase extends \Test\TestCase { * @param bool $password */ protected static function loginHelper($user, $create = false, $password = false) { - if ($password === false) { $password = $user; } @@ -129,5 +127,4 @@ abstract class TestCase extends \Test\TestCase { $isInitialized->setValue($storage, false); $isInitialized->setAccessible(false); } - } diff --git a/apps/federatedfilesharing/tests/TokenHandlerTest.php b/apps/federatedfilesharing/tests/TokenHandlerTest.php index 8ddc4bc039b..50479654752 100644 --- a/apps/federatedfilesharing/tests/TokenHandlerTest.php +++ b/apps/federatedfilesharing/tests/TokenHandlerTest.php @@ -47,7 +47,6 @@ class TokenHandlerTest extends \Test\TestCase { } public function testGenerateToken() { - $this->secureRandom->expects($this->once())->method('generate') ->with( $this->expectedTokenLength, @@ -56,7 +55,5 @@ class TokenHandlerTest extends \Test\TestCase { ->willReturn('mytoken'); $this->assertSame('mytoken', $this->tokenHandler->generateToken()); - } - } diff --git a/apps/federation/lib/AppInfo/Application.php b/apps/federation/lib/AppInfo/Application.php index 119756b16e4..cc5f63309af 100644 --- a/apps/federation/lib/AppInfo/Application.php +++ b/apps/federation/lib/AppInfo/Application.php @@ -57,7 +57,6 @@ class Application extends App { * list of trusted servers. */ public function registerHooks() { - $container = $this->getContainer(); $hooksManager = $container->query(Hooks::class); @@ -81,5 +80,4 @@ class Application extends App { } }); } - } diff --git a/apps/federation/lib/BackgroundJob/GetSharedSecret.php b/apps/federation/lib/BackgroundJob/GetSharedSecret.php index ad526885d0f..c86c7f1d75a 100644 --- a/apps/federation/lib/BackgroundJob/GetSharedSecret.php +++ b/apps/federation/lib/BackgroundJob/GetSharedSecret.php @@ -181,7 +181,6 @@ class GetSharedSecret extends Job { ); $status = $result->getStatusCode(); - } catch (ClientException $e) { $status = $e->getCode(); if ($status === Http::STATUS_FORBIDDEN) { @@ -232,7 +231,6 @@ class GetSharedSecret extends Job { $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE); } } - } /** diff --git a/apps/federation/lib/BackgroundJob/RequestSharedSecret.php b/apps/federation/lib/BackgroundJob/RequestSharedSecret.php index 4eaa94a53d5..990f5025bf5 100644 --- a/apps/federation/lib/BackgroundJob/RequestSharedSecret.php +++ b/apps/federation/lib/BackgroundJob/RequestSharedSecret.php @@ -142,7 +142,6 @@ class RequestSharedSecret extends Job { } protected function run($argument) { - $target = $argument['url']; $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime(); $currentTime = $this->timeFactory->getTime(); @@ -179,7 +178,6 @@ class RequestSharedSecret extends Job { ); $status = $result->getStatusCode(); - } catch (ClientException $e) { $status = $e->getCode(); if ($status === Http::STATUS_FORBIDDEN) { @@ -205,7 +203,6 @@ class RequestSharedSecret extends Job { ) { $this->retainJob = true; } - } /** diff --git a/apps/federation/lib/Command/SyncFederationAddressBooks.php b/apps/federation/lib/Command/SyncFederationAddressBooks.php index cad000cf71f..709cd60b3ba 100644 --- a/apps/federation/lib/Command/SyncFederationAddressBooks.php +++ b/apps/federation/lib/Command/SyncFederationAddressBooks.php @@ -57,13 +57,11 @@ class SyncFederationAddressBooks extends Command { * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { - $progress = new ProgressBar($output); $progress->start(); $this->syncService->syncThemAll(function ($url, $ex) use ($progress, $output) { if ($ex instanceof \Exception) { $output->writeln("Error while syncing $url : " . $ex->getMessage()); - } else { $progress->advance(); } diff --git a/apps/federation/lib/Controller/OCSAuthAPIController.php b/apps/federation/lib/Controller/OCSAuthAPIController.php index 38293dca736..ecd0757f6fb 100644 --- a/apps/federation/lib/Controller/OCSAuthAPIController.php +++ b/apps/federation/lib/Controller/OCSAuthAPIController.php @@ -46,7 +46,7 @@ use OCP\Security\ISecureRandom; * * @package OCA\Federation\Controller */ -class OCSAuthAPIController extends OCSController{ +class OCSAuthAPIController extends OCSController { /** @var ISecureRandom */ private $secureRandom; @@ -181,7 +181,6 @@ class OCSAuthAPIController extends OCSController{ * @throws OCSForbiddenException */ public function getSharedSecret($url, $token) { - if ($this->trustedServers->isTrustedServer($url) === false) { $this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']); throw new OCSForbiddenException(); diff --git a/apps/federation/lib/Controller/SettingsController.php b/apps/federation/lib/Controller/SettingsController.php index 00b2885f66d..7f68f238366 100644 --- a/apps/federation/lib/Controller/SettingsController.php +++ b/apps/federation/lib/Controller/SettingsController.php @@ -119,5 +119,4 @@ class SettingsController extends Controller { return true; } - } diff --git a/apps/federation/lib/DbHandler.php b/apps/federation/lib/DbHandler.php index 6adad5b69d1..dddb7e13297 100644 --- a/apps/federation/lib/DbHandler.php +++ b/apps/federation/lib/DbHandler.php @@ -330,5 +330,4 @@ class DbHandler { $statement->closeCursor(); return !empty($result); } - } diff --git a/apps/federation/lib/Hooks.php b/apps/federation/lib/Hooks.php index 3f6a45422a7..f02409ef242 100644 --- a/apps/federation/lib/Hooks.php +++ b/apps/federation/lib/Hooks.php @@ -44,5 +44,4 @@ class Hooks { $this->trustedServers->addServer($params['server']); } } - } diff --git a/apps/federation/lib/Middleware/AddServerMiddleware.php b/apps/federation/lib/Middleware/AddServerMiddleware.php index 043d10d0455..ffce7710223 100644 --- a/apps/federation/lib/Middleware/AddServerMiddleware.php +++ b/apps/federation/lib/Middleware/AddServerMiddleware.php @@ -87,7 +87,5 @@ class AddServerMiddleware extends Middleware { ['message' => $message], Http::STATUS_BAD_REQUEST ); - } - } diff --git a/apps/federation/lib/Settings/Admin.php b/apps/federation/lib/Settings/Admin.php index d363397e9e7..9dd06dc8f53 100644 --- a/apps/federation/lib/Settings/Admin.php +++ b/apps/federation/lib/Settings/Admin.php @@ -65,5 +65,4 @@ class Admin implements ISettings { public function getPriority() { return 30; } - } diff --git a/apps/federation/lib/SyncFederationAddressBooks.php b/apps/federation/lib/SyncFederationAddressBooks.php index f0e3d2ba38b..3ec233df037 100644 --- a/apps/federation/lib/SyncFederationAddressBooks.php +++ b/apps/federation/lib/SyncFederationAddressBooks.php @@ -60,7 +60,6 @@ class SyncFederationAddressBooks { * @param \Closure $callback */ public function syncThemAll(\Closure $callback) { - $trustedServers = $this->dbHandler->getAllServer(); foreach ($trustedServers as $trustedServer) { $url = $trustedServer['url']; diff --git a/apps/federation/lib/TrustedServers.php b/apps/federation/lib/TrustedServers.php index 2a3a2d809b9..3d659e7eb95 100644 --- a/apps/federation/lib/TrustedServers.php +++ b/apps/federation/lib/TrustedServers.php @@ -239,7 +239,6 @@ class TrustedServers { ); if ($result->getStatusCode() === Http::STATUS_OK) { $isValidOwnCloud = $this->checkOwnCloudVersion($result->getBody()); - } } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ @@ -282,9 +281,7 @@ class TrustedServers { strpos($url, 'https://') === 0 || strpos($url, 'http://') === 0 ) { - return $url; - } return 'https://' . $url; diff --git a/apps/federation/templates/settings-admin.php b/apps/federation/templates/settings-admin.php index f0c2db81961..2bc3684ccd9 100644 --- a/apps/federation/templates/settings-admin.php +++ b/apps/federation/templates/settings-admin.php @@ -11,17 +11,19 @@ style('federation', 'settings-admin')

t('Federation allows you to connect with other trusted servers to exchange the user directory. For example this will be used to auto-complete external users for federated sharing.')); ?>

- /> + />

    - +
  • - + diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php index ba84d718df6..691b9fb19a4 100644 --- a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php @@ -158,7 +158,6 @@ class GetSharedSecretTest extends TestCase { } $getSharedSecret->execute($this->jobList); - } public function dataTestExecute() { diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php index f35654b0895..2ef6fd4250d 100644 --- a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php @@ -150,7 +150,6 @@ class RequestSharedSecretTest extends TestCase { } $requestSharedSecret->execute($this->jobList); - } public function dataTestExecute() { @@ -167,7 +166,6 @@ class RequestSharedSecretTest extends TestCase { * @param int $statusCode */ public function testRun($statusCode) { - $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; diff --git a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php index c8a79748534..791928a8ccc 100644 --- a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php +++ b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php @@ -91,7 +91,6 @@ class OCSAuthAPIControllerTest extends TestCase { $this->timeFactory->method('getTime') ->willReturn($this->currentTime); - } /** @@ -103,7 +102,6 @@ class OCSAuthAPIControllerTest extends TestCase { * @param bool $ok */ public function testRequestSharedSecret($token, $localToken, $isTrustedServer, $ok) { - $url = 'url'; $this->trustedServers @@ -144,7 +142,6 @@ class OCSAuthAPIControllerTest extends TestCase { * @param bool $ok */ public function testGetSharedSecret($isTrustedServer, $isValidToken, $ok) { - $url = 'url'; $token = 'token'; @@ -169,7 +166,7 @@ class OCSAuthAPIControllerTest extends TestCase { $ocsAuthApi->expects($this->any()) ->method('isValidToken')->with($url, $token)->willReturn($isValidToken); - if($ok) { + if ($ok) { $this->secureRandom->expects($this->once())->method('generate')->with(32) ->willReturn('secret'); $this->trustedServers->expects($this->once()) @@ -197,5 +194,4 @@ class OCSAuthAPIControllerTest extends TestCase { [false, false, false], ]; } - } diff --git a/apps/federation/tests/Controller/SettingsControllerTest.php b/apps/federation/tests/Controller/SettingsControllerTest.php index 48c9b91268a..90db0b58035 100644 --- a/apps/federation/tests/Controller/SettingsControllerTest.php +++ b/apps/federation/tests/Controller/SettingsControllerTest.php @@ -127,7 +127,6 @@ class SettingsControllerTest extends TestCase { $this->assertTrue( $this->invokePrivate($this->controller, 'checkServer', ['url']) ); - } /** @@ -153,7 +152,6 @@ class SettingsControllerTest extends TestCase { $this->assertTrue( $this->invokePrivate($this->controller, 'checkServer', ['url']) ); - } /** @@ -167,5 +165,4 @@ class SettingsControllerTest extends TestCase { [false, false] ]; } - } diff --git a/apps/federation/tests/HooksTest.php b/apps/federation/tests/HooksTest.php index 0bbf2bfb7ac..afb6b2408f9 100644 --- a/apps/federation/tests/HooksTest.php +++ b/apps/federation/tests/HooksTest.php @@ -66,7 +66,6 @@ class HooksTest extends TestCase { } $this->hooks->addServerHook(['server' => 'url']); - } public function dataTestAddServerHook() { diff --git a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php index a43ad557dae..a50f5e5851f 100644 --- a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php +++ b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php @@ -70,7 +70,6 @@ class AddServerMiddlewareTest extends TestCase { * @param string $hint */ public function testAfterException($exception, $hint) { - $this->logger->expects($this->once())->method('logException'); $this->l10n->expects($this->any())->method('t') @@ -99,5 +98,4 @@ class AddServerMiddlewareTest extends TestCase { [new \Exception('message'), 'message'], ]; } - } diff --git a/apps/federation/tests/TrustedServersTest.php b/apps/federation/tests/TrustedServersTest.php index 59b1c577e75..67814ee96ac 100644 --- a/apps/federation/tests/TrustedServersTest.php +++ b/apps/federation/tests/TrustedServersTest.php @@ -100,7 +100,6 @@ class TrustedServersTest extends TestCase { $this->dispatcher, $this->timeFactory ); - } /** @@ -267,7 +266,6 @@ class TrustedServersTest extends TestCase { * @param bool $expected */ public function testIsOwnCloudServer($statusCode, $isValidOwnCloudVersion, $expected) { - $server = 'server1'; /** @var \PHPUnit_Framework_MockObject_MockObject | TrustedServers $trustedServers */ @@ -306,7 +304,6 @@ class TrustedServersTest extends TestCase { $this->assertSame($expected, $trustedServers->isOwnCloudServer($server) ); - } public function dataTestIsOwnCloudServer() { diff --git a/apps/files/ajax/download.php b/apps/files/ajax/download.php index e6be330c9b3..25d70c7ebcf 100644 --- a/apps/files/ajax/download.php +++ b/apps/files/ajax/download.php @@ -46,7 +46,7 @@ if (!is_array($files_list)) { * the content must not be longer than 32 characters and must only contain * alphanumeric characters */ -if(isset($_GET['downloadStartSecret']) +if (isset($_GET['downloadStartSecret']) && !isset($_GET['downloadStartSecret'][32]) && preg_match('!^[a-zA-Z0-9]+$!', $_GET['downloadStartSecret']) === 1) { setcookie('ocDownloadStarted', $_GET['downloadStartSecret'], time() + 20, '/'); diff --git a/apps/files/lib/Activity/FavoriteProvider.php b/apps/files/lib/Activity/FavoriteProvider.php index 38d40fde047..9cf1255765b 100644 --- a/apps/files/lib/Activity/FavoriteProvider.php +++ b/apps/files/lib/Activity/FavoriteProvider.php @@ -32,7 +32,6 @@ use OCP\IURLGenerator; use OCP\L10N\IFactory; class FavoriteProvider implements IProvider { - const SUBJECT_ADDED = 'added_favorite'; const SUBJECT_REMOVED = 'removed_favorite'; @@ -97,7 +96,6 @@ class FavoriteProvider implements IProvider { * @since 11.0.0 */ public function parseShortVersion(IEvent $event) { - if ($event->getSubject() === self::SUBJECT_ADDED) { $event->setParsedSubject($this->l->t('Added to favorites')); if ($this->activityManager->getRequirePNG()) { @@ -128,7 +126,6 @@ class FavoriteProvider implements IProvider { * @since 11.0.0 */ public function parseLongVersion(IEvent $event, IEvent $previousEvent = null) { - if ($event->getSubject() === self::SUBJECT_ADDED) { $subject = $this->l->t('You added {file} to your favorites'); if ($this->activityManager->getRequirePNG()) { diff --git a/apps/files/lib/AppInfo/Application.php b/apps/files/lib/AppInfo/Application.php index dd7ea19ba4a..9ee705f11c3 100644 --- a/apps/files/lib/AppInfo/Application.php +++ b/apps/files/lib/AppInfo/Application.php @@ -47,7 +47,6 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IContainer; class Application extends App { - public const APP_ID = 'files'; public function __construct(array $urlParams=[]) { diff --git a/apps/files/lib/BackgroundJob/CleanupDirectEditingTokens.php b/apps/files/lib/BackgroundJob/CleanupDirectEditingTokens.php index f3c473fb2fc..4b4f36663ab 100644 --- a/apps/files/lib/BackgroundJob/CleanupDirectEditingTokens.php +++ b/apps/files/lib/BackgroundJob/CleanupDirectEditingTokens.php @@ -27,7 +27,6 @@ use OC\BackgroundJob\TimedJob; use OCP\DirectEditing\IManager; class CleanupDirectEditingTokens extends TimedJob { - private const INTERVAL_MINUTES = 15 * 60; /** diff --git a/apps/files/lib/BackgroundJob/CleanupFileLocks.php b/apps/files/lib/BackgroundJob/CleanupFileLocks.php index 45729fd1e36..a69ee51bfb1 100644 --- a/apps/files/lib/BackgroundJob/CleanupFileLocks.php +++ b/apps/files/lib/BackgroundJob/CleanupFileLocks.php @@ -53,7 +53,7 @@ class CleanupFileLocks extends TimedJob { */ public function run($argument) { $lockingProvider = \OC::$server->getLockingProvider(); - if($lockingProvider instanceof DBLockingProvider) { + if ($lockingProvider instanceof DBLockingProvider) { $lockingProvider->cleanExpiredLocks(); } } diff --git a/apps/files/lib/BackgroundJob/DeleteOrphanedItems.php b/apps/files/lib/BackgroundJob/DeleteOrphanedItems.php index 5c0c92b6034..b0f91b70401 100644 --- a/apps/files/lib/BackgroundJob/DeleteOrphanedItems.php +++ b/apps/files/lib/BackgroundJob/DeleteOrphanedItems.php @@ -31,7 +31,6 @@ use OCP\DB\QueryBuilder\IQueryBuilder; * Delete all share entries that have no matching entries in the file cache table. */ class DeleteOrphanedItems extends TimedJob { - const CHUNK_SIZE = 200; /** @var \OCP\IDBConnection */ @@ -150,5 +149,4 @@ class DeleteOrphanedItems extends TimedJob { $this->logger->debug("$deletedEntries orphaned comment read marks deleted", ['app' => 'DeleteOrphanedItems']); return $deletedEntries; } - } diff --git a/apps/files/lib/BackgroundJob/TransferOwnership.php b/apps/files/lib/BackgroundJob/TransferOwnership.php index ec89adafa86..2498cc865ff 100644 --- a/apps/files/lib/BackgroundJob/TransferOwnership.php +++ b/apps/files/lib/BackgroundJob/TransferOwnership.php @@ -122,7 +122,6 @@ class TransferOwnership extends QueuedJob { } $this->mapper->delete($transfer); - } private function failedNotication(Transfer $transfer): void { diff --git a/apps/files/lib/Capabilities.php b/apps/files/lib/Capabilities.php index ad5c4e1b773..c46ad01af71 100644 --- a/apps/files/lib/Capabilities.php +++ b/apps/files/lib/Capabilities.php @@ -75,6 +75,4 @@ class Capabilities implements ICapability { ], ]; } - - } diff --git a/apps/files/lib/Collaboration/Resources/ResourceProvider.php b/apps/files/lib/Collaboration/Resources/ResourceProvider.php index d747253f8ff..b4a97afbb56 100644 --- a/apps/files/lib/Collaboration/Resources/ResourceProvider.php +++ b/apps/files/lib/Collaboration/Resources/ResourceProvider.php @@ -37,7 +37,6 @@ use OCP\IURLGenerator; use OCP\IUser; class ResourceProvider implements IProvider { - public const RESOURCE_TYPE = 'file'; /** @var IRootFolder */ diff --git a/apps/files/lib/Command/DeleteOrphanedFiles.php b/apps/files/lib/Command/DeleteOrphanedFiles.php index 2a63f344a92..c5072983ef4 100644 --- a/apps/files/lib/Command/DeleteOrphanedFiles.php +++ b/apps/files/lib/Command/DeleteOrphanedFiles.php @@ -32,7 +32,6 @@ use Symfony\Component\Console\Output\OutputInterface; * Delete all file entries that have no matching entries in the storage table. */ class DeleteOrphanedFiles extends Command { - const CHUNK_SIZE = 200; /** @@ -79,5 +78,4 @@ class DeleteOrphanedFiles extends Command { $output->writeln("$deletedEntries orphaned file cache entries deleted"); } - } diff --git a/apps/files/lib/Command/Scan.php b/apps/files/lib/Command/Scan.php index 024899e5f5c..c75073e428f 100644 --- a/apps/files/lib/Command/Scan.php +++ b/apps/files/lib/Command/Scan.php @@ -321,5 +321,4 @@ class Scan extends Base { } return $connection; } - } diff --git a/apps/files/lib/Command/TransferOwnership.php b/apps/files/lib/Command/TransferOwnership.php index 7ada9ce8820..b1d90452c23 100644 --- a/apps/files/lib/Command/TransferOwnership.php +++ b/apps/files/lib/Command/TransferOwnership.php @@ -115,5 +115,4 @@ class TransferOwnership extends Command { return 0; } - } diff --git a/apps/files/lib/Controller/AjaxController.php b/apps/files/lib/Controller/AjaxController.php index 00637cc0936..52b774915ea 100644 --- a/apps/files/lib/Controller/AjaxController.php +++ b/apps/files/lib/Controller/AjaxController.php @@ -33,7 +33,6 @@ use OCP\Files\NotFoundException; use OCP\IRequest; class AjaxController extends Controller { - public function __construct(string $appName, IRequest $request) { parent::__construct($appName, $request); } diff --git a/apps/files/lib/Controller/ApiController.php b/apps/files/lib/Controller/ApiController.php index 3819e07909d..2aa3b777225 100644 --- a/apps/files/lib/Controller/ApiController.php +++ b/apps/files/lib/Controller/ApiController.php @@ -339,5 +339,4 @@ class ApiController extends Controller { $node = $this->userFolder->get($folderpath); return $node->getType(); } - } diff --git a/apps/files/lib/Controller/TransferOwnershipController.php b/apps/files/lib/Controller/TransferOwnershipController.php index 43b198fe18b..fb3f3dffd6c 100644 --- a/apps/files/lib/Controller/TransferOwnershipController.php +++ b/apps/files/lib/Controller/TransferOwnershipController.php @@ -193,5 +193,4 @@ class TransferOwnershipController extends OCSController { return new DataResponse([], Http::STATUS_OK); } - } diff --git a/apps/files/lib/Controller/ViewController.php b/apps/files/lib/Controller/ViewController.php index 7c5d2a08b88..73ee589fdbc 100644 --- a/apps/files/lib/Controller/ViewController.php +++ b/apps/files/lib/Controller/ViewController.php @@ -205,7 +205,6 @@ class ViewController extends Controller { $navBarPositionPosition = 6; $currentCount = 0; foreach ($favElements['folders'] as $dir) { - $link = $this->urlGenerator->linkToRoute('files.view.index', ['dir' => $dir, 'view' => 'files']); $sortingValue = ++$currentCount; $element = [ diff --git a/apps/files/lib/Db/TransferOwnership.php b/apps/files/lib/Db/TransferOwnership.php index 73c39ccebd2..acde06a977c 100644 --- a/apps/files/lib/Db/TransferOwnership.php +++ b/apps/files/lib/Db/TransferOwnership.php @@ -57,6 +57,4 @@ class TransferOwnership extends Entity { $this->addType('fileId', 'integer'); $this->addType('nodeName', 'string'); } - - } diff --git a/apps/files/lib/Db/TransferOwnershipMapper.php b/apps/files/lib/Db/TransferOwnershipMapper.php index 2cca83ba178..e1e373eaab9 100644 --- a/apps/files/lib/Db/TransferOwnershipMapper.php +++ b/apps/files/lib/Db/TransferOwnershipMapper.php @@ -46,5 +46,4 @@ class TransferOwnershipMapper extends QBMapper { return $this->findEntity($qb); } - } diff --git a/apps/files/lib/Event/LoadAdditionalScriptsEvent.php b/apps/files/lib/Event/LoadAdditionalScriptsEvent.php index 51682be6a41..d9c80a23207 100644 --- a/apps/files/lib/Event/LoadAdditionalScriptsEvent.php +++ b/apps/files/lib/Event/LoadAdditionalScriptsEvent.php @@ -29,7 +29,6 @@ namespace OCA\Files\Event; use OCP\EventDispatcher\Event; class LoadAdditionalScriptsEvent extends Event { - private $hiddenFields = []; public function addHiddenField(string $name, string $value): void { diff --git a/apps/files/lib/Event/LoadSidebar.php b/apps/files/lib/Event/LoadSidebar.php index a16eb1439ee..8f3892c60c2 100644 --- a/apps/files/lib/Event/LoadSidebar.php +++ b/apps/files/lib/Event/LoadSidebar.php @@ -29,5 +29,4 @@ namespace OCA\Files\Event; use OCP\EventDispatcher\Event; class LoadSidebar extends Event { - } diff --git a/apps/files/lib/Exception/TransferOwnershipException.php b/apps/files/lib/Exception/TransferOwnershipException.php index dad5dc13679..2fe7287f88f 100644 --- a/apps/files/lib/Exception/TransferOwnershipException.php +++ b/apps/files/lib/Exception/TransferOwnershipException.php @@ -29,5 +29,4 @@ namespace OCA\Files\Exception; use Exception; class TransferOwnershipException extends Exception { - } diff --git a/apps/files/lib/Helper.php b/apps/files/lib/Helper.php index b3a62aee1c5..3431fb2ffc7 100644 --- a/apps/files/lib/Helper.php +++ b/apps/files/lib/Helper.php @@ -73,7 +73,7 @@ class Helper { * @return string icon URL */ public static function determineIcon($file) { - if($file['type'] === 'dir') { + if ($file['type'] === 'dir') { $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir'); // TODO: move this part to the client side, using mountType if ($file->isShared()) { @@ -81,7 +81,7 @@ class Helper { } elseif ($file->isMounted()) { $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external'); } - }else{ + } else { $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype()); } @@ -234,7 +234,6 @@ class Helper { if (!empty($tags)) { foreach ($tags as $fileId => $fileTags) { - foreach ($fileList as $key => $fileData) { if ($fileId !== $fileData[$fileIdentifier]) { continue; diff --git a/apps/files/lib/Listener/LegacyLoadAdditionalScriptsAdapter.php b/apps/files/lib/Listener/LegacyLoadAdditionalScriptsAdapter.php index 8dddb079eb0..298d7194cde 100644 --- a/apps/files/lib/Listener/LegacyLoadAdditionalScriptsAdapter.php +++ b/apps/files/lib/Listener/LegacyLoadAdditionalScriptsAdapter.php @@ -55,5 +55,4 @@ class LegacyLoadAdditionalScriptsAdapter implements IEventListener { $event->addHiddenField($name, $value); } } - } diff --git a/apps/files/lib/Listener/LoadSidebarListener.php b/apps/files/lib/Listener/LoadSidebarListener.php index cc99c102081..902b6bd387a 100644 --- a/apps/files/lib/Listener/LoadSidebarListener.php +++ b/apps/files/lib/Listener/LoadSidebarListener.php @@ -43,5 +43,4 @@ class LoadSidebarListener implements IEventListener { // TODO: remove when all tabs migrated to the new api Util::addScript('files', 'fileinfomodel'); } - } diff --git a/apps/files/lib/Service/DirectEditingService.php b/apps/files/lib/Service/DirectEditingService.php index c33fbe5d883..91e6a0acbb2 100644 --- a/apps/files/lib/Service/DirectEditingService.php +++ b/apps/files/lib/Service/DirectEditingService.php @@ -82,5 +82,4 @@ class DirectEditingService { } return $capabilities; } - } diff --git a/apps/files/lib/Service/OwnershipTransferService.php b/apps/files/lib/Service/OwnershipTransferService.php index 3415a2fd9e7..a838eb45eab 100644 --- a/apps/files/lib/Service/OwnershipTransferService.php +++ b/apps/files/lib/Service/OwnershipTransferService.php @@ -317,5 +317,4 @@ class OwnershipTransferService { $progress->finish(); $output->writeln(''); } - } diff --git a/apps/files/lib/Settings/PersonalSettings.php b/apps/files/lib/Settings/PersonalSettings.php index 40f12b830ad..ff5bf164dea 100644 --- a/apps/files/lib/Settings/PersonalSettings.php +++ b/apps/files/lib/Settings/PersonalSettings.php @@ -31,7 +31,6 @@ use OCP\AppFramework\Http\TemplateResponse; use OCP\Settings\ISettings; class PersonalSettings implements ISettings { - public function getForm(): TemplateResponse { return new TemplateResponse(Application::APP_ID, 'settings-personal'); } @@ -43,5 +42,4 @@ class PersonalSettings implements ISettings { public function getPriority(): int { return 90; } - } diff --git a/apps/files/templates/appnavigation.php b/apps/files/templates/appnavigation.php index 8992d266e49..f57295e8887 100644 --- a/apps/files/templates/appnavigation.php +++ b/apps/files/templates/appnavigation.php @@ -12,7 +12,7 @@ script(\OCA\Files\AppInfo\Application::APP_ID, 'dist/files-app-settings'); } ?> - +
  • t('%s used', [$_['usage']])); ?>

    @@ -66,15 +66,16 @@ script(\OCA\Files\AppInfo\Application::APP_ID, 'dist/files-app-settings'); * @return int Returns the pinned value */ function NavigationListElements($item, $l, $pinned) { - strpos($item['classes'] ?? '', 'pinned') !== false ? $pinned++ : ''; - ?> + strpos($item['classes'] ?? '', 'pinned') !== false ? $pinned++ : ''; ?>
  • data-dir="" data-view="" data-expandedstate="" class="nav- - + open" folderposition="" > @@ -85,17 +86,17 @@ function NavigationListElements($item, $l, $pinned) { + if (isset($item['sublist'])) { + ?>
      + } ?>
    - +
  • @@ -127,5 +128,6 @@ function NavigationElementMenu($item) {

- checked="checked" /> + checked="checked" /> diff --git a/apps/files/templates/list.php b/apps/files/templates/list.php index ff23c1aee95..ff79c771c0a 100644 --- a/apps/files/templates/list.php +++ b/apps/files/templates/list.php @@ -12,7 +12,7 @@ */ ?> - + diff --git a/apps/files/tests/Activity/Filter/GenericTest.php b/apps/files/tests/Activity/Filter/GenericTest.php index 89169a0e85c..eb55ab2699f 100644 --- a/apps/files/tests/Activity/Filter/GenericTest.php +++ b/apps/files/tests/Activity/Filter/GenericTest.php @@ -36,7 +36,6 @@ use Test\TestCase; * @group DB */ class GenericTest extends TestCase { - public function dataFilters() { return [ [Favorites::class], diff --git a/apps/files/tests/Activity/Setting/GenericTest.php b/apps/files/tests/Activity/Setting/GenericTest.php index 0ebb29d9de3..e741a3e02a8 100644 --- a/apps/files/tests/Activity/Setting/GenericTest.php +++ b/apps/files/tests/Activity/Setting/GenericTest.php @@ -34,7 +34,6 @@ use OCP\Activity\ISetting; use Test\TestCase; class GenericTest extends TestCase { - public function dataSettings() { return [ [FavoriteAction::class], diff --git a/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php b/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php index b7ef5387090..13ccc678b36 100644 --- a/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php +++ b/apps/files/tests/BackgroundJob/DeleteOrphanedItemsJobTest.php @@ -257,5 +257,4 @@ class DeleteOrphanedItemsJobTest extends \Test\TestCase { ->execute(); $this->cleanMapping('comments_read_markers'); } - } diff --git a/apps/files/tests/BackgroundJob/ScanFilesTest.php b/apps/files/tests/BackgroundJob/ScanFilesTest.php index b236f753adb..75557955d6a 100644 --- a/apps/files/tests/BackgroundJob/ScanFilesTest.php +++ b/apps/files/tests/BackgroundJob/ScanFilesTest.php @@ -150,5 +150,4 @@ class ScanFilesTest extends TestCase { $this->invokePrivate($this->scanFiles, 'run', [[]]); } - } diff --git a/apps/files/tests/Command/DeleteOrphanedFilesTest.php b/apps/files/tests/Command/DeleteOrphanedFilesTest.php index 8d6098ff18d..e0a8a72aba3 100644 --- a/apps/files/tests/Command/DeleteOrphanedFilesTest.php +++ b/apps/files/tests/Command/DeleteOrphanedFilesTest.php @@ -72,7 +72,7 @@ class DeleteOrphanedFilesTest extends TestCase { protected function tearDown(): void { $userManager = \OC::$server->getUserManager(); $user1 = $userManager->get($this->user1); - if($user1) { + if ($user1) { $user1->delete(); } diff --git a/apps/files/tests/Controller/ApiControllerTest.php b/apps/files/tests/Controller/ApiControllerTest.php index b35d9d7b95d..d347cffdd81 100644 --- a/apps/files/tests/Controller/ApiControllerTest.php +++ b/apps/files/tests/Controller/ApiControllerTest.php @@ -246,5 +246,4 @@ class ApiControllerTest extends TestCase { $this->assertEquals($expected, $actual); } - } diff --git a/apps/files/tests/Controller/ViewControllerTest.php b/apps/files/tests/Controller/ViewControllerTest.php index c00f30c890a..50eb40079a0 100644 --- a/apps/files/tests/Controller/ViewControllerTest.php +++ b/apps/files/tests/Controller/ViewControllerTest.php @@ -138,7 +138,7 @@ class ViewControllerTest extends TestCase { [$this->user->getUID(), 'files', 'show_grid', true], ]); - $this->config + $this->config ->expects($this->any()) ->method('getAppValue') ->willReturnArgument(2); diff --git a/apps/files/tests/HelperTest.php b/apps/files/tests/HelperTest.php index 6b824e8ead8..867d2dab4b0 100644 --- a/apps/files/tests/HelperTest.php +++ b/apps/files/tests/HelperTest.php @@ -31,7 +31,6 @@ * Class Helper */ class HelperTest extends \Test\TestCase { - private function makeFileInfo($name, $size, $mtime, $isDir = false) { return new \OC\Files\FileInfo( '/' . $name, diff --git a/apps/files/tests/Service/TagServiceTest.php b/apps/files/tests/Service/TagServiceTest.php index 8870c315947..ca6d98909ed 100644 --- a/apps/files/tests/Service/TagServiceTest.php +++ b/apps/files/tests/Service/TagServiceTest.php @@ -111,13 +111,14 @@ class TagServiceTest extends \Test\TestCase { ]) ->setMethods($methods) ->getMock(); - } protected function tearDown(): void { \OC_User::setUserId(''); $user = \OC::$server->getUserManager()->get($this->user); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } } public function testUpdateFileTags() { @@ -162,7 +163,6 @@ class TagServiceTest extends \Test\TestCase { } public function testFavoriteActivity() { - $subdir = $this->root->newFolder('subdir'); $file = $subdir->newFile('test.txt'); diff --git a/apps/files_external/lib/AppInfo/Application.php b/apps/files_external/lib/AppInfo/Application.php index cc587dcd80f..0a81f227b15 100644 --- a/apps/files_external/lib/AppInfo/Application.php +++ b/apps/files_external/lib/AppInfo/Application.php @@ -181,5 +181,4 @@ class Application extends App implements IBackendProvider, IAuthMechanismProvide $container->query(KerberosAuth::class), ]; } - } diff --git a/apps/files_external/lib/Command/Export.php b/apps/files_external/lib/Command/Export.php index 8d5f6990318..242f408a54d 100644 --- a/apps/files_external/lib/Command/Export.php +++ b/apps/files_external/lib/Command/Export.php @@ -29,7 +29,6 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class Export extends ListCommand { - protected function configure() { $this ->setName('files_external:export') diff --git a/apps/files_external/lib/Config/SimpleSubstitutionTrait.php b/apps/files_external/lib/Config/SimpleSubstitutionTrait.php index b736216842b..cd57f973a21 100644 --- a/apps/files_external/lib/Config/SimpleSubstitutionTrait.php +++ b/apps/files_external/lib/Config/SimpleSubstitutionTrait.php @@ -63,12 +63,12 @@ trait SimpleSubstitutionTrait { */ protected function checkPlaceholder(): void { $this->sanitizedPlaceholder = trim(strtolower($this->placeholder)); - if(!(bool)\preg_match('/^[a-z0-9]*$/', $this->sanitizedPlaceholder)) { + if (!(bool)\preg_match('/^[a-z0-9]*$/', $this->sanitizedPlaceholder)) { throw new \RuntimeException(sprintf( 'Invalid placeholder %s, only [a-z0-9] are allowed', $this->sanitizedPlaceholder )); } - if($this->sanitizedPlaceholder === '') { + if ($this->sanitizedPlaceholder === '') { throw new \RuntimeException('Invalid empty placeholder'); } } @@ -79,7 +79,7 @@ trait SimpleSubstitutionTrait { * @return mixed */ protected function substituteIfString($value, string $replacement) { - if(is_string($value)) { + if (is_string($value)) { return str_ireplace('$' . $this->sanitizedPlaceholder, $replacement, $value); } return $value; diff --git a/apps/files_external/lib/Config/UserContext.php b/apps/files_external/lib/Config/UserContext.php index 94ac02c545b..fe65c2f2bf6 100644 --- a/apps/files_external/lib/Config/UserContext.php +++ b/apps/files_external/lib/Config/UserContext.php @@ -67,24 +67,24 @@ class UserContext { if ($this->userId !== null) { return $this->userId; } - if($this->session && $this->session->getUser() !== null) { + if ($this->session && $this->session->getUser() !== null) { return $this->session->getUser()->getUID(); } try { $shareToken = $this->request->getParam('token'); $share = $this->shareManager->getShareByToken($shareToken); return $share->getShareOwner(); - } catch (ShareNotFound $e) {} + } catch (ShareNotFound $e) { + } return null; } protected function getUser(): ?IUser { $userId = $this->getUserId(); - if($userId !== null) { + if ($userId !== null) { return $this->userManager->get($userId); } return null; } - } diff --git a/apps/files_external/lib/Config/UserPlaceholderHandler.php b/apps/files_external/lib/Config/UserPlaceholderHandler.php index 4922143fa63..bc324931a7e 100644 --- a/apps/files_external/lib/Config/UserPlaceholderHandler.php +++ b/apps/files_external/lib/Config/UserPlaceholderHandler.php @@ -35,7 +35,7 @@ class UserPlaceholderHandler extends UserContext implements IConfigHandler { public function handle($optionValue) { $this->placeholder = 'user'; $uid = $this->getUserId(); - if($uid === null) { + if ($uid === null) { return $optionValue; } return $this->processInput($optionValue, $uid); diff --git a/apps/files_external/lib/Controller/ApiController.php b/apps/files_external/lib/Controller/ApiController.php index 9da869ce5a8..6418e5d73ad 100644 --- a/apps/files_external/lib/Controller/ApiController.php +++ b/apps/files_external/lib/Controller/ApiController.php @@ -100,7 +100,7 @@ class ApiController extends OCSController { $user = $this->userSession->getUser()->getUID(); $mounts = \OC_Mount_Config::getAbsoluteMountPoints($user); - foreach($mounts as $mountPoint => $mount) { + foreach ($mounts as $mountPoint => $mount) { $entries[] = $this->formatMount($mountPoint, $mount); } diff --git a/apps/files_external/lib/Controller/GlobalStoragesController.php b/apps/files_external/lib/Controller/GlobalStoragesController.php index 398399d820d..d42facb18ac 100644 --- a/apps/files_external/lib/Controller/GlobalStoragesController.php +++ b/apps/files_external/lib/Controller/GlobalStoragesController.php @@ -183,8 +183,5 @@ class GlobalStoragesController extends StoragesController { $this->formatStorageForUI($storage), Http::STATUS_OK ); - } - - } diff --git a/apps/files_external/lib/Controller/StoragesController.php b/apps/files_external/lib/Controller/StoragesController.php index d087a5e3900..a3a2712520a 100644 --- a/apps/files_external/lib/Controller/StoragesController.php +++ b/apps/files_external/lib/Controller/StoragesController.php @@ -363,5 +363,4 @@ abstract class StoragesController extends Controller { return new DataResponse([], Http::STATUS_NO_CONTENT); } - } diff --git a/apps/files_external/lib/Controller/UserGlobalStoragesController.php b/apps/files_external/lib/Controller/UserGlobalStoragesController.php index 3773461d00c..1f7eb595701 100644 --- a/apps/files_external/lib/Controller/UserGlobalStoragesController.php +++ b/apps/files_external/lib/Controller/UserGlobalStoragesController.php @@ -186,7 +186,6 @@ class UserGlobalStoragesController extends StoragesController { $this->formatStorageForUI($storage), Http::STATUS_OK ); - } /** @@ -206,5 +205,4 @@ class UserGlobalStoragesController extends StoragesController { } } } - } diff --git a/apps/files_external/lib/Controller/UserStoragesController.php b/apps/files_external/lib/Controller/UserStoragesController.php index 787e7affaf5..8c588fc967e 100644 --- a/apps/files_external/lib/Controller/UserStoragesController.php +++ b/apps/files_external/lib/Controller/UserStoragesController.php @@ -211,7 +211,6 @@ class UserStoragesController extends StoragesController { $this->formatStorageForUI($storage), Http::STATUS_OK ); - } /** @@ -224,5 +223,4 @@ class UserStoragesController extends StoragesController { public function destroy($id) { return parent::destroy($id); } - } diff --git a/apps/files_external/lib/Lib/Auth/AmazonS3/AccessKey.php b/apps/files_external/lib/Lib/Auth/AmazonS3/AccessKey.php index 78c9241a83c..4822789ba2b 100644 --- a/apps/files_external/lib/Lib/Auth/AmazonS3/AccessKey.php +++ b/apps/files_external/lib/Lib/Auth/AmazonS3/AccessKey.php @@ -32,7 +32,6 @@ use OCP\IL10N; * Amazon S3 access key authentication */ class AccessKey extends AuthMechanism { - const SCHEME_AMAZONS3_ACCESSKEY = 'amazons3_accesskey'; public function __construct(IL10N $l) { @@ -46,5 +45,4 @@ class AccessKey extends AuthMechanism { ->setType(DefinitionParameter::VALUE_PASSWORD), ]); } - } diff --git a/apps/files_external/lib/Lib/Auth/AuthMechanism.php b/apps/files_external/lib/Lib/Auth/AuthMechanism.php index cd8f8242e30..c13774ea5e0 100644 --- a/apps/files_external/lib/Lib/Auth/AuthMechanism.php +++ b/apps/files_external/lib/Lib/Auth/AuthMechanism.php @@ -118,5 +118,4 @@ class AuthMechanism implements \JsonSerializable { return $this->validateStorageDefinition($storage); } - } diff --git a/apps/files_external/lib/Lib/Auth/Builtin.php b/apps/files_external/lib/Lib/Auth/Builtin.php index 87c98d6957b..0f3d5342c6e 100644 --- a/apps/files_external/lib/Lib/Auth/Builtin.php +++ b/apps/files_external/lib/Lib/Auth/Builtin.php @@ -29,7 +29,6 @@ use OCP\IL10N; * Builtin authentication mechanism, for legacy backends */ class Builtin extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('builtin::builtin') @@ -37,5 +36,4 @@ class Builtin extends AuthMechanism { ->setText($l->t('Builtin')) ; } - } diff --git a/apps/files_external/lib/Lib/Auth/InvalidAuth.php b/apps/files_external/lib/Lib/Auth/InvalidAuth.php index 8aff7bc163d..61302125b4f 100644 --- a/apps/files_external/lib/Lib/Auth/InvalidAuth.php +++ b/apps/files_external/lib/Lib/Auth/InvalidAuth.php @@ -41,5 +41,4 @@ class InvalidAuth extends AuthMechanism { ->setText('Unknown auth mechanism backend ' . $invalidId) ; } - } diff --git a/apps/files_external/lib/Lib/Auth/NullMechanism.php b/apps/files_external/lib/Lib/Auth/NullMechanism.php index 57b9774b441..e7a30ea613e 100644 --- a/apps/files_external/lib/Lib/Auth/NullMechanism.php +++ b/apps/files_external/lib/Lib/Auth/NullMechanism.php @@ -29,7 +29,6 @@ use OCP\IL10N; * Null authentication mechanism */ class NullMechanism extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('null::null') @@ -37,5 +36,4 @@ class NullMechanism extends AuthMechanism { ->setText($l->t('None')) ; } - } diff --git a/apps/files_external/lib/Lib/Auth/OAuth1/OAuth1.php b/apps/files_external/lib/Lib/Auth/OAuth1/OAuth1.php index 26b8c6348db..d93a09292ad 100644 --- a/apps/files_external/lib/Lib/Auth/OAuth1/OAuth1.php +++ b/apps/files_external/lib/Lib/Auth/OAuth1/OAuth1.php @@ -32,7 +32,6 @@ use OCP\IL10N; * OAuth1 authentication */ class OAuth1 extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('oauth1::oauth1') @@ -52,5 +51,4 @@ class OAuth1 extends AuthMechanism { ->addCustomJs('oauth1') ; } - } diff --git a/apps/files_external/lib/Lib/Auth/OAuth2/OAuth2.php b/apps/files_external/lib/Lib/Auth/OAuth2/OAuth2.php index 8fbe412c2cf..17add489776 100644 --- a/apps/files_external/lib/Lib/Auth/OAuth2/OAuth2.php +++ b/apps/files_external/lib/Lib/Auth/OAuth2/OAuth2.php @@ -32,7 +32,6 @@ use OCP\IL10N; * OAuth2 authentication */ class OAuth2 extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('oauth2::oauth2') @@ -50,5 +49,4 @@ class OAuth2 extends AuthMechanism { ->addCustomJs('oauth2') ; } - } diff --git a/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV2.php b/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV2.php index 688911b7d52..723ecc5068b 100644 --- a/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV2.php +++ b/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV2.php @@ -33,7 +33,6 @@ use OCP\IL10N; * OpenStack Keystone authentication */ class OpenStackV2 extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('openstack::openstack') @@ -48,5 +47,4 @@ class OpenStackV2 extends AuthMechanism { ]) ; } - } diff --git a/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV3.php b/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV3.php index 75f2fc3173c..c8a78f52c41 100644 --- a/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV3.php +++ b/apps/files_external/lib/Lib/Auth/OpenStack/OpenStackV3.php @@ -36,7 +36,6 @@ use OCP\IL10N; * OpenStack Keystone authentication */ class OpenStackV3 extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('openstack::openstackv3') @@ -51,5 +50,4 @@ class OpenStackV3 extends AuthMechanism { ]) ; } - } diff --git a/apps/files_external/lib/Lib/Auth/OpenStack/Rackspace.php b/apps/files_external/lib/Lib/Auth/OpenStack/Rackspace.php index 2d3fbcdcc73..4fa2a07440c 100644 --- a/apps/files_external/lib/Lib/Auth/OpenStack/Rackspace.php +++ b/apps/files_external/lib/Lib/Auth/OpenStack/Rackspace.php @@ -32,7 +32,6 @@ use OCP\IL10N; * Rackspace authentication */ class Rackspace extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('openstack::rackspace') @@ -45,5 +44,4 @@ class Rackspace extends AuthMechanism { ]) ; } - } diff --git a/apps/files_external/lib/Lib/Auth/Password/GlobalAuth.php b/apps/files_external/lib/Lib/Auth/Password/GlobalAuth.php index 8051e863609..de6e34c4443 100644 --- a/apps/files_external/lib/Lib/Auth/Password/GlobalAuth.php +++ b/apps/files_external/lib/Lib/Auth/Password/GlobalAuth.php @@ -36,7 +36,6 @@ use OCP\Security\ICredentialsManager; * Global Username and Password */ class GlobalAuth extends AuthMechanism { - const CREDENTIALS_IDENTIFIER = 'password::global'; /** @var ICredentialsManager */ @@ -86,5 +85,4 @@ class GlobalAuth extends AuthMechanism { $storage->setBackendOption('password', $credentials['password']); } } - } diff --git a/apps/files_external/lib/Lib/Auth/Password/LoginCredentials.php b/apps/files_external/lib/Lib/Auth/Password/LoginCredentials.php index fe5f11ca203..0165bb6d077 100644 --- a/apps/files_external/lib/Lib/Auth/Password/LoginCredentials.php +++ b/apps/files_external/lib/Lib/Auth/Password/LoginCredentials.php @@ -35,7 +35,6 @@ use OCP\Security\ICredentialsManager; * Username and password from login credentials, saved in DB */ class LoginCredentials extends AuthMechanism { - const CREDENTIALS_IDENTIFIER = 'password::logincredentials/credentials'; /** @var ISession */ @@ -87,5 +86,4 @@ class LoginCredentials extends AuthMechanism { $storage->setBackendOption('user', $credentials['user']); $storage->setBackendOption('password', $credentials['password']); } - } diff --git a/apps/files_external/lib/Lib/Auth/Password/Password.php b/apps/files_external/lib/Lib/Auth/Password/Password.php index 4429379fda1..79be4282014 100644 --- a/apps/files_external/lib/Lib/Auth/Password/Password.php +++ b/apps/files_external/lib/Lib/Auth/Password/Password.php @@ -32,7 +32,6 @@ use OCP\IL10N; * Basic password authentication mechanism */ class Password extends AuthMechanism { - public function __construct(IL10N $l) { $this ->setIdentifier('password::password') @@ -44,5 +43,4 @@ class Password extends AuthMechanism { ->setType(DefinitionParameter::VALUE_PASSWORD), ]); } - } diff --git a/apps/files_external/lib/Lib/Auth/Password/SessionCredentials.php b/apps/files_external/lib/Lib/Auth/Password/SessionCredentials.php index 1e899c79d7e..47fb044f885 100644 --- a/apps/files_external/lib/Lib/Auth/Password/SessionCredentials.php +++ b/apps/files_external/lib/Lib/Auth/Password/SessionCredentials.php @@ -65,5 +65,4 @@ class SessionCredentials extends AuthMechanism { public function wrapStorage(Storage $storage) { return new SessionStorageWrapper(['storage' => $storage]); } - } diff --git a/apps/files_external/lib/Lib/Auth/Password/UserGlobalAuth.php b/apps/files_external/lib/Lib/Auth/Password/UserGlobalAuth.php index 80829b6a07c..ea39cabb2d0 100644 --- a/apps/files_external/lib/Lib/Auth/Password/UserGlobalAuth.php +++ b/apps/files_external/lib/Lib/Auth/Password/UserGlobalAuth.php @@ -40,7 +40,6 @@ use OCP\Security\ICredentialsManager; * User provided Global Username and Password */ class UserGlobalAuth extends AuthMechanism { - private const CREDENTIALS_IDENTIFIER = 'password::global'; /** @var ICredentialsManager */ @@ -59,7 +58,7 @@ class UserGlobalAuth extends AuthMechanism { public function saveBackendOptions(IUser $user, $id, $backendOptions) { // backendOptions are set when invoked via Files app // but they are not set when invoked via ext storage settings - if(!isset($backendOptions['user']) && !isset($backendOptions['password'])) { + if (!isset($backendOptions['user']) && !isset($backendOptions['password'])) { return; } // make sure we're not setting any unexpected keys @@ -83,5 +82,4 @@ class UserGlobalAuth extends AuthMechanism { $storage->setBackendOption('password', $credentials['password']); } } - } diff --git a/apps/files_external/lib/Lib/Auth/Password/UserProvided.php b/apps/files_external/lib/Lib/Auth/Password/UserProvided.php index 0594730d1b8..552b707b544 100644 --- a/apps/files_external/lib/Lib/Auth/Password/UserProvided.php +++ b/apps/files_external/lib/Lib/Auth/Password/UserProvided.php @@ -37,7 +37,6 @@ use OCP\Security\ICredentialsManager; * User provided Username and Password */ class UserProvided extends AuthMechanism implements IUserProvided { - const CREDENTIALS_IDENTIFIER_PREFIX = 'password::userprovided/'; /** @var ICredentialsManager */ @@ -85,5 +84,4 @@ class UserProvided extends AuthMechanism implements IUserProvided { $storage->setBackendOption('user', $credentials['user']); $storage->setBackendOption('password', $credentials['password']); } - } diff --git a/apps/files_external/lib/Lib/Auth/PublicKey/RSA.php b/apps/files_external/lib/Lib/Auth/PublicKey/RSA.php index 2135b758818..f3e6c891e73 100644 --- a/apps/files_external/lib/Lib/Auth/PublicKey/RSA.php +++ b/apps/files_external/lib/Lib/Auth/PublicKey/RSA.php @@ -83,5 +83,4 @@ class RSA extends AuthMechanism { return $rsa->createKey($keyLength); } - } diff --git a/apps/files_external/lib/Lib/Backend/AmazonS3.php b/apps/files_external/lib/Lib/Backend/AmazonS3.php index dff2cca9f23..5473975f372 100644 --- a/apps/files_external/lib/Lib/Backend/AmazonS3.php +++ b/apps/files_external/lib/Lib/Backend/AmazonS3.php @@ -31,7 +31,6 @@ use OCA\Files_External\Lib\LegacyDependencyCheckPolyfill; use OCP\IL10N; class AmazonS3 extends Backend { - use LegacyDependencyCheckPolyfill; public function __construct(IL10N $l, AccessKey $legacyAuth) { @@ -59,5 +58,4 @@ class AmazonS3 extends Backend { ->setLegacyAuthMechanism($legacyAuth) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/Backend.php b/apps/files_external/lib/Lib/Backend/Backend.php index 4b3d5c31011..69d41f85ecf 100644 --- a/apps/files_external/lib/Lib/Backend/Backend.php +++ b/apps/files_external/lib/Lib/Backend/Backend.php @@ -57,7 +57,6 @@ use OCA\Files_External\Lib\VisibilityTrait; * Object can affect storage mounting */ class Backend implements \JsonSerializable { - use VisibilityTrait; use FrontendDefinitionTrait; use PriorityTrait; @@ -162,5 +161,4 @@ class Backend implements \JsonSerializable { public function validateStorage(StorageConfig $storage) { return $this->validateStorageDefinition($storage); } - } diff --git a/apps/files_external/lib/Lib/Backend/DAV.php b/apps/files_external/lib/Lib/Backend/DAV.php index c7c13143628..0991c5ac1df 100644 --- a/apps/files_external/lib/Lib/Backend/DAV.php +++ b/apps/files_external/lib/Lib/Backend/DAV.php @@ -31,7 +31,6 @@ use OCA\Files_External\Lib\LegacyDependencyCheckPolyfill; use OCP\IL10N; class DAV extends Backend { - use LegacyDependencyCheckPolyfill; public function __construct(IL10N $l, Password $legacyAuth) { @@ -51,5 +50,4 @@ class DAV extends Backend { ->setLegacyAuthMechanism($legacyAuth) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/FTP.php b/apps/files_external/lib/Lib/Backend/FTP.php index 63be8fa5696..bc35a5d386a 100644 --- a/apps/files_external/lib/Lib/Backend/FTP.php +++ b/apps/files_external/lib/Lib/Backend/FTP.php @@ -31,7 +31,6 @@ use OCA\Files_External\Lib\LegacyDependencyCheckPolyfill; use OCP\IL10N; class FTP extends Backend { - use LegacyDependencyCheckPolyfill; public function __construct(IL10N $l, Password $legacyAuth) { @@ -51,5 +50,4 @@ class FTP extends Backend { ->setLegacyAuthMechanism($legacyAuth) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/LegacyBackend.php b/apps/files_external/lib/Lib/Backend/LegacyBackend.php index a1d6bbfad63..87dabda8bb6 100644 --- a/apps/files_external/lib/Lib/Backend/LegacyBackend.php +++ b/apps/files_external/lib/Lib/Backend/LegacyBackend.php @@ -32,7 +32,6 @@ use OCA\Files_External\Lib\MissingDependency; * Legacy compatibility for OC_Mount_Config::registerBackend() */ class LegacyBackend extends Backend { - use LegacyDependencyCheckPolyfill { LegacyDependencyCheckPolyfill::checkDependencies as doCheckDependencies; } @@ -101,5 +100,4 @@ class LegacyBackend extends Backend { } return []; } - } diff --git a/apps/files_external/lib/Lib/Backend/Local.php b/apps/files_external/lib/Lib/Backend/Local.php index b22b0db5749..67b50e127e9 100644 --- a/apps/files_external/lib/Lib/Backend/Local.php +++ b/apps/files_external/lib/Lib/Backend/Local.php @@ -31,7 +31,6 @@ use OCA\Files_External\Service\BackendService; use OCP\IL10N; class Local extends Backend { - public function __construct(IL10N $l, NullMechanism $legacyAuth) { $this ->setIdentifier('local') @@ -47,5 +46,4 @@ class Local extends Backend { ->setLegacyAuthMechanism($legacyAuth) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/OwnCloud.php b/apps/files_external/lib/Lib/Backend/OwnCloud.php index 1221cf9ef63..876f8709cc3 100644 --- a/apps/files_external/lib/Lib/Backend/OwnCloud.php +++ b/apps/files_external/lib/Lib/Backend/OwnCloud.php @@ -31,7 +31,6 @@ use OCA\Files_External\Lib\DefinitionParameter; use OCP\IL10N; class OwnCloud extends Backend { - public function __construct(IL10N $l, Password $legacyAuth) { $this ->setIdentifier('owncloud') @@ -49,5 +48,4 @@ class OwnCloud extends Backend { ->setLegacyAuthMechanism($legacyAuth) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/SFTP.php b/apps/files_external/lib/Lib/Backend/SFTP.php index 88e9ce14b4a..a7f97c6b79a 100644 --- a/apps/files_external/lib/Lib/Backend/SFTP.php +++ b/apps/files_external/lib/Lib/Backend/SFTP.php @@ -30,7 +30,6 @@ use OCA\Files_External\Lib\DefinitionParameter; use OCP\IL10N; class SFTP extends Backend { - public function __construct(IL10N $l, Password $legacyAuth) { $this ->setIdentifier('sftp') @@ -47,5 +46,4 @@ class SFTP extends Backend { ->setLegacyAuthMechanism($legacyAuth) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/SFTP_Key.php b/apps/files_external/lib/Lib/Backend/SFTP_Key.php index a9420a909e8..924d6a62ffe 100644 --- a/apps/files_external/lib/Lib/Backend/SFTP_Key.php +++ b/apps/files_external/lib/Lib/Backend/SFTP_Key.php @@ -30,7 +30,6 @@ use OCA\Files_External\Lib\DefinitionParameter; use OCP\IL10N; class SFTP_Key extends Backend { - public function __construct(IL10N $l, RSA $legacyAuth, SFTP $sftpBackend) { $this ->setIdentifier('\OC\Files\Storage\SFTP_Key') @@ -46,5 +45,4 @@ class SFTP_Key extends Backend { ->deprecateTo($sftpBackend) ; } - } diff --git a/apps/files_external/lib/Lib/Backend/SMB.php b/apps/files_external/lib/Lib/Backend/SMB.php index 20501e5bfe1..eefeb137bf8 100644 --- a/apps/files_external/lib/Lib/Backend/SMB.php +++ b/apps/files_external/lib/Lib/Backend/SMB.php @@ -38,7 +38,6 @@ use OCP\IL10N; use OCP\IUser; class SMB extends Backend { - use LegacyDependencyCheckPolyfill; public function __construct(IL10N $l, Password $legacyAuth) { @@ -90,5 +89,4 @@ class SMB extends Backend { $storage->setBackendOption('auth', $smbAuth); } - } diff --git a/apps/files_external/lib/Lib/Backend/SMB_OC.php b/apps/files_external/lib/Lib/Backend/SMB_OC.php index 9c28a52e049..439d85164cc 100644 --- a/apps/files_external/lib/Lib/Backend/SMB_OC.php +++ b/apps/files_external/lib/Lib/Backend/SMB_OC.php @@ -37,7 +37,6 @@ use OCP\IUser; * Deprecated SMB_OC class - use SMB with the password::sessioncredentials auth mechanism */ class SMB_OC extends Backend { - use LegacyDependencyCheckPolyfill; public function __construct(IL10N $l, SessionCredentials $legacyAuth, SMB $smbBackend) { @@ -69,5 +68,4 @@ class SMB_OC extends Backend { $storage->setBackendOption('share', $share); } } - } diff --git a/apps/files_external/lib/Lib/Backend/Swift.php b/apps/files_external/lib/Lib/Backend/Swift.php index 5d4d5ec1408..25ed72337a1 100644 --- a/apps/files_external/lib/Lib/Backend/Swift.php +++ b/apps/files_external/lib/Lib/Backend/Swift.php @@ -33,7 +33,6 @@ use OCA\Files_External\Lib\LegacyDependencyCheckPolyfill; use OCP\IL10N; class Swift extends Backend { - use LegacyDependencyCheckPolyfill; public function __construct(IL10N $l, OpenStackV2 $openstackAuth, Rackspace $rackspaceAuth) { @@ -60,5 +59,4 @@ class Swift extends Backend { }) ; } - } diff --git a/apps/files_external/lib/Lib/Config/IAuthMechanismProvider.php b/apps/files_external/lib/Lib/Config/IAuthMechanismProvider.php index 674f3ccf371..e8f142c01da 100644 --- a/apps/files_external/lib/Lib/Config/IAuthMechanismProvider.php +++ b/apps/files_external/lib/Lib/Config/IAuthMechanismProvider.php @@ -36,5 +36,4 @@ interface IAuthMechanismProvider { * @return AuthMechanism[] */ public function getAuthMechanisms(); - } diff --git a/apps/files_external/lib/Lib/Config/IBackendProvider.php b/apps/files_external/lib/Lib/Config/IBackendProvider.php index fd0deadcb23..7757f204c8c 100644 --- a/apps/files_external/lib/Lib/Config/IBackendProvider.php +++ b/apps/files_external/lib/Lib/Config/IBackendProvider.php @@ -36,5 +36,4 @@ interface IBackendProvider { * @return Backend[] */ public function getBackends(); - } diff --git a/apps/files_external/lib/Lib/DependencyTrait.php b/apps/files_external/lib/Lib/DependencyTrait.php index df7e29c7a79..b88a111392a 100644 --- a/apps/files_external/lib/Lib/DependencyTrait.php +++ b/apps/files_external/lib/Lib/DependencyTrait.php @@ -35,5 +35,4 @@ trait DependencyTrait { public function checkDependencies() { return []; // no dependencies by default } - } diff --git a/apps/files_external/lib/Lib/IdentifierTrait.php b/apps/files_external/lib/Lib/IdentifierTrait.php index 9aa6095c25e..6bdde976753 100644 --- a/apps/files_external/lib/Lib/IdentifierTrait.php +++ b/apps/files_external/lib/Lib/IdentifierTrait.php @@ -100,5 +100,4 @@ trait IdentifierTrait { } return $data; } - } diff --git a/apps/files_external/lib/Lib/LegacyDependencyCheckPolyfill.php b/apps/files_external/lib/Lib/LegacyDependencyCheckPolyfill.php index cf720b35a5b..787872511f9 100644 --- a/apps/files_external/lib/Lib/LegacyDependencyCheckPolyfill.php +++ b/apps/files_external/lib/Lib/LegacyDependencyCheckPolyfill.php @@ -64,5 +64,4 @@ trait LegacyDependencyCheckPolyfill { return $ret; } - } diff --git a/apps/files_external/lib/Lib/PriorityTrait.php b/apps/files_external/lib/Lib/PriorityTrait.php index f6cfb7c4dfb..12e30de231f 100644 --- a/apps/files_external/lib/Lib/PriorityTrait.php +++ b/apps/files_external/lib/Lib/PriorityTrait.php @@ -57,5 +57,4 @@ trait PriorityTrait { public static function priorityCompare(PriorityTrait $a, PriorityTrait $b) { return ($a->getPriority() - $b->getPriority()); } - } diff --git a/apps/files_external/lib/Lib/SessionStorageWrapper.php b/apps/files_external/lib/Lib/SessionStorageWrapper.php index de082ccc3ad..2b8f2b8613b 100644 --- a/apps/files_external/lib/Lib/SessionStorageWrapper.php +++ b/apps/files_external/lib/Lib/SessionStorageWrapper.php @@ -39,5 +39,4 @@ class SessionStorageWrapper extends PermissionsMask { $arguments['mask'] = Constants::PERMISSION_ALL & ~Constants::PERMISSION_SHARE; parent::__construct($arguments); } - } diff --git a/apps/files_external/lib/Lib/Storage/AmazonS3.php b/apps/files_external/lib/Lib/Storage/AmazonS3.php index 99cfcb594a9..0fb520cf9d4 100644 --- a/apps/files_external/lib/Lib/Storage/AmazonS3.php +++ b/apps/files_external/lib/Lib/Storage/AmazonS3.php @@ -649,7 +649,6 @@ class AmazonS3 extends \OC\Files\Storage\Common { $path2 = $this->normalizePath($path2); if ($this->is_file($path1)) { - if ($this->copy($path1, $path2) === false) { return false; } @@ -659,7 +658,6 @@ class AmazonS3 extends \OC\Files\Storage\Common { return false; } } else { - if ($this->copy($path1, $path2) === false) { return false; } @@ -704,5 +702,4 @@ class AmazonS3 extends \OC\Files\Storage\Common { public static function checkDependencies() { return true; } - } diff --git a/apps/files_external/lib/Lib/Storage/FTP.php b/apps/files_external/lib/Lib/Storage/FTP.php index 0015f3008ef..d514bd7b7b0 100644 --- a/apps/files_external/lib/Lib/Storage/FTP.php +++ b/apps/files_external/lib/Lib/Storage/FTP.php @@ -38,7 +38,7 @@ namespace OCA\Files_External\Lib\Storage; use Icewind\Streams\CallbackWrapper; use Icewind\Streams\RetryWrapper; -class FTP extends StreamWrapper{ +class FTP extends StreamWrapper { private $password; private $user; private $host; @@ -65,7 +65,6 @@ class FTP extends StreamWrapper{ } else { throw new \Exception('Creating FTP storage failed'); } - } public function getId() { @@ -93,8 +92,7 @@ class FTP extends StreamWrapper{ public function unlink($path) { if ($this->is_dir($path)) { return $this->rmdir($path); - } - else { + } else { $url = $this->constructUrl($path); $result = unlink($url); clearstatcache(true, $url); @@ -102,7 +100,7 @@ class FTP extends StreamWrapper{ } } public function fopen($path,$mode) { - switch($mode) { + switch ($mode) { case 'r': case 'rb': case 'w': @@ -154,5 +152,4 @@ class FTP extends StreamWrapper{ return ['ftp']; } } - } diff --git a/apps/files_external/lib/Lib/Storage/OwnCloud.php b/apps/files_external/lib/Lib/Storage/OwnCloud.php index 1738aacd258..d8e3ee321b7 100644 --- a/apps/files_external/lib/Lib/Storage/OwnCloud.php +++ b/apps/files_external/lib/Lib/Storage/OwnCloud.php @@ -55,19 +55,18 @@ class OwnCloud extends \OC\Files\Storage\DAV implements IDisableEncryptionStorag } $contextPath = ''; $hostSlashPos = strpos($host, '/'); - if ($hostSlashPos !== false){ + if ($hostSlashPos !== false) { $contextPath = substr($host, $hostSlashPos); $host = substr($host, 0, $hostSlashPos); } - if (substr($contextPath, -1) !== '/'){ + if (substr($contextPath, -1) !== '/') { $contextPath .= '/'; } - if (isset($params['root'])){ + if (isset($params['root'])) { $root = '/' . ltrim($params['root'], '/'); - } - else{ + } else { $root = '/'; } diff --git a/apps/files_external/lib/Lib/Storage/SFTP.php b/apps/files_external/lib/Lib/Storage/SFTP.php index 9682ebd4535..bc6cd663b6d 100644 --- a/apps/files_external/lib/Lib/Storage/SFTP.php +++ b/apps/files_external/lib/Lib/Storage/SFTP.php @@ -70,7 +70,7 @@ class SFTP extends \OC\Files\Storage\Common { } $parsed = parse_url($host); - if(is_array($parsed) && isset($parsed['port'])) { + if (is_array($parsed) && isset($parsed['port'])) { return [$parsed['host'], $parsed['port']]; } elseif (is_array($parsed)) { return [$parsed['host'], 22]; @@ -310,13 +310,13 @@ class SFTP extends \OC\Files\Storage\Common { $id = md5('sftp:' . $path); $dirStream = []; - foreach($list as $file) { + foreach ($list as $file) { if ($file !== '.' && $file !== '..') { $dirStream[] = $file; } } return IteratorDirectory::wrap($dirStream); - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } } @@ -335,7 +335,6 @@ class SFTP extends \OC\Files\Storage\Common { return 'dir'; } } catch (\Exception $e) { - } return false; } @@ -368,7 +367,7 @@ class SFTP extends \OC\Files\Storage\Common { public function fopen($path, $mode) { try { $absPath = $this->absPath($path); - switch($mode) { + switch ($mode) { case 'r': case 'rb': if (!$this->file_exists($path)) { diff --git a/apps/files_external/lib/Lib/Storage/SFTPReadStream.php b/apps/files_external/lib/Lib/Storage/SFTPReadStream.php index 455b4a7cf28..a3023d1a22b 100644 --- a/apps/files_external/lib/Lib/Storage/SFTPReadStream.php +++ b/apps/files_external/lib/Lib/Storage/SFTPReadStream.php @@ -200,5 +200,4 @@ class SFTPReadStream implements File { return false; } } - } diff --git a/apps/files_external/lib/Lib/Storage/SFTPWriteStream.php b/apps/files_external/lib/Lib/Storage/SFTPWriteStream.php index b5bc3ab667d..50faf8f466c 100644 --- a/apps/files_external/lib/Lib/Storage/SFTPWriteStream.php +++ b/apps/files_external/lib/Lib/Storage/SFTPWriteStream.php @@ -178,5 +178,4 @@ class SFTPWriteStream implements File { return false; } } - } diff --git a/apps/files_external/lib/Lib/Storage/SMB.php b/apps/files_external/lib/Lib/Storage/SMB.php index 506774d5cea..d010fb54840 100644 --- a/apps/files_external/lib/Lib/Storage/SMB.php +++ b/apps/files_external/lib/Lib/Storage/SMB.php @@ -185,7 +185,7 @@ class SMB extends Common implements INotifyStorage { } catch (ForbiddenException $e) { // with php-smbclient, this exceptions is thrown when the provided password is invalid. // Possible is also ForbiddenException with a different error code, so we check it. - if($e->getCode() === 1) { + if ($e->getCode() === 1) { $this->throwUnavailable($e); } throw $e; diff --git a/apps/files_external/lib/Lib/Storage/StreamWrapper.php b/apps/files_external/lib/Lib/Storage/StreamWrapper.php index 5d85aaace6e..b77b9e0fe46 100644 --- a/apps/files_external/lib/Lib/Storage/StreamWrapper.php +++ b/apps/files_external/lib/Lib/Storage/StreamWrapper.php @@ -126,5 +126,4 @@ abstract class StreamWrapper extends \OC\Files\Storage\Common { public function stat($path) { return stat($this->constructUrl($path)); } - } diff --git a/apps/files_external/lib/Lib/Storage/Swift.php b/apps/files_external/lib/Lib/Storage/Swift.php index a928f5b75d9..96fb4f0ac9a 100644 --- a/apps/files_external/lib/Lib/Storage/Swift.php +++ b/apps/files_external/lib/Lib/Storage/Swift.php @@ -316,7 +316,6 @@ class Swift extends \OC\Files\Storage\Common { ]); return false; } - } public function stat($path) { @@ -505,7 +504,6 @@ class Swift extends \OC\Files\Storage\Common { ]); return false; } - } elseif ($fileType === 'dir') { try { $source = $this->fetchObject($path1 . '/'); @@ -533,7 +531,6 @@ class Swift extends \OC\Files\Storage\Common { $target = $path2 . '/' . $file; $this->copy($source, $target); } - } else { //file does not exist return false; @@ -625,5 +622,4 @@ class Swift extends \OC\Files\Storage\Common { public static function checkDependencies() { return true; } - } diff --git a/apps/files_external/lib/Lib/StorageConfig.php b/apps/files_external/lib/Lib/StorageConfig.php index aba5d3247c8..5ed65918b22 100644 --- a/apps/files_external/lib/Lib/StorageConfig.php +++ b/apps/files_external/lib/Lib/StorageConfig.php @@ -215,10 +215,10 @@ class StorageConfig implements \JsonSerializable { * @param array $backendOptions backend options */ public function setBackendOptions($backendOptions) { - if($this->getBackend() instanceof Backend) { + if ($this->getBackend() instanceof Backend) { $parameters = $this->getBackend()->getParameters(); - foreach($backendOptions as $key => $value) { - if(isset($parameters[$key])) { + foreach ($backendOptions as $key => $value) { + if (isset($parameters[$key])) { switch ($parameters[$key]->getType()) { case \OCA\Files_External\Lib\DefinitionParameter::VALUE_BOOLEAN: $value = (bool)$value; diff --git a/apps/files_external/lib/Lib/StorageModifierTrait.php b/apps/files_external/lib/Lib/StorageModifierTrait.php index 2d7140e68a9..304eadb2254 100644 --- a/apps/files_external/lib/Lib/StorageModifierTrait.php +++ b/apps/files_external/lib/Lib/StorageModifierTrait.php @@ -64,5 +64,4 @@ trait StorageModifierTrait { public function wrapStorage(Storage $storage) { return $storage; } - } diff --git a/apps/files_external/lib/Lib/VisibilityTrait.php b/apps/files_external/lib/Lib/VisibilityTrait.php index a056891403e..dc4ba7b366f 100644 --- a/apps/files_external/lib/Lib/VisibilityTrait.php +++ b/apps/files_external/lib/Lib/VisibilityTrait.php @@ -134,5 +134,4 @@ trait VisibilityTrait { public function removeAllowedVisibility($allowedVisibility) { return $this->setAllowedVisibility($this->allowedVisibility & ~$allowedVisibility); } - } diff --git a/apps/files_external/lib/Migration/DummyUserSession.php b/apps/files_external/lib/Migration/DummyUserSession.php index 496c4dfa760..10ab505cd3b 100644 --- a/apps/files_external/lib/Migration/DummyUserSession.php +++ b/apps/files_external/lib/Migration/DummyUserSession.php @@ -70,5 +70,4 @@ class DummyUserSession implements IUserSession { public function setImpersonatingUserID(bool $useCurrentUser = true): void { //no OP } - } diff --git a/apps/files_external/lib/Service/BackendService.php b/apps/files_external/lib/Service/BackendService.php index 6c2ea72b840..617b44651ae 100644 --- a/apps/files_external/lib/Service/BackendService.php +++ b/apps/files_external/lib/Service/BackendService.php @@ -111,7 +111,7 @@ class BackendService { private function callForRegistrations() { static $eventSent = false; - if(!$eventSent) { + if (!$eventSent) { \OC::$server->getEventDispatcher()->dispatch( 'OCA\\Files_External::loadAdditionalBackends', new GenericEvent() @@ -322,15 +322,15 @@ class BackendService { */ public function registerConfigHandler(string $placeholder, callable $configHandlerLoader) { $placeholder = trim(strtolower($placeholder)); - if(!(bool)\preg_match('/^[a-z0-9]*$/', $placeholder)) { + if (!(bool)\preg_match('/^[a-z0-9]*$/', $placeholder)) { throw new \RuntimeException(sprintf( 'Invalid placeholder %s, only [a-z0-9] are allowed', $placeholder )); } - if($placeholder === '') { + if ($placeholder === '') { throw new \RuntimeException('Invalid empty placeholder'); } - if(isset($this->configHandlerLoaders[$placeholder]) || isset($this->configHandlers[$placeholder])) { + if (isset($this->configHandlerLoaders[$placeholder]) || isset($this->configHandlers[$placeholder])) { throw new \RuntimeException(sprintf('A handler is already registered for %s', $placeholder)); } $this->configHandlerLoaders[$placeholder] = $configHandlerLoader; @@ -341,7 +341,7 @@ class BackendService { $newLoaded = false; foreach ($this->configHandlerLoaders as $placeholder => $loader) { $handler = $loader(); - if(!$handler instanceof IConfigHandler) { + if (!$handler instanceof IConfigHandler) { throw new \RuntimeException(sprintf( 'Handler for %s is not an instance of IConfigHandler', $placeholder )); @@ -350,7 +350,7 @@ class BackendService { $newLoaded = true; } $this->configHandlerLoaders = []; - if($newLoaded) { + if ($newLoaded) { // ensure those with longest placeholders come first, // to avoid substring matches uksort($this->configHandlers, function ($phA, $phB) { diff --git a/apps/files_external/lib/Service/DBConfigService.php b/apps/files_external/lib/Service/DBConfigService.php index 265848289f3..51373e8dda6 100644 --- a/apps/files_external/lib/Service/DBConfigService.php +++ b/apps/files_external/lib/Service/DBConfigService.php @@ -140,7 +140,7 @@ class DBConfigService { $stmt->closeCursor(); foreach ($result as $row) { - if((int)$row['count'] > 1) { + if ((int)$row['count'] > 1) { $this->removeApplicable($row['mount_id'], $applicableType, $applicableId); } else { $this->removeMount($row['mount_id']); @@ -343,7 +343,7 @@ class DBConfigService { ->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)) ->setValue('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)) ->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { $builder = $this->connection->getQueryBuilder(); $query = $builder->update('external_config') ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)) @@ -366,7 +366,7 @@ class DBConfigService { ->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)) ->setValue('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR)) ->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { $builder = $this->connection->getQueryBuilder(); $query = $builder->update('external_options') ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR)) @@ -384,7 +384,7 @@ class DBConfigService { ->setValue('type', $builder->createNamedParameter($type)) ->setValue('value', $builder->createNamedParameter($value)) ->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { // applicable exists already } } diff --git a/apps/files_external/lib/Service/UserGlobalStoragesService.php b/apps/files_external/lib/Service/UserGlobalStoragesService.php index 0cad7b2535e..7b9af773233 100644 --- a/apps/files_external/lib/Service/UserGlobalStoragesService.php +++ b/apps/files_external/lib/Service/UserGlobalStoragesService.php @@ -34,7 +34,6 @@ use OCP\IUserSession; * Read-only access available, attempting to write will throw DomainException */ class UserGlobalStoragesService extends GlobalStoragesService { - use UserTrait; /** @var IGroupManager */ diff --git a/apps/files_external/lib/Settings/Admin.php b/apps/files_external/lib/Settings/Admin.php index fe2d7598a17..d3c2c07aa83 100644 --- a/apps/files_external/lib/Settings/Admin.php +++ b/apps/files_external/lib/Settings/Admin.php @@ -92,5 +92,4 @@ class Admin implements ISettings { public function getPriority() { return 40; } - } diff --git a/apps/files_external/lib/Settings/Personal.php b/apps/files_external/lib/Settings/Personal.php index 927955cb420..de94793a6af 100644 --- a/apps/files_external/lib/Settings/Personal.php +++ b/apps/files_external/lib/Settings/Personal.php @@ -100,5 +100,4 @@ class Personal implements ISettings { public function getPriority() { return 40; } - } diff --git a/apps/files_external/lib/config.php b/apps/files_external/lib/config.php index c02d9d71566..c69955c3406 100644 --- a/apps/files_external/lib/config.php +++ b/apps/files_external/lib/config.php @@ -247,7 +247,7 @@ class OC_Mount_Config { return StorageNotAvailableException::STATUS_SUCCESS; } foreach ($options as $key => &$option) { - if($key === 'password') { + if ($key === 'password') { // no replacements in passwords continue; } diff --git a/apps/files_external/templates/settings.php b/apps/files_external/templates/settings.php index 0142b206b3e..0ccf8366a91 100644 --- a/apps/files_external/templates/settings.php +++ b/apps/files_external/templates/settings.php @@ -46,7 +46,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || switch ($parameter->getType()) { case DefinitionParameter::VALUE_PASSWORD: ?> - + class="" data-parameter="getName()); ?>" @@ -79,7 +81,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || - + class="" data-parameter="getName()); ?>" @@ -100,7 +104,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN ||

t('External storages')); ?>

t('External storage enables you to mount external storage services and devices as secondary Nextcloud storage devices. You may also allow users to mount their own external storage services.')); ?>

- + '> @@ -109,7 +115,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || - '.$l->t('Available for').''); ?> + '.$l->t('Available for').''); +} ?> @@ -142,7 +150,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || }); ?> - getDeprecateTo()) continue; // ignore deprecated backends?> + getDeprecateTo()) { + continue; + } // ignore deprecated backends?> @@ -167,7 +177,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || /> + value="1" />

class="hidden"> @@ -180,7 +192,9 @@ $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || getDeprecateTo()): ?> - isVisibleFor(BackendService::VISIBILITY_PERSONAL)) print_unescaped(' checked="checked"'); ?> /> + isVisibleFor(BackendService::VISIBILITY_PERSONAL)) { + print_unescaped(' checked="checked"'); + } ?> />
diff --git a/apps/files_external/tests/Auth/AuthMechanismTest.php b/apps/files_external/tests/Auth/AuthMechanismTest.php index dcdc8d42aec..8a4321466c8 100644 --- a/apps/files_external/tests/Auth/AuthMechanismTest.php +++ b/apps/files_external/tests/Auth/AuthMechanismTest.php @@ -28,7 +28,6 @@ use OCA\Files_External\Lib\Backend\Backend; use OCA\Files_External\Lib\StorageConfig; class AuthMechanismTest extends \Test\TestCase { - public function testJsonSerialization() { $mechanism = $this->getMockBuilder(AuthMechanism::class) ->setMethods(['jsonSerializeDefinition']) @@ -82,5 +81,4 @@ class AuthMechanismTest extends \Test\TestCase { $this->assertEquals($expectedSuccess, $mechanism->validateStorage($storageConfig)); } - } diff --git a/apps/files_external/tests/Auth/Password/GlobalAuth.php b/apps/files_external/tests/Auth/Password/GlobalAuth.php index f6e6b0b55ac..8edf7358ed8 100644 --- a/apps/files_external/tests/Auth/Password/GlobalAuth.php +++ b/apps/files_external/tests/Auth/Password/GlobalAuth.php @@ -118,5 +118,4 @@ class GlobalAuthTest extends TestCase { $this->instance->manipulateStorageConfig($storage); $this->assertEquals([], $storage->getBackendOptions()); } - } diff --git a/apps/files_external/tests/Backend/BackendTest.php b/apps/files_external/tests/Backend/BackendTest.php index 10853d9197c..ca7cc7d7b2c 100644 --- a/apps/files_external/tests/Backend/BackendTest.php +++ b/apps/files_external/tests/Backend/BackendTest.php @@ -28,7 +28,6 @@ use OCA\Files_External\Lib\Backend\Backend; use OCA\Files_External\Lib\StorageConfig; class BackendTest extends \Test\TestCase { - public function testJsonSerialization() { $backend = $this->getMockBuilder(Backend::class) ->setMethods(['jsonSerializeDefinition']) @@ -89,5 +88,4 @@ class BackendTest extends \Test\TestCase { $this->assertEquals('foobar', $backend->getLegacyAuthMechanism(['other' => true])); $this->assertEquals('foobar', $backend->getLegacyAuthMechanism()); } - } diff --git a/apps/files_external/tests/Backend/LegacyBackendTest.php b/apps/files_external/tests/Backend/LegacyBackendTest.php index 71957466c7d..c929058c2b5 100644 --- a/apps/files_external/tests/Backend/LegacyBackendTest.php +++ b/apps/files_external/tests/Backend/LegacyBackendTest.php @@ -111,5 +111,4 @@ class LegacyBackendTest extends \Test\TestCase { $dependencies = $backend->checkDependencies(); $this->assertCount(0, $dependencies); } - } diff --git a/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php b/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php index 443a13eccef..5fc03cad9e4 100644 --- a/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php +++ b/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php @@ -98,5 +98,4 @@ class UserPlaceholderHandlerTest extends \Test\TestCase { ->willThrowException(new ShareNotFound()); $this->assertSame($option, $this->handler->handle($option)); } - } diff --git a/apps/files_external/tests/Controller/StoragesControllerTest.php b/apps/files_external/tests/Controller/StoragesControllerTest.php index 4e07751fb3d..40d0154d992 100644 --- a/apps/files_external/tests/Controller/StoragesControllerTest.php +++ b/apps/files_external/tests/Controller/StoragesControllerTest.php @@ -403,5 +403,4 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); } } - } diff --git a/apps/files_external/tests/Controller/UserStoragesControllerTest.php b/apps/files_external/tests/Controller/UserStoragesControllerTest.php index 2c3da44b3b2..109a0335146 100644 --- a/apps/files_external/tests/Controller/UserStoragesControllerTest.php +++ b/apps/files_external/tests/Controller/UserStoragesControllerTest.php @@ -110,5 +110,4 @@ class UserStoragesControllerTest extends StoragesControllerTest { $this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); } - } diff --git a/apps/files_external/tests/DefinitionParameterTest.php b/apps/files_external/tests/DefinitionParameterTest.php index 862d3deb557..b0a48509d65 100644 --- a/apps/files_external/tests/DefinitionParameterTest.php +++ b/apps/files_external/tests/DefinitionParameterTest.php @@ -27,7 +27,6 @@ namespace OCA\Files_External\Tests; use OCA\Files_External\Lib\DefinitionParameter as Param; class DefinitionParameterTest extends \Test\TestCase { - public function testJsonSerialization() { $param = new Param('foo', 'bar'); $this->assertEquals([ diff --git a/apps/files_external/tests/FrontendDefinitionTraitTest.php b/apps/files_external/tests/FrontendDefinitionTraitTest.php index ad5cb903214..c4eab6f0122 100644 --- a/apps/files_external/tests/FrontendDefinitionTraitTest.php +++ b/apps/files_external/tests/FrontendDefinitionTraitTest.php @@ -29,7 +29,6 @@ use OCA\Files_External\Lib\DefinitionParameter; use OCA\Files_External\Lib\StorageConfig; class FrontendDefinitionTraitTest extends \Test\TestCase { - public function testJsonSerialization() { $param = $this->getMockBuilder(DefinitionParameter::class) ->disableOriginalConstructor() diff --git a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php index b5c8ae3b2c6..b873a18694d 100644 --- a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php +++ b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php @@ -50,5 +50,4 @@ class LegacyDependencyCheckPolyfillTest extends \Test\TestCase { $this->assertEquals('program', $dependencies[1]->getDependency()); $this->assertEquals('cannot find program', $dependencies[1]->getMessage()); } - } diff --git a/apps/files_external/tests/OwnCloudFunctionsTest.php b/apps/files_external/tests/OwnCloudFunctionsTest.php index 35c3637ecf7..7ce72ce62d6 100644 --- a/apps/files_external/tests/OwnCloudFunctionsTest.php +++ b/apps/files_external/tests/OwnCloudFunctionsTest.php @@ -35,7 +35,6 @@ namespace OCA\Files_External\Tests; * @package OCA\Files_External\Tests */ class OwnCloudFunctionsTest extends \Test\TestCase { - function configUrlProvider() { return [ [ diff --git a/apps/files_external/tests/Service/BackendServiceTest.php b/apps/files_external/tests/Service/BackendServiceTest.php index 2c4587923d8..0964f48572b 100644 --- a/apps/files_external/tests/Service/BackendServiceTest.php +++ b/apps/files_external/tests/Service/BackendServiceTest.php @@ -242,7 +242,9 @@ class BackendServiceTest extends \Test\TestCase { $service = new BackendService($this->config); $mock = $this->createMock(IConfigHandler::class); - $cb = function () use ($mock) { return $mock; }; + $cb = function () use ($mock) { + return $mock; + }; foreach ($placeholders as $placeholder) { $service->registerConfigHandler($placeholder, $cb); } @@ -253,7 +255,9 @@ class BackendServiceTest extends \Test\TestCase { $mock = $this->createMock(IConfigHandler::class); $mock->expects($this->exactly(3)) ->method('handle'); - $cb = function () use ($mock) { return $mock; }; + $cb = function () use ($mock) { + return $mock; + }; $service->registerConfigHandler('one', $cb); $service->registerConfigHandler('2', $cb); $service->registerConfigHandler('Three', $cb); @@ -265,5 +269,4 @@ class BackendServiceTest extends \Test\TestCase { $handler->handle('Something'); } } - } diff --git a/apps/files_external/tests/Service/GlobalStoragesServiceTest.php b/apps/files_external/tests/Service/GlobalStoragesServiceTest.php index bc831b1e95c..b977a4b3eb6 100644 --- a/apps/files_external/tests/Service/GlobalStoragesServiceTest.php +++ b/apps/files_external/tests/Service/GlobalStoragesServiceTest.php @@ -445,7 +445,6 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { $updatedApplicableUsers, $updatedApplicableGroups, $expectedCalls) { - $storage = $this->makeTestStorageData(); $storage->setApplicableUsers($sourceApplicableUsers); $storage->setApplicableGroups($sourceApplicableGroups); @@ -603,7 +602,6 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { $sourceApplicableUsers, $sourceApplicableGroups, $expectedCalls) { - $storage = $this->makeTestStorageData(); $storage->setApplicableUsers($sourceApplicableUsers); $storage->setApplicableGroups($sourceApplicableGroups); @@ -626,5 +624,4 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ); } } - } diff --git a/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php b/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php index 633399197f2..c23d741b23d 100644 --- a/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php +++ b/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php @@ -153,10 +153,8 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { $this->service->getStorage($newStorage->getId()); $this->fail('Failed asserting that storage can\'t be accessed by id'); } catch (NotFoundException $e) { - } } - } diff --git a/apps/files_external/tests/Storage/Amazons3Test.php b/apps/files_external/tests/Storage/Amazons3Test.php index 0e9ec3dbaa6..2aaeede47c3 100644 --- a/apps/files_external/tests/Storage/Amazons3Test.php +++ b/apps/files_external/tests/Storage/Amazons3Test.php @@ -38,7 +38,6 @@ use OCA\Files_External\Lib\Storage\AmazonS3; * @package OCA\Files_External\Tests\Storage */ class Amazons3Test extends \Test\Files\Storage\Storage { - private $config; protected function setUp(): void { diff --git a/apps/files_external/tests/Storage/OwncloudTest.php b/apps/files_external/tests/Storage/OwncloudTest.php index 0f63709614d..6a07bcf498f 100644 --- a/apps/files_external/tests/Storage/OwncloudTest.php +++ b/apps/files_external/tests/Storage/OwncloudTest.php @@ -37,7 +37,6 @@ use OCA\Files_External\Lib\Storage\OwnCloud; * @package OCA\Files_External\Tests\Storage */ class OwncloudTest extends \Test\Files\Storage\Storage { - private $config; protected function setUp(): void { diff --git a/apps/files_external/tests/Storage/SwiftTest.php b/apps/files_external/tests/Storage/SwiftTest.php index 1300aa03038..d90608a2886 100644 --- a/apps/files_external/tests/Storage/SwiftTest.php +++ b/apps/files_external/tests/Storage/SwiftTest.php @@ -39,7 +39,6 @@ use OCA\Files_External\Lib\Storage\Swift; * @package OCA\Files_External\Tests\Storage */ class SwiftTest extends \Test\Files\Storage\Storage { - private $config; /** diff --git a/apps/files_external/tests/Storage/WebdavTest.php b/apps/files_external/tests/Storage/WebdavTest.php index 88e2d4a0181..03b1d41eae5 100644 --- a/apps/files_external/tests/Storage/WebdavTest.php +++ b/apps/files_external/tests/Storage/WebdavTest.php @@ -39,7 +39,6 @@ use OC\Files\Type\Detection; * @package OCA\Files_External\Tests\Storage */ class WebdavTest extends \Test\Files\Storage\Storage { - protected function setUp(): void { parent::setUp(); diff --git a/apps/files_external/tests/StorageConfigTest.php b/apps/files_external/tests/StorageConfigTest.php index 01dab4d95a0..2f0a8fdba50 100644 --- a/apps/files_external/tests/StorageConfigTest.php +++ b/apps/files_external/tests/StorageConfigTest.php @@ -32,7 +32,6 @@ use OCA\Files_External\Lib\DefinitionParameter; use OCA\Files_External\Lib\StorageConfig; class StorageConfigTest extends \Test\TestCase { - public function testJsonSerialization() { $backend = $this->getMockBuilder(Backend::class) ->disableOriginalConstructor() @@ -81,5 +80,4 @@ class StorageConfigTest extends \Test\TestCase { $this->assertSame(['group1', 'group2'], $json['applicableGroups']); $this->assertSame(['preview' => false], $json['mountOptions']); } - } diff --git a/apps/files_sharing/lib/Activity/Providers/Downloads.php b/apps/files_sharing/lib/Activity/Providers/Downloads.php index 91ad8322e6f..23c55e08a26 100644 --- a/apps/files_sharing/lib/Activity/Providers/Downloads.php +++ b/apps/files_sharing/lib/Activity/Providers/Downloads.php @@ -26,8 +26,6 @@ namespace OCA\Files_Sharing\Activity\Providers; use OCP\Activity\IEvent; class Downloads extends Base { - - const SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED = 'public_shared_file_downloaded'; const SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED = 'public_shared_folder_downloaded'; diff --git a/apps/files_sharing/lib/Activity/Providers/Groups.php b/apps/files_sharing/lib/Activity/Providers/Groups.php index 70e3c177e66..c6115a8dba0 100644 --- a/apps/files_sharing/lib/Activity/Providers/Groups.php +++ b/apps/files_sharing/lib/Activity/Providers/Groups.php @@ -35,7 +35,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory; class Groups extends Base { - const SUBJECT_SHARED_GROUP_SELF = 'shared_group_self'; const SUBJECT_RESHARED_GROUP_BY = 'reshared_group_by'; diff --git a/apps/files_sharing/lib/Activity/Providers/PublicLinks.php b/apps/files_sharing/lib/Activity/Providers/PublicLinks.php index 97fc66eaf69..0ebe6cdec0f 100644 --- a/apps/files_sharing/lib/Activity/Providers/PublicLinks.php +++ b/apps/files_sharing/lib/Activity/Providers/PublicLinks.php @@ -26,7 +26,6 @@ namespace OCA\Files_Sharing\Activity\Providers; use OCP\Activity\IEvent; class PublicLinks extends Base { - const SUBJECT_SHARED_LINK_SELF = 'shared_link_self'; const SUBJECT_RESHARED_LINK_BY = 'reshared_link_by'; const SUBJECT_UNSHARED_LINK_SELF = 'unshared_link_self'; @@ -55,7 +54,6 @@ class PublicLinks extends Base { $subject = $this->l->t('{actor} removed public link'); } elseif ($event->getSubject() === self::SUBJECT_LINK_BY_EXPIRED) { $subject = $this->l->t('Public link of {actor} expired'); - } else { throw new \InvalidArgumentException(); } @@ -91,7 +89,6 @@ class PublicLinks extends Base { $subject = $this->l->t('{actor} removed public link for {file}'); } elseif ($event->getSubject() === self::SUBJECT_LINK_BY_EXPIRED) { $subject = $this->l->t('Public link of {actor} for {file} expired'); - } else { throw new \InvalidArgumentException(); } @@ -127,5 +124,4 @@ class PublicLinks extends Base { } return []; } - } diff --git a/apps/files_sharing/lib/Activity/Providers/RemoteShares.php b/apps/files_sharing/lib/Activity/Providers/RemoteShares.php index b56100b6be9..2604288d448 100644 --- a/apps/files_sharing/lib/Activity/Providers/RemoteShares.php +++ b/apps/files_sharing/lib/Activity/Providers/RemoteShares.php @@ -33,7 +33,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory; class RemoteShares extends Base { - const SUBJECT_REMOTE_SHARE_ACCEPTED = 'remote_share_accepted'; const SUBJECT_REMOTE_SHARE_DECLINED = 'remote_share_declined'; const SUBJECT_REMOTE_SHARE_RECEIVED = 'remote_share_received'; diff --git a/apps/files_sharing/lib/Activity/Providers/Users.php b/apps/files_sharing/lib/Activity/Providers/Users.php index 4274e551899..aff5feddc01 100644 --- a/apps/files_sharing/lib/Activity/Providers/Users.php +++ b/apps/files_sharing/lib/Activity/Providers/Users.php @@ -28,8 +28,6 @@ namespace OCA\Files_Sharing\Activity\Providers; use OCP\Activity\IEvent; class Users extends Base { - - const SUBJECT_SHARED_USER_SELF = 'shared_user_self'; const SUBJECT_RESHARED_USER_BY = 'reshared_user_by'; const SUBJECT_UNSHARED_USER_SELF = 'unshared_user_self'; @@ -115,7 +113,6 @@ class Users extends Base { $subject = $this->l->t('Share for file {file} with {user} expired'); } elseif ($event->getSubject() === self::SUBJECT_EXPIRED) { $subject = $this->l->t('Share for file {file} expired'); - } else { throw new \InvalidArgumentException(); } diff --git a/apps/files_sharing/lib/AppInfo/Application.php b/apps/files_sharing/lib/AppInfo/Application.php index 2539b436592..2902b820af3 100644 --- a/apps/files_sharing/lib/AppInfo/Application.php +++ b/apps/files_sharing/lib/AppInfo/Application.php @@ -65,7 +65,6 @@ use OCP\Util; use Symfony\Component\EventDispatcher\GenericEvent; class Application extends App { - const APP_ID = 'files_sharing'; public function __construct(array $urlParams = []) { diff --git a/apps/files_sharing/lib/BackgroundJob/FederatedSharesDiscoverJob.php b/apps/files_sharing/lib/BackgroundJob/FederatedSharesDiscoverJob.php index 30530f15a5c..41f1d36ccf6 100644 --- a/apps/files_sharing/lib/BackgroundJob/FederatedSharesDiscoverJob.php +++ b/apps/files_sharing/lib/BackgroundJob/FederatedSharesDiscoverJob.php @@ -51,7 +51,7 @@ class FederatedSharesDiscoverJob extends TimedJob { ->from('share_external'); $result = $qb->execute(); - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $this->discoveryService->discover($row['remote'], 'FEDERATED_SHARING', true); } $result->closeCursor(); diff --git a/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php b/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php index 6dc0e06d6c6..f5eff5be0cc 100644 --- a/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php +++ b/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php @@ -51,23 +51,23 @@ class ShareRecipientSorter implements ISorter { public function sort(array &$sortArray, array $context) { // let's be tolerant. Comments uses "files" by default, other usages are often singular - if($context['itemType'] !== 'files' && $context['itemType'] !== 'file') { + if ($context['itemType'] !== 'files' && $context['itemType'] !== 'file') { return; } $user = $this->userSession->getUser(); - if($user === null) { + if ($user === null) { return; } $userFolder = $this->rootFolder->getUserFolder($user->getUID()); /** @var Node[] $nodes */ $nodes = $userFolder->getById((int)$context['itemId']); - if(count($nodes) === 0) { + if (count($nodes) === 0) { return; } $al = $this->shareManager->getAccessList($nodes[0]); foreach ($sortArray as $type => &$byType) { - if(!isset($al[$type]) || !is_array($al[$type])) { + if (!isset($al[$type]) || !is_array($al[$type])) { continue; } @@ -80,7 +80,7 @@ class ShareRecipientSorter implements ISorter { usort($workArray, function ($a, $b) use ($al, $type) { $result = $this->compare($a[1], $b[1], $al[$type]); - if($result === 0) { + if ($result === 0) { $result = $a[0] - $b[0]; } return $result; diff --git a/apps/files_sharing/lib/Command/CleanupRemoteStorages.php b/apps/files_sharing/lib/Command/CleanupRemoteStorages.php index 309f882e65c..2eb79f87762 100644 --- a/apps/files_sharing/lib/Command/CleanupRemoteStorages.php +++ b/apps/files_sharing/lib/Command/CleanupRemoteStorages.php @@ -60,7 +60,6 @@ class CleanupRemoteStorages extends Command { } public function execute(InputInterface $input, OutputInterface $output) { - $remoteStorages = $this->getRemoteStorages(); $output->writeln(count($remoteStorages) . ' remote storage(s) need(s) to be checked'); @@ -138,7 +137,6 @@ class CleanupRemoteStorages extends Command { } public function getRemoteStorages() { - $queryBuilder = $this->connection->getQueryBuilder(); $queryBuilder->select(['id', 'numeric_id']) ->from('storages') @@ -166,7 +164,6 @@ class CleanupRemoteStorages extends Command { } public function getRemoteShareIds() { - $queryBuilder = $this->connection->getQueryBuilder(); $queryBuilder->select(['id', 'share_token', 'remote']) ->from('share_external'); diff --git a/apps/files_sharing/lib/Command/ExiprationNotification.php b/apps/files_sharing/lib/Command/ExiprationNotification.php index e228975a9b5..6fd04bcdccc 100644 --- a/apps/files_sharing/lib/Command/ExiprationNotification.php +++ b/apps/files_sharing/lib/Command/ExiprationNotification.php @@ -95,6 +95,4 @@ class ExiprationNotification extends Command { $this->notificationManager->notify($notification); } } - - } diff --git a/apps/files_sharing/lib/Controller/DeletedShareAPIController.php b/apps/files_sharing/lib/Controller/DeletedShareAPIController.php index fc58b5d1209..89a5e0e02aa 100644 --- a/apps/files_sharing/lib/Controller/DeletedShareAPIController.php +++ b/apps/files_sharing/lib/Controller/DeletedShareAPIController.php @@ -93,7 +93,6 @@ class DeletedShareAPIController extends OCSController { * @suppress PhanUndeclaredClassMethod */ private function formatShare(IShare $share): array { - $result = [ 'id' => $share->getFullId(), 'share_type' => $share->getShareType(), @@ -154,7 +153,6 @@ class DeletedShareAPIController extends OCSController { } return $result; - } /** diff --git a/apps/files_sharing/lib/Controller/ExternalSharesController.php b/apps/files_sharing/lib/Controller/ExternalSharesController.php index 0a26f8f9f56..c5dd21cda30 100644 --- a/apps/files_sharing/lib/Controller/ExternalSharesController.php +++ b/apps/files_sharing/lib/Controller/ExternalSharesController.php @@ -151,5 +151,4 @@ class ExternalSharesController extends Controller { return new DataResponse(false); } } - } diff --git a/apps/files_sharing/lib/Controller/PublicPreviewController.php b/apps/files_sharing/lib/Controller/PublicPreviewController.php index d0c2296f0db..0e58057351f 100644 --- a/apps/files_sharing/lib/Controller/PublicPreviewController.php +++ b/apps/files_sharing/lib/Controller/PublicPreviewController.php @@ -96,7 +96,6 @@ class PublicPreviewController extends PublicShareController { int $y = 32, $a = false ) { - if ($token === '' || $x === 0 || $y === 0) { return new DataResponse([], Http::STATUS_BAD_REQUEST); } diff --git a/apps/files_sharing/lib/Controller/ShareAPIController.php b/apps/files_sharing/lib/Controller/ShareAPIController.php index 40a9a387dde..37dc76faaaf 100644 --- a/apps/files_sharing/lib/Controller/ShareAPIController.php +++ b/apps/files_sharing/lib/Controller/ShareAPIController.php @@ -270,7 +270,8 @@ class ShareAPIController extends OCSController { try { $result = array_merge($result, $this->getRoomShareHelper()->formatShare($share)); - } catch (QueryException $e) {} + } catch (QueryException $e) { + } } @@ -594,7 +595,6 @@ class ShareAPIController extends OCSController { * @return array */ private function getSharedWithMe($node, bool $includeTags): array { - $userShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_USER, $node, -1, 0); $groupShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_GROUP, $node, -1, 0); $circleShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_CIRCLE, $node, -1, 0); @@ -709,7 +709,6 @@ class ShareAPIController extends OCSController { string $path = '', string $include_tags = 'false' ): DataResponse { - $node = null; if ($path !== '') { $userFolder = $this->rootFolder->getUserFolder($this->currentUser); @@ -754,7 +753,6 @@ class ShareAPIController extends OCSController { string $viewer, $node = null, bool $sharedWithMe = false, bool $reShares = false, bool $subFiles = false, bool $includeTags = false ): array { - if ($sharedWithMe) { return $this->getSharedWithMe($node, $includeTags); } @@ -1463,7 +1461,6 @@ class ShareAPIController extends OCSController { * @return IShare[] */ private function getSharesFromNode(string $viewer, $node, bool $reShares): array { - $providers = [ Share::SHARE_TYPE_USER, Share::SHARE_TYPE_GROUP, @@ -1580,7 +1577,6 @@ class ShareAPIController extends OCSController { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\Api\v1\Circles')) { - $hasCircleId = (substr($share->getSharedWith(), -1) === ']'); $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0); $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' ')); @@ -1655,5 +1651,4 @@ class ShareAPIController extends OCSController { } } } - } diff --git a/apps/files_sharing/lib/Controller/ShareController.php b/apps/files_sharing/lib/Controller/ShareController.php index 48914e27771..2ea57068f25 100644 --- a/apps/files_sharing/lib/Controller/ShareController.php +++ b/apps/files_sharing/lib/Controller/ShareController.php @@ -250,7 +250,7 @@ class ShareController extends AuthPublicShareController { $itemType = $itemSource = $uidOwner = ''; $token = $share; $exception = null; - if($share instanceof \OCP\Share\IShare) { + if ($share instanceof \OCP\Share\IShare) { try { $token = $share->getToken(); $uidOwner = $share->getSharedBy(); @@ -269,7 +269,7 @@ class ShareController extends AuthPublicShareController { 'errorCode' => $errorCode, 'errorMessage' => $errorMessage, ]); - if(!is_null($exception)) { + if (!is_null($exception)) { throw $exception; } } @@ -366,7 +366,6 @@ class ShareController extends AuthPublicShareController { $hideFileList = false; if ($shareNode instanceof \OCP\Files\Folder) { - $shareIsFolder = true; try { @@ -553,7 +552,7 @@ class ShareController extends AuthPublicShareController { $share = $this->shareManager->getShareByToken($token); - if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) { + if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) { return new \OCP\AppFramework\Http\DataResponse('Share is read-only'); } @@ -676,7 +675,6 @@ class ShareController extends AuthPublicShareController { $subNode = $node->get($file); $this->singleFileDownloaded($share, $subNode); } - } /** @@ -738,7 +736,6 @@ class ShareController extends AuthPublicShareController { $affectedUser, $fileId, $filePath) { - $event = $this->activityManager->generateEvent(); $event->setApp('files_sharing') ->setType('public_links') @@ -747,6 +744,4 @@ class ShareController extends AuthPublicShareController { ->setObject('files', $fileId, $filePath); $this->activityManager->publish($event); } - - } diff --git a/apps/files_sharing/lib/Controller/ShareInfoController.php b/apps/files_sharing/lib/Controller/ShareInfoController.php index 31f98f91c03..315a562abef 100644 --- a/apps/files_sharing/lib/Controller/ShareInfoController.php +++ b/apps/files_sharing/lib/Controller/ShareInfoController.php @@ -88,7 +88,6 @@ class ShareInfoController extends ApiController { try { $node = $node->get($dir); } catch (NotFoundException $e) { - } } diff --git a/apps/files_sharing/lib/Controller/ShareesAPIController.php b/apps/files_sharing/lib/Controller/ShareesAPIController.php index a8cd2196629..557a92d0fca 100644 --- a/apps/files_sharing/lib/Controller/ShareesAPIController.php +++ b/apps/files_sharing/lib/Controller/ShareesAPIController.php @@ -212,7 +212,7 @@ class ShareesAPIController extends OCSController { list($result, $hasMoreResults) = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset); // extra treatment for 'exact' subarray, with a single merge expected keys might be lost - if(isset($result['exact'])) { + if (isset($result['exact'])) { $result['exact'] = array_merge($this->result['exact'], $result['exact']); } $this->result = array_merge($this->result, $result); diff --git a/apps/files_sharing/lib/DeleteOrphanedSharesJob.php b/apps/files_sharing/lib/DeleteOrphanedSharesJob.php index 33267a94c4e..8438b6ac4f7 100644 --- a/apps/files_sharing/lib/DeleteOrphanedSharesJob.php +++ b/apps/files_sharing/lib/DeleteOrphanedSharesJob.php @@ -62,5 +62,4 @@ class DeleteOrphanedSharesJob extends TimedJob { $deletedEntries = $connection->executeUpdate($sql); $logger->debug("$deletedEntries orphaned share(s) deleted", ['app' => 'DeleteOrphanedSharesJob']); } - } diff --git a/apps/files_sharing/lib/Exceptions/SharingRightsException.php b/apps/files_sharing/lib/Exceptions/SharingRightsException.php index 02d197d4034..db346774bdb 100644 --- a/apps/files_sharing/lib/Exceptions/SharingRightsException.php +++ b/apps/files_sharing/lib/Exceptions/SharingRightsException.php @@ -33,5 +33,4 @@ use Exception; * @package OCA\Files_Sharing\Exceptions */ class SharingRightsException extends Exception { - } diff --git a/apps/files_sharing/lib/ExpireSharesJob.php b/apps/files_sharing/lib/ExpireSharesJob.php index ef90a04dba1..19684ec8964 100644 --- a/apps/files_sharing/lib/ExpireSharesJob.php +++ b/apps/files_sharing/lib/ExpireSharesJob.php @@ -68,10 +68,9 @@ class ExpireSharesJob extends TimedJob { ); $shares = $qb->execute(); - while($share = $shares->fetch()) { + while ($share = $shares->fetch()) { \OC\Share\Share::unshare($share['item_type'], $share['file_source'], \OCP\Share::SHARE_TYPE_LINK, null, $share['uid_owner']); } $shares->closeCursor(); } - } diff --git a/apps/files_sharing/lib/External/Manager.php b/apps/files_sharing/lib/External/Manager.php index ee547ce9114..3923fdf09d3 100644 --- a/apps/files_sharing/lib/External/Manager.php +++ b/apps/files_sharing/lib/External/Manager.php @@ -151,12 +151,11 @@ class Manager { * @throws \Doctrine\DBAL\DBALException */ public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) { - $user = $user ? $user : $this->uid; $accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING; $name = Filesystem::normalizePath('/' . $name); - if ($accepted !== IShare::STATUS_ACCEPTED) { + if ($accepted !== IShare::STATUS_ACCEPTED) { // To avoid conflicts with the mount point generation later, // we only use a temporary mount point name here. The real // mount point name will be generated when accepting the share, @@ -258,7 +257,6 @@ class Manager { } return false; - } /** @@ -268,7 +266,6 @@ class Manager { * @return bool True if the share could be accepted, false otherwise */ public function acceptShare($id) { - $share = $this->getShare($id); $result = false; @@ -280,7 +277,7 @@ class Manager { $hash = md5($mountPoint); $userShareAccepted = false; - if((int)$share['share_type'] === Share::SHARE_TYPE_USER) { + if ((int)$share['share_type'] === Share::SHARE_TYPE_USER) { $acceptShare = $this->connection->prepare(' UPDATE `*PREFIX*share_external` SET `accepted` = ?, @@ -321,7 +318,6 @@ class Manager { * @return bool True if the share could be declined, false otherwise */ public function declineShare($id) { - $share = $this->getShare($id); $result = false; @@ -374,10 +370,9 @@ class Manager { * @return boolean */ private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) { - $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback); - if($result === true) { + if ($result === true) { return true; } @@ -446,7 +441,6 @@ class Manager { } return false; - } @@ -509,7 +503,6 @@ class Manager { } public function removeShare($mountPoint) { - $mountPointObj = $this->mountManager->find($mountPoint); $id = $mountPointObj->getStorage()->getCache()->getId(''); @@ -545,7 +538,7 @@ class Manager { $result = (bool)$query->execute([0, (int)$share['id']]); } - if($result) { + if ($result) { $this->removeReShares($id); } @@ -590,7 +583,7 @@ class Manager { if ($result) { $shares = $getShare->fetchAll(); - foreach($shares as $share) { + foreach ($shares as $share) { $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline'); } } diff --git a/apps/files_sharing/lib/External/Scanner.php b/apps/files_sharing/lib/External/Scanner.php index afa8687d280..8962bb68c07 100644 --- a/apps/files_sharing/lib/External/Scanner.php +++ b/apps/files_sharing/lib/External/Scanner.php @@ -37,7 +37,7 @@ class Scanner extends \OC\Files\Cache\Scanner { /** {@inheritDoc} */ public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { - if(!$this->storage->remoteIsOwnCloud()) { + if (!$this->storage->remoteIsOwnCloud()) { return parent::scan($path, $recursive, $recursive, $lock); } diff --git a/apps/files_sharing/lib/External/Storage.php b/apps/files_sharing/lib/External/Storage.php index 1390c0a4f56..0d5f620ddf2 100644 --- a/apps/files_sharing/lib/External/Storage.php +++ b/apps/files_sharing/lib/External/Storage.php @@ -266,7 +266,7 @@ class Storage extends DAV implements ISharedStorage, IDisableEncryptionStorage { */ private function testRemoteUrl($url) { $cache = $this->memcacheFactory->createDistributed('files_sharing_remote_url'); - if($cache->hasKey($url)) { + if ($cache->hasKey($url)) { return (bool)$cache->get($url); } @@ -297,7 +297,7 @@ class Storage extends DAV implements ISharedStorage, IDisableEncryptionStorage { * @return bool */ public function remoteIsOwnCloud() { - if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) { + if (defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) { return false; } return true; @@ -315,7 +315,7 @@ class Storage extends DAV implements ISharedStorage, IDisableEncryptionStorage { $password = $this->getPassword(); // If remote is not an ownCloud do not try to get any share info - if(!$this->remoteIsOwnCloud()) { + if (!$this->remoteIsOwnCloud()) { return ['status' => 'unsupported']; } @@ -387,7 +387,7 @@ class Storage extends DAV implements ISharedStorage, IDisableEncryptionStorage { try { $ocmPermissions = json_decode($ocmPermissions); $ncPermissions = 0; - foreach($ocmPermissions as $permission) { + foreach ($ocmPermissions as $permission) { switch (strtolower($permission)) { case 'read': $ncPermissions += Constants::PERMISSION_READ; diff --git a/apps/files_sharing/lib/Helper.php b/apps/files_sharing/lib/Helper.php index 3efb4e25eef..d3c6deeec2e 100644 --- a/apps/files_sharing/lib/Helper.php +++ b/apps/files_sharing/lib/Helper.php @@ -31,7 +31,6 @@ use OC\Files\Filesystem; use OC\Files\View; class Helper { - public static function registerHooks() { \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook'); \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren'); @@ -86,7 +85,6 @@ class Helper { } return $shareFolder; - } /** @@ -97,5 +95,4 @@ class Helper { public static function setShareFolder($shareFolder) { \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder); } - } diff --git a/apps/files_sharing/lib/Hooks.php b/apps/files_sharing/lib/Hooks.php index 9b547ea295e..a37a497f2bd 100644 --- a/apps/files_sharing/lib/Hooks.php +++ b/apps/files_sharing/lib/Hooks.php @@ -30,7 +30,6 @@ namespace OCA\Files_Sharing; use OC\Files\Filesystem; class Hooks { - public static function deleteUser($params) { $manager = new External\Manager( \OC::$server->getDatabaseConnection(), diff --git a/apps/files_sharing/lib/ISharedStorage.php b/apps/files_sharing/lib/ISharedStorage.php index 2f0888589ca..0b7444deb0b 100644 --- a/apps/files_sharing/lib/ISharedStorage.php +++ b/apps/files_sharing/lib/ISharedStorage.php @@ -23,6 +23,5 @@ namespace OCA\Files_Sharing; -interface ISharedStorage{ - +interface ISharedStorage { } diff --git a/apps/files_sharing/lib/Listener/LoadSidebarListener.php b/apps/files_sharing/lib/Listener/LoadSidebarListener.php index ba2ce54eeb4..636a8c7757e 100644 --- a/apps/files_sharing/lib/Listener/LoadSidebarListener.php +++ b/apps/files_sharing/lib/Listener/LoadSidebarListener.php @@ -40,5 +40,4 @@ class LoadSidebarListener implements IEventListener { Util::addScript(Application::APP_ID, 'dist/files_sharing_tab'); } - } diff --git a/apps/files_sharing/lib/Listener/ShareInteractionListener.php b/apps/files_sharing/lib/Listener/ShareInteractionListener.php index 0e409773e54..e698d16d823 100644 --- a/apps/files_sharing/lib/Listener/ShareInteractionListener.php +++ b/apps/files_sharing/lib/Listener/ShareInteractionListener.php @@ -37,7 +37,6 @@ use OCP\Share\IShare; use function in_array; class ShareInteractionListener implements IEventListener { - private const SUPPORTED_SHARE_TYPES = [ IShare::TYPE_USER, IShare::TYPE_EMAIL, @@ -92,5 +91,4 @@ class ShareInteractionListener implements IEventListener { $this->dispatcher->dispatchTyped($interactionEvent); } - } diff --git a/apps/files_sharing/lib/Listener/UserAddedToGroupListener.php b/apps/files_sharing/lib/Listener/UserAddedToGroupListener.php index a1a20ad5f47..623591da310 100644 --- a/apps/files_sharing/lib/Listener/UserAddedToGroupListener.php +++ b/apps/files_sharing/lib/Listener/UserAddedToGroupListener.php @@ -80,5 +80,4 @@ class UserAddedToGroupListener implements IEventListener { $acceptDefault = $this->config->getUserValue($userId, Application::APP_ID, 'default_accept', $defaultAcceptSystemConfig) === 'yes'; return (!$this->config->getSystemValueBool('sharing.force_share_accept', false) && $acceptDefault); } - } diff --git a/apps/files_sharing/lib/Listener/UserShareAcceptanceListener.php b/apps/files_sharing/lib/Listener/UserShareAcceptanceListener.php index 758138bb7f0..ec7bc5b86fe 100644 --- a/apps/files_sharing/lib/Listener/UserShareAcceptanceListener.php +++ b/apps/files_sharing/lib/Listener/UserShareAcceptanceListener.php @@ -72,7 +72,6 @@ class UserShareAcceptanceListener implements IEventListener { $this->handleAutoAccept($share, $user->getUID()); } } - } private function handleAutoAccept(IShare $share, string $userId) { @@ -82,5 +81,4 @@ class UserShareAcceptanceListener implements IEventListener { $this->shareManager->acceptShare($share, $userId); } } - } diff --git a/apps/files_sharing/lib/Middleware/SharingCheckMiddleware.php b/apps/files_sharing/lib/Middleware/SharingCheckMiddleware.php index 63a67bb5b48..24f1899a312 100644 --- a/apps/files_sharing/lib/Middleware/SharingCheckMiddleware.php +++ b/apps/files_sharing/lib/Middleware/SharingCheckMiddleware.php @@ -93,7 +93,7 @@ class SharingCheckMiddleware extends Middleware { * @throws ShareNotFound */ public function beforeController($controller, $methodName) { - if(!$this->isSharingEnabled()) { + if (!$this->isSharingEnabled()) { throw new NotFoundException('Sharing is disabled.'); } @@ -113,7 +113,7 @@ class SharingCheckMiddleware extends Middleware { * @throws \Exception */ public function afterException($controller, $methodName, \Exception $exception) { - if(is_a($exception, NotFoundException::class)) { + if (is_a($exception, NotFoundException::class)) { return new NotFoundResponse(); } @@ -129,7 +129,6 @@ class SharingCheckMiddleware extends Middleware { * @return bool */ private function externalSharesChecks() { - if (!$this->reflector->hasAnnotation('NoIncomingFederatedSharingRequired') && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') !== 'yes') { return false; @@ -150,13 +149,10 @@ class SharingCheckMiddleware extends Middleware { private function isSharingEnabled() { // FIXME: This check is done here since the route is globally defined and not inside the files_sharing app // Check whether the sharing application is enabled - if(!$this->appManager->isEnabledForUser($this->appName)) { + if (!$this->appManager->isEnabledForUser($this->appName)) { return false; } return true; } - - - } diff --git a/apps/files_sharing/lib/Migration/OwncloudGuestShareType.php b/apps/files_sharing/lib/Migration/OwncloudGuestShareType.php index 9b0fee38bac..237c6aca243 100644 --- a/apps/files_sharing/lib/Migration/OwncloudGuestShareType.php +++ b/apps/files_sharing/lib/Migration/OwncloudGuestShareType.php @@ -79,5 +79,4 @@ class OwncloudGuestShareType implements IRepairStep { return $appVersion === '0.10.0' || $this->config->getAppValue('core', 'vendor', '') === 'owncloud'; } - } diff --git a/apps/files_sharing/lib/Migration/SetAcceptedStatus.php b/apps/files_sharing/lib/Migration/SetAcceptedStatus.php index a48ca8fa6a8..386f7299d40 100644 --- a/apps/files_sharing/lib/Migration/SetAcceptedStatus.php +++ b/apps/files_sharing/lib/Migration/SetAcceptedStatus.php @@ -77,5 +77,4 @@ class SetAcceptedStatus implements IRepairStep { $appVersion = $this->config->getAppValue('files_sharing', 'installed_version', '0.0.0'); return version_compare($appVersion, '1.10.1', '<'); } - } diff --git a/apps/files_sharing/lib/Migration/SetPasswordColumn.php b/apps/files_sharing/lib/Migration/SetPasswordColumn.php index a666aa4dd3e..5580bd46a5b 100644 --- a/apps/files_sharing/lib/Migration/SetPasswordColumn.php +++ b/apps/files_sharing/lib/Migration/SetPasswordColumn.php @@ -86,12 +86,10 @@ class SetPasswordColumn implements IRepairStep { ->where($clearQuery->expr()->eq('share_type', $clearQuery->createNamedParameter(Share::SHARE_TYPE_LINK))); $clearQuery->execute(); - } protected function shouldRun() { $appVersion = $this->config->getAppValue('files_sharing', 'installed_version', '0.0.0'); return version_compare($appVersion, '1.4.0', '<'); } - } diff --git a/apps/files_sharing/lib/MountProvider.php b/apps/files_sharing/lib/MountProvider.php index dd880d13306..c318d18ed82 100644 --- a/apps/files_sharing/lib/MountProvider.php +++ b/apps/files_sharing/lib/MountProvider.php @@ -74,7 +74,6 @@ class MountProvider implements IMountProvider { * @return \OCP\Files\Mount\IMountPoint[] */ public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) { - $shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1); $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1)); $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_CIRCLE, null, -1)); diff --git a/apps/files_sharing/lib/Notification/Notifier.php b/apps/files_sharing/lib/Notification/Notifier.php index 07c41882917..6db19d3bd5f 100644 --- a/apps/files_sharing/lib/Notification/Notifier.php +++ b/apps/files_sharing/lib/Notification/Notifier.php @@ -149,7 +149,6 @@ class Notifier implements INotifier { } protected function parseShareInvitation(IShare $share, INotification $notification, IL10N $l): INotification { - if ($share->getShareType() === IShare::TYPE_USER) { if ($share->getStatus() !== IShare::STATUS_PENDING) { throw new AlreadyProcessedException(); diff --git a/apps/files_sharing/lib/Settings/Personal.php b/apps/files_sharing/lib/Settings/Personal.php index 3e83869a582..bfca0b46e07 100644 --- a/apps/files_sharing/lib/Settings/Personal.php +++ b/apps/files_sharing/lib/Settings/Personal.php @@ -64,5 +64,4 @@ class Personal implements ISettings { public function getPriority(): int { return 90; } - } diff --git a/apps/files_sharing/lib/ShareBackend/File.php b/apps/files_sharing/lib/ShareBackend/File.php index fdbd0da96a3..2db6c374c85 100644 --- a/apps/files_sharing/lib/ShareBackend/File.php +++ b/apps/files_sharing/lib/ShareBackend/File.php @@ -37,7 +37,6 @@ namespace OCA\Files_Sharing\ShareBackend; use OCA\FederatedFileSharing\FederatedShareProvider; class File implements \OCP\Share_Backend_File_Dependent { - const FORMAT_SHARED_STORAGE = 0; const FORMAT_GET_FOLDER_CONTENTS = 1; const FORMAT_FILE_APP_ROOT = 2; diff --git a/apps/files_sharing/lib/ShareBackend/Folder.php b/apps/files_sharing/lib/ShareBackend/Folder.php index 7713c8b6b11..c51740cd6d0 100644 --- a/apps/files_sharing/lib/ShareBackend/Folder.php +++ b/apps/files_sharing/lib/ShareBackend/Folder.php @@ -109,7 +109,6 @@ class Folder extends File implements \OCP\Share_Backend_Collection { $mimetype = -1; } while (!empty($parents)) { - $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); $parents = array_map(function ($parent) use ($qb) { @@ -136,5 +135,4 @@ class Folder extends File implements \OCP\Share_Backend_Collection { } return $children; } - } diff --git a/apps/files_sharing/lib/SharedMount.php b/apps/files_sharing/lib/SharedMount.php index 91f3c39ba05..487011584c7 100644 --- a/apps/files_sharing/lib/SharedMount.php +++ b/apps/files_sharing/lib/SharedMount.php @@ -89,7 +89,6 @@ class SharedMount extends MountPoint implements MoveableMount { * @return string */ private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints, CappedMemoryCache $folderExistCache) { - $mountPoint = basename($share->getTarget()); $parent = dirname($share->getTarget()); @@ -193,7 +192,6 @@ class SharedMount extends MountPoint implements MoveableMount { * @return bool */ public function moveMount($target) { - $relTargetPath = $this->stripUserFilesPath($target); $share = $this->storage->getShare(); diff --git a/apps/files_sharing/lib/Updater.php b/apps/files_sharing/lib/Updater.php index 652ff171880..828453be765 100644 --- a/apps/files_sharing/lib/Updater.php +++ b/apps/files_sharing/lib/Updater.php @@ -91,7 +91,6 @@ class Updater { * @param string $newPath new path relative to data/user/files */ static private function renameChildren($oldPath, $newPath) { - $absNewPath = \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath); $absOldPath = \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath); @@ -105,5 +104,4 @@ class Updater { } } } - } diff --git a/apps/files_sharing/templates/public.php b/apps/files_sharing/templates/public.php index 5c462b51aa6..751303e8109 100644 --- a/apps/files_sharing/templates/public.php +++ b/apps/files_sharing/templates/public.php @@ -50,7 +50,7 @@ $maxUploadFilesize = min($upload_max_filesize, $post_max_size); checked="checked" /> + checked="checked" /> diff --git a/apps/files_sharing/tests/ApiTest.php b/apps/files_sharing/tests/ApiTest.php index b8d5a21a739..2d262a0104a 100644 --- a/apps/files_sharing/tests/ApiTest.php +++ b/apps/files_sharing/tests/ApiTest.php @@ -53,7 +53,6 @@ use OCP\Share\IShare; * TODO: convert to real intergration tests */ class ApiTest extends TestCase { - const TEST_FOLDER_NAME = '/folder_share_api_test'; const APP_NAME = 'files_sharing'; @@ -91,7 +90,7 @@ class ApiTest extends TestCase { } protected function tearDown(): void { - if($this->view instanceof \OC\Files\View) { + if ($this->view instanceof \OC\Files\View) { $this->view->unlink($this->filename); $this->view->deleteAll($this->folder); } @@ -163,7 +162,6 @@ class ApiTest extends TestCase { $ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1); $ocs->deleteShare($data['id']); $ocs->cleanup(); - } @@ -197,7 +195,6 @@ class ApiTest extends TestCase { $ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1); $ocs->deleteShare($data['id']); $ocs->cleanup(); - } public function testCreateShareLink() { @@ -249,7 +246,6 @@ class ApiTest extends TestCase { } function testEnforceLinkPassword() { - $password = md5(time()); $config = \OC::$server->getConfig(); $config->setAppValue('core', 'shareapi_enforce_links_password', 'yes'); @@ -259,7 +255,6 @@ class ApiTest extends TestCase { $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, \OCP\Share::SHARE_TYPE_LINK); $this->fail(); } catch (OCSForbiddenException $e) { - } $ocs->cleanup(); @@ -268,7 +263,6 @@ class ApiTest extends TestCase { $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, \OCP\Share::SHARE_TYPE_LINK, null, 'false', ''); $this->fail(); } catch (OCSForbiddenException $e) { - } $ocs->cleanup(); @@ -290,7 +284,6 @@ class ApiTest extends TestCase { $ocs->updateShare($data['id']); $this->fail(); } catch (OCSBadRequestException $e) { - } $ocs->cleanup(); @@ -933,7 +926,6 @@ class ApiTest extends TestCase { * @depends testCreateShareLink */ function testUpdateShare() { - $password = md5(time()); $node1 = $this->userFolder->get($this->filename); @@ -1054,7 +1046,6 @@ class ApiTest extends TestCase { $ocs->updateShare($share1->getId()); $this->fail(); } catch (OCSBadRequestException $e) { - } $ocs->cleanup(); @@ -1069,7 +1060,6 @@ class ApiTest extends TestCase { $ocs->updateShare($share1->getId()); $this->fail(); } catch (OCSBadRequestException $e) { - } $ocs->cleanup(); @@ -1372,7 +1362,7 @@ class ApiTest extends TestCase { try { $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, \OCP\Share::SHARE_TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d')); $this->fail(); - } catch(OCSException $e) { + } catch (OCSException $e) { $this->assertEquals(404, $e->getCode()); $this->assertEquals('Expiration date is in the past', $e->getMessage()); } diff --git a/apps/files_sharing/tests/CacheTest.php b/apps/files_sharing/tests/CacheTest.php index 94e5504aece..355a1a8bb1b 100644 --- a/apps/files_sharing/tests/CacheTest.php +++ b/apps/files_sharing/tests/CacheTest.php @@ -129,7 +129,7 @@ class CacheTest extends TestCase { } protected function tearDown(): void { - if($this->sharedCache) { + if ($this->sharedCache) { $this->sharedCache->clear(); } @@ -219,7 +219,6 @@ class CacheTest extends TestCase { $this->verifyFiles($expectedFiles, $results); } - } /** * Test searching by mime type diff --git a/apps/files_sharing/tests/CapabilitiesTest.php b/apps/files_sharing/tests/CapabilitiesTest.php index e4c15887636..a49074cb60e 100644 --- a/apps/files_sharing/tests/CapabilitiesTest.php +++ b/apps/files_sharing/tests/CapabilitiesTest.php @@ -285,5 +285,4 @@ class CapabilitiesTest extends \Test\TestCase { $this->assertArrayHasKey('federation', $result); $this->assertFalse($result['federation']['outgoing']); } - } diff --git a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php index 9be1141f35f..dd03ffc6668 100644 --- a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php +++ b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php @@ -191,6 +191,5 @@ class CleanupRemoteStoragesTest extends TestCase { $this->assertFalse($this->doesStorageExist($this->storages[3]['numeric_id'])); $this->assertTrue($this->doesStorageExist($this->storages[4]['numeric_id'])); $this->assertFalse($this->doesStorageExist($this->storages[5]['numeric_id'])); - } } diff --git a/apps/files_sharing/tests/Controller/ShareControllerTest.php b/apps/files_sharing/tests/Controller/ShareControllerTest.php index a43c050634b..2f1df959afb 100644 --- a/apps/files_sharing/tests/Controller/ShareControllerTest.php +++ b/apps/files_sharing/tests/Controller/ShareControllerTest.php @@ -162,7 +162,9 @@ class ShareControllerTest extends \Test\TestCase { \OC_User::setUserId(''); Filesystem::tearDown(); $user = \OC::$server->getUserManager()->get($this->user); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } \OC_User::setIncognitoMode(false); \OC::$server->getSession()->set('public_link_authenticated', ''); @@ -208,7 +210,6 @@ class ShareControllerTest extends \Test\TestCase { public function testShowShare() { - $note = 'personal note'; $this->shareController->setToken('token'); @@ -356,7 +357,6 @@ class ShareControllerTest extends \Test\TestCase { } public function testShowShareWithPrivateName() { - $note = 'personal note'; $this->shareController->setToken('token'); diff --git a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php index 0ed98f27cd3..a885750a566 100644 --- a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php +++ b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php @@ -100,11 +100,11 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase { $userManager = \OC::$server->getUserManager(); $user1 = $userManager->get($this->user1); - if($user1) { + if ($user1) { $user1->delete(); } $user2 = $userManager->get($this->user2); - if($user2) { + if ($user2) { $user2->delete(); } diff --git a/apps/files_sharing/tests/EncryptedSizePropagationTest.php b/apps/files_sharing/tests/EncryptedSizePropagationTest.php index 23f552260d6..9a8ff29d70a 100644 --- a/apps/files_sharing/tests/EncryptedSizePropagationTest.php +++ b/apps/files_sharing/tests/EncryptedSizePropagationTest.php @@ -42,5 +42,4 @@ class EncryptedSizePropagationTest extends SizePropagationTest { $this->loginWithEncryption($name); return new View('/' . $name . '/files'); } - } diff --git a/apps/files_sharing/tests/ExpireSharesJobTest.php b/apps/files_sharing/tests/ExpireSharesJobTest.php index 4fe1ccc7719..f8bf900cb79 100644 --- a/apps/files_sharing/tests/ExpireSharesJobTest.php +++ b/apps/files_sharing/tests/ExpireSharesJobTest.php @@ -78,11 +78,11 @@ class ExpireSharesJobTest extends \Test\TestCase { $userManager = \OC::$server->getUserManager(); $user1 = $userManager->get($this->user1); - if($user1) { + if ($user1) { $user1->delete(); } $user2 = $userManager->get($this->user2); - if($user2) { + if ($user2) { $user2->delete(); } @@ -213,5 +213,4 @@ class ExpireSharesJobTest extends \Test\TestCase { $shares = $this->getShares(); $this->assertCount(1, $shares); } - } diff --git a/apps/files_sharing/tests/External/CacheTest.php b/apps/files_sharing/tests/External/CacheTest.php index 466806e09cb..be8911961df 100644 --- a/apps/files_sharing/tests/External/CacheTest.php +++ b/apps/files_sharing/tests/External/CacheTest.php @@ -130,5 +130,4 @@ class CacheTest extends TestCase { $results[0]['displayname_owner'] ); } - } diff --git a/apps/files_sharing/tests/External/ManagerTest.php b/apps/files_sharing/tests/External/ManagerTest.php index 5a1e8ad14e1..9c84cb668ef 100644 --- a/apps/files_sharing/tests/External/ManagerTest.php +++ b/apps/files_sharing/tests/External/ManagerTest.php @@ -123,7 +123,6 @@ class ManagerTest extends TestCase { } public function testAddShare() { - $shareData1 = [ 'remote' => 'http://localhost', 'token' => 'token1', diff --git a/apps/files_sharing/tests/ExternalStorageTest.php b/apps/files_sharing/tests/ExternalStorageTest.php index f2bf5738f36..fa8df930a4e 100644 --- a/apps/files_sharing/tests/ExternalStorageTest.php +++ b/apps/files_sharing/tests/ExternalStorageTest.php @@ -39,7 +39,6 @@ use OCP\Http\Client\IResponse; * @group DB */ class ExternalStorageTest extends \Test\TestCase { - function optionsProvider() { return [ [ @@ -125,7 +124,6 @@ class ExternalStorageTest extends \Test\TestCase { * Dummy subclass to make it possible to access private members */ class TestSharingExternalStorage extends \OCA\Files_Sharing\External\Storage { - public function getBaseUri() { return $this->createBaseUri(); } diff --git a/apps/files_sharing/tests/HelperTest.php b/apps/files_sharing/tests/HelperTest.php index 4a27ca4afec..a4311f908b3 100644 --- a/apps/files_sharing/tests/HelperTest.php +++ b/apps/files_sharing/tests/HelperTest.php @@ -47,7 +47,5 @@ class HelperTest extends TestCase { // cleanup \OC::$server->getConfig()->deleteSystemValue('share_folder'); - } - } diff --git a/apps/files_sharing/tests/LockingTest.php b/apps/files_sharing/tests/LockingTest.php index bb50cc5bd38..c6a799f64a6 100644 --- a/apps/files_sharing/tests/LockingTest.php +++ b/apps/files_sharing/tests/LockingTest.php @@ -104,7 +104,6 @@ class LockingTest extends TestCase { } public function testChangeLock() { - Filesystem::initMountPoints($this->recipientUid); $recipientView = new View('/' . $this->recipientUid . '/files'); $recipientView->lockFile('bar.txt', ILockingProvider::LOCK_SHARED); diff --git a/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php b/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php index 08d8e6e1486..c290183d046 100644 --- a/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php +++ b/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php @@ -154,5 +154,4 @@ class ShareInfoMiddlewareTest extends TestCase { } class ShareInfoMiddlewareTestController extends Controller { - } diff --git a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php index 29dafb5762d..2c33f5617b7 100644 --- a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php +++ b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php @@ -101,14 +101,12 @@ class SharingCheckMiddlewareTest extends \Test\TestCase { } public function externalSharesChecksDataProvider() { - $data = []; foreach ([false, true] as $annIn) { foreach ([false, true] as $annOut) { foreach ([false, true] as $confIn) { foreach ([false, true] as $confOut) { - $res = true; if (!$annIn && !$confIn) { $res = false; @@ -186,7 +184,6 @@ class SharingCheckMiddlewareTest extends \Test\TestCase { } public function testBeforeControllerWithShareControllerWithSharingEnabled() { - $share = $this->createMock(IShare::class); $this->appManager @@ -229,6 +226,4 @@ class SharingCheckMiddlewareTest extends \Test\TestCase { public function testAfterExceptionWithS2SException() { $this->assertEquals(new JSONResponse('My Exception message', 405), $this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new S2SException('My Exception message'))); } - - } diff --git a/apps/files_sharing/tests/ShareTest.php b/apps/files_sharing/tests/ShareTest.php index 63c2f2d19e3..313c8d8ac56 100644 --- a/apps/files_sharing/tests/ShareTest.php +++ b/apps/files_sharing/tests/ShareTest.php @@ -34,7 +34,6 @@ namespace OCA\Files_Sharing\Tests; * @group DB */ class ShareTest extends TestCase { - const TEST_FOLDER_NAME = '/folder_share_api_test'; private static $tempStorage; @@ -128,7 +127,6 @@ class ShareTest extends TestCase { } public function testShareWithDifferentShareFolder() { - $fileinfo = $this->view->getFileInfo($this->filename); $folderinfo = $this->view->getFileInfo($this->folder); @@ -203,7 +201,6 @@ class ShareTest extends TestCase { * @dataProvider dataProviderTestFileSharePermissions */ public function testFileSharePermissions($permission, $expectedvalid) { - $pass = true; try { $this->share( @@ -237,7 +234,6 @@ class ShareTest extends TestCase { } public function testFileOwner() { - $this->share( \OCP\Share::SHARE_TYPE_USER, $this->filename, diff --git a/apps/files_sharing/tests/SharedMountTest.php b/apps/files_sharing/tests/SharedMountTest.php index f3fe96d2c3d..59c0e3b76af 100644 --- a/apps/files_sharing/tests/SharedMountTest.php +++ b/apps/files_sharing/tests/SharedMountTest.php @@ -287,7 +287,9 @@ class SharedMountTest extends TestCase { foreach ($allPermissions as $before) { foreach ($allPermissions as $after) { - if ($before === $after) { continue; } + if ($before === $after) { + continue; + } $data[] = [ 'file', @@ -309,7 +311,9 @@ class SharedMountTest extends TestCase { foreach ($allPermissions as $before) { foreach ($allPermissions as $after) { - if ($before === $after) { continue; } + if ($before === $after) { + continue; + } $data[] = [ 'folder', @@ -331,7 +335,6 @@ class SharedMountTest extends TestCase { * @dataProvider dataPermissionMovedGroupShare */ public function testPermissionMovedGroupShare($type, $beforePerm, $afterPerm) { - if ($type === 'file') { $path = $this->filename; } elseif ($type === 'folder') { @@ -456,7 +459,6 @@ class SharedMountTest extends TestCase { $testGroup->removeUser($user2); $testGroup->removeUser($user3); } - } class DummyTestClassSharedMount extends \OCA\Files_Sharing\SharedMount { diff --git a/apps/files_sharing/tests/SharedStorageTest.php b/apps/files_sharing/tests/SharedStorageTest.php index 936295f45b7..7d20d98585f 100644 --- a/apps/files_sharing/tests/SharedStorageTest.php +++ b/apps/files_sharing/tests/SharedStorageTest.php @@ -40,7 +40,6 @@ use OCP\Share\IShare; * @group DB */ class SharedStorageTest extends TestCase { - protected function setUp(): void { parent::setUp(); \OCA\Files_Trashbin\Trashbin::registerHooks(); @@ -565,7 +564,6 @@ class SharedStorageTest extends TestCase { $this->view->unlink($this->folder); $this->shareManager->deleteShare($share); - } public function testInitWithNonExistingUser() { diff --git a/apps/files_sharing/tests/TestCase.php b/apps/files_sharing/tests/TestCase.php index c9f024cd67a..323fc06f321 100644 --- a/apps/files_sharing/tests/TestCase.php +++ b/apps/files_sharing/tests/TestCase.php @@ -130,11 +130,17 @@ abstract class TestCase extends \Test\TestCase { public static function tearDownAfterClass(): void { // cleanup users $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER1); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER2); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER3); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } // delete group $group = \OC::$server->getGroupManager()->get(self::TEST_FILES_SHARING_API_GROUP1); @@ -161,7 +167,6 @@ abstract class TestCase extends \Test\TestCase { * @param bool $password */ protected static function loginHelper($user, $create = false, $password = false) { - if ($password === false) { $password = $user; } @@ -218,7 +223,6 @@ abstract class TestCase extends \Test\TestCase { $result->closeCursor(); return $share; - } /** diff --git a/apps/files_sharing/tests/UnshareChildrenTest.php b/apps/files_sharing/tests/UnshareChildrenTest.php index d12bda4006c..56fdeb44a30 100644 --- a/apps/files_sharing/tests/UnshareChildrenTest.php +++ b/apps/files_sharing/tests/UnshareChildrenTest.php @@ -35,7 +35,6 @@ namespace OCA\Files_Sharing\Tests; * @package OCA\Files_Sharing\Tests */ class UnshareChildrenTest extends TestCase { - protected $subsubfolder; const TEST_FOLDER_NAME = '/folder_share_api_test'; @@ -75,7 +74,6 @@ class UnshareChildrenTest extends TestCase { * @medium */ public function testUnshareChildren() { - $fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder); $this->share( diff --git a/apps/files_sharing/tests/UpdaterTest.php b/apps/files_sharing/tests/UpdaterTest.php index 7ca883c78f8..0abc76df433 100644 --- a/apps/files_sharing/tests/UpdaterTest.php +++ b/apps/files_sharing/tests/UpdaterTest.php @@ -36,7 +36,6 @@ namespace OCA\Files_Sharing\Tests; * @group DB */ class UpdaterTest extends TestCase { - const TEST_FOLDER_NAME = '/folder_share_updater_test'; public static function setUpBeforeClass(): void { @@ -199,7 +198,6 @@ class UpdaterTest extends TestCase { * if a folder gets renamed all children mount points should be renamed too */ public function testRename() { - $fileinfo = \OC\Files\Filesystem::getFileInfo($this->folder); $share = $this->share( @@ -234,5 +232,4 @@ class UpdaterTest extends TestCase { // cleanup $this->shareManager->deleteShare($share); } - } diff --git a/apps/files_trashbin/lib/AppInfo/Application.php b/apps/files_trashbin/lib/AppInfo/Application.php index 6a810e9218e..e86a401d2fd 100644 --- a/apps/files_trashbin/lib/AppInfo/Application.php +++ b/apps/files_trashbin/lib/AppInfo/Application.php @@ -78,11 +78,11 @@ class Application extends App { $appManager = $server->getAppManager(); /** @var ITrashManager $trashManager */ $trashManager = $this->getContainer()->getServer()->query(ITrashManager::class); - foreach($appManager->getInstalledApps() as $app) { + foreach ($appManager->getInstalledApps() as $app) { $appInfo = $appManager->getAppInfo($app); if (isset($appInfo['trash'])) { $backends = $appInfo['trash']; - foreach($backends as $backend) { + foreach ($backends as $backend) { $class = $backend['@value']; $for = $backend['@attributes']['for']; diff --git a/apps/files_trashbin/lib/Capabilities.php b/apps/files_trashbin/lib/Capabilities.php index 0051df5c4ea..988c4ec815f 100644 --- a/apps/files_trashbin/lib/Capabilities.php +++ b/apps/files_trashbin/lib/Capabilities.php @@ -45,5 +45,4 @@ class Capabilities implements ICapability { ] ]; } - } diff --git a/apps/files_trashbin/lib/Command/CleanUp.php b/apps/files_trashbin/lib/Command/CleanUp.php index b4e04f56fb4..59acbdcd000 100644 --- a/apps/files_trashbin/lib/Command/CleanUp.php +++ b/apps/files_trashbin/lib/Command/CleanUp.php @@ -130,5 +130,4 @@ class CleanUp extends Command { $query->execute(); } } - } diff --git a/apps/files_trashbin/lib/Command/ExpireTrash.php b/apps/files_trashbin/lib/Command/ExpireTrash.php index 46d2de46e36..fdf7f89b2ce 100644 --- a/apps/files_trashbin/lib/Command/ExpireTrash.php +++ b/apps/files_trashbin/lib/Command/ExpireTrash.php @@ -71,7 +71,6 @@ class ExpireTrash extends Command { } protected function execute(InputInterface $input, OutputInterface $output) { - $maxAge = $this->expiration->getMaxAgeAsTimestamp(); if (!$maxAge) { $output->writeln("No expiry configured."); diff --git a/apps/files_trashbin/lib/Controller/PreviewController.php b/apps/files_trashbin/lib/Controller/PreviewController.php index f06265ec371..4195d584c8e 100644 --- a/apps/files_trashbin/lib/Controller/PreviewController.php +++ b/apps/files_trashbin/lib/Controller/PreviewController.php @@ -93,7 +93,6 @@ class PreviewController extends Controller { int $x = 128, int $y = 128 ) { - if ($fileId === -1 || $x === 0 || $y === 0) { return new DataResponse([], Http::STATUS_BAD_REQUEST); } diff --git a/apps/files_trashbin/lib/Helper.php b/apps/files_trashbin/lib/Helper.php index 2e47abbae7b..31ebdfa265e 100644 --- a/apps/files_trashbin/lib/Helper.php +++ b/apps/files_trashbin/lib/Helper.php @@ -70,7 +70,6 @@ class Helper { $pathparts = pathinfo($entryName); $timestamp = substr($pathparts['extension'], 1); $name = $pathparts['filename']; - } elseif ($timestamp === null) { // for subfolders we need to calculate the timestamp only once $parts = explode('/', ltrim($dir, '/')); diff --git a/apps/files_trashbin/lib/Sabre/AbstractTrashFile.php b/apps/files_trashbin/lib/Sabre/AbstractTrashFile.php index b21579e9e34..ad80711ff1d 100644 --- a/apps/files_trashbin/lib/Sabre/AbstractTrashFile.php +++ b/apps/files_trashbin/lib/Sabre/AbstractTrashFile.php @@ -29,7 +29,7 @@ namespace OCA\Files_Trashbin\Sabre; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\IFile; -abstract class AbstractTrashFile extends AbstractTrash implements IFile , ITrash{ +abstract class AbstractTrashFile extends AbstractTrash implements IFile , ITrash { public function put($data) { throw new Forbidden(); } diff --git a/apps/files_trashbin/lib/Sabre/PropfindPlugin.php b/apps/files_trashbin/lib/Sabre/PropfindPlugin.php index 53619c6e85c..1920ed17863 100644 --- a/apps/files_trashbin/lib/Sabre/PropfindPlugin.php +++ b/apps/files_trashbin/lib/Sabre/PropfindPlugin.php @@ -35,7 +35,6 @@ use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; class PropfindPlugin extends ServerPlugin { - const TRASHBIN_FILENAME = '{http://nextcloud.org/ns}trashbin-filename'; const TRASHBIN_ORIGINAL_LOCATION = '{http://nextcloud.org/ns}trashbin-original-location'; const TRASHBIN_DELETION_TIME = '{http://nextcloud.org/ns}trashbin-deletion-time'; @@ -111,5 +110,4 @@ class PropfindPlugin extends ServerPlugin { return ''; }); } - } diff --git a/apps/files_trashbin/lib/Sabre/RestoreFolder.php b/apps/files_trashbin/lib/Sabre/RestoreFolder.php index 9b9c07f1c52..c31e7dfb492 100644 --- a/apps/files_trashbin/lib/Sabre/RestoreFolder.php +++ b/apps/files_trashbin/lib/Sabre/RestoreFolder.php @@ -75,5 +75,4 @@ class RestoreFolder implements ICollection, IMoveTarget { return $sourceNode->restore(); } - } diff --git a/apps/files_trashbin/lib/Sabre/RootCollection.php b/apps/files_trashbin/lib/Sabre/RootCollection.php index 95300f923ff..55fd0bc7d5b 100644 --- a/apps/files_trashbin/lib/Sabre/RootCollection.php +++ b/apps/files_trashbin/lib/Sabre/RootCollection.php @@ -70,5 +70,4 @@ class RootCollection extends AbstractPrincipalCollection { public function getName(): string { return 'trashbin'; } - } diff --git a/apps/files_trashbin/lib/Trash/BackendNotFoundException.php b/apps/files_trashbin/lib/Trash/BackendNotFoundException.php index 798b55dbd8c..2554faade4d 100644 --- a/apps/files_trashbin/lib/Trash/BackendNotFoundException.php +++ b/apps/files_trashbin/lib/Trash/BackendNotFoundException.php @@ -24,5 +24,4 @@ namespace OCA\Files_Trashbin\Trash; class BackendNotFoundException extends \Exception { - } diff --git a/apps/files_trashbin/lib/Trash/LegacyTrashBackend.php b/apps/files_trashbin/lib/Trash/LegacyTrashBackend.php index d6f8a07746f..68ee8c1c517 100644 --- a/apps/files_trashbin/lib/Trash/LegacyTrashBackend.php +++ b/apps/files_trashbin/lib/Trash/LegacyTrashBackend.php @@ -93,7 +93,6 @@ class LegacyTrashBackend implements ITrashBackend { } else { Trashbin::delete($item->getTrashPath(), $user->getUID(), null); } - } public function moveToTrash(IStorage $storage, string $internalPath): bool { diff --git a/apps/files_trashbin/lib/Trashbin.php b/apps/files_trashbin/lib/Trashbin.php index a308ec78532..adfdf1364be 100644 --- a/apps/files_trashbin/lib/Trashbin.php +++ b/apps/files_trashbin/lib/Trashbin.php @@ -316,7 +316,6 @@ class Trashbin { */ private static function retainVersions($filename, $owner, $ownerPath, $timestamp) { if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) { - $user = User::getUser(); $rootView = new View('/'); @@ -326,7 +325,6 @@ class Trashbin { } self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); } elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { - foreach ($versions as $v) { if ($owner !== $user) { self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); @@ -461,9 +459,7 @@ class Trashbin { * @return false|null */ private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) { - if (\OCP\App::isEnabled('files_versions')) { - $user = User::getUser(); $rootView = new View('/'); @@ -513,7 +509,7 @@ class Trashbin { // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) $filePaths = []; - foreach($fileInfos as $fileInfo){ + foreach ($fileInfos as $fileInfo) { $filePaths[] = $view->getRelativePath($fileInfo->getPath()); } unset($fileInfos); // save memory @@ -522,7 +518,7 @@ class Trashbin { \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]); // Single-File Hooks - foreach($filePaths as $path){ + foreach ($filePaths as $path) { self::emitTrashbinPreDelete($path); } @@ -535,7 +531,7 @@ class Trashbin { \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]); // Single-File Hooks - foreach($filePaths as $path){ + foreach ($filePaths as $path) { self::emitTrashbinPostDelete($path); } @@ -673,7 +669,7 @@ class Trashbin { private static function calculateFreeSpace($trashbinSize, $user) { $softQuota = true; $userObject = \OC::$server->getUserManager()->get($user); - if(is_null($userObject)) { + if (is_null($userObject)) { return 0; } $quota = $userObject->getQuota(); @@ -692,7 +688,7 @@ class Trashbin { // subtract size of files and current trash bin size from quota if ($softQuota) { $userFolder = \OC::$server->getUserFolder($user); - if(is_null($userFolder)) { + if (is_null($userFolder)) { return 0; } $free = $quota - $userFolder->getSize(false); // remaining free space for user @@ -714,7 +710,6 @@ class Trashbin { * @param string $user user id */ public static function resizeTrash($user) { - $size = self::getTrashbinSize($user); $freeSpace = self::calculateFreeSpace($size, $user); @@ -998,7 +993,6 @@ class Trashbin { * @return bool */ public static function isEmpty($user) { - $view = new View('/' . $user . '/files_trashbin'); if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { while ($file = readdir($dh)) { diff --git a/apps/files_trashbin/tests/Command/CleanUpTest.php b/apps/files_trashbin/tests/Command/CleanUpTest.php index 71391f5288d..18ea42e78cc 100644 --- a/apps/files_trashbin/tests/Command/CleanUpTest.php +++ b/apps/files_trashbin/tests/Command/CleanUpTest.php @@ -106,7 +106,7 @@ class CleanUpTest extends TestCase { ->method('nodeExists') ->with('/' . $this->user0 . '/files_trashbin') ->willReturn($nodeExists); - if($nodeExists) { + if ($nodeExists) { $this->rootFolder->expects($this->once()) ->method('get') ->with('/' . $this->user0 . '/files_trashbin') @@ -140,7 +140,6 @@ class CleanUpTest extends TestCase { ->fetchAll(); $this->assertSame(10, count($result)); } - } public function dataTestRemoveDeletedFiles() { return [ @@ -239,5 +238,4 @@ class CleanUpTest extends TestCase { $this->invokePrivate($this->cleanup, 'execute', [$inputInterface, $outputInterface]); } - } diff --git a/apps/files_trashbin/tests/StorageTest.php b/apps/files_trashbin/tests/StorageTest.php index 6047e488a77..3b27e13e88f 100644 --- a/apps/files_trashbin/tests/StorageTest.php +++ b/apps/files_trashbin/tests/StorageTest.php @@ -94,7 +94,9 @@ class StorageTest extends \Test\TestCase { \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin'); $this->logout(); $user = \OC::$server->getUserManager()->get($this->user); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } \OC_Hook::clear(); parent::tearDown(); } @@ -577,7 +579,6 @@ class StorageTest extends \Test\TestCase { $this->assertSame($expected, $this->invokePrivate($storage, 'shouldMoveToTrash', [$path]) ); - } public function dataTestShouldMoveToTrash() { diff --git a/apps/files_trashbin/tests/TrashbinTest.php b/apps/files_trashbin/tests/TrashbinTest.php index 2e9e130244c..fbf1b1c1c13 100644 --- a/apps/files_trashbin/tests/TrashbinTest.php +++ b/apps/files_trashbin/tests/TrashbinTest.php @@ -37,7 +37,6 @@ use OCA\Files_Sharing\AppInfo\Application; * @group DB */ class TrashbinTest extends \Test\TestCase { - const TEST_TRASHBIN_USER1 = "test-trashbin-user1"; const TEST_TRASHBIN_USER2 = "test-trashbin-user2"; @@ -210,7 +209,6 @@ class TrashbinTest extends \Test\TestCase { * correctly */ public function testExpireOldFilesShared() { - $currentTime = time(); $folder = "trashTest-" . $currentTime . '/'; $expiredDate = $currentTime - 3 * 24 * 60 * 60; @@ -673,7 +671,6 @@ class TrashbinTest extends \Test\TestCase { try { \OC::$server->getUserManager()->createUser($user, $user); } catch (\Exception $e) { // catch username is already being used from previous aborted runs - } } diff --git a/apps/files_versions/lib/AppInfo/Application.php b/apps/files_versions/lib/AppInfo/Application.php index 040b72a8f0a..36d7b6d2767 100644 --- a/apps/files_versions/lib/AppInfo/Application.php +++ b/apps/files_versions/lib/AppInfo/Application.php @@ -42,7 +42,6 @@ use OCP\AppFramework\IAppContainer; use OCP\EventDispatcher\IEventDispatcher; class Application extends App { - const APP_ID = 'files_versions'; public function __construct(array $urlParams = []) { @@ -95,11 +94,11 @@ class Application extends App { public function registerVersionBackends() { $server = $this->getContainer()->getServer(); $appManager = $server->getAppManager(); - foreach($appManager->getInstalledApps() as $app) { + foreach ($appManager->getInstalledApps() as $app) { $appInfo = $appManager->getAppInfo($app); if (isset($appInfo['versions'])) { $backends = $appInfo['versions']; - foreach($backends as $backend) { + foreach ($backends as $backend) { if (isset($backend['@value'])) { $this->loadBackend($backend); } else { @@ -131,5 +130,4 @@ class Application extends App { $dispatcher->addServiceListener(LoadAdditionalScriptsEvent::class, LoadAdditionalListener::class); $dispatcher->addServiceListener(LoadSidebar::class, LoadSidebarListener::class); } - } diff --git a/apps/files_versions/lib/BackgroundJob/ExpireVersions.php b/apps/files_versions/lib/BackgroundJob/ExpireVersions.php index eb4287376e9..4c8f82a1c76 100644 --- a/apps/files_versions/lib/BackgroundJob/ExpireVersions.php +++ b/apps/files_versions/lib/BackgroundJob/ExpireVersions.php @@ -31,7 +31,6 @@ use OCP\IUser; use OCP\IUserManager; class ExpireVersions extends \OC\BackgroundJob\TimedJob { - const ITEMS_PER_SESSION = 1000; /** diff --git a/apps/files_versions/lib/Command/CleanUp.php b/apps/files_versions/lib/Command/CleanUp.php index b5b8f3dcfdb..397a1450578 100644 --- a/apps/files_versions/lib/Command/CleanUp.php +++ b/apps/files_versions/lib/Command/CleanUp.php @@ -61,7 +61,6 @@ class CleanUp extends Command { protected function execute(InputInterface $input, OutputInterface $output) { - $users = $input->getArgument('user_id'); if (!empty($users)) { foreach ($users as $user) { @@ -110,5 +109,4 @@ class CleanUp extends Command { $this->rootFolder->get('/' . $user . '/files_versions')->delete(); } } - } diff --git a/apps/files_versions/lib/Command/ExpireVersions.php b/apps/files_versions/lib/Command/ExpireVersions.php index d67542db259..944e0136691 100644 --- a/apps/files_versions/lib/Command/ExpireVersions.php +++ b/apps/files_versions/lib/Command/ExpireVersions.php @@ -70,7 +70,6 @@ class ExpireVersions extends Command { } protected function execute(InputInterface $input, OutputInterface $output) { - $maxAge = $this->expiration->getMaxAgeAsTimestamp(); if (!$maxAge) { $output->writeln("No expiry configured."); diff --git a/apps/files_versions/lib/Events/CreateVersionEvent.php b/apps/files_versions/lib/Events/CreateVersionEvent.php index 4f6ddd4367b..90281bd8ca7 100644 --- a/apps/files_versions/lib/Events/CreateVersionEvent.php +++ b/apps/files_versions/lib/Events/CreateVersionEvent.php @@ -78,5 +78,4 @@ class CreateVersionEvent extends Event { public function shouldCreateVersion() { return $this->createVersion; } - } diff --git a/apps/files_versions/lib/Expiration.php b/apps/files_versions/lib/Expiration.php index a56042e76b8..c9c91d67d7f 100644 --- a/apps/files_versions/lib/Expiration.php +++ b/apps/files_versions/lib/Expiration.php @@ -164,7 +164,7 @@ class Expiration { ); } - if (!$isValid){ + if (!$isValid) { $minValue = 'auto'; $maxValue = 'auto'; } diff --git a/apps/files_versions/lib/Hooks.php b/apps/files_versions/lib/Hooks.php index 179a404ed9a..0603228192c 100644 --- a/apps/files_versions/lib/Hooks.php +++ b/apps/files_versions/lib/Hooks.php @@ -40,7 +40,6 @@ use OC\Files\View; use OCP\Util; class Hooks { - public static function connectHooks() { // Listen to write signals Util::connectHook('OC_Filesystem', 'write', Hooks::class, 'write_hook'); @@ -58,7 +57,7 @@ class Hooks { */ public static function write_hook($params) { $path = $params[Filesystem::signal_param_path]; - if($path !== '') { + if ($path !== '') { Storage::store($path); } } @@ -73,7 +72,7 @@ class Hooks { */ public static function remove_hook($params) { $path = $params[Filesystem::signal_param_path]; - if($path !== '') { + if ($path !== '') { Storage::delete($path); } } @@ -84,9 +83,9 @@ class Hooks { */ public static function pre_remove_hook($params) { $path = $params[Filesystem::signal_param_path]; - if($path !== '') { - Storage::markDeletedFile($path); - } + if ($path !== '') { + Storage::markDeletedFile($path); + } } /** @@ -99,7 +98,7 @@ class Hooks { public static function rename_hook($params) { $oldpath = $params['oldpath']; $newpath = $params['newpath']; - if($oldpath !== '' && $newpath !== '') { + if ($oldpath !== '' && $newpath !== '') { Storage::renameOrCopy($oldpath, $newpath, 'rename'); } } @@ -114,7 +113,7 @@ class Hooks { public static function copy_hook($params) { $oldpath = $params['oldpath']; $newpath = $params['newpath']; - if($oldpath !== '' && $newpath !== '') { + if ($oldpath !== '' && $newpath !== '') { Storage::renameOrCopy($oldpath, $newpath, 'copy'); } } diff --git a/apps/files_versions/lib/Listener/LoadAdditionalListener.php b/apps/files_versions/lib/Listener/LoadAdditionalListener.php index f6d67341074..bebd98eaca9 100644 --- a/apps/files_versions/lib/Listener/LoadAdditionalListener.php +++ b/apps/files_versions/lib/Listener/LoadAdditionalListener.php @@ -43,5 +43,4 @@ class LoadAdditionalListener implements IEventListener { // we properly split it between files list and sidebar Util::addScript(Application::APP_ID, 'files_versions'); } - } diff --git a/apps/files_versions/lib/Listener/LoadSidebarListener.php b/apps/files_versions/lib/Listener/LoadSidebarListener.php index 875fe8b3fc5..3ea696c0418 100644 --- a/apps/files_versions/lib/Listener/LoadSidebarListener.php +++ b/apps/files_versions/lib/Listener/LoadSidebarListener.php @@ -43,5 +43,4 @@ class LoadSidebarListener implements IEventListener { // we properly split it between files list and sidebar Util::addScript(Application::APP_ID, 'files_versions'); } - } diff --git a/apps/files_versions/lib/Sabre/Plugin.php b/apps/files_versions/lib/Sabre/Plugin.php index cde5e319c8f..41c3ff5a5a8 100644 --- a/apps/files_versions/lib/Sabre/Plugin.php +++ b/apps/files_versions/lib/Sabre/Plugin.php @@ -81,5 +81,4 @@ class Plugin extends ServerPlugin { . '; filename="' . rawurlencode($filename) . '"'); } } - } diff --git a/apps/files_versions/lib/Sabre/RestoreFolder.php b/apps/files_versions/lib/Sabre/RestoreFolder.php index 89f379e3c1c..5b52a5777ae 100644 --- a/apps/files_versions/lib/Sabre/RestoreFolder.php +++ b/apps/files_versions/lib/Sabre/RestoreFolder.php @@ -77,5 +77,4 @@ class RestoreFolder implements ICollection, IMoveTarget { $sourceNode->rollBack(); return true; } - } diff --git a/apps/files_versions/lib/Sabre/RootCollection.php b/apps/files_versions/lib/Sabre/RootCollection.php index e305b758c8d..fb68e0f0bfc 100644 --- a/apps/files_versions/lib/Sabre/RootCollection.php +++ b/apps/files_versions/lib/Sabre/RootCollection.php @@ -81,5 +81,4 @@ class RootCollection extends AbstractPrincipalCollection { public function getName() { return 'versions'; } - } diff --git a/apps/files_versions/lib/Storage.php b/apps/files_versions/lib/Storage.php index a149e352e3d..f62650e539d 100644 --- a/apps/files_versions/lib/Storage.php +++ b/apps/files_versions/lib/Storage.php @@ -57,7 +57,6 @@ use OCP\Lock\ILockingProvider; use OCP\User; class Storage { - const DEFAULTENABLED=true; const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota const VERSIONS_ROOT = 'files_versions/'; @@ -139,7 +138,6 @@ class Storage { * @return array with user id and path */ public static function getSourcePathAndUser($source) { - if (isset(self::$sourcePathAndUser[$source])) { $uid = self::$sourcePathAndUser[$source]['uid']; $path = self::$sourcePathAndUser[$source]['path']; @@ -241,13 +239,11 @@ class Storage { * Delete versions of a file */ public static function delete($path) { - $deletedFile = self::$deletedFiles[$path]; $uid = $deletedFile['uid']; $filename = $deletedFile['filename']; if (!Filesystem::file_exists($path)) { - $view = new View('/' . $uid . '/files_versions'); $versions = self::getVersions($uid, $filename); @@ -318,7 +314,6 @@ class Storage { if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) { self::scheduleExpire($targetOwner, $targetPath); } - } /** @@ -389,7 +384,6 @@ class Storage { } return false; - } /** @@ -531,7 +525,6 @@ class Storage { * @return string for example "5 days ago" */ private static function getHumanReadableTimestamp($timestamp) { - $diff = time() - $timestamp; if ($diff < 60) { // first minute @@ -549,7 +542,6 @@ class Storage { } else { return round($diff / 29030400) . " years ago"; } - } /** @@ -750,7 +742,7 @@ class Storage { if ($quota >= 0) { if ($softQuota) { $userFolder = \OC::$server->getUserFolder($uid); - if(is_null($userFolder)) { + if (is_null($userFolder)) { $availableSpace = 0; } else { $free = $quota - $userFolder->getSize(false); // remaining free space for user @@ -790,7 +782,7 @@ class Storage { } $logger = \OC::$server->getLogger(); - foreach($toDelete as $key => $path) { + foreach ($toDelete as $key => $path) { \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]); self::deleteVersion($versionsFileview, $path); \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]); @@ -854,5 +846,4 @@ class Storage { } return self::$application->getContainer()->query(Expiration::class); } - } diff --git a/apps/files_versions/lib/Versions/BackendNotFoundException.php b/apps/files_versions/lib/Versions/BackendNotFoundException.php index 4b4bf96f1ce..5338d5eea37 100644 --- a/apps/files_versions/lib/Versions/BackendNotFoundException.php +++ b/apps/files_versions/lib/Versions/BackendNotFoundException.php @@ -24,5 +24,4 @@ namespace OCA\Files_Versions\Versions; class BackendNotFoundException extends \Exception { - } diff --git a/apps/files_versions/tests/Command/CleanupTest.php b/apps/files_versions/tests/Command/CleanupTest.php index 1fad960f952..89474954161 100644 --- a/apps/files_versions/tests/Command/CleanupTest.php +++ b/apps/files_versions/tests/Command/CleanupTest.php @@ -65,14 +65,13 @@ class CleanupTest extends TestCase { * @param boolean $nodeExists */ public function testDeleteVersions($nodeExists) { - $this->rootFolder->expects($this->once()) ->method('nodeExists') ->with('/testUser/files_versions') ->willReturn($nodeExists); - if($nodeExists) { + if ($nodeExists) { $this->rootFolder->expects($this->once()) ->method('get') ->with('/testUser/files_versions') @@ -167,5 +166,4 @@ class CleanupTest extends TestCase { $this->invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); } - } diff --git a/apps/files_versions/tests/Controller/PreviewControllerTest.php b/apps/files_versions/tests/Controller/PreviewControllerTest.php index 084bb25da82..64732ac8633 100644 --- a/apps/files_versions/tests/Controller/PreviewControllerTest.php +++ b/apps/files_versions/tests/Controller/PreviewControllerTest.php @@ -182,5 +182,4 @@ class PreviewControllerTest extends TestCase { $this->assertEquals($expected, $res); } - } diff --git a/apps/files_versions/tests/VersioningTest.php b/apps/files_versions/tests/VersioningTest.php index ae052335a95..c3ae186e73e 100644 --- a/apps/files_versions/tests/VersioningTest.php +++ b/apps/files_versions/tests/VersioningTest.php @@ -47,7 +47,6 @@ use OCP\IUser; * @group DB */ class VersioningTest extends \Test\TestCase { - const TEST_VERSIONS_USER = 'test-versions-user'; const TEST_VERSIONS_USER2 = 'test-versions-user2'; const USERS_VERSIONS_ROOT = '/test-versions-user/files_versions'; @@ -72,9 +71,13 @@ class VersioningTest extends \Test\TestCase { public static function tearDownAfterClass(): void { // cleanup test user $user = \OC::$server->getUserManager()->get(self::TEST_VERSIONS_USER); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } $user = \OC::$server->getUserManager()->get(self::TEST_VERSIONS_USER2); - if ($user !== null) { $user->delete(); } + if ($user !== null) { + $user->delete(); + } parent::tearDownAfterClass(); } @@ -146,7 +149,7 @@ class VersioningTest extends \Test\TestCase { $this->assertEquals($sizeOfAllDeletedFiles, $size); // the deleted array should only contain versions which should be deleted - foreach($deleted as $key => $path) { + foreach ($deleted as $key => $path) { unset($versions[$key]); $this->assertEquals("delete", substr($path, 0, strlen("delete"))); } @@ -155,7 +158,6 @@ class VersioningTest extends \Test\TestCase { foreach ($versions as $version) { $this->assertEquals("keep", $version['path']); } - } public function versionsProvider() { @@ -277,7 +279,6 @@ class VersioningTest extends \Test\TestCase { } public function testRename() { - \OC\Files\Filesystem::file_put_contents("test.txt", "test file"); $t1 = time(); @@ -307,7 +308,6 @@ class VersioningTest extends \Test\TestCase { } public function testRenameInSharedFolder() { - \OC\Files\Filesystem::mkdir('folder1'); \OC\Files\Filesystem::mkdir('folder1/folder2'); \OC\Files\Filesystem::file_put_contents("folder1/test.txt", "test file"); @@ -358,7 +358,6 @@ class VersioningTest extends \Test\TestCase { } public function testMoveFolder() { - \OC\Files\Filesystem::mkdir('folder1'); \OC\Files\Filesystem::mkdir('folder2'); \OC\Files\Filesystem::file_put_contents('folder1/test.txt', 'test file'); @@ -392,7 +391,6 @@ class VersioningTest extends \Test\TestCase { public function testMoveFileIntoSharedFolderAsRecipient() { - \OC\Files\Filesystem::mkdir('folder1'); $fileInfo = \OC\Files\Filesystem::getFileInfo('folder1'); @@ -443,7 +441,6 @@ class VersioningTest extends \Test\TestCase { } public function testMoveFolderIntoSharedFolderAsRecipient() { - \OC\Files\Filesystem::mkdir('folder1'); $node = \OC::$server->getUserFolder(self::TEST_VERSIONS_USER)->get('folder1'); @@ -495,7 +492,6 @@ class VersioningTest extends \Test\TestCase { } public function testRenameSharedFile() { - \OC\Files\Filesystem::file_put_contents("test.txt", "test file"); $t1 = time(); @@ -545,7 +541,6 @@ class VersioningTest extends \Test\TestCase { } public function testCopy() { - \OC\Files\Filesystem::file_put_contents("test.txt", "test file"); $t1 = time(); @@ -579,7 +574,6 @@ class VersioningTest extends \Test\TestCase { * the correct 'path' and 'name' */ public function testGetVersions() { - $t1 = time(); // second version is two weeks older, this way we make sure that no // version will be expired @@ -944,7 +938,6 @@ class VersioningTest extends \Test\TestCase { * @param bool $create */ public static function loginHelper($user, $create = false) { - if ($create) { $backend = new \Test\Util\User\Dummy(); $backend->createUser($user, $user); @@ -964,7 +957,6 @@ class VersioningTest extends \Test\TestCase { \OC_Util::setupFS($user); \OC::$server->getUserFolder($user); } - } // extend the original class to make it possible to test protected methods @@ -975,6 +967,5 @@ class VersionStorageToTest extends \OCA\Files_Versions\Storage { */ public function callProtectedGetExpireList($time, $versions) { return self::getExpireList($time, $versions); - } } diff --git a/apps/lookup_server_connector/lib/AppInfo/Application.php b/apps/lookup_server_connector/lib/AppInfo/Application.php index aad11c4eff4..f5fa5cb7c2e 100644 --- a/apps/lookup_server_connector/lib/AppInfo/Application.php +++ b/apps/lookup_server_connector/lib/AppInfo/Application.php @@ -57,6 +57,5 @@ class Application extends App { $updateLookupServer = \OC::$server->query(UpdateLookupServer::class); $updateLookupServer->userUpdated($user); }); - } } diff --git a/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php b/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php index b57d1a00acc..272d66e9491 100644 --- a/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php +++ b/apps/lookup_server_connector/lib/BackgroundJobs/RetryJob.php @@ -176,7 +176,6 @@ class RetryJob extends Job { 'lookup_server_connector', 'update_retries' ); - } catch (\Exception $e) { // An error occurred, retry later $this->retainJob = true; diff --git a/apps/lookup_server_connector/lib/UpdateLookupServer.php b/apps/lookup_server_connector/lib/UpdateLookupServer.php index e3c1e48be1e..5b029532904 100644 --- a/apps/lookup_server_connector/lib/UpdateLookupServer.php +++ b/apps/lookup_server_connector/lib/UpdateLookupServer.php @@ -87,5 +87,4 @@ class UpdateLookupServer { $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') === 'yes' && $this->config->getSystemValueString('lookup_server', 'https://lookup.nextcloud.com') !== ''; } - } diff --git a/apps/oauth2/lib/Controller/SettingsController.php b/apps/oauth2/lib/Controller/SettingsController.php index 038509786d5..89685bbee19 100644 --- a/apps/oauth2/lib/Controller/SettingsController.php +++ b/apps/oauth2/lib/Controller/SettingsController.php @@ -81,7 +81,6 @@ class SettingsController extends Controller { public function addClient(string $name, string $redirectUri): JSONResponse { - if (filter_var($redirectUri, FILTER_VALIDATE_URL) === false) { return new JSONResponse(['message' => $this->l->t('Your redirect URL needs to be a full URL for example: https://yourdomain.com/path')], Http::STATUS_BAD_REQUEST); } diff --git a/apps/oauth2/lib/Exceptions/AccessTokenNotFoundException.php b/apps/oauth2/lib/Exceptions/AccessTokenNotFoundException.php index 66c982a29db..6033568f15f 100644 --- a/apps/oauth2/lib/Exceptions/AccessTokenNotFoundException.php +++ b/apps/oauth2/lib/Exceptions/AccessTokenNotFoundException.php @@ -26,4 +26,5 @@ declare(strict_types=1); namespace OCA\OAuth2\Exceptions; -class AccessTokenNotFoundException extends \Exception {} +class AccessTokenNotFoundException extends \Exception { +} diff --git a/apps/oauth2/lib/Exceptions/ClientNotFoundException.php b/apps/oauth2/lib/Exceptions/ClientNotFoundException.php index 91fcaa99893..7f7dad04320 100644 --- a/apps/oauth2/lib/Exceptions/ClientNotFoundException.php +++ b/apps/oauth2/lib/Exceptions/ClientNotFoundException.php @@ -26,4 +26,5 @@ declare(strict_types=1); namespace OCA\OAuth2\Exceptions; -class ClientNotFoundException extends \Exception {} +class ClientNotFoundException extends \Exception { +} diff --git a/apps/oauth2/lib/Migration/SetTokenExpiration.php b/apps/oauth2/lib/Migration/SetTokenExpiration.php index 6332ae85ca1..b9538ee4ab5 100644 --- a/apps/oauth2/lib/Migration/SetTokenExpiration.php +++ b/apps/oauth2/lib/Migration/SetTokenExpiration.php @@ -64,7 +64,7 @@ class SetTokenExpiration implements IRepairStep { $cursor = $qb->execute(); - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $token = AccessToken::fromRow($row); try { $appToken = $this->tokenProvider->getTokenById($token->getTokenId()); @@ -76,5 +76,4 @@ class SetTokenExpiration implements IRepairStep { } $cursor->closeCursor(); } - } diff --git a/apps/provisioning_api/lib/Controller/AUserData.php b/apps/provisioning_api/lib/Controller/AUserData.php index 3579202b36f..31a8322e4a7 100644 --- a/apps/provisioning_api/lib/Controller/AUserData.php +++ b/apps/provisioning_api/lib/Controller/AUserData.php @@ -100,14 +100,14 @@ abstract class AUserData extends OCSController { // Check if the target user exists $targetUserObject = $this->userManager->get($userId); - if($targetUserObject === null) { + if ($targetUserObject === null) { throw new OCSNotFoundException('User does not exist'); } // Should be at least Admin Or SubAdmin! if ($this->groupManager->isAdmin($currentLoggedInUser->getUID()) || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) { - $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true'; + $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true'; } else { // Check they are looking up themselves if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) { @@ -167,7 +167,7 @@ abstract class AUserData extends OCSController { protected function getUserSubAdminGroupsData(string $userId): array { $user = $this->userManager->get($userId); // Check if the user exists - if($user === null) { + if ($user === null) { throw new OCSNotFoundException('User does not exist'); } @@ -215,5 +215,4 @@ abstract class AUserData extends OCSController { } return $data; } - } diff --git a/apps/provisioning_api/lib/Controller/AppsController.php b/apps/provisioning_api/lib/Controller/AppsController.php index d5a8de91772..e59440e5e8c 100644 --- a/apps/provisioning_api/lib/Controller/AppsController.php +++ b/apps/provisioning_api/lib/Controller/AppsController.php @@ -64,11 +64,11 @@ class AppsController extends OCSController { public function getApps(string $filter = null): DataResponse { $apps = (new OC_App())->listAllApps(); $list = []; - foreach($apps as $app) { + foreach ($apps as $app) { $list[] = $app['id']; } - if($filter){ - switch($filter){ + if ($filter) { + switch ($filter) { case 'enabled': return new DataResponse(['apps' => \OC_App::getEnabledApps()]); break; @@ -80,7 +80,6 @@ class AppsController extends OCSController { // Invalid filter variable throw new OCSException('', 101); } - } else { return new DataResponse(['apps' => $list]); } @@ -93,7 +92,7 @@ class AppsController extends OCSController { */ public function getAppInfo(string $app): DataResponse { $info = \OCP\App::getAppInfo($app); - if(!is_null($info)) { + if (!is_null($info)) { return new DataResponse(OC_App::getAppInfo($app)); } @@ -124,5 +123,4 @@ class AppsController extends OCSController { $this->appManager->disableApp($app); return new DataResponse(); } - } diff --git a/apps/provisioning_api/lib/Controller/GroupsController.php b/apps/provisioning_api/lib/Controller/GroupsController.php index 435f0410217..7f2da88a097 100644 --- a/apps/provisioning_api/lib/Controller/GroupsController.php +++ b/apps/provisioning_api/lib/Controller/GroupsController.php @@ -163,7 +163,7 @@ class GroupsController extends AUserData { } // Check subadmin has access to this group - if($this->groupManager->isAdmin($user->getUID()) + if ($this->groupManager->isAdmin($user->getUID()) || $isSubadminOfGroup) { $users = $this->groupManager->get($groupId)->getUsers(); $users = array_map(function ($user) { @@ -201,7 +201,7 @@ class GroupsController extends AUserData { } // Check subadmin has access to this group - if($this->groupManager->isAdmin($currentUser->getUID()) || $isSubadminOfGroup) { + if ($this->groupManager->isAdmin($currentUser->getUID()) || $isSubadminOfGroup) { $users = $group->searchUsers($search, $limit, $offset); // Extract required number @@ -219,7 +219,7 @@ class GroupsController extends AUserData { // only showing its id $usersDetails[$userId] = ['id' => $userId]; } - } catch(OCSNotFoundException $e) { + } catch (OCSNotFoundException $e) { // continue if a users ceased to exist. } } @@ -240,12 +240,12 @@ class GroupsController extends AUserData { */ public function addGroup(string $groupid): DataResponse { // Validate name - if(empty($groupid)) { + if (empty($groupid)) { $this->logger->error('Group name not supplied', ['app' => 'provisioning_api']); throw new OCSException('Invalid group name', 101); } // Check if it exists - if($this->groupManager->groupExists($groupid)){ + if ($this->groupManager->groupExists($groupid)) { throw new OCSException('group exists', 102); } $this->groupManager->createGroup($groupid); @@ -283,9 +283,9 @@ class GroupsController extends AUserData { */ public function deleteGroup(string $groupId): DataResponse { // Check it exists - if(!$this->groupManager->groupExists($groupId)){ + if (!$this->groupManager->groupExists($groupId)) { throw new OCSException('', 101); - } elseif($groupId === 'admin' || !$this->groupManager->get($groupId)->delete()){ + } elseif ($groupId === 'admin' || !$this->groupManager->get($groupId)->delete()) { // Cannot delete admin group throw new OCSException('', 102); } @@ -301,7 +301,7 @@ class GroupsController extends AUserData { public function getSubAdminsOfGroup(string $groupId): DataResponse { // Check group exists $targetGroup = $this->groupManager->get($groupId); - if($targetGroup === null) { + if ($targetGroup === null) { throw new OCSException('Group does not exist', 101); } @@ -315,5 +315,4 @@ class GroupsController extends AUserData { return new DataResponse($uids); } - } diff --git a/apps/provisioning_api/lib/Controller/UsersController.php b/apps/provisioning_api/lib/Controller/UsersController.php index ff67a880c13..bd327ffe441 100644 --- a/apps/provisioning_api/lib/Controller/UsersController.php +++ b/apps/provisioning_api/lib/Controller/UsersController.php @@ -140,7 +140,7 @@ class UsersController extends AUserData { // Admin? Or SubAdmin? $uid = $user->getUID(); $subAdminManager = $this->groupManager->getSubAdmin(); - if ($this->groupManager->isAdmin($uid)){ + if ($this->groupManager->isAdmin($uid)) { $users = $this->userManager->search($search, $limit, $offset); } elseif ($subAdminManager->isSubAdmin($user)) { $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user); @@ -173,7 +173,7 @@ class UsersController extends AUserData { // Admin? Or SubAdmin? $uid = $currentUser->getUID(); $subAdminManager = $this->groupManager->getSubAdmin(); - if ($this->groupManager->isAdmin($uid)){ + if ($this->groupManager->isAdmin($uid)) { $users = $this->userManager->search($search, $limit, $offset); $users = array_keys($users); } elseif ($subAdminManager->isSubAdmin($currentUser)) { @@ -250,7 +250,7 @@ class UsersController extends AUserData { $isAdmin = $this->groupManager->isAdmin($user->getUID()); $subAdminManager = $this->groupManager->getSubAdmin(); - if(empty($userid) && $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes') { + if (empty($userid) && $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes') { $userid = $this->createNewUserId(); } @@ -352,7 +352,6 @@ class UsersController extends AUserData { } return new DataResponse(['id' => $userid]); - } catch (HintException $e) { $this->logger->logException($e, [ 'message' => 'Failed addUser attempt with hint exception.', @@ -414,7 +413,6 @@ class UsersController extends AUserData { $data['display-name'] = $data['displayname']; unset($data['displayname']); return new DataResponse($data); - } throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); @@ -530,7 +528,7 @@ class UsersController extends AUserData { throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); } // Process the edit - switch($key) { + switch ($key) { case 'display': case AccountManager::PROPERTY_DISPLAYNAME: $targetUser->setDisplayName($value); @@ -755,7 +753,6 @@ class UsersController extends AUserData { throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); } } - } /** @@ -835,7 +832,6 @@ class UsersController extends AUserData { // Not an admin, so the user must be a subadmin of this group, but that is not allowed. throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105); } - } elseif (!$this->groupManager->isAdmin($loggedInUser->getUID())) { /** @var IGroup[] $subAdminGroups */ $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); @@ -973,7 +969,7 @@ class UsersController extends AUserData { try { $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false); $this->newUserMailHelper->sendMail($targetUser, $emailTemplate); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->logger->logException($e, [ 'message' => "Can't send new user mail to $email", 'level' => ILogger::ERROR, diff --git a/apps/provisioning_api/lib/FederatedFileSharingFactory.php b/apps/provisioning_api/lib/FederatedFileSharingFactory.php index 63a0f0ff200..6a630542af5 100644 --- a/apps/provisioning_api/lib/FederatedFileSharingFactory.php +++ b/apps/provisioning_api/lib/FederatedFileSharingFactory.php @@ -40,5 +40,4 @@ class FederatedFileSharingFactory { public function get(): Application { return $this->serverContainer->query(Application::class); } - } diff --git a/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php b/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php index a87f69a25b3..50a00a1e93f 100644 --- a/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php +++ b/apps/provisioning_api/tests/Controller/AppConfigControllerTest.php @@ -49,7 +49,6 @@ class AppConfigControllerTest extends TestCase { $this->config = $this->createMock(IConfig::class); $this->appConfig = $this->createMock(IAppConfig::class); - } /** @@ -105,7 +104,6 @@ class AppConfigControllerTest extends TestCase { * @param int $status */ public function testGetKeys($app, $keys, $throws, $status) { - $api = $this->getInstance(['verifyAppId']); if ($throws instanceof \Exception) { $api->expects($this->once()) @@ -153,7 +151,6 @@ class AppConfigControllerTest extends TestCase { * @param int $status */ public function testGetValue($app, $key, $default, $return, $throws, $status) { - $api = $this->getInstance(['verifyAppId']); if ($throws instanceof \Exception) { $api->expects($this->once()) @@ -202,7 +199,6 @@ class AppConfigControllerTest extends TestCase { * @param int $status */ public function testSetValue($app, $key, $value, $appThrows, $keyThrows, $status) { - $api = $this->getInstance(['verifyAppId', 'verifyConfigKey']); if ($appThrows instanceof \Exception) { $api->expects($this->once()) @@ -267,7 +263,6 @@ class AppConfigControllerTest extends TestCase { * @param int $status */ public function testDeleteValue($app, $key, $appThrows, $keyThrows, $status) { - $api = $this->getInstance(['verifyAppId', 'verifyConfigKey']); if ($appThrows instanceof \Exception) { $api->expects($this->once()) diff --git a/apps/provisioning_api/tests/Controller/AppsControllerTest.php b/apps/provisioning_api/tests/Controller/AppsControllerTest.php index bfc7a2f623a..28867f0b80b 100644 --- a/apps/provisioning_api/tests/Controller/AppsControllerTest.php +++ b/apps/provisioning_api/tests/Controller/AppsControllerTest.php @@ -102,7 +102,7 @@ class AppsControllerTest extends \OCA\Provisioning_API\Tests\TestCase { $data = $result->getData(); $apps = (new \OC_App)->listAllApps(); $list = []; - foreach($apps as $app) { + foreach ($apps as $app) { $list[] = $app['id']; } $disabled = array_diff($list, \OC_App::getEnabledApps()); diff --git a/apps/provisioning_api/tests/Controller/GroupsControllerTest.php b/apps/provisioning_api/tests/Controller/GroupsControllerTest.php index 70a920b743e..0ed6d58e217 100644 --- a/apps/provisioning_api/tests/Controller/GroupsControllerTest.php +++ b/apps/provisioning_api/tests/Controller/GroupsControllerTest.php @@ -219,7 +219,6 @@ class GroupsControllerTest extends \Test\TestCase { $result = $this->api->getGroups($search, $limit, $offset); $this->assertEquals(['groups' => ['group1', 'group2']], $result->getData()); - } /** @@ -260,7 +259,6 @@ class GroupsControllerTest extends \Test\TestCase { ] ]], $result->getData()); - } public function testGetGroupAsSubadmin() { diff --git a/apps/provisioning_api/tests/Controller/UsersControllerTest.php b/apps/provisioning_api/tests/Controller/UsersControllerTest.php index aff12547ec0..48b970e9687 100644 --- a/apps/provisioning_api/tests/Controller/UsersControllerTest.php +++ b/apps/provisioning_api/tests/Controller/UsersControllerTest.php @@ -440,7 +440,7 @@ class UsersControllerTest extends TestCase { ->expects($this->any()) ->method('getAppValue') ->willReturnCallback(function ($appid, $key, $default) { - if($key === 'newUser.generateUserID') { + if ($key === 'newUser.generateUserID') { return 'yes'; } return null; @@ -477,7 +477,9 @@ class UsersControllerTest extends TestCase { $this->secureRandom->expects($this->any()) ->method('generate') ->with(10) - ->willReturnCallback(function () { return (string)rand(1000000000, 9999999999); }); + ->willReturnCallback(function () { + return (string)rand(1000000000, 9999999999); + }); $this->assertTrue(key_exists( 'id', @@ -495,7 +497,7 @@ class UsersControllerTest extends TestCase { ->expects($this->any()) ->method('getAppValue') ->willReturnCallback(function ($appid, $key, $default) { - if($key === 'newUser.generateUserID') { + if ($key === 'newUser.generateUserID') { return 'yes'; } return null; @@ -538,7 +540,7 @@ class UsersControllerTest extends TestCase { ->expects($this->any()) ->method('getAppValue') ->willReturnCallback(function ($appid, $key, $default) { - if($key === 'newUser.requireEmail') { + if ($key === 'newUser.requireEmail') { return 'yes'; } return null; @@ -1590,7 +1592,6 @@ class UsersControllerTest extends TestCase { } public function testEditUserSelfEditChangeLanguage() { - $this->l10nFactory->expects($this->once()) ->method('findAvailableLanguages') ->willReturn(['en', 'de', 'sv']); @@ -1683,7 +1684,6 @@ class UsersControllerTest extends TestCase { } public function testEditUserAdminEditChangeLanguage() { - $this->l10nFactory->expects($this->once()) ->method('findAvailableLanguages') ->willReturn(['en', 'de', 'sv']); diff --git a/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php b/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php index 368fa40356f..b3b2184b2ba 100644 --- a/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php +++ b/apps/provisioning_api/tests/Middleware/ProvisioningApiMiddlewareTest.php @@ -118,6 +118,5 @@ class ProvisioningApiMiddlewareTest extends TestCase { $this->assertTrue($forwared); $this->assertSame($exception, $e); } - } } diff --git a/apps/provisioning_api/tests/TestCase.php b/apps/provisioning_api/tests/TestCase.php index f2495cdba62..7ddebfcf322 100644 --- a/apps/provisioning_api/tests/TestCase.php +++ b/apps/provisioning_api/tests/TestCase.php @@ -65,7 +65,7 @@ abstract class TestCase extends \Test\TestCase { } protected function tearDown(): void { - foreach($this->users as $user) { + foreach ($this->users as $user) { $user->delete(); } diff --git a/apps/settings/lib/Activity/GroupProvider.php b/apps/settings/lib/Activity/GroupProvider.php index 65ca2627775..ab34e907ca3 100644 --- a/apps/settings/lib/Activity/GroupProvider.php +++ b/apps/settings/lib/Activity/GroupProvider.php @@ -36,7 +36,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory as L10nFactory; class GroupProvider implements IProvider { - public const ADDED_TO_GROUP = 'group_added'; public const REMOVED_FROM_GROUP = 'group_removed'; diff --git a/apps/settings/lib/Activity/Provider.php b/apps/settings/lib/Activity/Provider.php index ecf653eb0e4..5023b4af199 100644 --- a/apps/settings/lib/Activity/Provider.php +++ b/apps/settings/lib/Activity/Provider.php @@ -38,7 +38,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory; class Provider implements IProvider { - public const PASSWORD_CHANGED_BY = 'password_changed_by'; public const PASSWORD_CHANGED_SELF = 'password_changed_self'; public const PASSWORD_RESET = 'password_changed'; @@ -106,14 +105,12 @@ class Provider implements IProvider { $subject = $this->l->t('You changed your password'); } elseif ($event->getSubject() === self::PASSWORD_RESET) { $subject = $this->l->t('Your password was reset by an administrator'); - } elseif ($event->getSubject() === self::EMAIL_CHANGED_BY) { $subject = $this->l->t('{actor} changed your email address'); } elseif ($event->getSubject() === self::EMAIL_CHANGED_SELF) { $subject = $this->l->t('You changed your email address'); } elseif ($event->getSubject() === self::EMAIL_CHANGED) { $subject = $this->l->t('Your email address was changed by an administrator'); - } elseif ($event->getSubject() === self::APP_TOKEN_CREATED) { $subject = $this->l->t('You created app password "{token}"'); } elseif ($event->getSubject() === self::APP_TOKEN_DELETED) { @@ -124,7 +121,6 @@ class Provider implements IProvider { $subject = $this->l->t('You granted filesystem access to app password "{token}"'); } elseif ($event->getSubject() === self::APP_TOKEN_FILESYSTEM_REVOKED) { $subject = $this->l->t('You revoked filesystem access from app password "{token}"'); - } else { throw new \InvalidArgumentException('Unknown subject'); } diff --git a/apps/settings/lib/Activity/SecurityFilter.php b/apps/settings/lib/Activity/SecurityFilter.php index dd0312232fe..d814571897c 100644 --- a/apps/settings/lib/Activity/SecurityFilter.php +++ b/apps/settings/lib/Activity/SecurityFilter.php @@ -63,5 +63,4 @@ class SecurityFilter implements IFilter { public function getPriority() { return 30; } - } diff --git a/apps/settings/lib/Activity/SecurityProvider.php b/apps/settings/lib/Activity/SecurityProvider.php index 568006d03cc..20156bbc407 100644 --- a/apps/settings/lib/Activity/SecurityProvider.php +++ b/apps/settings/lib/Activity/SecurityProvider.php @@ -109,5 +109,4 @@ class SecurityProvider implements IProvider { } return $event; } - } diff --git a/apps/settings/lib/Activity/SecuritySetting.php b/apps/settings/lib/Activity/SecuritySetting.php index d276285d484..c9ed42b2e2a 100644 --- a/apps/settings/lib/Activity/SecuritySetting.php +++ b/apps/settings/lib/Activity/SecuritySetting.php @@ -62,5 +62,4 @@ class SecuritySetting implements ISetting { public function isDefaultEnabledStream() { return true; } - } diff --git a/apps/settings/lib/AppInfo/Application.php b/apps/settings/lib/AppInfo/Application.php index f53a5ddcf51..809fe6cf844 100644 --- a/apps/settings/lib/AppInfo/Application.php +++ b/apps/settings/lib/AppInfo/Application.php @@ -54,7 +54,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; class Application extends App { - const APP_ID = 'settings'; /** @@ -80,7 +79,7 @@ class Application extends App { $container->registerService('isSubAdmin', function (IContainer $c) { $userObject = \OC::$server->getUserSession()->getUser(); $isSubAdmin = false; - if($userObject !== null) { + if ($userObject !== null) { $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject); } return $isSubAdmin; @@ -158,7 +157,6 @@ class Application extends App { /** @var Hooks $hooks */ $hooks = $this->getContainer()->query(Hooks::class); $hooks->addUserToGroup($group, $user); - } public function removeUserFromGroup(IGroup $group, IUser $user): void { diff --git a/apps/settings/lib/BackgroundJobs/VerifyUserData.php b/apps/settings/lib/BackgroundJobs/VerifyUserData.php index a5c46c603bf..e77d95ff4d9 100644 --- a/apps/settings/lib/BackgroundJobs/VerifyUserData.php +++ b/apps/settings/lib/BackgroundJobs/VerifyUserData.php @@ -100,7 +100,6 @@ class VerifyUserData extends Job { * @param ILogger|null $logger */ public function execute($jobList, ILogger $logger = null) { - if ($this->shouldRun($this->argument)) { parent::execute($jobList, $logger); $jobList->remove($this, $this->argument); @@ -110,14 +109,12 @@ class VerifyUserData extends Job { $this->resetVerificationState(); } } - } protected function run($argument) { - $try = (int)$argument['try'] + 1; - switch($argument['type']) { + switch ($argument['type']) { case AccountManager::PROPERTY_WEBSITE: $result = $this->verifyWebsite($argument); break; @@ -143,7 +140,6 @@ class VerifyUserData extends Job { * @return bool true if we could check the verification code, otherwise false */ protected function verifyWebsite(array $argument) { - $result = false; $url = rtrim($argument['data'], '/') . '/.well-known/' . 'CloudIdVerificationCode.txt'; @@ -188,7 +184,7 @@ class VerifyUserData extends Job { * @return bool true if we could check the verification code, otherwise false */ protected function verifyViaLookupServer(array $argument, $dataType) { - if(empty($this->lookupServerUrl) || + if (empty($this->lookupServerUrl) || $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes') !== 'yes' || $this->config->getSystemValue('has_internet_connection', true) === false) { return false; @@ -249,7 +245,6 @@ class VerifyUserData extends Job { if (is_array($body) && isset($body['federationId']) && $body['federationId'] === $cloudId) { return $body; } - } catch (\Exception $e) { // do nothing, we will just re-try later } @@ -299,5 +294,4 @@ class VerifyUserData extends Job { $this->accountManager->updateUser($user, $accountData); } } - } diff --git a/apps/settings/lib/Controller/AdminSettingsController.php b/apps/settings/lib/Controller/AdminSettingsController.php index e7b1a27a637..c50ffc6f1e7 100644 --- a/apps/settings/lib/Controller/AdminSettingsController.php +++ b/apps/settings/lib/Controller/AdminSettingsController.php @@ -82,7 +82,7 @@ class AdminSettingsController extends Controller { ); $formatted = $this->formatSettings($settings); // Do not show legacy forms for sub admins - if($section === 'additional' && !$isSubAdmin) { + if ($section === 'additional' && !$isSubAdmin) { $formatted['content'] .= $this->getLegacyForms(); } return $formatted; @@ -117,6 +117,4 @@ class AdminSettingsController extends Controller { return $out->fetchPage(); } - - } diff --git a/apps/settings/lib/Controller/AppSettingsController.php b/apps/settings/lib/Controller/AppSettingsController.php index f40a8024b6d..7dbbaca1a45 100644 --- a/apps/settings/lib/Controller/AppSettingsController.php +++ b/apps/settings/lib/Controller/AppSettingsController.php @@ -149,9 +149,9 @@ class AppSettingsController extends Controller { private function getAppsWithUpdates() { $appClass = new \OC_App(); $apps = $appClass->listAllApps(); - foreach($apps as $key => $app) { + foreach ($apps as $key => $app) { $newVersion = $this->installer->isUpdateAvailable($app['id']); - if($newVersion === false) { + if ($newVersion === false) { unset($apps[$key]); } } @@ -169,7 +169,6 @@ class AppSettingsController extends Controller { ]; } return $result; - } /** @@ -186,7 +185,7 @@ class AppSettingsController extends Controller { $formattedCategories = []; $categories = $this->categoryFetcher->get(); - foreach($categories as $category) { + foreach ($categories as $category) { $formattedCategories[] = [ 'id' => $category['id'], 'ident' => $category['id'], @@ -217,10 +216,10 @@ class AppSettingsController extends Controller { // add bundle information $bundles = $this->bundleFetcher->getBundles(); - foreach($bundles as $bundle) { - foreach($bundle->getAppIdentifiers() as $identifier) { - foreach($this->allApps as &$app) { - if($app['id'] === $identifier) { + foreach ($bundles as $bundle) { + foreach ($bundle->getAppIdentifiers() as $identifier) { + foreach ($this->allApps as &$app) { + if ($app['id'] === $identifier) { $app['bundleIds'][] = $bundle->getIdentifier(); continue; } @@ -240,7 +239,6 @@ class AppSettingsController extends Controller { * @throws \Exception */ public function listApps(): JSONResponse { - $this->fetchApps(); $apps = $this->getAllApps(); @@ -255,7 +253,7 @@ class AppSettingsController extends Controller { } $newVersion = $this->installer->isUpdateAvailable($appData['id']); - if($newVersion) { + if ($newVersion) { $appData['update'] = $newVersion; } @@ -307,16 +305,16 @@ class AppSettingsController extends Controller { $versionParser = new VersionParser(); $formattedApps = []; $apps = $this->appFetcher->get(); - foreach($apps as $app) { + foreach ($apps as $app) { // Skip all apps not in the requested category if ($requestedCategory !== '') { $isInCategory = false; - foreach($app['categories'] as $category) { - if($category === $requestedCategory) { + foreach ($app['categories'] as $category) { + if ($category === $requestedCategory) { $isInCategory = true; } } - if(!$isInCategory) { + if (!$isInCategory) { continue; } } @@ -326,28 +324,28 @@ class AppSettingsController extends Controller { } $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']); $nextCloudVersionDependencies = []; - if($nextCloudVersion->getMinimumVersion() !== '') { + if ($nextCloudVersion->getMinimumVersion() !== '') { $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion(); } - if($nextCloudVersion->getMaximumVersion() !== '') { + if ($nextCloudVersion->getMaximumVersion() !== '') { $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion(); } $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']); $existsLocally = \OC_App::getAppPath($app['id']) !== false; $phpDependencies = []; - if($phpVersion->getMinimumVersion() !== '') { + if ($phpVersion->getMinimumVersion() !== '') { $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion(); } - if($phpVersion->getMaximumVersion() !== '') { + if ($phpVersion->getMaximumVersion() !== '') { $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion(); } - if(isset($app['releases'][0]['minIntSize'])) { + if (isset($app['releases'][0]['minIntSize'])) { $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize']; } $authors = ''; - foreach($app['authors'] as $key => $author) { + foreach ($app['authors'] as $key => $author) { $authors .= $author['name']; - if($key !== count($app['authors']) - 1) { + if ($key !== count($app['authors']) - 1) { $authors .= ', '; } } @@ -355,12 +353,12 @@ class AppSettingsController extends Controller { $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2); $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no'); $groups = null; - if($enabledValue !== 'no' && $enabledValue !== 'yes') { + if ($enabledValue !== 'no' && $enabledValue !== 'yes') { $groups = $enabledValue; } $currentVersion = ''; - if($this->appManager->isInstalled($app['id'])) { + if ($this->appManager->isInstalled($app['id'])) { $currentVersion = $this->appManager->getAppVersion($app['id']); } else { $currentLanguage = $app['releases'][0]['version']; @@ -442,7 +440,7 @@ class AppSettingsController extends Controller { $installer = \OC::$server->query(Installer::class); $isDownloaded = $installer->isDownloaded($appId); - if(!$isDownloaded) { + if (!$isDownloaded) { $installer->downloadApp($appId); } @@ -458,7 +456,6 @@ class AppSettingsController extends Controller { } } return new JSONResponse(['data' => ['update_required' => $updateRequired]]); - } catch (\Exception $e) { $this->logger->logException($e); return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR); @@ -515,7 +512,7 @@ class AppSettingsController extends Controller { public function uninstallApp(string $appId): JSONResponse { $appId = OC_App::cleanAppId($appId); $result = $this->installer->removeApp($appId); - if($result !== false) { + if ($result !== false) { $this->appManager->clearAppsCache(); return new JSONResponse(['data' => ['appid' => $appId]]); } @@ -558,5 +555,4 @@ class AppSettingsController extends Controller { $this->appManager->ignoreNextcloudRequirementForApp($appId); return new JSONResponse(); } - } diff --git a/apps/settings/lib/Controller/AuthSettingsController.php b/apps/settings/lib/Controller/AuthSettingsController.php index 405044746a3..0296a1ac5cb 100644 --- a/apps/settings/lib/Controller/AuthSettingsController.php +++ b/apps/settings/lib/Controller/AuthSettingsController.php @@ -126,8 +126,7 @@ class AuthSettingsController extends Controller { } catch (SessionNotAvailableException $ex) { return $this->getServiceNotAvailableResponse(); } - if ($this->userSession->getImpersonatingUserID() !== null) - { + if ($this->userSession->getImpersonatingUserID() !== null) { return $this->getServiceNotAvailableResponse(); } diff --git a/apps/settings/lib/Controller/CertificateController.php b/apps/settings/lib/Controller/CertificateController.php index d23821bdf9c..b7ce1749660 100644 --- a/apps/settings/lib/Controller/CertificateController.php +++ b/apps/settings/lib/Controller/CertificateController.php @@ -126,7 +126,6 @@ class CertificateController extends Controller { * @return DataResponse */ public function removePersonalRootCertificate($certificateIdentifier) { - if ($this->isCertificateImportAllowed() === false) { return new DataResponse(['Individual certificate management disabled'], Http::STATUS_FORBIDDEN); } @@ -168,7 +167,6 @@ class CertificateController extends Controller { * @return DataResponse */ public function removeSystemRootCertificate($certificateIdentifier) { - if ($this->isCertificateImportAllowed() === false) { return new DataResponse(['Individual certificate management disabled'], Http::STATUS_FORBIDDEN); } diff --git a/apps/settings/lib/Controller/ChangePasswordController.php b/apps/settings/lib/Controller/ChangePasswordController.php index 20b8357a6a9..439731b22eb 100644 --- a/apps/settings/lib/Controller/ChangePasswordController.php +++ b/apps/settings/lib/Controller/ChangePasswordController.php @@ -108,8 +108,8 @@ class ChangePasswordController extends Controller { 'status' => 'error' ]); } - // password policy app throws exception - } catch(HintException $e) { + // password policy app throws exception + } catch (HintException $e) { return new JSONResponse([ 'status' => 'error', 'data' => [ @@ -221,8 +221,8 @@ class ChangePasswordController extends Controller { } else { // now we know that everything is fine regarding the recovery password, let's try to change the password try { $result = $targetUser->setPassword($password, $recoveryPassword); - // password policy app throws exception - } catch(HintException $e) { + // password policy app throws exception + } catch (HintException $e) { return new JSONResponse([ 'status' => 'error', 'data' => [ @@ -256,8 +256,8 @@ class ChangePasswordController extends Controller { ], ]); } - // password policy app throws exception - } catch(HintException $e) { + // password policy app throws exception + } catch (HintException $e) { return new JSONResponse([ 'status' => 'error', 'data' => [ diff --git a/apps/settings/lib/Controller/CheckSetupController.php b/apps/settings/lib/Controller/CheckSetupController.php index e386f29a94e..a0d374e5b44 100644 --- a/apps/settings/lib/Controller/CheckSetupController.php +++ b/apps/settings/lib/Controller/CheckSetupController.php @@ -137,7 +137,7 @@ class CheckSetupController extends Controller { 'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org' ]); - foreach($siteArray as $site) { + foreach ($siteArray as $site) { if ($this->isSiteReachable($site)) { return false; } @@ -208,40 +208,40 @@ class CheckSetupController extends Controller { // Don't run check when: // 1. Server has `has_internet_connection` set to false // 2. AppStore AND S2S is disabled - if(!$this->config->getSystemValue('has_internet_connection', true)) { + if (!$this->config->getSystemValue('has_internet_connection', true)) { return ''; } - if(!$this->config->getSystemValue('appstoreenabled', true) + if (!$this->config->getSystemValue('appstoreenabled', true) && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no' && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') { return ''; } $versionString = $this->getCurlVersion(); - if(isset($versionString['ssl_version'])) { + if (isset($versionString['ssl_version'])) { $versionString = $versionString['ssl_version']; } else { return ''; } $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing'); - if(!$this->config->getSystemValue('appstoreenabled', true)) { + if (!$this->config->getSystemValue('appstoreenabled', true)) { $features = (string)$this->l10n->t('Federated Cloud Sharing'); } // Check if at least OpenSSL after 1.01d or 1.0.2b - if(strpos($versionString, 'OpenSSL/') === 0) { + if (strpos($versionString, 'OpenSSL/') === 0) { $majorVersion = substr($versionString, 8, 5); $patchRelease = substr($versionString, 13, 6); - if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) || + if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) || ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) { return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]); } } // Check if NSS and perform heuristic check - if(strpos($versionString, 'NSS/') === 0) { + if (strpos($versionString, 'NSS/') === 0) { try { $firstClient = $this->clientService->newClient(); $firstClient->get('https://nextcloud.com/'); @@ -249,7 +249,7 @@ class CheckSetupController extends Controller { $secondClient = $this->clientService->newClient(); $secondClient->get('https://nextcloud.com/'); } catch (ClientException $e) { - if($e->getResponse()->getStatusCode() === 400) { + if ($e->getResponse()->getStatusCode() === 400) { return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]); } } @@ -344,13 +344,13 @@ class CheckSetupController extends Controller { * @return DataResponse */ public function getFailedIntegrityCheckFiles() { - if(!$this->checker->isCodeCheckEnforced()) { + if (!$this->checker->isCodeCheckEnforced()) { return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.'); } $completeResults = $this->checker->getResults(); - if(!empty($completeResults)) { + if (!empty($completeResults)) { $formattedTextResponse = 'Technical information ===================== The following list covers which files have failed the integrity check. Please read @@ -360,12 +360,12 @@ them. Results ======= '; - foreach($completeResults as $context => $contextResult) { + foreach ($completeResults as $context => $contextResult) { $formattedTextResponse .= "- $context\n"; - foreach($contextResult as $category => $result) { + foreach ($contextResult as $category => $result) { $formattedTextResponse .= "\t- $category\n"; - if($category !== 'EXCEPTION') { + if ($category !== 'EXCEPTION') { foreach ($result as $key => $results) { $formattedTextResponse .= "\t\t- $key\n"; } @@ -374,7 +374,6 @@ Results $formattedTextResponse .= "\t\t- $results\n"; } } - } } @@ -406,23 +405,23 @@ Raw output protected function isOpcacheProperlySetup() { $iniWrapper = new IniGetWrapper(); - if(!$iniWrapper->getBool('opcache.enable')) { + if (!$iniWrapper->getBool('opcache.enable')) { return false; } - if(!$iniWrapper->getBool('opcache.save_comments')) { + if (!$iniWrapper->getBool('opcache.save_comments')) { return false; } - if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) { + if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) { return false; } - if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) { + if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) { return false; } - if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) { + if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) { return false; } diff --git a/apps/settings/lib/Controller/CommonSettingsTrait.php b/apps/settings/lib/Controller/CommonSettingsTrait.php index 7aa202429eb..f5c8bb465fd 100644 --- a/apps/settings/lib/Controller/CommonSettingsTrait.php +++ b/apps/settings/lib/Controller/CommonSettingsTrait.php @@ -38,7 +38,7 @@ use OCP\Settings\IIconSection; use OCP\Settings\IManager as ISettingsManager; use OCP\Settings\ISettings; -trait CommonSettingsTrait { +trait CommonSettingsTrait { /** @var ISettingsManager */ private $settingsManager; @@ -85,11 +85,11 @@ trait CommonSettingsTrait { protected function formatSections($sections, $currentSection, $type, $currentType, bool $subAdminOnly = false) { $templateParameters = []; /** @var \OCP\Settings\ISection[] $prioritizedSections */ - foreach($sections as $prioritizedSections) { + foreach ($sections as $prioritizedSections) { foreach ($prioritizedSections as $section) { - if($type === 'admin') { + if ($type === 'admin') { $settings = $this->settingsManager->getAdminSettings($section->getID(), $subAdminOnly); - } elseif($type === 'personal') { + } elseif ($type === 'personal') { $settings = $this->settingsManager->getPersonalSettings($section->getID()); } if (empty($settings) && !($section->getID() === 'additional' && count(\OC_App::getForms('admin')) > 0)) { diff --git a/apps/settings/lib/Controller/HelpController.php b/apps/settings/lib/Controller/HelpController.php index cf470d6af4b..58fb18ea2c5 100644 --- a/apps/settings/lib/Controller/HelpController.php +++ b/apps/settings/lib/Controller/HelpController.php @@ -71,7 +71,7 @@ class HelpController extends Controller { public function help(string $mode = 'user'): TemplateResponse { $this->navigationManager->setActiveEntry('help'); - if(!isset($mode) || $mode !== 'admin') { + if (!isset($mode) || $mode !== 'admin') { $mode = 'user'; } @@ -93,7 +93,5 @@ class HelpController extends Controller { $policy->addAllowedFrameDomain('\'self\''); $response->setContentSecurityPolicy($policy); return $response; - } - } diff --git a/apps/settings/lib/Controller/LogSettingsController.php b/apps/settings/lib/Controller/LogSettingsController.php index 648b0ff1c3b..31abc144371 100644 --- a/apps/settings/lib/Controller/LogSettingsController.php +++ b/apps/settings/lib/Controller/LogSettingsController.php @@ -51,7 +51,7 @@ class LogSettingsController extends Controller { * @return StreamResponse */ public function download() { - if(!$this->log instanceof Log) { + if (!$this->log instanceof Log) { throw new \UnexpectedValueException('Log file not available'); } $resp = new StreamResponse($this->log->getLogPath()); diff --git a/apps/settings/lib/Controller/MailSettingsController.php b/apps/settings/lib/Controller/MailSettingsController.php index 5dc0ff9d890..94f9d72cafd 100644 --- a/apps/settings/lib/Controller/MailSettingsController.php +++ b/apps/settings/lib/Controller/MailSettingsController.php @@ -93,10 +93,9 @@ class MailSettingsController extends Controller { $mail_smtpauth, $mail_smtpport, $mail_sendmailmode) { - $params = get_defined_vars(); $configs = []; - foreach($params as $key => $value) { + foreach ($params as $key => $value) { $configs[$key] = empty($value) ? null : $value; } @@ -168,5 +167,4 @@ class MailSettingsController extends Controller { return new DataResponse($this->l10n->t('You need to set your user email before being able to send test emails.'), Http::STATUS_BAD_REQUEST); } - } diff --git a/apps/settings/lib/Controller/PersonalSettingsController.php b/apps/settings/lib/Controller/PersonalSettingsController.php index 12d8af3af17..0aff8bee649 100644 --- a/apps/settings/lib/Controller/PersonalSettingsController.php +++ b/apps/settings/lib/Controller/PersonalSettingsController.php @@ -65,7 +65,6 @@ class PersonalSettingsController extends Controller { */ public function index($section) { return $this->getIndexResponse('personal', $section); - } /** @@ -75,7 +74,7 @@ class PersonalSettingsController extends Controller { protected function getSettings($section) { $settings = $this->settingsManager->getPersonalSettings($section); $formatted = $this->formatSettings($settings); - if($section === 'additional') { + if ($section === 'additional') { $formatted['content'] .= $this->getLegacyForms(); } return $formatted; diff --git a/apps/settings/lib/Controller/TwoFactorSettingsController.php b/apps/settings/lib/Controller/TwoFactorSettingsController.php index 77d8e882354..36b554c8181 100644 --- a/apps/settings/lib/Controller/TwoFactorSettingsController.php +++ b/apps/settings/lib/Controller/TwoFactorSettingsController.php @@ -56,5 +56,4 @@ class TwoFactorSettingsController extends Controller { return new JSONResponse($this->mandatoryTwoFactor->getState()); } - } diff --git a/apps/settings/lib/Controller/UsersController.php b/apps/settings/lib/Controller/UsersController.php index 5a4ebd122f8..abc4715df6c 100644 --- a/apps/settings/lib/Controller/UsersController.php +++ b/apps/settings/lib/Controller/UsersController.php @@ -172,7 +172,7 @@ class UsersController extends Controller { $groupsInfo->setSorting($sortGroupsBy); list($adminGroup, $groups) = $groupsInfo->get(); - if(!$isLDAPUsed && $this->appManager->isEnabledForUser('user_ldap')) { + if (!$isLDAPUsed && $this->appManager->isEnabledForUser('user_ldap')) { $isLDAPUsed = (bool)array_reduce($this->userManager->getBackends(), function ($ldapFound, $backend) { return $ldapFound || $backend instanceof User_Proxy; }); @@ -181,7 +181,7 @@ class UsersController extends Controller { $disabledUsers = -1; $userCount = 0; - if(!$isLDAPUsed) { + if (!$isLDAPUsed) { if ($this->isAdmin) { $disabledUsers = $this->userManager->countDisabledUsers(); $userCount = array_reduce($this->userManager->countUsers(), function ($v, $w) { @@ -193,7 +193,7 @@ class UsersController extends Controller { $userGroups = $this->groupManager->getUserGroups($user); $groupsNames = []; - foreach($groups as $key => $group) { + foreach ($groups as $key => $group) { // $userCount += (int)$group['usercount']; array_push($groupsNames, $group['name']); // we prevent subadmins from looking up themselves @@ -447,7 +447,6 @@ class UsersController extends Controller { * @return DataResponse */ public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse { - $user = $this->userSession->getUser(); if ($user === null) { diff --git a/apps/settings/lib/Controller/WebAuthnController.php b/apps/settings/lib/Controller/WebAuthnController.php index cbc396b675f..c1ce7a6cf98 100644 --- a/apps/settings/lib/Controller/WebAuthnController.php +++ b/apps/settings/lib/Controller/WebAuthnController.php @@ -37,7 +37,6 @@ use OCP\IUserSession; use Webauthn\PublicKeyCredentialCreationOptions; class WebAuthnController extends Controller { - private const WEBAUTHN_REGISTRATION = 'webauthn_registration'; /** @var Manager */ diff --git a/apps/settings/lib/Hooks.php b/apps/settings/lib/Hooks.php index baa8941bd32..851f2f143dc 100644 --- a/apps/settings/lib/Hooks.php +++ b/apps/settings/lib/Hooks.php @@ -157,7 +157,6 @@ class Hooks { * @throws \BadMethodCallException */ public function onChangeEmail(IUser $user, $oldMailAddress) { - if ($oldMailAddress === $user->getEMailAddress() || $user->getLastLogin() === 0) { // Email didn't really change or user didn't login, diff --git a/apps/settings/lib/Mailer/NewUserMailHelper.php b/apps/settings/lib/Mailer/NewUserMailHelper.php index ca6a5947527..75b1593c6b1 100644 --- a/apps/settings/lib/Mailer/NewUserMailHelper.php +++ b/apps/settings/lib/Mailer/NewUserMailHelper.php @@ -139,7 +139,7 @@ class NewUserMailHelper { $emailTemplate->addHeading($l10n->t('Welcome aboard %s', [$displayName])); } $emailTemplate->addBodyText($l10n->t('Welcome to your %s account, you can add, protect, and share your data.', [$this->themingDefaults->getName()])); - if($user->getBackendClassName() !== 'LDAP') { + if ($user->getBackendClassName() !== 'LDAP') { $emailTemplate->addBodyText($l10n->t('Your username is: %s', [$userId])); } if ($generatePasswordResetToken) { diff --git a/apps/settings/lib/Middleware/SubadminMiddleware.php b/apps/settings/lib/Middleware/SubadminMiddleware.php index ffc507e50e0..7fa30c8e26c 100644 --- a/apps/settings/lib/Middleware/SubadminMiddleware.php +++ b/apps/settings/lib/Middleware/SubadminMiddleware.php @@ -65,8 +65,8 @@ class SubadminMiddleware extends Middleware { * @throws \Exception */ public function beforeController($controller, $methodName) { - if(!$this->reflector->hasAnnotation('NoSubadminRequired')) { - if(!$this->isSubAdmin) { + if (!$this->reflector->hasAnnotation('NoSubadminRequired')) { + if (!$this->isSubAdmin) { throw new NotAdminException($this->l10n->t('Logged in user must be a subadmin')); } } @@ -81,7 +81,7 @@ class SubadminMiddleware extends Middleware { * @throws \Exception */ public function afterException($controller, $methodName, \Exception $exception) { - if($exception instanceof NotAdminException) { + if ($exception instanceof NotAdminException) { $response = new TemplateResponse('core', '403', [], 'guest'); $response->setStatus(Http::STATUS_FORBIDDEN); return $response; @@ -89,5 +89,4 @@ class SubadminMiddleware extends Middleware { throw $exception; } - } diff --git a/apps/settings/lib/Settings/Personal/PersonalInfo.php b/apps/settings/lib/Settings/Personal/PersonalInfo.php index e6bc4388359..152259b743f 100644 --- a/apps/settings/lib/Settings/Personal/PersonalInfo.php +++ b/apps/settings/lib/Settings/Personal/PersonalInfo.php @@ -95,7 +95,7 @@ class PersonalInfo implements ISettings { public function getForm() { $federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing'); $lookupServerUploadEnabled = false; - if($federatedFileSharingEnabled) { + if ($federatedFileSharingEnabled) { $federatedFileSharing = \OC::$server->query(Application::class); $shareProvider = $federatedFileSharing->getFederatedShareProvider(); $lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled(); @@ -194,7 +194,7 @@ class PersonalInfo implements ISettings { */ private function getLanguages(IUser $user) { $forceLanguage = $this->config->getSystemValue('force_language', false); - if($forceLanguage !== false) { + if ($forceLanguage !== false) { return []; } @@ -227,7 +227,7 @@ class PersonalInfo implements ISettings { private function getLocales(IUser $user) { $forceLanguage = $this->config->getSystemValue('force_locale', false); - if($forceLanguage !== false) { + if ($forceLanguage !== false) { return []; } @@ -243,8 +243,7 @@ class PersonalInfo implements ISettings { return $userLocaleString === $value['code']; }); - if (!empty($userLocale)) - { + if (!empty($userLocale)) { $userLocale = reset($userLocale); } @@ -289,5 +288,4 @@ class PersonalInfo implements ISettings { } return $messageParameters; } - } diff --git a/apps/settings/lib/Settings/Personal/Security/Authtokens.php b/apps/settings/lib/Settings/Personal/Security/Authtokens.php index 3e33723a62b..22aca1660d9 100644 --- a/apps/settings/lib/Settings/Personal/Security/Authtokens.php +++ b/apps/settings/lib/Settings/Personal/Security/Authtokens.php @@ -117,5 +117,4 @@ class Authtokens implements ISettings { return $data; }, $tokens); } - } diff --git a/apps/settings/lib/Settings/Personal/Security/TwoFactor.php b/apps/settings/lib/Settings/Personal/Security/TwoFactor.php index 4db8f6f8ab2..ca20274b33d 100644 --- a/apps/settings/lib/Settings/Personal/Security/TwoFactor.php +++ b/apps/settings/lib/Settings/Personal/Security/TwoFactor.php @@ -66,7 +66,6 @@ class TwoFactor implements ISettings { 'twoFactorProviderData' => $this->getTwoFactorProviderData(), 'themedark' => $this->config->getUserValue($this->uid, 'accessibility', 'theme', false) ]); - } public function getSection(): string { diff --git a/apps/settings/templates/help.php b/apps/settings/templates/help.php index 0eccf78cc90..045f45d5d8a 100644 --- a/apps/settings/templates/help.php +++ b/apps/settings/templates/help.php @@ -4,14 +4,18 @@

  • - t('User documentation')); ?>
  • - +
  • - t('Administrator documentation')); ?> diff --git a/apps/settings/templates/settings-vue.php b/apps/settings/templates/settings-vue.php index f04d577fdae..8db9dc6286b 100644 --- a/apps/settings/templates/settings-vue.php +++ b/apps/settings/templates/settings-vue.php @@ -25,7 +25,8 @@ script('settings', 'vue-settings-apps-users-management'); style('settings', 'settings'); // Do we have some data to inject ? -if(is_array($_['serverData'])) { -?> - - +if (is_array($_['serverData'])) { + ?> + + diff --git a/apps/settings/templates/settings/additional.php b/apps/settings/templates/settings/additional.php index 3af78adde71..ac6b91e8d76 100644 --- a/apps/settings/templates/settings/additional.php +++ b/apps/settings/templates/settings/additional.php @@ -26,7 +26,7 @@ ?> -
    $name): @@ -121,11 +127,15 @@ $mail_sendmailmode = [ /> + />

    -

    > +

    > @@ -135,7 +145,9 @@ $mail_sendmailmode = [

    -

    > +

    > diff --git a/apps/settings/templates/settings/admin/overview.php b/apps/settings/templates/settings/admin/overview.php index 9eb6fc1c1f5..a9f5ad0d77f 100644 --- a/apps/settings/templates/settings/admin/overview.php +++ b/apps/settings/templates/settings/admin/overview.php @@ -45,7 +45,11 @@ t('Checking for system and security issues.'));?>

-
+
        diff --git a/apps/settings/templates/settings/admin/security.php b/apps/settings/templates/settings/admin/security.php index 0e32399f325..f0689b948af 100644 --- a/apps/settings/templates/settings/admin/security.php +++ b/apps/settings/templates/settings/admin/security.php @@ -43,7 +43,9 @@ script('settings', 'vue-settings-admin-security');

        /> + value="1" />

        @@ -62,8 +64,12 @@ script('settings', 'vue-settings-admin-security'); value="t("Enable encryption")); ?>" />

        -
        -
        +
        +
        t('No encryption module loaded, please enable an encryption module in the app menu.')); @@ -75,8 +81,8 @@ script('settings', 'vue-settings-admin-security'); name="default_encryption_module" value="" > + p('checked'); + } ?>>
        @@ -84,7 +90,9 @@ script('settings', 'vue-settings-admin-security');
        -
        +
        t('You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please enable the "Default encryption module" and run \'occ encryption:migrate\'')); @@ -92,7 +100,8 @@ script('settings', 'vue-settings-admin-security'); p($l->t('You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one.')); ?> - +
        diff --git a/apps/settings/templates/settings/admin/server.php b/apps/settings/templates/settings/admin/server.php index bde4423f67f..c848ef5c494 100644 --- a/apps/settings/templates/settings/admin/server.php +++ b/apps/settings/templates/settings/admin/server.php @@ -30,19 +30,19 @@

        t('Background jobs'));?>

        getDateTimeFormatter(); - $absolute_time = $formatter->formatDateTime($_['lastcron'], 'long', 'long'); - $maxAgeAbsoluteTime = $formatter->formatDateTime($_['cronMaxAge'], 'long', 'long'); - if (time() - $_['lastcron'] > 600) { ?> + $formatter = \OC::$server->getDateTimeFormatter(); + $absolute_time = $formatter->formatDateTime($_['lastcron'], 'long', 'long'); + $maxAgeAbsoluteTime = $formatter->formatDateTime($_['cronMaxAge'], 'long', 'long'); + if (time() - $_['lastcron'] > 600) { ?> t("Last job execution ran %s. Something seems wrong.", [$relative_time]));?> 12*3600) { - if ($_['backgroundjobs_mode'] === 'cron') { ?> + if ($_['backgroundjobs_mode'] === 'cron') { ?> t("Some jobs haven’t been executed since %s. Please consider increasing the execution frequency.", [$maxAgeRelativeTime]));?> @@ -53,13 +53,13 @@ t("Some jobs didn’t execute since %s. Please consider switching to system cron.", [$maxAgeRelativeTime]));?> + } else { ?> t("Last job ran %s.", [$relative_time]));?> +} else { ?> t("Background job didn’t run yet!")); } ?> @@ -75,33 +75,33 @@

        > + print_unescaped('checked="checked"'); + } ?>>
        t("Execute one task with each page loaded")); ?>

        > + print_unescaped('checked="checked"'); + } ?>>
        t("cron.php is registered at a webcron service to call cron.php every 5 minutes over HTTP.")); ?>

        >
        t("Use system cron service to call the cron.php file every 5 minutes.")); ?> - t('The cron.php needs to be executed by the system user "%s".', [$_['cli_based_cron_user']])); - } else { - print_unescaped(str_replace( + t('The cron.php needs to be executed by the system user "%s".', [$_['cli_based_cron_user']])); + } else { + print_unescaped(str_replace( ['{linkstart}', '{linkend}'], ['', ' ↗'], $l->t('To run this you need the PHP POSIX extension. See {linkstart}PHP documentation{linkend} for more details.') diff --git a/apps/settings/templates/settings/admin/sharing.php b/apps/settings/templates/settings/admin/sharing.php index 0cfbb3e8492..bd75b04eedb 100644 --- a/apps/settings/templates/settings/admin/sharing.php +++ b/apps/settings/templates/settings/admin/sharing.php @@ -34,110 +34,172 @@

        t('As admin you can fine-tune the sharing behavior. Please see the documentation for more information.'));?>

        /> + value="1" />

        -

        +

        /> + value="1" />

        -

        +

        t('Expire after ')); ?> ' /> t('days')); ?> /> + value="1" />

        -

        +

        /> + value="1" />

        -

        +

        /> + value="1" />
        /> + value="1" />
        /> + value="1" />
        /> + value="1" />

        -

        +

        t('Expire after ')); ?> ' /> t('days')); ?> /> + value="1" />

        -

        +

        /> + value="1" />

        -

        +

        /> + value="1" />

        -

        +

        /> + value="1" />

        -

        +

        /> + value="1" />

        -

        +


        t('These groups will still be able to receive shares, but not to initiate them.')); ?>

        -

        +

        /> + />

        -

        +

        /> + />

        /> + />
        - +

        t('Default share permissions'));?>

        -

        +

        /> + class="noautosave checkbox" value="" />

        diff --git a/apps/settings/templates/settings/frame.php b/apps/settings/templates/settings/frame.php index d6658e9c631..5f7186559ab 100644 --- a/apps/settings/templates/settings/frame.php +++ b/apps/settings/templates/settings/frame.php @@ -30,17 +30,16 @@ script('files', 'jquery.fileupload');
          - +
        • t('Personal')); ?>
        • getURLGenerator()->linkToRoute('settings.PersonalSettings.index', ['section' => $form['anchor']]); $class = 'nav-icon-' . $form['anchor']; $sectionName = $form['section-name']; - $active = $form['active'] ? ' class="active"' : ''; - ?> + $active = $form['active'] ? ' class="active"' : ''; ?>
        • > @@ -57,19 +56,17 @@ script('files', 'jquery.fileupload'); ?>
        • t('Administration')); ?>
        • getURLGenerator()->linkToRoute('settings.AdminSettings.index', ['section' => $form['anchor']]); $class = 'nav-icon-' . $form['anchor']; $sectionName = $form['section-name']; - $active = $form['active'] ? ' class="active"' : ''; - ?> + $active = $form['active'] ? ' class="active"' : ''; ?>
        • > diff --git a/apps/settings/templates/settings/personal/personal.info.php b/apps/settings/templates/settings/personal/personal.info.php index ad5f8ac547f..ac95b9eddbf 100644 --- a/apps/settings/templates/settings/personal/personal.info.php +++ b/apps/settings/templates/settings/personal/personal.info.php @@ -67,7 +67,7 @@ script('settings', [
        - + @@ -92,7 +92,7 @@ script('settings', [

        - 80): ?> class="warn" > + 80): ?> class="warn" >
        @@ -109,15 +109,21 @@ script('settings', [ + value="" autocomplete="on" autocapitalize="none" autocorrect="off" /> - - t('No display name set')); } ?> + + t('No display name set')); + } ?> - + @@ -132,10 +138,12 @@ script('settings', [ -
        +
        + placeholder="t('Your email address')); ?>" autocomplete="on" autocapitalize="none" autocorrect="off" /> - - t('No email address set')); }?> + + t('No email address set')); + }?> - + t('For password reset and notifications')); ?> - + @@ -175,12 +189,14 @@ script('settings', [
        - + value="" placeholder="t('Your phone number')); ?>" autocomplete="on" autocapitalize="none" autocorrect="off" /> - + @@ -197,12 +213,14 @@ script('settings', [ - + placeholder="t('Your postal address')); ?>" value="" autocomplete="on" autocapitalize="none" autocorrect="off" /> - + @@ -219,11 +237,13 @@ script('settings', [ - -
        + +
        + >
        @@ -248,10 +270,12 @@ script('settings', [ + /> - + @@ -268,11 +292,13 @@ script('settings', [
        - -
        + +
        + >
        @@ -297,10 +325,12 @@ script('settings', [ + /> - + @@ -319,13 +349,13 @@ script('settings', [ - + - + @@ -349,7 +379,7 @@ script('settings', [ t($_['activelocale']['name']));?> - + @@ -358,7 +388,7 @@ script('settings', [ - + diff --git a/apps/settings/templates/settings/personal/security/password.php b/apps/settings/templates/settings/personal/security/password.php index 23959f7d9c2..7edd9e20126 100644 --- a/apps/settings/templates/settings/personal/security/password.php +++ b/apps/settings/templates/settings/personal/security/password.php @@ -27,12 +27,12 @@ script('settings', [ 'vue-settings-personal-security', ]); -if($_['passwordChangeSupported']) { +if ($_['passwordChangeSupported']) { script('settings', 'security_password'); } ?> - +

        t('Password'));?>

        Saved diff --git a/apps/settings/templates/settings/personal/security/twofactor.php b/apps/settings/templates/settings/personal/security/twofactor.php index f5e5b7025c2..127833b4bbc 100644 --- a/apps/settings/templates/settings/personal/security/twofactor.php +++ b/apps/settings/templates/settings/personal/security/twofactor.php @@ -41,19 +41,16 @@ declare(strict_types=1); if ($provider instanceof \OCP\Authentication\TwoFactorAuth\IProvidesIcons) { if ($_['themedark']) { $icon = $provider->getLightIcon(); - } - else { + } else { $icon = $provider->getDarkIcon(); } //fallback icon if the 2factor provider doesn't provide an icon. } else { if ($_['themedark']) { $icon = image_path('core', 'actions/password-white.svg'); - } - else { + } else { $icon = image_path('core', 'actions/password.svg'); } - } /** @var \OCP\Authentication\TwoFactorAuth\IPersonalProviderSettings $settings */ $settings = $data['settings']; diff --git a/apps/settings/tests/Activity/SecurityFilterTest.php b/apps/settings/tests/Activity/SecurityFilterTest.php index 750e242c889..4f9d9a87ef1 100644 --- a/apps/settings/tests/Activity/SecurityFilterTest.php +++ b/apps/settings/tests/Activity/SecurityFilterTest.php @@ -85,5 +85,4 @@ class SecurityFilterTest extends TestCase { public function testGetPriority() { $this->assertEquals(30, $this->filter->getPriority()); } - } diff --git a/apps/settings/tests/Activity/SecurityProviderTest.php b/apps/settings/tests/Activity/SecurityProviderTest.php index 7deac1f7ddb..174f6049b34 100644 --- a/apps/settings/tests/Activity/SecurityProviderTest.php +++ b/apps/settings/tests/Activity/SecurityProviderTest.php @@ -135,5 +135,4 @@ class SecurityProviderTest extends TestCase { $this->expectException(InvalidArgumentException::class); $this->provider->parse($lang, $event); } - } diff --git a/apps/settings/tests/Activity/SecuritySettingTest.php b/apps/settings/tests/Activity/SecuritySettingTest.php index da53f8b38e9..e66d3e0dc10 100644 --- a/apps/settings/tests/Activity/SecuritySettingTest.php +++ b/apps/settings/tests/Activity/SecuritySettingTest.php @@ -29,7 +29,6 @@ use OCP\IL10N; use Test\TestCase; class SecuritySettingTest extends TestCase { - private $l10n; /** @var SecuritySetting */ @@ -71,5 +70,4 @@ class SecuritySettingTest extends TestCase { $this->assertTrue($this->setting->isDefaultEnabledMail()); $this->assertTrue($this->setting->isDefaultEnabledStream()); } - } diff --git a/apps/settings/tests/Controller/AuthSettingsControllerTest.php b/apps/settings/tests/Controller/AuthSettingsControllerTest.php index 1d24a90794f..b642b1c06c5 100644 --- a/apps/settings/tests/Controller/AuthSettingsControllerTest.php +++ b/apps/settings/tests/Controller/AuthSettingsControllerTest.php @@ -479,5 +479,4 @@ class AuthSettingsControllerTest extends TestCase { $expected = new JSONResponse([]); $this->assertEquals($expected, $response); } - } diff --git a/apps/settings/tests/Controller/CertificateControllerTest.php b/apps/settings/tests/Controller/CertificateControllerTest.php index a04906a6811..0259868321d 100644 --- a/apps/settings/tests/Controller/CertificateControllerTest.php +++ b/apps/settings/tests/Controller/CertificateControllerTest.php @@ -193,5 +193,4 @@ class CertificateControllerTest extends \Test\TestCase { $this->assertEquals(new DataResponse(), $this->certificateController->removePersonalRootCertificate('CertificateToRemove')); } - } diff --git a/apps/settings/tests/Controller/CheckSetupControllerTest.php b/apps/settings/tests/Controller/CheckSetupControllerTest.php index 86acf8acced..ebbe9fd95b7 100644 --- a/apps/settings/tests/Controller/CheckSetupControllerTest.php +++ b/apps/settings/tests/Controller/CheckSetupControllerTest.php @@ -719,7 +719,7 @@ class CheckSetupControllerTest extends TestCase { ->expects($this->once()) ->method('getCurlVersion') ->willReturn(['ssl_version' => 'OpenSSL/1.0.1d']); - $this->assertSame('', $this->invokePrivate($this->checkSetupController, 'isUsedTlsLibOutdated')); + $this->assertSame('', $this->invokePrivate($this->checkSetupController, 'isUsedTlsLibOutdated')); } public function testIsUsedTlsLibOutdatedWithMatchingOpenSslVersion1() { diff --git a/apps/settings/tests/Controller/MailSettingsControllerTest.php b/apps/settings/tests/Controller/MailSettingsControllerTest.php index 7d17ac80407..7611d6bcf68 100644 --- a/apps/settings/tests/Controller/MailSettingsControllerTest.php +++ b/apps/settings/tests/Controller/MailSettingsControllerTest.php @@ -133,7 +133,6 @@ class MailSettingsControllerTest extends \Test\TestCase { null ); $this->assertSame(Http::STATUS_OK, $response->getStatus()); - } public function testStoreCredentials() { @@ -189,5 +188,4 @@ class MailSettingsControllerTest extends \Test\TestCase { $response = $this->mailController->sendTestMail(); $this->assertSame(Http::STATUS_OK, $response->getStatus()); } - } diff --git a/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php b/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php index d7da886c991..1d7c7db8924 100644 --- a/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php +++ b/apps/settings/tests/Controller/TwoFactorSettingsControllerTest.php @@ -82,5 +82,4 @@ class TwoFactorSettingsControllerTest extends TestCase { $this->assertEquals($expected, $resp); } - } diff --git a/apps/settings/tests/Controller/UsersControllerTest.php b/apps/settings/tests/Controller/UsersControllerTest.php index 65258252016..9029b1af396 100644 --- a/apps/settings/tests/Controller/UsersControllerTest.php +++ b/apps/settings/tests/Controller/UsersControllerTest.php @@ -113,8 +113,9 @@ class UsersControllerTest extends \Test\TestCase { $this->encryptionModule = $this->createMock(IEncryptionModule::class); $this->encryptionManager->expects($this->any())->method('getEncryptionModules') - ->willReturn(['encryptionModule' => ['callback' => function () { return $this->encryptionModule;}]]); - + ->willReturn(['encryptionModule' => ['callback' => function () { + return $this->encryptionModule; + }]]); } /** @@ -444,12 +445,11 @@ class UsersControllerTest extends \Test\TestCase { * @dataProvider dataTestGetVerificationCode */ public function testGetVerificationCode($account, $type, $dataBefore, $expectedData, $onlyVerificationCode) { - $message = 'Use my Federated Cloud ID to share with me: user@nextcloud.com'; $signature = 'theSignature'; $code = $message . ' ' . $signature; - if($type === AccountManager::PROPERTY_TWITTER) { + if ($type === AccountManager::PROPERTY_TWITTER) { $code = $message . ' ' . md5($signature); } @@ -485,7 +485,6 @@ class UsersControllerTest extends \Test\TestCase { } public function dataTestGetVerificationCode() { - $accountDataBefore = [ AccountManager::PROPERTY_WEBSITE => ['value' => 'https://nextcloud.com', 'verified' => AccountManager::NOT_VERIFIED], AccountManager::PROPERTY_TWITTER => ['value' => '@nextclouders', 'verified' => AccountManager::NOT_VERIFIED, 'signature' => 'theSignature'], @@ -513,7 +512,6 @@ class UsersControllerTest extends \Test\TestCase { * test get verification code in case no valid user was given */ public function testGetVerificationCodeInvalidUser() { - $controller = $this->getController(); $this->userSession->expects($this->once())->method('getUser')->willReturn(null); $result = $controller->getVerificationCode('account', false); @@ -541,8 +539,11 @@ class UsersControllerTest extends \Test\TestCase { $this->encryptionManager->expects($this->any()) ->method('getEncryptionModule') ->willReturnCallback(function () use ($encryptionModuleLoaded) { - if ($encryptionModuleLoaded) return $this->encryptionModule; - else throw new ModuleDoesNotExistsException(); + if ($encryptionModuleLoaded) { + return $this->encryptionModule; + } else { + throw new ModuleDoesNotExistsException(); + } }); $this->encryptionModule->expects($this->any()) ->method('needDetailedAccessList') @@ -565,5 +566,4 @@ class UsersControllerTest extends \Test\TestCase { [false, false, false, true], ]; } - } diff --git a/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php b/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php index ad0b7108423..e03e05c149a 100644 --- a/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php +++ b/apps/settings/tests/Settings/Personal/Security/AuthtokensTest.php @@ -130,5 +130,4 @@ class AuthtokensTest extends TestCase { $expected = new TemplateResponse('settings', 'settings/personal/security/authtokens'); $this->assertEquals($expected, $form); } - } diff --git a/apps/settings/tests/Settings/Personal/Security/PasswordTest.php b/apps/settings/tests/Settings/Personal/Security/PasswordTest.php index 7785338d86d..db766747fe7 100644 --- a/apps/settings/tests/Settings/Personal/Security/PasswordTest.php +++ b/apps/settings/tests/Settings/Personal/Security/PasswordTest.php @@ -74,5 +74,4 @@ class PasswordTest extends TestCase { ]); $this->assertEquals($expected, $form); } - } diff --git a/apps/sharebymail/lib/Activity.php b/apps/sharebymail/lib/Activity.php index 279055538d9..757b2692e86 100644 --- a/apps/sharebymail/lib/Activity.php +++ b/apps/sharebymail/lib/Activity.php @@ -272,7 +272,6 @@ class Activity implements IProvider { } else { $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg'))); } - } else { throw new \InvalidArgumentException(); } diff --git a/apps/sharebymail/lib/AppInfo/Application.php b/apps/sharebymail/lib/AppInfo/Application.php index d294f9716ea..7acb43cfbed 100644 --- a/apps/sharebymail/lib/AppInfo/Application.php +++ b/apps/sharebymail/lib/AppInfo/Application.php @@ -32,7 +32,6 @@ use OCP\AppFramework\App; use OCP\Util; class Application extends App { - public function __construct(array $urlParams = []) { parent::__construct('sharebymail', $urlParams); @@ -47,5 +46,4 @@ class Application extends App { Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider'); Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings'); } - } diff --git a/apps/sharebymail/lib/Settings/Admin.php b/apps/sharebymail/lib/Settings/Admin.php index 251269293ef..23881212692 100644 --- a/apps/sharebymail/lib/Settings/Admin.php +++ b/apps/sharebymail/lib/Settings/Admin.php @@ -39,7 +39,6 @@ class Admin implements ISettings { * @return TemplateResponse */ public function getForm() { - $parameters = [ 'sendPasswordMail' => $this->settingsManager->sendPasswordByMail(), 'enforcePasswordProtection' => $this->settingsManager->enforcePasswordProtection() @@ -65,5 +64,4 @@ class Admin implements ISettings { public function getPriority() { return 40; } - } diff --git a/apps/sharebymail/lib/Settings/SettingsManager.php b/apps/sharebymail/lib/Settings/SettingsManager.php index 8e784e80237..cded3e1713d 100644 --- a/apps/sharebymail/lib/Settings/SettingsManager.php +++ b/apps/sharebymail/lib/Settings/SettingsManager.php @@ -57,5 +57,4 @@ class SettingsManager { $enforcePassword = $this->config->getAppValue('sharebymail', 'enforcePasswordProtection', $this->enforcePasswordProtectionDefault); return $enforcePassword === 'yes'; } - } diff --git a/apps/sharebymail/lib/ShareByMailProvider.php b/apps/sharebymail/lib/ShareByMailProvider.php index 220f3e6454b..4292ac9bf18 100644 --- a/apps/sharebymail/lib/ShareByMailProvider.php +++ b/apps/sharebymail/lib/ShareByMailProvider.php @@ -173,7 +173,6 @@ class ShareByMailProvider implements IShareProvider { * @throws \Exception */ public function create(IShare $share) { - $shareWith = $share->getSharedWith(); /* * Check if file is not already shared with the remote user @@ -204,7 +203,6 @@ class ShareByMailProvider implements IShareProvider { $data = $this->getRawShare($shareId); return $this->createShareObject($data); - } /** @@ -261,7 +259,6 @@ class ShareByMailProvider implements IShareProvider { * @param string $type */ protected function createShareActivity(IShare $share, string $type = 'share') { - $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); $this->publishActivity( @@ -285,7 +282,6 @@ class ShareByMailProvider implements IShareProvider { (string) $ownerFolder->getRelativePath($ownerPath) ); } - } /** @@ -296,7 +292,6 @@ class ShareByMailProvider implements IShareProvider { * @param bool $sendToSelf */ protected function createPasswordSendActivity(IShare $share, $sharedWith, $sendToSelf) { - $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); if ($sendToSelf) { @@ -336,7 +331,6 @@ class ShareByMailProvider implements IShareProvider { ->setAffectedUser($affectedUser) ->setObject('files', $fileId, $filePath); $this->activityManager->publish($event); - } /** @@ -389,7 +383,6 @@ class ShareByMailProvider implements IShareProvider { } return $shareId; - } /** @@ -447,7 +440,7 @@ class ShareByMailProvider implements IShareProvider { // The "Reply-To" is set to the sharer if an mail address is configured // also the default footer contains a "Do not reply" which needs to be adjusted. $initiatorEmail = $initiatorUser->getEMailAddress(); - if($initiatorEmail !== null) { + if ($initiatorEmail !== null) { $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')); } else { @@ -466,7 +459,6 @@ class ShareByMailProvider implements IShareProvider { * @return bool */ protected function sendPassword(IShare $share, $password) { - $filename = $share->getNode()->getName(); $initiator = $share->getSharedBy(); $shareWith = $share->getSharedWith(); @@ -526,7 +518,6 @@ class ShareByMailProvider implements IShareProvider { } protected function sendNote(IShare $share) { - $recipient = $share->getSharedWith(); @@ -577,7 +568,6 @@ class ShareByMailProvider implements IShareProvider { $message->setTo([$recipient]); $message->useTemplate($emailTemplate); $this->mailer->send($message); - } /** @@ -590,7 +580,6 @@ class ShareByMailProvider implements IShareProvider { * @throws \Exception */ protected function sendPasswordToOwner(IShare $share, $password) { - $filename = $share->getNode()->getName(); $initiator = $this->userManager->get($share->getSharedBy()); $initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null; @@ -668,7 +657,7 @@ class ShareByMailProvider implements IShareProvider { ->orderBy('id'); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $children[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -728,13 +717,12 @@ class ShareByMailProvider implements IShareProvider { * @return IShare The share object */ public function update(IShare $share, $plainTextPassword = null) { - $originalShare = $this->getShareById($share->getId()); // a real password was given $validPassword = $plainTextPassword !== null && $plainTextPassword !== ''; - if($validPassword && ($originalShare->getPassword() !== $share->getPassword() || + if ($validPassword && ($originalShare->getPassword() !== $share->getPassword() || ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) { $this->sendPassword($share, $plainTextPassword); } @@ -844,7 +832,7 @@ class ShareByMailProvider implements IShareProvider { $cursor = $qb->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -896,7 +884,7 @@ class ShareByMailProvider implements IShareProvider { ->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -935,7 +923,7 @@ class ShareByMailProvider implements IShareProvider { $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShareObject($data); } $cursor->closeCursor(); @@ -996,7 +984,6 @@ class ShareByMailProvider implements IShareProvider { * @throws ShareNotFound */ protected function createShareObject($data) { - $share = new Share($this->rootFolder, $this->userManager); $share->setId((int)$data['id']) ->setShareType((int)$data['share_type']) @@ -1204,7 +1191,7 @@ class ShareByMailProvider implements IShareProvider { ); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { try { $share = $this->createShareObject($data); } catch (InvalidShare $e) { diff --git a/apps/sharebymail/templates/settings-admin.php b/apps/sharebymail/templates/settings-admin.php index 5b16f551a56..52b9ea29593 100644 --- a/apps/sharebymail/templates/settings-admin.php +++ b/apps/sharebymail/templates/settings-admin.php @@ -10,9 +10,13 @@ style('sharebymail', 'settings-admin');

        t('Allows users to share a personalized link to a file or folder by putting in an email address.')); ?>

        - /> + />
        - /> + />

        diff --git a/apps/sharebymail/tests/SettingsTest.php b/apps/sharebymail/tests/SettingsTest.php index 220f455a26a..83bf12da21e 100644 --- a/apps/sharebymail/tests/SettingsTest.php +++ b/apps/sharebymail/tests/SettingsTest.php @@ -28,7 +28,7 @@ use OCA\ShareByMail\Settings; use OCA\ShareByMail\Settings\SettingsManager; use Test\TestCase; -class SettingsTest extends TestCase { +class SettingsTest extends TestCase { /** @var Settings */ private $instance; @@ -93,5 +93,4 @@ class SettingsTest extends TestCase { $this->instance->announceShareByMailSettings(['array' => &$before]); $this->assertSame($after, $before); } - } diff --git a/apps/sharebymail/tests/ShareByMailProviderTest.php b/apps/sharebymail/tests/ShareByMailProviderTest.php index f340fbfa35d..f77b3afefce 100644 --- a/apps/sharebymail/tests/ShareByMailProviderTest.php +++ b/apps/sharebymail/tests/ShareByMailProviderTest.php @@ -139,7 +139,6 @@ class ShareByMailProviderTest extends TestCase { * @return \PHPUnit_Framework_MockObject_MockObject | ShareByMailProvider */ private function getInstance(array $mockedMethods = []) { - $instance = $this->getMockBuilder('OCA\ShareByMail\ShareByMailProvider') ->setConstructorArgs( [ @@ -179,7 +178,6 @@ class ShareByMailProviderTest extends TestCase { $this->hasher, $this->capabilitiesManager ); - } protected function tearDown(): void { @@ -353,7 +351,6 @@ class ShareByMailProviderTest extends TestCase { $this->assertSame(42, $this->invokePrivate($instance, 'createMailShare', [$this->share]) ); - } @@ -383,7 +380,6 @@ class ShareByMailProviderTest extends TestCase { $this->assertSame(42, $this->invokePrivate($instance, 'createMailShare', [$this->share]) ); - } public function testGenerateToken() { @@ -445,11 +441,9 @@ class ShareByMailProviderTest extends TestCase { $this->assertSame($password, $result[0]['password']); $this->assertSame($sendPasswordByTalk, (bool)$result[0]['password_by_talk']); $this->assertSame($hideDownload, (bool)$result[0]['hide_download']); - } public function testUpdate() { - $itemSource = 11; $itemType = 'file'; $shareWith = 'user@server.com'; @@ -603,7 +597,6 @@ class ShareByMailProviderTest extends TestCase { } public function testGetShareByPath() { - $itemSource = 11; $itemType = 'file'; $shareWith = 'user@server.com'; @@ -639,7 +632,6 @@ class ShareByMailProviderTest extends TestCase { } public function testGetShareByToken() { - $itemSource = 11; $itemType = 'file'; $shareWith = 'user@server.com'; @@ -726,7 +718,6 @@ class ShareByMailProviderTest extends TestCase { } public function testUserDeleted() { - $itemSource = 11; $itemType = 'file'; $shareWith = 'user@server.com'; @@ -757,7 +748,6 @@ class ShareByMailProviderTest extends TestCase { $this->assertTrue(is_array($after)); $this->assertSame(1, count($after)); $this->assertSame($id, (int)$after[0]['id']); - } public function testGetRawShare() { diff --git a/apps/systemtags/lib/Activity/Provider.php b/apps/systemtags/lib/Activity/Provider.php index 459ab03bd1d..c60aad31d62 100644 --- a/apps/systemtags/lib/Activity/Provider.php +++ b/apps/systemtags/lib/Activity/Provider.php @@ -33,7 +33,6 @@ use OCP\IUserManager; use OCP\L10N\IFactory; class Provider implements IProvider { - const CREATE_TAG = 'create_tag'; const UPDATE_TAG = 'update_tag'; const DELETE_TAG = 'delete_tag'; diff --git a/apps/systemtags/lib/Controller/LastUsedController.php b/apps/systemtags/lib/Controller/LastUsedController.php index 10707463d48..da188474329 100644 --- a/apps/systemtags/lib/Controller/LastUsedController.php +++ b/apps/systemtags/lib/Controller/LastUsedController.php @@ -55,6 +55,8 @@ class LastUsedController extends Controller { public function getLastUsedTagIds() { $lastUsed = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'systemtags', 'last_used', '[]'); $tagIds = json_decode($lastUsed, true); - return new DataResponse(array_map(function ($id) { return (string) $id; }, $tagIds)); + return new DataResponse(array_map(function ($id) { + return (string) $id; + }, $tagIds)); } } diff --git a/apps/systemtags/lib/Settings/Admin.php b/apps/systemtags/lib/Settings/Admin.php index 185281cc53a..d4eaa74f3cd 100644 --- a/apps/systemtags/lib/Settings/Admin.php +++ b/apps/systemtags/lib/Settings/Admin.php @@ -53,5 +53,4 @@ class Admin implements ISettings { public function getPriority() { return 70; } - } diff --git a/apps/theming/lib/Controller/IconController.php b/apps/theming/lib/Controller/IconController.php index 73d3606a3df..c0bc22de8ee 100644 --- a/apps/theming/lib/Controller/IconController.php +++ b/apps/theming/lib/Controller/IconController.php @@ -133,7 +133,7 @@ class IconController extends Controller { $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']); } } - if($response === null) { + if ($response === null) { $fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon.png'; $response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/x-icon']); } @@ -169,7 +169,7 @@ class IconController extends Controller { $response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/png']); } } - if($response === null) { + if ($response === null) { $fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon-touch.png'; $response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/png']); } diff --git a/apps/theming/lib/Controller/ThemingController.php b/apps/theming/lib/Controller/ThemingController.php index e1fbb227774..6184796406d 100644 --- a/apps/theming/lib/Controller/ThemingController.php +++ b/apps/theming/lib/Controller/ThemingController.php @@ -414,7 +414,7 @@ class ThemingController extends Controller { * since we need to add the cacheBuster value to the url */ $cssCached = $this->scssCacher->process($appPath, 'css/theming.scss', 'theming'); - if(!$cssCached) { + if (!$cssCached) { return new NotFoundResponse(); } diff --git a/apps/theming/lib/IconBuilder.php b/apps/theming/lib/IconBuilder.php index 2380e960c70..77079851d69 100644 --- a/apps/theming/lib/IconBuilder.php +++ b/apps/theming/lib/IconBuilder.php @@ -127,7 +127,7 @@ class IconBuilder { */ public function renderAppIcon($app, $size) { $appIcon = $this->util->getAppIcon($app); - if($appIcon === false) { + if ($appIcon === false) { return false; } if ($appIcon instanceof ISimpleFile) { @@ -138,7 +138,7 @@ class IconBuilder { $mime = mime_content_type($appIcon); } - if($appIconContent === false || $appIconContent === "") { + if ($appIconContent === false || $appIconContent === "") { return false; } @@ -150,8 +150,8 @@ class IconBuilder { '' . ''; // resize svg magic as this seems broken in Imagemagick - if($mime === "image/svg+xml" || substr($appIconContent, 0, 4) === "".$appIconContent; } else { $svg = $appIconContent; @@ -163,7 +163,7 @@ class IconBuilder { $res = $tmp->getImageResolution(); $tmp->destroy(); - if($x>$y) { + if ($x>$y) { $max = $x; } else { $max = $y; @@ -237,5 +237,4 @@ class IconBuilder { return false; } } - } diff --git a/apps/theming/lib/ImageManager.php b/apps/theming/lib/ImageManager.php index 53189181bfa..35a03c30c43 100644 --- a/apps/theming/lib/ImageManager.php +++ b/apps/theming/lib/ImageManager.php @@ -234,11 +234,11 @@ class ImageManager { */ public function shouldReplaceIcons() { $cache = $this->cacheFactory->createDistributed('theming-' . $this->urlGenerator->getBaseUrl()); - if($value = $cache->get('shouldReplaceIcons')) { + if ($value = $cache->get('shouldReplaceIcons')) { return (bool)$value; } $value = false; - if(extension_loaded('imagick')) { + if (extension_loaded('imagick')) { if (count(\Imagick::queryFormats('SVG')) >= 1) { $value = true; } diff --git a/apps/theming/lib/Settings/Admin.php b/apps/theming/lib/Settings/Admin.php index cd59b167365..518aace2c35 100644 --- a/apps/theming/lib/Settings/Admin.php +++ b/apps/theming/lib/Settings/Admin.php @@ -107,5 +107,4 @@ class Admin implements ISettings { public function getPriority(): int { return 5; } - } diff --git a/apps/theming/lib/ThemingDefaults.php b/apps/theming/lib/ThemingDefaults.php index 413e2a9e64f..059dc55cb99 100644 --- a/apps/theming/lib/ThemingDefaults.php +++ b/apps/theming/lib/ThemingDefaults.php @@ -188,9 +188,10 @@ class ThemingDefaults extends \OC_Defaults { }, $navigation); $links = array_merge($links, $guestNavigation); - $legalLinks = ''; $divider = ''; - foreach($links as $link) { - if($link['url'] !== '' + $legalLinks = ''; + $divider = ''; + foreach ($links as $link) { + if ($link['url'] !== '' && filter_var($link['url'], FILTER_VALIDATE_URL) ) { $legalLinks .= $divider . 'config->getAppValue('theming', 'cachebuster', '0'); - if(!$logo || !$logoExists) { - if($useSvg) { + if (!$logo || !$logoExists) { + if ($useSvg) { $logo = $this->urlGenerator->imagePath('core', 'logo/logo.svg'); } else { $logo = $this->urlGenerator->imagePath('core', 'logo/logo.png'); @@ -309,7 +310,7 @@ class ThemingDefaults extends \OC_Defaults { } $variables['has-legal-links'] = 'false'; - if($this->getImprintUrl() !== '' || $this->getPrivacyUrl() !== '') { + if ($this->getImprintUrl() !== '' || $this->getPrivacyUrl() !== '') { $variables['has-legal-links'] = 'true'; } @@ -350,7 +351,8 @@ class ThemingDefaults extends \OC_Defaults { if (file_exists($appPath . '/img/manifest.json')) { return false; } - } catch (AppPathNotFoundException $e) {} + } catch (AppPathNotFoundException $e) { + } $route = $this->urlGenerator->linkToRoute('theming.Theming.getManifest'); } if (strpos($image, 'filetypes/') === 0 && file_exists(\OC::$SERVERROOT . '/core/img/' . $image)) { @@ -372,7 +374,6 @@ class ThemingDefaults extends \OC_Defaults { $this->config->setAppValue('theming', 'cachebuster', (int)$cacheBusterKey+1); $this->cacheFactory->createDistributed('theming-')->clear(); $this->cacheFactory->createDistributed('imagePath')->clear(); - } /** diff --git a/apps/theming/lib/Util.php b/apps/theming/lib/Util.php index d66aeb3db2c..d3c0043b2a3 100644 --- a/apps/theming/lib/Util.php +++ b/apps/theming/lib/Util.php @@ -66,7 +66,7 @@ class Util { */ public function invertTextColor($color) { $l = $this->calculateLuma($color); - if($l>0.6) { + if ($l>0.6) { return true; } else { return false; @@ -81,7 +81,7 @@ class Util { */ public function elementColor($color) { $l = $this->calculateLuminance($color); - if($l>0.8) { + if ($l>0.8) { return '#aaaaaa'; } return $color; @@ -153,7 +153,8 @@ class Util { if (file_exists($icon)) { return $icon; } - } catch (AppPathNotFoundException $e) {} + } catch (AppPathNotFoundException $e) { + } if ($this->config->getAppValue('theming', 'logoMime', '') !== '') { $logoFile = null; @@ -162,7 +163,8 @@ class Util { if ($folder !== null) { return $folder->getFile('logo'); } - } catch (NotFoundException $e) {} + } catch (NotFoundException $e) { + } } return \OC::$SERVERROOT . '/core/img/logo/logo.svg'; } @@ -248,5 +250,4 @@ class Util { } return $backgroundLogo && $backgroundLogo !== 'backgroundColor' && $backgroundExists; } - } diff --git a/apps/theming/tests/CapabilitiesTest.php b/apps/theming/tests/CapabilitiesTest.php index 1f871d101d8..6364f953c57 100644 --- a/apps/theming/tests/CapabilitiesTest.php +++ b/apps/theming/tests/CapabilitiesTest.php @@ -42,7 +42,7 @@ use Test\TestCase; * * @package OCA\Theming\Tests */ -class CapabilitiesTest extends TestCase { +class CapabilitiesTest extends TestCase { /** @var ThemingDefaults|\PHPUnit_Framework_MockObject_MockObject */ protected $theming; @@ -175,7 +175,7 @@ class CapabilitiesTest extends TestCase { ->method('isBackgroundThemed') ->willReturn($backgroundThemed); - if($background !== 'backgroundColor') { + if ($background !== 'backgroundColor') { $this->theming->expects($this->once()) ->method('getBackground') ->willReturn($background); diff --git a/apps/theming/tests/Controller/IconControllerTest.php b/apps/theming/tests/Controller/IconControllerTest.php index 59608f41a68..05b74c58e79 100644 --- a/apps/theming/tests/Controller/IconControllerTest.php +++ b/apps/theming/tests/Controller/IconControllerTest.php @@ -205,5 +205,4 @@ class IconControllerTest extends TestCase { $expected->cacheFor(86400); $this->assertEquals($expected, $this->iconController->getTouchIcon()); } - } diff --git a/apps/theming/tests/Controller/ThemingControllerTest.php b/apps/theming/tests/Controller/ThemingControllerTest.php index d1890f7df5c..b9c291c9578 100644 --- a/apps/theming/tests/Controller/ThemingControllerTest.php +++ b/apps/theming/tests/Controller/ThemingControllerTest.php @@ -401,7 +401,7 @@ class ThemingControllerTest extends TestCase { $file = $this->createMock(ISimpleFile::class); $folder = $this->createMock(ISimpleFolder::class); - if($folderExists) { + if ($folderExists) { $this->appData ->expects($this->once()) ->method('getFolder') @@ -476,7 +476,7 @@ class ThemingControllerTest extends TestCase { $file = $this->createMock(ISimpleFile::class); $folder = $this->createMock(ISimpleFolder::class); - if($folderExists) { + if ($folderExists) { $this->appData ->expects($this->once()) ->method('getFolder') @@ -963,5 +963,4 @@ class ThemingControllerTest extends TestCase { $response->cacheFor(3600); $this->assertEquals($response, $this->themingController->getManifest('core')); } - } diff --git a/apps/theming/tests/IconBuilderTest.php b/apps/theming/tests/IconBuilderTest.php index 1a05235e2dc..4d1a0daf3b1 100644 --- a/apps/theming/tests/IconBuilderTest.php +++ b/apps/theming/tests/IconBuilderTest.php @@ -68,7 +68,7 @@ class IconBuilderTest extends TestCase { } private function checkImagick() { - if(!extension_loaded('imagick')) { + if (!extension_loaded('imagick')) { $this->markTestSkipped('Imagemagick is required for dynamic icon generation.'); } $checkImagick = new \Imagick(); diff --git a/apps/theming/tests/ImageManagerTest.php b/apps/theming/tests/ImageManagerTest.php index 19896be21a2..4098c466da7 100644 --- a/apps/theming/tests/ImageManagerTest.php +++ b/apps/theming/tests/ImageManagerTest.php @@ -69,7 +69,7 @@ class ImageManagerTest extends TestCase { } private function checkImagick() { - if(!extension_loaded('imagick')) { + if (!extension_loaded('imagick')) { $this->markTestSkipped('Imagemagick is required for dynamic icon generation.'); } $checkImagick = new \Imagick(); @@ -172,7 +172,6 @@ class ImageManagerTest extends TestCase { ->method('getAbsoluteUrl') ->willReturn('url-to-image-absolute?v=0'); $this->assertEquals('url-to-image-absolute?v=0', $this->imageManager->getImageUrlAbsolute('logo', false)); - } public function testGetImage() { @@ -326,5 +325,4 @@ class ImageManagerTest extends TestCase { ->willReturn($folders[2]); $this->imageManager->cleanup(); } - } diff --git a/apps/theming/tests/ServicesTest.php b/apps/theming/tests/ServicesTest.php index 62618abcd96..d530d321aeb 100644 --- a/apps/theming/tests/ServicesTest.php +++ b/apps/theming/tests/ServicesTest.php @@ -43,7 +43,7 @@ use Test\TestCase; * @group DB * @package OCA\Theming\Tests */ -class ServicesTest extends TestCase { +class ServicesTest extends TestCase { /** @var \OCA\Activity\AppInfo\Application */ protected $app; diff --git a/apps/theming/tests/ThemingDefaultsTest.php b/apps/theming/tests/ThemingDefaultsTest.php index a06cdb8f7a8..e5b6fb72db0 100644 --- a/apps/theming/tests/ThemingDefaultsTest.php +++ b/apps/theming/tests/ThemingDefaultsTest.php @@ -777,5 +777,4 @@ class ThemingDefaultsTest extends TestCase { ->willReturn('themingRoute'); $this->assertEquals($result, $this->template->replaceImagePath($app, $image)); } - } diff --git a/apps/theming/tests/UtilTest.php b/apps/theming/tests/UtilTest.php index 969d35f7d27..51cb76f9559 100644 --- a/apps/theming/tests/UtilTest.php +++ b/apps/theming/tests/UtilTest.php @@ -165,7 +165,7 @@ class UtilTest extends TestCase { * @dataProvider dataGetAppImage */ public function testGetAppImage($app, $image, $expected) { - if($app !== 'core') { + if ($app !== 'core') { $this->appManager->expects($this->once()) ->method('getAppPath') ->with($app) @@ -238,5 +238,4 @@ class UtilTest extends TestCase { ->willReturn($folder); $this->assertEquals($expected, $this->util->isBackgroundThemed()); } - } diff --git a/apps/twofactor_backupcodes/lib/Activity/Provider.php b/apps/twofactor_backupcodes/lib/Activity/Provider.php index ac62ebabd05..12c71f68d1c 100644 --- a/apps/twofactor_backupcodes/lib/Activity/Provider.php +++ b/apps/twofactor_backupcodes/lib/Activity/Provider.php @@ -75,5 +75,4 @@ class Provider implements IProvider { } return $event; } - } diff --git a/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php b/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php index 61dbffb3214..5d6d428cecc 100644 --- a/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php +++ b/apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php @@ -66,5 +66,4 @@ class CheckBackupCodes extends QueuedJob { } }); } - } diff --git a/apps/twofactor_backupcodes/lib/Controller/SettingsController.php b/apps/twofactor_backupcodes/lib/Controller/SettingsController.php index 2d87af3183f..04ec2e19e95 100644 --- a/apps/twofactor_backupcodes/lib/Controller/SettingsController.php +++ b/apps/twofactor_backupcodes/lib/Controller/SettingsController.php @@ -64,5 +64,4 @@ class SettingsController extends Controller { 'state' => $this->storage->getBackupCodesState($user), ]); } - } diff --git a/apps/twofactor_backupcodes/lib/Db/BackupCode.php b/apps/twofactor_backupcodes/lib/Db/BackupCode.php index bbd40bf3643..02d1932d50b 100644 --- a/apps/twofactor_backupcodes/lib/Db/BackupCode.php +++ b/apps/twofactor_backupcodes/lib/Db/BackupCode.php @@ -44,5 +44,4 @@ class BackupCode extends Entity { /** @var int */ protected $used; - } diff --git a/apps/twofactor_backupcodes/lib/Db/BackupCodeMapper.php b/apps/twofactor_backupcodes/lib/Db/BackupCodeMapper.php index 73883b3eb30..48c3fd6a84d 100644 --- a/apps/twofactor_backupcodes/lib/Db/BackupCodeMapper.php +++ b/apps/twofactor_backupcodes/lib/Db/BackupCodeMapper.php @@ -31,7 +31,6 @@ use OCP\IDBConnection; use OCP\IUser; class BackupCodeMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'twofactor_backupcodes'); } @@ -69,5 +68,4 @@ class BackupCodeMapper extends QBMapper { ->where($qb->expr()->eq('user_id', $qb->createNamedParameter($uid))); $qb->execute(); } - } diff --git a/apps/twofactor_backupcodes/lib/Event/CodesGenerated.php b/apps/twofactor_backupcodes/lib/Event/CodesGenerated.php index 7db29bdf765..d1e5e29d4b5 100644 --- a/apps/twofactor_backupcodes/lib/Event/CodesGenerated.php +++ b/apps/twofactor_backupcodes/lib/Event/CodesGenerated.php @@ -45,5 +45,4 @@ class CodesGenerated extends Event { public function getUser(): IUser { return $this->user; } - } diff --git a/apps/twofactor_backupcodes/lib/Listener/ActivityPublisher.php b/apps/twofactor_backupcodes/lib/Listener/ActivityPublisher.php index 99dd39b5b1d..d7240677b6c 100644 --- a/apps/twofactor_backupcodes/lib/Listener/ActivityPublisher.php +++ b/apps/twofactor_backupcodes/lib/Listener/ActivityPublisher.php @@ -66,5 +66,4 @@ class ActivityPublisher implements IEventListener { } } } - } diff --git a/apps/twofactor_backupcodes/lib/Listener/ProviderDisabled.php b/apps/twofactor_backupcodes/lib/Listener/ProviderDisabled.php index 9dfecee0df7..f3242aa8c8a 100644 --- a/apps/twofactor_backupcodes/lib/Listener/ProviderDisabled.php +++ b/apps/twofactor_backupcodes/lib/Listener/ProviderDisabled.php @@ -64,5 +64,4 @@ class ProviderDisabled implements IEventListener { $this->jobList->remove(RememberBackupCodesJob::class, ['uid' => $event->getUser()->getUID()]); } } - } diff --git a/apps/twofactor_backupcodes/lib/Listener/ProviderEnabled.php b/apps/twofactor_backupcodes/lib/Listener/ProviderEnabled.php index de3d52ef436..d43af2e4590 100644 --- a/apps/twofactor_backupcodes/lib/Listener/ProviderEnabled.php +++ b/apps/twofactor_backupcodes/lib/Listener/ProviderEnabled.php @@ -61,5 +61,4 @@ class ProviderEnabled implements IEventListener { $this->jobList->add(RememberBackupCodesJob::class, ['uid' => $event->getUser()->getUID()]); } - } diff --git a/apps/twofactor_backupcodes/lib/Listener/RegistryUpdater.php b/apps/twofactor_backupcodes/lib/Listener/RegistryUpdater.php index 48e231facb3..011950a0979 100644 --- a/apps/twofactor_backupcodes/lib/Listener/RegistryUpdater.php +++ b/apps/twofactor_backupcodes/lib/Listener/RegistryUpdater.php @@ -50,5 +50,4 @@ class RegistryUpdater implements IEventListener { $this->registry->enableProviderFor($this->provider, $event->getUser()); } } - } diff --git a/apps/twofactor_backupcodes/lib/Migration/CheckBackupCodes.php b/apps/twofactor_backupcodes/lib/Migration/CheckBackupCodes.php index d5b3758f37f..e43a99b9e0a 100644 --- a/apps/twofactor_backupcodes/lib/Migration/CheckBackupCodes.php +++ b/apps/twofactor_backupcodes/lib/Migration/CheckBackupCodes.php @@ -46,5 +46,4 @@ class CheckBackupCodes implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(\OCA\TwoFactorBackupCodes\BackgroundJob\CheckBackupCodes::class); } - } diff --git a/apps/twofactor_backupcodes/lib/Migration/Version1002Date20170926101419.php b/apps/twofactor_backupcodes/lib/Migration/Version1002Date20170926101419.php index cd922454ea0..f8df9e69844 100644 --- a/apps/twofactor_backupcodes/lib/Migration/Version1002Date20170926101419.php +++ b/apps/twofactor_backupcodes/lib/Migration/Version1002Date20170926101419.php @@ -40,5 +40,4 @@ class Version1002Date20170926101419 extends BigIntMigration { 'twofactor_backupcodes' => ['id'], ]; } - } diff --git a/apps/twofactor_backupcodes/lib/Migration/Version1002Date20180821043638.php b/apps/twofactor_backupcodes/lib/Migration/Version1002Date20180821043638.php index 3cbadb455a6..1138bcd6bd2 100644 --- a/apps/twofactor_backupcodes/lib/Migration/Version1002Date20180821043638.php +++ b/apps/twofactor_backupcodes/lib/Migration/Version1002Date20180821043638.php @@ -50,5 +50,4 @@ class Version1002Date20180821043638 extends SimpleMigrationStep { return $schema; } - } diff --git a/apps/twofactor_backupcodes/lib/Provider/BackupCodesProvider.php b/apps/twofactor_backupcodes/lib/Provider/BackupCodesProvider.php index 6d60f589e52..9b7ce1ed7de 100644 --- a/apps/twofactor_backupcodes/lib/Provider/BackupCodesProvider.php +++ b/apps/twofactor_backupcodes/lib/Provider/BackupCodesProvider.php @@ -165,5 +165,4 @@ class BackupCodesProvider implements IProvider, IProvidesPersonalSettings { $this->initialStateService->provideInitialState($this->appName, 'state', $state); return new Personal(); } - } diff --git a/apps/twofactor_backupcodes/lib/Service/BackupCodeStorage.php b/apps/twofactor_backupcodes/lib/Service/BackupCodeStorage.php index ffb456792a4..fb604d80aab 100644 --- a/apps/twofactor_backupcodes/lib/Service/BackupCodeStorage.php +++ b/apps/twofactor_backupcodes/lib/Service/BackupCodeStorage.php @@ -34,7 +34,6 @@ use OCP\Security\IHasher; use OCP\Security\ISecureRandom; class BackupCodeStorage { - private static $CODE_LENGTH = 16; /** @var BackupCodeMapper */ @@ -133,5 +132,4 @@ class BackupCodeStorage { } return false; } - } diff --git a/apps/twofactor_backupcodes/lib/Settings/Personal.php b/apps/twofactor_backupcodes/lib/Settings/Personal.php index e7cfcb77ca6..062016d0d05 100644 --- a/apps/twofactor_backupcodes/lib/Settings/Personal.php +++ b/apps/twofactor_backupcodes/lib/Settings/Personal.php @@ -35,5 +35,4 @@ class Personal implements IPersonalProviderSettings { public function getBody(): Template { return new Template('twofactor_backupcodes', 'personal'); } - } diff --git a/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php b/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php index 89cd88e05e3..ae5a10232e9 100644 --- a/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php +++ b/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php @@ -120,5 +120,4 @@ class BackupCodeMapperTest extends TestCase { $this->mapper->insert($code); } - } diff --git a/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php b/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php index 8cd20df85a7..dbfc6fa70e1 100644 --- a/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php +++ b/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php @@ -107,5 +107,4 @@ class BackupCodeStorageTest extends TestCase { ]; $this->assertEquals($stateAllUsed, $this->storage->getBackupCodesState($user)); } - } diff --git a/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php b/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php index 050d5d06a5a..464b65dbebb 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php @@ -130,5 +130,4 @@ class ProviderTest extends TestCase { $this->expectException(InvalidArgumentException::class); $this->provider->parse($lang, $event); } - } diff --git a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php index 3b443c9fe6b..43873e6cc89 100644 --- a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php @@ -133,6 +133,4 @@ class CheckBackupCodeTest extends TestCase { $this->invokePrivate($this->checkBackupCodes, 'run', [[]]); } - - } diff --git a/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php b/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php index 95d94e4fc0d..1ced1dbf684 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php @@ -83,5 +83,4 @@ class SettingsControllerTest extends TestCase { $this->assertInstanceOf(JSONResponse::class, $response); $this->assertEquals($expected, $response->getData()); } - } diff --git a/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php b/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php index 84f56f927f7..b8922b2cbbe 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Event/CodesGeneratedTest.php @@ -31,7 +31,6 @@ use OCP\IUser; use Test\TestCase; class CodesGeneratedTest extends TestCase { - public function testCodeGeneratedEvent() { $user = $this->createMock(IUser::class); diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php index 2aec2e72d94..a786d5b7f5b 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php @@ -96,5 +96,4 @@ class ActivityPublisherTest extends TestCase { $this->listener->handle($event); } - } diff --git a/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php b/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php index 69df82a43fd..1c33cca2cb6 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Provider/BackupCodesProviderTest.php @@ -157,5 +157,4 @@ class BackupCodesProviderTest extends TestCase { $this->assertTrue($this->provider->isActive($user)); } - } diff --git a/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php b/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php index ab895f4d854..20cad61530d 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php @@ -235,5 +235,4 @@ class BackupCodeStorageTest extends TestCase { $this->assertFalse($this->storage->validateCode($user, 'CHALLENGE')); } - } diff --git a/apps/updatenotification/lib/Notification/BackgroundJob.php b/apps/updatenotification/lib/Notification/BackgroundJob.php index d352375163f..b32ec024a16 100644 --- a/apps/updatenotification/lib/Notification/BackgroundJob.php +++ b/apps/updatenotification/lib/Notification/BackgroundJob.php @@ -37,7 +37,6 @@ use OCP\IGroupManager; use OCP\Notification\IManager; class BackgroundJob extends TimedJob { - protected $connectionNotifications = [3, 7, 14, 30]; /** @var IConfig */ diff --git a/apps/updatenotification/lib/ResetTokenBackgroundJob.php b/apps/updatenotification/lib/ResetTokenBackgroundJob.php index 9bd414d1e5c..d64a26c62e8 100644 --- a/apps/updatenotification/lib/ResetTokenBackgroundJob.php +++ b/apps/updatenotification/lib/ResetTokenBackgroundJob.php @@ -59,9 +59,8 @@ class ResetTokenBackgroundJob extends TimedJob { */ protected function run($argument) { // Delete old tokens after 2 days - if($this->timeFactory->getTime() - $this->config->getAppValue('core', 'updater.secret.created', $this->timeFactory->getTime()) >= 172800) { + if ($this->timeFactory->getTime() - $this->config->getAppValue('core', 'updater.secret.created', $this->timeFactory->getTime()) >= 172800) { $this->config->deleteSystemValue('updater.secret'); } } - } diff --git a/apps/updatenotification/lib/Settings/Admin.php b/apps/updatenotification/lib/Settings/Admin.php index db2efffc46b..f623e69e02e 100644 --- a/apps/updatenotification/lib/Settings/Admin.php +++ b/apps/updatenotification/lib/Settings/Admin.php @@ -126,22 +126,22 @@ class Admin implements ISettings { protected function filterChanges(array $changes): array { $filtered = []; - if(isset($changes['changelogURL'])) { + if (isset($changes['changelogURL'])) { $filtered['changelogURL'] = $changes['changelogURL']; } - if(!isset($changes['whatsNew'])) { + if (!isset($changes['whatsNew'])) { return $filtered; } $iterator = $this->l10nFactory->getLanguageIterator(); do { $lang = $iterator->current(); - if(isset($changes['whatsNew'][$lang])) { + if (isset($changes['whatsNew'][$lang])) { $filtered['whatsNew'] = $changes['whatsNew'][$lang]; return $filtered; } $iterator->next(); - } while($lang !== 'en' && $iterator->valid()); + } while ($lang !== 'en' && $iterator->valid()); return $filtered; } diff --git a/apps/updatenotification/tests/Controller/AdminControllerTest.php b/apps/updatenotification/tests/Controller/AdminControllerTest.php index 597b646ee6b..e40364cce09 100644 --- a/apps/updatenotification/tests/Controller/AdminControllerTest.php +++ b/apps/updatenotification/tests/Controller/AdminControllerTest.php @@ -101,5 +101,4 @@ class AdminControllerTest extends TestCase { $expected = new DataResponse('MyGeneratedToken'); $this->assertEquals($expected, $this->adminController->createCredentials()); } - } diff --git a/apps/updatenotification/tests/Notification/BackgroundJobTest.php b/apps/updatenotification/tests/Notification/BackgroundJobTest.php index 04b0260811e..92f7bc2a8aa 100644 --- a/apps/updatenotification/tests/Notification/BackgroundJobTest.php +++ b/apps/updatenotification/tests/Notification/BackgroundJobTest.php @@ -80,7 +80,8 @@ class BackgroundJobTest extends TestCase { $this->client, $this->installer ); - } { + } + { return $this->getMockBuilder(BackgroundJob::class) ->setConstructorArgs([ $this->config, diff --git a/apps/updatenotification/tests/Notification/NotifierTest.php b/apps/updatenotification/tests/Notification/NotifierTest.php index 6c36a8a74aa..e071fb06b23 100644 --- a/apps/updatenotification/tests/Notification/NotifierTest.php +++ b/apps/updatenotification/tests/Notification/NotifierTest.php @@ -77,7 +77,8 @@ class NotifierTest extends TestCase { $this->userSession, $this->groupManager ); - } { + } + { return $this->getMockBuilder(Notifier::class) ->setConstructorArgs([ $this->urlGenerator, diff --git a/apps/user_ldap/ajax/clearMappings.php b/apps/user_ldap/ajax/clearMappings.php index 5102822ce4e..b485d62dead 100644 --- a/apps/user_ldap/ajax/clearMappings.php +++ b/apps/user_ldap/ajax/clearMappings.php @@ -36,7 +36,7 @@ use OCA\User_LDAP\Mapping\GroupMapping; $subject = (string)$_POST['ldap_clear_mapping']; $mapping = null; try { - if($subject === 'user') { + if ($subject === 'user') { $mapping = new UserMapping(\OC::$server->getDatabaseConnection()); $result = $mapping->clearCb( function ($uid) { @@ -46,12 +46,12 @@ try { \OC::$server->getUserManager()->emit('\OC\User', 'postUnassignedUserId', [$uid]); } ); - } elseif($subject === 'group') { + } elseif ($subject === 'group') { $mapping = new GroupMapping(\OC::$server->getDatabaseConnection()); $result = $mapping->clear(); } - if($mapping === null || !$result) { + if ($mapping === null || !$result) { $l = \OC::$server->getL10N('user_ldap'); throw new \Exception($l->t('Failed to clear the mappings.')); } diff --git a/apps/user_ldap/ajax/deleteConfiguration.php b/apps/user_ldap/ajax/deleteConfiguration.php index 32b86f75fbd..f4f6eaf267d 100644 --- a/apps/user_ldap/ajax/deleteConfiguration.php +++ b/apps/user_ldap/ajax/deleteConfiguration.php @@ -33,7 +33,7 @@ $prefix = (string)$_POST['ldap_serverconfig_chooser']; $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig()); -if($helper->deleteServerConfiguration($prefix)) { +if ($helper->deleteServerConfiguration($prefix)) { \OC_JSON::success(); } else { $l = \OC::$server->getL10N('user_ldap'); diff --git a/apps/user_ldap/ajax/getNewServerConfigPrefix.php b/apps/user_ldap/ajax/getNewServerConfigPrefix.php index 6bf25729418..6118ac18566 100644 --- a/apps/user_ldap/ajax/getNewServerConfigPrefix.php +++ b/apps/user_ldap/ajax/getNewServerConfigPrefix.php @@ -39,7 +39,7 @@ $nk = 's'.str_pad($ln+1, 2, '0', STR_PAD_LEFT); $resultData = ['configPrefix' => $nk]; $newConfig = new \OCA\User_LDAP\Configuration($nk, false); -if(isset($_POST['copyConfig'])) { +if (isset($_POST['copyConfig'])) { $originalConfig = new \OCA\User_LDAP\Configuration($_POST['copyConfig']); $newConfig->setConfiguration($originalConfig->getConfiguration()); } else { diff --git a/apps/user_ldap/ajax/setConfiguration.php b/apps/user_ldap/ajax/setConfiguration.php index 2f6c318fa25..08d3680187b 100644 --- a/apps/user_ldap/ajax/setConfiguration.php +++ b/apps/user_ldap/ajax/setConfiguration.php @@ -37,8 +37,8 @@ $prefix = (string)$_POST['ldap_serverconfig_chooser']; // the Wizard-like tabs handle it on their own $chkboxes = ['ldap_configuration_active', 'ldap_override_main_server', 'ldap_turn_off_cert_check']; -foreach($chkboxes as $boxid) { - if(!isset($_POST[$boxid])) { +foreach ($chkboxes as $boxid) { + if (!isset($_POST[$boxid])) { $_POST[$boxid] = 0; } } diff --git a/apps/user_ldap/ajax/testConfiguration.php b/apps/user_ldap/ajax/testConfiguration.php index 3fe2337c86e..22cdea388c1 100644 --- a/apps/user_ldap/ajax/testConfiguration.php +++ b/apps/user_ldap/ajax/testConfiguration.php @@ -68,7 +68,7 @@ try { try { $ldapWrapper->read($connection->getConnectionResource(), '', 'objectClass=*', ['dn']); } catch (\Exception $e) { - if($e->getCode() === 1) { + if ($e->getCode() === 1) { \OC_JSON::error(['message' => $l->t('Invalid configuration: Anonymous binding is not allowed.')]); exit; } diff --git a/apps/user_ldap/ajax/wizard.php b/apps/user_ldap/ajax/wizard.php index ccd7e5937c0..34c9729f6f3 100644 --- a/apps/user_ldap/ajax/wizard.php +++ b/apps/user_ldap/ajax/wizard.php @@ -36,13 +36,13 @@ $l = \OC::$server->getL10N('user_ldap'); -if(!isset($_POST['action'])) { +if (!isset($_POST['action'])) { \OC_JSON::error(['message' => $l->t('No action specified')]); } $action = (string)$_POST['action']; -if(!isset($_POST['ldap_serverconfig_chooser'])) { +if (!isset($_POST['ldap_serverconfig_chooser'])) { \OC_JSON::error(['message' => $l->t('No configuration specified')]); } $prefix = (string)$_POST['ldap_serverconfig_chooser']; @@ -76,7 +76,7 @@ $access = new \OCA\User_LDAP\Access( $wizard = new \OCA\User_LDAP\Wizard($configuration, $ldapWrapper, $access); -switch($action) { +switch ($action) { case 'guessPortAndTLS': case 'guessBaseDN': case 'detectEmailAttribute': @@ -95,7 +95,7 @@ switch($action) { case 'countInBaseDN': try { $result = $wizard->$action(); - if($result !== false) { + if ($result !== false) { \OC_JSON::success($result->getResultArray()); exit; } @@ -111,7 +111,7 @@ switch($action) { try { $loginName = $_POST['ldap_test_loginname']; $result = $wizard->$action($loginName); - if($result !== false) { + if ($result !== false) { \OC_JSON::success($result->getResultArray()); exit; } @@ -127,14 +127,14 @@ switch($action) { case 'save': $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false; $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null; - if($key === false || is_null($val)) { + if ($key === false || is_null($val)) { \OC_JSON::error(['message' => $l->t('No data specified')]); exit; } $cfg = [$key => $val]; $setParameters = []; $configuration->setConfiguration($cfg, $setParameters); - if(!in_array($key, $setParameters)) { + if (!in_array($key, $setParameters)) { \OC_JSON::error(['message' => $l->t($key. ' Could not set configuration %s', $setParameters[0])]); exit; diff --git a/apps/user_ldap/appinfo/app.php b/apps/user_ldap/appinfo/app.php index 3cbae3f4743..c2d61ba61a2 100644 --- a/apps/user_ldap/appinfo/app.php +++ b/apps/user_ldap/appinfo/app.php @@ -38,7 +38,7 @@ $app = \OC::$server->query(\OCA\User_LDAP\AppInfo\Application::class); $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig()); $configPrefixes = $helper->getServerConfigurationPrefixes(true); -if(count($configPrefixes) > 0) { +if (count($configPrefixes) > 0) { $ldapWrapper = new OCA\User_LDAP\LDAP(); $ocConfig = \OC::$server->getConfig(); $notificationManager = \OC::$server->getNotificationManager(); diff --git a/apps/user_ldap/appinfo/install.php b/apps/user_ldap/appinfo/install.php index 4def7508f18..78dd81e951d 100644 --- a/apps/user_ldap/appinfo/install.php +++ b/apps/user_ldap/appinfo/install.php @@ -25,7 +25,7 @@ */ $config = \OC::$server->getConfig(); $state = $config->getSystemValue('ldapIgnoreNamingRules', 'doSet'); -if($state === 'doSet') { +if ($state === 'doSet') { \OC::$server->getConfig()->setSystemValue('ldapIgnoreNamingRules', false); } diff --git a/apps/user_ldap/lib/Access.php b/apps/user_ldap/lib/Access.php index 5677f3614cc..6744b044cdf 100644 --- a/apps/user_ldap/lib/Access.php +++ b/apps/user_ldap/lib/Access.php @@ -134,7 +134,7 @@ class Access extends LDAPUtility { * @return AbstractMapping */ public function getUserMapper() { - if(is_null($this->userMapper)) { + if (is_null($this->userMapper)) { throw new \Exception('UserMapper was not assigned to this Access instance.'); } return $this->userMapper; @@ -154,7 +154,7 @@ class Access extends LDAPUtility { * @return AbstractMapping */ public function getGroupMapper() { - if(is_null($this->groupMapper)) { + if (is_null($this->groupMapper)) { throw new \Exception('GroupMapper was not assigned to this Access instance.'); } return $this->groupMapper; @@ -187,14 +187,14 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ public function readAttribute($dn, $attr, $filter = 'objectClass=*') { - if(!$this->checkConnection()) { + if (!$this->checkConnection()) { \OCP\Util::writeLog('user_ldap', 'No LDAP Connector assigned, access impossible for readAttribute.', ILogger::WARN); return false; } $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { //LDAP not available \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); return false; @@ -217,7 +217,7 @@ class Access extends LDAPUtility { $isRangeRequest = false; do { $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); - if(is_bool($result)) { + if (is_bool($result)) { // when an exists request was run and it was successful, an empty // array must be returned return $result ? [] : false; @@ -239,7 +239,7 @@ class Access extends LDAPUtility { ); $values = array_merge($values, $normalizedResult); - if($result['rangeHigh'] === '*') { + if ($result['rangeHigh'] === '*') { // when server replies with * as high range value, there are // no more results left return $values; @@ -249,7 +249,7 @@ class Access extends LDAPUtility { $isRangeRequest = true; } } - } while($isRangeRequest); + } while ($isRangeRequest); \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG); return false; @@ -306,12 +306,12 @@ class Access extends LDAPUtility { */ public function extractAttributeValuesFromResult($result, $attribute) { $values = []; - if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { + if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) { $lowercaseAttribute = strtolower($attribute); - for($i=0;$i<$result[$attribute]['count'];$i++) { - if($this->resemblesDN($attribute)) { + for ($i=0;$i<$result[$attribute]['count'];$i++) { + if ($this->resemblesDN($attribute)) { $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); - } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { + } elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); } else { $values[] = $result[$attribute][$i]; @@ -333,10 +333,10 @@ class Access extends LDAPUtility { */ public function extractRangeData($result, $attribute) { $keys = array_keys($result); - foreach($keys as $key) { - if($key !== $attribute && strpos($key, $attribute) === 0) { + foreach ($keys as $key) { + if ($key !== $attribute && strpos($key, $attribute) === 0) { $queryData = explode(';', $key); - if(strpos($queryData[1], 'range=') === 0) { + if (strpos($queryData[1], 'range=') === 0) { $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); $data = [ 'values' => $result[$key], @@ -361,11 +361,11 @@ class Access extends LDAPUtility { * @throws \Exception */ public function setPassword($userDN, $password) { - if((int)$this->connection->turnOnPasswordChange !== 1) { + if ((int)$this->connection->turnOnPasswordChange !== 1) { throw new \Exception('LDAP password changes are disabled.'); } $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { //LDAP not available \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); return false; @@ -374,7 +374,7 @@ class Access extends LDAPUtility { // try PASSWD extended operation first return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) || @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); - } catch(ConstraintViolationException $e) { + } catch (ConstraintViolationException $e) { throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); } } @@ -416,17 +416,17 @@ class Access extends LDAPUtility { */ public function getDomainDNFromDN($dn) { $allParts = $this->ldap->explodeDN($dn, 0); - if($allParts === false) { + if ($allParts === false) { //not a valid DN return ''; } $domainParts = []; $dcFound = false; - foreach($allParts as $part) { - if(!$dcFound && strpos($part, 'dc=') === 0) { + foreach ($allParts as $part) { + if (!$dcFound && strpos($part, 'dc=') === 0) { $dcFound = true; } - if($dcFound) { + if ($dcFound) { $domainParts[] = $part; } } @@ -452,7 +452,7 @@ class Access extends LDAPUtility { //Check whether the DN belongs to the Base, to avoid issues on multi- //server setups - if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { + if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { return $fdn; } @@ -471,7 +471,7 @@ class Access extends LDAPUtility { //To avoid bypassing the base DN settings under certain circumstances //with the group support, check whether the provided DN matches one of //the given Bases - if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { + if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { return false; } @@ -489,11 +489,11 @@ class Access extends LDAPUtility { */ public function groupsMatchFilter($groupDNs) { $validGroupDNs = []; - foreach($groupDNs as $dn) { + foreach ($groupDNs as $dn) { $cacheKey = 'groupsMatchFilter-'.$dn; $groupMatchFilter = $this->connection->getFromCache($cacheKey); - if(!is_null($groupMatchFilter)) { - if($groupMatchFilter) { + if (!is_null($groupMatchFilter)) { + if ($groupMatchFilter) { $validGroupDNs[] = $dn; } continue; @@ -501,19 +501,18 @@ class Access extends LDAPUtility { // Check the base DN first. If this is not met already, we don't // need to ask the server at all. - if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { + if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { $this->connection->writeToCache($cacheKey, false); continue; } $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter); - if(is_array($result)) { + if (is_array($result)) { $this->connection->writeToCache($cacheKey, true); $validGroupDNs[] = $dn; } else { $this->connection->writeToCache($cacheKey, false); } - } return $validGroupDNs; } @@ -530,7 +529,7 @@ class Access extends LDAPUtility { //To avoid bypassing the base DN settings under certain circumstances //with the group support, check whether the provided DN matches one of //the given Bases - if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { + if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { return false; } @@ -550,7 +549,7 @@ class Access extends LDAPUtility { */ public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) { $newlyMapped = false; - if($isUser) { + if ($isUser) { $mapper = $this->getUserMapper(); $nameAttribute = $this->connection->ldapUserDisplayName; $filter = $this->connection->ldapUserFilter; @@ -562,15 +561,15 @@ class Access extends LDAPUtility { //let's try to retrieve the Nextcloud name from the mappings table $ncName = $mapper->getNameByDN($fdn); - if(is_string($ncName)) { + if (is_string($ncName)) { return $ncName; } //second try: get the UUID and check if it is known. Then, update the DN and return the name. $uuid = $this->getUUID($fdn, $isUser, $record); - if(is_string($uuid)) { + if (is_string($uuid)) { $ncName = $mapper->getNameByUUID($uuid); - if(is_string($ncName)) { + if (is_string($ncName)) { $mapper->setDNbyUUID($fdn, $uuid); return $ncName; } @@ -580,16 +579,16 @@ class Access extends LDAPUtility { return false; } - if(is_null($ldapName)) { + if (is_null($ldapName)) { $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter); - if(!isset($ldapName[0]) && empty($ldapName[0])) { + if (!isset($ldapName[0]) && empty($ldapName[0])) { \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO); return false; } $ldapName = $ldapName[0]; } - if($isUser) { + if ($isUser) { $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr; if ($usernameAttribute !== '') { $username = $this->readAttribute($fdn, $usernameAttribute); @@ -620,14 +619,14 @@ class Access extends LDAPUtility { // outside of core user management will still cache the user as non-existing. $originalTTL = $this->connection->ldapCacheTTL; $this->connection->setConfiguration(['ldapCacheTTL' => 0]); - if($intName !== '' + if ($intName !== '' && (($isUser && !$this->ncUserManager->userExists($intName)) || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName)) ) ) { $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser); - if($newlyMapped) { + if ($newlyMapped) { return $intName; } } @@ -635,7 +634,7 @@ class Access extends LDAPUtility { $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); $altName = $this->createAltInternalOwnCloudName($intName, $isUser); if (is_string($altName)) { - if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { + if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { $newlyMapped = true; return $altName; } @@ -653,7 +652,7 @@ class Access extends LDAPUtility { string $uuid, bool $isUser ) :bool { - if($mapper->map($fdn, $name, $uuid)) { + if ($mapper->map($fdn, $name, $uuid)) { if ($this->ncUserManager instanceof PublicEmitter && $isUser) { $this->cacheUserExists($name); $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]); @@ -698,7 +697,7 @@ class Access extends LDAPUtility { * @throws \Exception */ private function ldap2NextcloudNames($ldapObjects, $isUsers) { - if($isUsers) { + if ($isUsers) { $nameAttribute = $this->connection->ldapUserDisplayName; $sndAttribute = $this->connection->ldapUserDisplayName2; } else { @@ -706,9 +705,9 @@ class Access extends LDAPUtility { } $nextcloudNames = []; - foreach($ldapObjects as $ldapObject) { + foreach ($ldapObjects as $ldapObject) { $nameByLDAP = null; - if(isset($ldapObject[$nameAttribute]) + if (isset($ldapObject[$nameAttribute]) && is_array($ldapObject[$nameAttribute]) && isset($ldapObject[$nameAttribute][0]) ) { @@ -717,19 +716,19 @@ class Access extends LDAPUtility { } $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); - if($ncName) { + if ($ncName) { $nextcloudNames[] = $ncName; - if($isUsers) { + if ($isUsers) { $this->updateUserState($ncName); //cache the user names so it does not need to be retrieved //again later (e.g. sharing dialogue). - if(is_null($nameByLDAP)) { + if (is_null($nameByLDAP)) { continue; } $sndName = isset($ldapObject[$sndAttribute][0]) ? $ldapObject[$sndAttribute][0] : ''; $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); - } elseif($nameByLDAP !== null) { + } elseif ($nameByLDAP !== null) { $this->cacheGroupDisplayName($ncName, $nameByLDAP); } } @@ -745,7 +744,7 @@ class Access extends LDAPUtility { */ public function updateUserState($ncname) { $user = $this->userManager->get($ncname); - if($user instanceof OfflineUser) { + if ($user instanceof OfflineUser) { $user->unmark(); } } @@ -785,7 +784,7 @@ class Access extends LDAPUtility { */ public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { $user = $this->userManager->get($ocName); - if($user === null) { + if ($user === null) { return; } $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); @@ -810,9 +809,9 @@ class Access extends LDAPUtility { $attempts = 0; //while loop is just a precaution. If a name is not generated within //20 attempts, something else is very wrong. Avoids infinite loop. - while($attempts < 20){ + while ($attempts < 20) { $altName = $name . '_' . rand(1000,9999); - if(!$this->ncUserManager->userExists($altName)) { + if (!$this->ncUserManager->userExists($altName)) { return $altName; } $attempts++; @@ -834,7 +833,7 @@ class Access extends LDAPUtility { */ private function _createAltInternalOwnCloudNameForGroups($name) { $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); - if(!$usedNames || count($usedNames) === 0) { + if (!$usedNames || count($usedNames) === 0) { $lastNo = 1; //will become name_2 } else { natsort($usedNames); @@ -845,11 +844,11 @@ class Access extends LDAPUtility { unset($usedNames); $attempts = 1; - while($attempts < 21){ + while ($attempts < 21) { // Check to be really sure it is unique // while loop is just a precaution. If a name is not generated within // 20 attempts, something else is very wrong. Avoids infinite loop. - if(!\OC::$server->getGroupManager()->groupExists($altName)) { + if (!\OC::$server->getGroupManager()->groupExists($altName)) { return $altName; } $altName = $name . '_' . ($lastNo + $attempts); @@ -867,7 +866,7 @@ class Access extends LDAPUtility { private function createAltInternalOwnCloudName($name, $isUser) { $originalTTL = $this->connection->ldapCacheTTL; $this->connection->setConfiguration(['ldapCacheTTL' => 0]); - if($isUser) { + if ($isUser) { $altName = $this->_createAltInternalOwnCloudNameForUsers($name); } else { $altName = $this->_createAltInternalOwnCloudNameForGroups($name); @@ -916,13 +915,13 @@ class Access extends LDAPUtility { public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) { $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); $recordsToUpdate = $ldapRecords; - if(!$forceApplyAttributes) { + if (!$forceApplyAttributes) { $isBackgroundJobModeAjax = $this->config ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) { $newlyMapped = false; $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record); - if(is_string($uid)) { + if (is_string($uid)) { $this->cacheUserExists($uid); } return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax); @@ -942,13 +941,13 @@ class Access extends LDAPUtility { */ public function batchApplyUserAttributes(array $ldapRecords) { $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); - foreach($ldapRecords as $userRecord) { - if(!isset($userRecord[$displayNameAttribute])) { + foreach ($ldapRecords as $userRecord) { + if (!isset($userRecord[$displayNameAttribute])) { // displayName is obligatory continue; } $ocName = $this->dn2ocname($userRecord['dn'][0], null, true); - if($ocName === false) { + if ($ocName === false) { continue; } $this->updateUserState($ocName); @@ -976,7 +975,7 @@ class Access extends LDAPUtility { array_walk($groupRecords, function ($record) { $newlyMapped = false; $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record); - if(!$newlyMapped && is_string($gid)) { + if (!$newlyMapped && is_string($gid)) { $this->cacheGroupExists($gid); } }); @@ -989,8 +988,8 @@ class Access extends LDAPUtility { * @return array */ private function fetchList($list, $manyAttributes) { - if(is_array($list)) { - if($manyAttributes) { + if (is_array($list)) { + if ($manyAttributes) { return $list; } else { $list = array_reduce($list, function ($carry, $item) { @@ -1020,7 +1019,7 @@ class Access extends LDAPUtility { */ public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { $result = []; - foreach($this->connection->ldapBaseUsers as $base) { + foreach ($this->connection->ldapBaseUsers as $base) { $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); } return $result; @@ -1036,7 +1035,7 @@ class Access extends LDAPUtility { */ public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) { $result = false; - foreach($this->connection->ldapBaseUsers as $base) { + foreach ($this->connection->ldapBaseUsers as $base) { $count = $this->count($filter, [$base], $attr, $limit, $offset); $result = is_int($count) ? (int)$result + $count : $result; } @@ -1057,7 +1056,7 @@ class Access extends LDAPUtility { */ public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { $result = []; - foreach($this->connection->ldapBaseGroups as $base) { + foreach ($this->connection->ldapBaseGroups as $base) { $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); } return $result; @@ -1075,7 +1074,7 @@ class Access extends LDAPUtility { */ public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) { $result = false; - foreach($this->connection->ldapBaseGroups as $base) { + foreach ($this->connection->ldapBaseGroups as $base) { $count = $this->count($filter, [$base], $attr, $limit, $offset); $result = is_int($count) ? (int)$result + $count : $result; } @@ -1092,7 +1091,7 @@ class Access extends LDAPUtility { */ public function countObjects($limit = null, $offset = null) { $result = false; - foreach($this->connection->ldapBase as $base) { + foreach ($this->connection->ldapBase as $base) { $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset); $result = is_int($count) ? (int)$result + $count : $result; } @@ -1137,7 +1136,7 @@ class Access extends LDAPUtility { $this->connection->resetConnectionResource(); $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { // Seems like we didn't find any resource. \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG); throw $e; @@ -1162,13 +1161,13 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { - if(!is_null($attr) && !is_array($attr)) { + if (!is_null($attr) && !is_array($attr)) { $attr = [mb_strtolower($attr, 'UTF-8')]; } // See if we have a resource, in case not cancel with message $cr = $this->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { // Seems like we didn't find any resource. // Return an empty array just like before. \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG); @@ -1182,7 +1181,7 @@ class Access extends LDAPUtility { $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); // cannot use $cr anymore, might have changed in the previous call! $error = $this->ldap->errno($this->connection->getConnectionResource()); - if(!is_array($sr) || $error !== 0) { + if (!is_array($sr) || $error !== 0) { \OCP\Util::writeLog('user_ldap', 'Attempt for Paging? '.print_r($pagedSearchOK, true), ILogger::ERROR); return false; } @@ -1207,26 +1206,26 @@ class Access extends LDAPUtility { */ private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { $cookie = null; - if($pagedSearchOK) { + if ($pagedSearchOK) { $cr = $this->connection->getConnectionResource(); - foreach($sr as $key => $res) { - if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { + foreach ($sr as $key => $res) { + if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); } } //browsing through prior pages to get the cookie for the new one - if($skipHandling) { + if ($skipHandling) { return false; } // if count is bigger, then the server does not support // paged search. Instead, he did a normal search. We set a // flag here, so the callee knows how to deal with it. - if($iFoundItems <= $limit) { + if ($iFoundItems <= $limit) { $this->pagedSearchedSuccessful = true; } } else { - if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { + if (!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { \OC::$server->getLogger()->debug( 'Paged search was not available', [ 'app' => 'user_ldap' ] @@ -1259,7 +1258,7 @@ class Access extends LDAPUtility { \OCP\Util::writeLog('user_ldap', 'Count filter: '.print_r($filter, true), ILogger::DEBUG); $limitPerPage = (int)$this->connection->ldapPagingSize; - if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { + if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) { $limitPerPage = $limit; } @@ -1269,7 +1268,7 @@ class Access extends LDAPUtility { do { $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); - if($search === false) { + if ($search === false) { return $counter > 0 ? $counter : false; } list($sr, $pagedSearchOK) = $search; @@ -1288,7 +1287,7 @@ class Access extends LDAPUtility { * Continue now depends on $hasMorePages value */ $continue = $pagedSearchOK && $hasMorePages; - } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); + } while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); return $counter; } @@ -1301,7 +1300,7 @@ class Access extends LDAPUtility { private function countEntriesInSearchResults($searchResults) { $counter = 0; - foreach($searchResults as $res) { + foreach ($searchResults as $res) { $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res); $counter += $count; } @@ -1323,7 +1322,7 @@ class Access extends LDAPUtility { */ public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { $limitPerPage = (int)$this->connection->ldapPagingSize; - if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { + if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) { $limitPerPage = $limit; } @@ -1337,13 +1336,13 @@ class Access extends LDAPUtility { $savedoffset = $offset; do { $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); - if($search === false) { + if ($search === false) { return []; } list($sr, $pagedSearchOK) = $search; $cr = $this->connection->getConnectionResource(); - if($skipHandling) { + if ($skipHandling) { //i.e. result do not need to be fetched, we just need the cookie //thus pass 1 or any other value as $iFoundItems because it is not //used @@ -1354,7 +1353,7 @@ class Access extends LDAPUtility { } $iFoundItems = 0; - foreach($sr as $res) { + foreach ($sr as $res) { $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); $iFoundItems = max($iFoundItems, $findings['count']); unset($findings['count']); @@ -1370,27 +1369,27 @@ class Access extends LDAPUtility { // if we're here, probably no connection resource is returned. // to make Nextcloud behave nicely, we simply give back an empty array. - if(is_null($findings)) { + if (is_null($findings)) { return []; } - if(!is_null($attr)) { + if (!is_null($attr)) { $selection = []; $i = 0; - foreach($findings as $item) { - if(!is_array($item)) { + foreach ($findings as $item) { + if (!is_array($item)) { continue; } $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); - foreach($attr as $key) { - if(isset($item[$key])) { - if(is_array($item[$key]) && isset($item[$key]['count'])) { + foreach ($attr as $key) { + if (isset($item[$key])) { + if (is_array($item[$key]) && isset($item[$key]['count'])) { unset($item[$key]['count']); } - if($key !== 'dn') { - if($this->resemblesDN($key)) { + if ($key !== 'dn') { + if ($this->resemblesDN($key)) { $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]); - } elseif($key === 'objectguid' || $key === 'guid') { + } elseif ($key === 'objectguid' || $key === 'guid') { $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])]; } else { $selection[$i][$key] = $item[$key]; @@ -1399,7 +1398,6 @@ class Access extends LDAPUtility { $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])]; } } - } $i++; } @@ -1408,7 +1406,7 @@ class Access extends LDAPUtility { //we slice the findings, when //a) paged search unsuccessful, though attempted //b) no paged search, but limit set - if((!$this->getPagedSearchResultState() + if ((!$this->getPagedSearchResultState() && $pagedSearchOK) || ( !$pagedSearchOK @@ -1428,13 +1426,13 @@ class Access extends LDAPUtility { public function sanitizeUsername($name) { $name = trim($name); - if($this->connection->ldapIgnoreNamingRules) { + if ($this->connection->ldapIgnoreNamingRules) { return $name; } // Transliteration to ASCII $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name); - if($transliterated !== false) { + if ($transliterated !== false) { // depending on system config iconv can work or not $name = $transliterated; } @@ -1445,7 +1443,7 @@ class Access extends LDAPUtility { // Every remaining disallowed characters will be removed $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); - if($name === '') { + if ($name === '') { throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters'); } @@ -1460,7 +1458,7 @@ class Access extends LDAPUtility { */ public function escapeFilterPart($input, $allowAsterisk = false) { $asterisk = ''; - if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { + if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { $asterisk = '*'; $input = mb_substr($input, 1, null, 'UTF-8'); } @@ -1496,7 +1494,7 @@ class Access extends LDAPUtility { */ private function combineFilter($filters, $operator) { $combinedFilter = '('.$operator; - foreach($filters as $filter) { + foreach ($filters as $filter) { if ($filter !== '' && $filter[0] !== '(') { $filter = '('.$filter.')'; } @@ -1538,16 +1536,16 @@ class Access extends LDAPUtility { * @throws \Exception */ private function getAdvancedFilterPartForSearch($search, $searchAttributes) { - if(!is_array($searchAttributes) || count($searchAttributes) < 2) { + if (!is_array($searchAttributes) || count($searchAttributes) < 2) { throw new \Exception('searchAttributes must be an array with at least two string'); } $searchWords = explode(' ', trim($search)); $wordFilters = []; - foreach($searchWords as $word) { + foreach ($searchWords as $word) { $word = $this->prepareSearchTerm($word); //every word needs to appear at least once $wordMatchOneAttrFilters = []; - foreach($searchAttributes as $attr) { + foreach ($searchAttributes as $attr) { $wordMatchOneAttrFilters[] = $attr . '=' . $word; } $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); @@ -1566,10 +1564,10 @@ class Access extends LDAPUtility { private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { $filter = []; $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); - if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { + if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { try { return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); - } catch(\Exception $e) { + } catch (\Exception $e) { \OCP\Util::writeLog( 'user_ldap', 'Creating advanced filter for search failed, falling back to simple method.', @@ -1579,17 +1577,17 @@ class Access extends LDAPUtility { } $search = $this->prepareSearchTerm($search); - if(!is_array($searchAttributes) || count($searchAttributes) === 0) { + if (!is_array($searchAttributes) || count($searchAttributes) === 0) { if ($fallbackAttribute === '') { return ''; } $filter[] = $fallbackAttribute . '=' . $search; } else { - foreach($searchAttributes as $attribute) { + foreach ($searchAttributes as $attribute) { $filter[] = $attribute . '=' . $search; } } - if(count($filter) === 1) { + if (count($filter) === 1) { return '('.$filter[0].')'; } return $this->combineFilterWithOr($filter); @@ -1640,7 +1638,7 @@ class Access extends LDAPUtility { 'ldapAgentName' => $name, 'ldapAgentPassword' => $password ]; - if(!$testConnection->setConfiguration($credentials)) { + if (!$testConnection->setConfiguration($credentials)) { return false; } return $testConnection->bind(); @@ -1662,30 +1660,30 @@ class Access extends LDAPUtility { // Sacrebleu! The UUID attribute is unknown :( We need first an // existing DN to be able to reliably detect it. $result = $this->search($filter, $base, ['dn'], 1); - if(!isset($result[0]) || !isset($result[0]['dn'])) { + if (!isset($result[0]) || !isset($result[0]['dn'])) { throw new \Exception('Cannot determine UUID attribute'); } $dn = $result[0]['dn'][0]; - if(!$this->detectUuidAttribute($dn, true)) { + if (!$this->detectUuidAttribute($dn, true)) { throw new \Exception('Cannot determine UUID attribute'); } } else { // The UUID attribute is either known or an override is given. // By calling this method we ensure that $this->connection->$uuidAttr // is definitely set - if(!$this->detectUuidAttribute('', true)) { + if (!$this->detectUuidAttribute('', true)) { throw new \Exception('Cannot determine UUID attribute'); } } $uuidAttr = $this->connection->ldapUuidUserAttribute; - if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { + if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { $uuid = $this->formatGuid2ForFilterUser($uuid); } $filter = $uuidAttr . '=' . $uuid; $result = $this->searchUsers($filter, ['dn'], 2); - if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { + if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { // we put the count into account to make sure that this is // really unique return $result[0]['dn'][0]; @@ -1705,7 +1703,7 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) { - if($isUser) { + if ($isUser) { $uuidAttr = 'ldapUuidUserAttribute'; $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; } else { @@ -1713,8 +1711,8 @@ class Access extends LDAPUtility { $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; } - if(!$force) { - if($this->connection->$uuidAttr !== 'auto') { + if (!$force) { + if ($this->connection->$uuidAttr !== 'auto') { return true; } elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') { $this->connection->$uuidAttr = $uuidOverride; @@ -1722,23 +1720,23 @@ class Access extends LDAPUtility { } $attribute = $this->connection->getFromCache($uuidAttr); - if(!$attribute === null) { + if (!$attribute === null) { $this->connection->$uuidAttr = $attribute; return true; } } - foreach(self::UUID_ATTRIBUTES as $attribute) { - if($ldapRecord !== null) { + foreach (self::UUID_ATTRIBUTES as $attribute) { + if ($ldapRecord !== null) { // we have the info from LDAP already, we don't need to talk to the server again - if(isset($ldapRecord[$attribute])) { + if (isset($ldapRecord[$attribute])) { $this->connection->$uuidAttr = $attribute; return true; } } $value = $this->readAttribute($dn, $attribute); - if(is_array($value) && isset($value[0]) && !empty($value[0])) { + if (is_array($value) && isset($value[0]) && !empty($value[0])) { \OC::$server->getLogger()->debug( 'Setting {attribute} as {subject}', [ @@ -1765,7 +1763,7 @@ class Access extends LDAPUtility { * @throws ServerNotAvailableException */ public function getUUID($dn, $isUser = true, $ldapRecord = null) { - if($isUser) { + if ($isUser) { $uuidAttr = 'ldapUuidUserAttribute'; $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; } else { @@ -1774,18 +1772,17 @@ class Access extends LDAPUtility { } $uuid = false; - if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { + if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { $attr = $this->connection->$uuidAttr; $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr); - if(!is_array($uuid) + if (!is_array($uuid) && $uuidOverride !== '' - && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) - { + && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) { $uuid = isset($ldapRecord[$this->connection->$uuidAttr]) ? $ldapRecord[$this->connection->$uuidAttr] : $this->readAttribute($dn, $this->connection->$uuidAttr); } - if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { + if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { $uuid = $uuid[0]; } } @@ -1802,15 +1799,15 @@ class Access extends LDAPUtility { private function convertObjectGUID2Str($oguid) { $hex_guid = bin2hex($oguid); $hex_guid_to_guid_str = ''; - for($k = 1; $k <= 4; ++$k) { + for ($k = 1; $k <= 4; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { + for ($k = 1; $k <= 2; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-'; - for($k = 1; $k <= 2; ++$k) { + for ($k = 1; $k <= 2; ++$k) { $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); } $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); @@ -1831,11 +1828,11 @@ class Access extends LDAPUtility { * @return string */ public function formatGuid2ForFilterUser($guid) { - if(!is_string($guid)) { + if (!is_string($guid)) { throw new \InvalidArgumentException('String expected'); } $blocks = explode('-', $guid); - if(count($blocks) !== 5) { + if (count($blocks) !== 5) { /* * Why not throw an Exception instead? This method is a utility * called only when trying to figure out whether a "missing" known @@ -1854,12 +1851,12 @@ class Access extends LDAPUtility { ); return $guid; } - for($i=0; $i < 3; $i++) { + for ($i=0; $i < 3; $i++) { $pairs = str_split($blocks[$i], 2); $pairs = array_reverse($pairs); $blocks[$i] = implode('', $pairs); } - for($i=0; $i < 5; $i++) { + for ($i=0; $i < 5; $i++) { $pairs = str_split($blocks[$i], 2); $blocks[$i] = '\\' . implode('\\', $pairs); } @@ -1877,12 +1874,12 @@ class Access extends LDAPUtility { $domainDN = $this->getDomainDNFromDN($dn); $cacheKey = 'getSID-'.$domainDN; $sid = $this->connection->getFromCache($cacheKey); - if(!is_null($sid)) { + if (!is_null($sid)) { return $sid; } $objectSid = $this->readAttribute($domainDN, 'objectsid'); - if(!is_array($objectSid) || empty($objectSid)) { + if (!is_array($objectSid) || empty($objectSid)) { $this->connection->writeToCache($cacheKey, false); return false; } @@ -1940,12 +1937,12 @@ class Access extends LDAPUtility { $belongsToBase = false; $bases = $this->helper->sanitizeDN($bases); - foreach($bases as $base) { + foreach ($bases as $base) { $belongsToBase = true; - if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { + if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { $belongsToBase = false; } - if($belongsToBase) { + if ($belongsToBase) { break; } } @@ -1974,16 +1971,16 @@ class Access extends LDAPUtility { * @return string containing the key or empty if none is cached */ private function getPagedResultCookie($base, $filter, $limit, $offset) { - if($offset === 0) { + if ($offset === 0) { return ''; } $offset -= $limit; //we work with cache here $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; $cookie = ''; - if(isset($this->cookies[$cacheKey])) { + if (isset($this->cookies[$cacheKey])) { $cookie = $this->cookies[$cacheKey]; - if(is_null($cookie)) { + if (is_null($cookie)) { $cookie = ''; } } @@ -2001,7 +1998,7 @@ class Access extends LDAPUtility { * @return bool */ public function hasMoreResults() { - if(empty($this->lastCookie) && $this->lastCookie !== '0') { + if (empty($this->lastCookie) && $this->lastCookie !== '0') { // as in RFC 2696, when all results are returned, the cookie will // be empty. return false; @@ -2021,7 +2018,7 @@ class Access extends LDAPUtility { */ private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { // allow '0' for 389ds - if(!empty($cookie) || $cookie === '0') { + if (!empty($cookie) || $cookie === '0') { $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; $this->cookies[$cacheKey] = $cookie; $this->lastCookie = $cookie; @@ -2058,10 +2055,9 @@ class Access extends LDAPUtility { .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, ILogger::DEBUG); //get the cookie from the search for the previous search, required by LDAP - foreach($bases as $base) { - + foreach ($bases as $base) { $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); - if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { + if (empty($cookie) && $cookie !== "0" && ($offset > 0)) { // no cookie known from a potential previous search. We need // to start from 0 to come to the desired page. cookie value // of '0' is valid, because 389ds @@ -2071,17 +2067,17 @@ class Access extends LDAPUtility { //still no cookie? obviously, the server does not like us. Let's skip paging efforts. // '0' is valid, because 389ds //TODO: remember this, probably does not change in the next request... - if(empty($cookie) && $cookie !== '0') { + if (empty($cookie) && $cookie !== '0') { $cookie = null; } } - if(!is_null($cookie)) { + if (!is_null($cookie)) { //since offset = 0, this is a new search. We abandon other searches that might be ongoing. $this->abandonPagedSearch(); $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', $this->connection->getConnectionResource(), $limit, false, $cookie); - if(!$pagedSearchOK) { + if (!$pagedSearchOK) { return false; } \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG); @@ -2089,14 +2085,13 @@ class Access extends LDAPUtility { $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset); \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]); } - } - /* ++ Fixing RHDS searches with pages with zero results ++ - * We coudn't get paged searches working with our RHDS for login ($limit = 0), - * due to pages with zero results. - * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination - * if we don't have a previous paged search. - */ + /* ++ Fixing RHDS searches with pages with zero results ++ + * We coudn't get paged searches working with our RHDS for login ($limit = 0), + * due to pages with zero results. + * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination + * if we don't have a previous paged search. + */ } elseif ($limit === 0 && !empty($this->lastCookie)) { // a search without limit was requested. However, if we do use // Paged Search once, we always must do it. This requires us to @@ -2125,5 +2120,4 @@ class Access extends LDAPUtility { } return false; } - } diff --git a/apps/user_ldap/lib/AccessFactory.php b/apps/user_ldap/lib/AccessFactory.php index 04d72a16f29..a85823a4564 100644 --- a/apps/user_ldap/lib/AccessFactory.php +++ b/apps/user_ldap/lib/AccessFactory.php @@ -44,8 +44,7 @@ class AccessFactory { Manager $userManager, Helper $helper, IConfig $config, - IUserManager $ncUserManager) - { + IUserManager $ncUserManager) { $this->ldap = $ldap; $this->userManager = $userManager; $this->helper = $helper; diff --git a/apps/user_ldap/lib/Command/CheckUser.php b/apps/user_ldap/lib/Command/CheckUser.php index 5b837e47b8e..430e9c35960 100644 --- a/apps/user_ldap/lib/Command/CheckUser.php +++ b/apps/user_ldap/lib/Command/CheckUser.php @@ -92,9 +92,9 @@ class CheckUser extends Command { $this->isAllowed($input->getOption('force')); $this->confirmUserIsMapped($uid); $exists = $this->backend->userExistsOnLDAP($uid); - if($exists === true) { + if ($exists === true) { $output->writeln('The user is still available on LDAP.'); - if($input->getOption('update')) { + if ($input->getOption('update')) { $this->updateUser($uid, $output); } return; @@ -130,7 +130,7 @@ class CheckUser extends Command { * @return true */ protected function isAllowed($force) { - if($this->helper->haveDisabledConfigurations() && !$force) { + if ($this->helper->haveDisabledConfigurations() && !$force) { throw new \Exception('Cannot check user existence, because ' . 'disabled LDAP configurations are present.'); } @@ -163,5 +163,4 @@ class CheckUser extends Command { $output->writeln('Error while trying to lookup and update attributes from LDAP'); } } - } diff --git a/apps/user_ldap/lib/Command/CreateEmptyConfig.php b/apps/user_ldap/lib/Command/CreateEmptyConfig.php index fab9c513141..8b2b19a5175 100644 --- a/apps/user_ldap/lib/Command/CreateEmptyConfig.php +++ b/apps/user_ldap/lib/Command/CreateEmptyConfig.php @@ -63,7 +63,7 @@ class CreateEmptyConfig extends Command { $configHolder->saveConfiguration(); $prose = ''; - if(!$input->getOption('only-print-prefix')) { + if (!$input->getOption('only-print-prefix')) { $prose = 'Created new configuration with configID '; } $output->writeln($prose . "{$configPrefix}"); diff --git a/apps/user_ldap/lib/Command/DeleteConfig.php b/apps/user_ldap/lib/Command/DeleteConfig.php index f62caf2902a..fd075ae70c3 100644 --- a/apps/user_ldap/lib/Command/DeleteConfig.php +++ b/apps/user_ldap/lib/Command/DeleteConfig.php @@ -61,7 +61,7 @@ class DeleteConfig extends Command { $success = $this->helper->deleteServerConfiguration($configPrefix); - if($success) { + if ($success) { $output->writeln("Deleted configuration with configID '{$configPrefix}'"); } else { $output->writeln("Cannot delete configuration with configID '{$configPrefix}'"); diff --git a/apps/user_ldap/lib/Command/Search.php b/apps/user_ldap/lib/Command/Search.php index edd4fa71ba0..3c05d6cc2ee 100644 --- a/apps/user_ldap/lib/Command/Search.php +++ b/apps/user_ldap/lib/Command/Search.php @@ -90,16 +90,16 @@ class Search extends Command { * @throws \InvalidArgumentException */ protected function validateOffsetAndLimit($offset, $limit) { - if($limit < 0) { + if ($limit < 0) { throw new \InvalidArgumentException('limit must be 0 or greater'); } - if($offset < 0) { + if ($offset < 0) { throw new \InvalidArgumentException('offset must be 0 or greater'); } - if($limit === 0 && $offset !== 0) { + if ($limit === 0 && $offset !== 0) { throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0'); } - if($offset > 0 && ($offset % $limit !== 0)) { + if ($offset > 0 && ($offset % $limit !== 0)) { throw new \InvalidArgumentException('offset must be a multiple of limit'); } } @@ -113,7 +113,7 @@ class Search extends Command { $limit = (int)$input->getOption('limit'); $this->validateOffsetAndLimit($offset, $limit); - if($input->getOption('group')) { + if ($input->getOption('group')) { $proxy = new Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager')); $getMethod = 'getGroups'; $printID = false; @@ -136,7 +136,7 @@ class Search extends Command { } $result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset); - foreach($result as $id => $name) { + foreach ($result as $id => $name) { $line = $name . ($printID ? ' ('.$id.')' : ''); $output->writeln($line); } diff --git a/apps/user_ldap/lib/Command/SetConfig.php b/apps/user_ldap/lib/Command/SetConfig.php index a1ddf3a591a..4c8c47b6411 100644 --- a/apps/user_ldap/lib/Command/SetConfig.php +++ b/apps/user_ldap/lib/Command/SetConfig.php @@ -36,7 +36,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SetConfig extends Command { - protected function configure() { $this ->setName('ldap:set-config') @@ -63,7 +62,7 @@ class SetConfig extends Command { $helper = new Helper(\OC::$server->getConfig()); $availableConfigs = $helper->getServerConfigurationPrefixes(); $configID = $input->getArgument('configID'); - if(!in_array($configID, $availableConfigs)) { + if (!in_array($configID, $availableConfigs)) { $output->writeln("Invalid configID"); return; } diff --git a/apps/user_ldap/lib/Command/ShowConfig.php b/apps/user_ldap/lib/Command/ShowConfig.php index f4af798d433..cbd94287f9b 100644 --- a/apps/user_ldap/lib/Command/ShowConfig.php +++ b/apps/user_ldap/lib/Command/ShowConfig.php @@ -69,9 +69,9 @@ class ShowConfig extends Command { protected function execute(InputInterface $input, OutputInterface $output) { $availableConfigs = $this->helper->getServerConfigurationPrefixes(); $configID = $input->getArgument('configID'); - if(!is_null($configID)) { + if (!is_null($configID)) { $configIDs[] = $configID; - if(!in_array($configIDs[0], $availableConfigs)) { + if (!in_array($configIDs[0], $availableConfigs)) { $output->writeln("Invalid configID"); return; } @@ -89,7 +89,7 @@ class ShowConfig extends Command { * @param bool $withPassword Set to TRUE to show plaintext passwords in output */ protected function renderConfigs($configIDs, $output, $withPassword) { - foreach($configIDs as $id) { + foreach ($configIDs as $id) { $configHolder = new Configuration($id); $configuration = $configHolder->getConfiguration(); ksort($configuration); @@ -97,11 +97,11 @@ class ShowConfig extends Command { $table = new Table($output); $table->setHeaders(['Configuration', $id]); $rows = []; - foreach($configuration as $key => $value) { - if($key === 'ldapAgentPassword' && !$withPassword) { + foreach ($configuration as $key => $value) { + if ($key === 'ldapAgentPassword' && !$withPassword) { $value = '***'; } - if(is_array($value)) { + if (is_array($value)) { $value = implode(';', $value); } $rows[] = [$key, $value]; diff --git a/apps/user_ldap/lib/Command/TestConfig.php b/apps/user_ldap/lib/Command/TestConfig.php index 6ddd420e4f0..0973e6245b3 100644 --- a/apps/user_ldap/lib/Command/TestConfig.php +++ b/apps/user_ldap/lib/Command/TestConfig.php @@ -35,7 +35,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class TestConfig extends Command { - protected function configure() { $this ->setName('ldap:test-config') @@ -52,17 +51,17 @@ class TestConfig extends Command { $helper = new Helper(\OC::$server->getConfig()); $availableConfigs = $helper->getServerConfigurationPrefixes(); $configID = $input->getArgument('configID'); - if(!in_array($configID, $availableConfigs)) { + if (!in_array($configID, $availableConfigs)) { $output->writeln("Invalid configID"); return; } $result = $this->testConfig($configID); - if($result === 0) { + if ($result === 0) { $output->writeln('The configuration is valid and the connection could be established!'); - } elseif($result === 1) { + } elseif ($result === 1) { $output->writeln('The configuration is invalid. Please have a look at the logs for further details.'); - } elseif($result === 2) { + } elseif ($result === 2) { $output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.'); } else { $output->writeln('Your LDAP server was kidnapped by aliens.'); @@ -81,12 +80,12 @@ class TestConfig extends Command { //ensure validation is run before we attempt the bind $connection->getConfiguration(); - if(!$connection->setConfiguration([ + if (!$connection->setConfiguration([ 'ldap_configuration_active' => 1, ])) { return 1; } - if($connection->bind()) { + if ($connection->bind()) { return 0; } return 2; diff --git a/apps/user_ldap/lib/Configuration.php b/apps/user_ldap/lib/Configuration.php index ccba7b43586..4076a6e8a3d 100644 --- a/apps/user_ldap/lib/Configuration.php +++ b/apps/user_ldap/lib/Configuration.php @@ -118,7 +118,7 @@ class Configuration { */ public function __construct($configPrefix, $autoRead = true) { $this->configPrefix = $configPrefix; - if($autoRead) { + if ($autoRead) { $this->readConfiguration(); } } @@ -128,7 +128,7 @@ class Configuration { * @return mixed|null */ public function __get($name) { - if(isset($this->config[$name])) { + if (isset($this->config[$name])) { return $this->config[$name]; } return null; @@ -159,22 +159,22 @@ class Configuration { * @return false|null */ public function setConfiguration($config, &$applied = null) { - if(!is_array($config)) { + if (!is_array($config)) { return false; } $cta = $this->getConfigTranslationArray(); - foreach($config as $inputKey => $val) { - if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) { + foreach ($config as $inputKey => $val) { + if (strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) { $key = $cta[$inputKey]; - } elseif(array_key_exists($inputKey, $this->config)) { + } elseif (array_key_exists($inputKey, $this->config)) { $key = $inputKey; } else { continue; } $setMethod = 'setValue'; - switch($key) { + switch ($key) { case 'ldapAgentPassword': $setMethod = 'setRawValue'; break; @@ -198,7 +198,7 @@ class Configuration { break; } $this->$setMethod($key, $val); - if(is_array($applied)) { + if (is_array($applied)) { $applied[] = $inputKey; // storing key as index avoids duplication, and as value for simplicity } @@ -208,15 +208,15 @@ class Configuration { } public function readConfiguration() { - if(!$this->configRead && !is_null($this->configPrefix)) { + if (!$this->configRead && !is_null($this->configPrefix)) { $cta = array_flip($this->getConfigTranslationArray()); - foreach($this->config as $key => $val) { - if(!isset($cta[$key])) { + foreach ($this->config as $key => $val) { + if (!isset($cta[$key])) { //some are determined continue; } $dbKey = $cta[$key]; - switch($key) { + switch ($key) { case 'ldapBase': case 'ldapBaseUsers': case 'ldapBaseGroups': @@ -259,7 +259,7 @@ class Configuration { */ public function saveConfiguration() { $cta = array_flip($this->getConfigTranslationArray()); - foreach($this->unsavedChanges as $key) { + foreach ($this->unsavedChanges as $key) { $value = $this->config[$key]; switch ($key) { case 'ldapAgentPassword': @@ -275,7 +275,7 @@ class Configuration { case 'ldapGroupFilterObjectclass': case 'ldapGroupFilterGroups': case 'ldapLoginFilterAttributes': - if(is_array($value)) { + if (is_array($value)) { $value = implode("\n", $value); } break; @@ -285,7 +285,7 @@ class Configuration { case 'ldapUuidGroupAttribute': continue 2; } - if(is_null($value)) { + if (is_null($value)) { $value = ''; } $this->saveValue($cta[$key], $value); @@ -300,7 +300,7 @@ class Configuration { */ protected function getMultiLine($varName) { $value = $this->getValue($varName); - if(empty($value)) { + if (empty($value)) { $value = ''; } else { $value = preg_split('/\r\n|\r|\n/', $value); @@ -316,21 +316,21 @@ class Configuration { * @param array|string $value to set */ protected function setMultiLine($varName, $value) { - if(empty($value)) { + if (empty($value)) { $value = ''; } elseif (!is_array($value)) { $value = preg_split('/\r\n|\r|\n|;/', $value); - if($value === false) { + if ($value === false) { $value = ''; } } - if(!is_array($value)) { + if (!is_array($value)) { $finalValue = trim($value); } else { $finalValue = []; - foreach($value as $key => $val) { - if(is_string($val)) { + foreach ($value as $key => $val) { + if (is_string($val)) { $val = trim($val); if ($val !== '') { //accidental line breaks are not wanted and can cause @@ -377,7 +377,7 @@ class Configuration { */ protected function getValue($varName) { static $defaults; - if(is_null($defaults)) { + if (is_null($defaults)) { $defaults = $this->getDefaults(); } return \OC::$server->getConfig()->getAppValue('user_ldap', @@ -392,7 +392,7 @@ class Configuration { * @param mixed $value to set */ protected function setValue($varName, $value) { - if(is_string($value)) { + if (is_string($value)) { $value = trim($value); } $this->config[$varName] = $value; @@ -554,7 +554,7 @@ class Configuration { * @throws \RuntimeException */ public function resolveRule($rule) { - if($rule === 'avatar') { + if ($rule === 'avatar') { return $this->getAvatarAttributes(); } throw new \RuntimeException('Invalid rule'); @@ -564,20 +564,19 @@ class Configuration { $value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT; $defaultAttributes = ['jpegphoto', 'thumbnailphoto']; - if($value === self::AVATAR_PREFIX_NONE) { + if ($value === self::AVATAR_PREFIX_NONE) { return []; } - if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) { + if (strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) { $attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE))); - if($attribute === '') { + if ($attribute === '') { return $defaultAttributes; } return [strtolower($attribute)]; } - if($value !== self::AVATAR_PREFIX_DEFAULT) { + if ($value !== self::AVATAR_PREFIX_DEFAULT) { \OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.'); } return $defaultAttributes; } - } diff --git a/apps/user_ldap/lib/Connection.php b/apps/user_ldap/lib/Connection.php index 51c35c2a665..cec4866b0ea 100644 --- a/apps/user_ldap/lib/Connection.php +++ b/apps/user_ldap/lib/Connection.php @@ -111,7 +111,7 @@ class Connection extends LDAPUtility { $this->configuration = new Configuration($configPrefix, !is_null($configID)); $memcache = \OC::$server->getMemCacheFactory(); - if($memcache->isAvailable()) { + if ($memcache->isAvailable()) { $this->cache = $memcache->createDistributed(); } $helper = new Helper(\OC::$server->getConfig()); @@ -120,7 +120,7 @@ class Connection extends LDAPUtility { } public function __destruct() { - if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { + if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { @$this->ldap->unbind($this->ldapConnectionRes); $this->bindResult = []; } @@ -132,7 +132,7 @@ class Connection extends LDAPUtility { public function __clone() { $this->configuration = new Configuration($this->configPrefix, !is_null($this->configID)); - if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { + if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { $this->bindResult = []; } $this->ldapConnectionRes = null; @@ -144,7 +144,7 @@ class Connection extends LDAPUtility { * @return bool|mixed */ public function __get($name) { - if(!$this->configured) { + if (!$this->configured) { $this->readConfiguration(); } @@ -160,7 +160,7 @@ class Connection extends LDAPUtility { $before = $this->configuration->$name; $this->configuration->$name = $value; $after = $this->configuration->$name; - if($before !== $after) { + if ($before !== $after) { if ($this->configID !== '' && $this->configID !== null) { $this->configuration->saveConfiguration(); } @@ -200,13 +200,13 @@ class Connection extends LDAPUtility { * Returns the LDAP handler */ public function getConnectionResource() { - if(!$this->ldapConnectionRes) { + if (!$this->ldapConnectionRes) { $this->init(); - } elseif(!$this->ldap->isResource($this->ldapConnectionRes)) { + } elseif (!$this->ldap->isResource($this->ldapConnectionRes)) { $this->ldapConnectionRes = null; $this->establishConnection(); } - if(is_null($this->ldapConnectionRes)) { + if (is_null($this->ldapConnectionRes)) { \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); throw new ServerNotAvailableException('Connection to LDAP server could not be established'); } @@ -217,7 +217,7 @@ class Connection extends LDAPUtility { * resets the connection resource */ public function resetConnectionResource() { - if(!is_null($this->ldapConnectionRes)) { + if (!is_null($this->ldapConnectionRes)) { @$this->ldap->unbind($this->ldapConnectionRes); $this->ldapConnectionRes = null; $this->bindResult = []; @@ -230,7 +230,7 @@ class Connection extends LDAPUtility { */ private function getCacheKey($key) { $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; - if(is_null($key)) { + if (is_null($key)) { return $prefix; } return $prefix.hash('sha256', $key); @@ -241,10 +241,10 @@ class Connection extends LDAPUtility { * @return mixed|null */ public function getFromCache($key) { - if(!$this->configured) { + if (!$this->configured) { $this->readConfiguration(); } - if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { + if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) { return null; } $key = $this->getCacheKey($key); @@ -259,10 +259,10 @@ class Connection extends LDAPUtility { * @return string */ public function writeToCache($key, $value) { - if(!$this->configured) { + if (!$this->configured) { $this->readConfiguration(); } - if(is_null($this->cache) + if (is_null($this->cache) || !$this->configuration->ldapCacheTTL || !$this->configuration->ldapConfigurationActive) { return null; @@ -273,7 +273,7 @@ class Connection extends LDAPUtility { } public function clearCache() { - if(!is_null($this->cache)) { + if (!is_null($this->cache)) { $this->cache->clear($this->getCacheKey(null)); } } @@ -285,7 +285,7 @@ class Connection extends LDAPUtility { * @return null */ private function readConfiguration($force = false) { - if((!$this->configured || $force) && !is_null($this->configID)) { + if ((!$this->configured || $force) && !is_null($this->configID)) { $this->configuration->readConfiguration(); $this->configured = $this->validateConfiguration(); } @@ -298,12 +298,12 @@ class Connection extends LDAPUtility { * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters */ public function setConfiguration($config, &$setParameters = null) { - if(is_null($setParameters)) { + if (is_null($setParameters)) { $setParameters = []; } $this->doNotValidate = false; $this->configuration->setConfiguration($config, $setParameters); - if(count($setParameters) > 0) { + if (count($setParameters) > 0) { $this->configured = $this->validateConfiguration(); } @@ -330,10 +330,10 @@ class Connection extends LDAPUtility { $config = $this->configuration->getConfiguration(); $cta = $this->configuration->getConfigTranslationArray(); $result = []; - foreach($cta as $dbkey => $configkey) { - switch($configkey) { + foreach ($cta as $dbkey => $configkey) { + switch ($configkey) { case 'homeFolderNamingRule': - if(strpos($config[$configkey], 'attr:') === 0) { + if (strpos($config[$configkey], 'attr:') === 0) { $result[$dbkey] = substr($config[$configkey], 5); } else { $result[$dbkey] = ''; @@ -344,7 +344,7 @@ class Connection extends LDAPUtility { case 'ldapBaseGroups': case 'ldapAttributesForUserSearch': case 'ldapAttributesForGroupSearch': - if(is_array($config[$configkey])) { + if (is_array($config[$configkey])) { $result[$dbkey] = implode("\n", $config[$configkey]); break; } //else follows default @@ -357,23 +357,23 @@ class Connection extends LDAPUtility { private function doSoftValidation() { //if User or Group Base are not set, take over Base DN setting - foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { + foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { $val = $this->configuration->$keyBase; - if(empty($val)) { + if (empty($val)) { $this->configuration->$keyBase = $this->configuration->ldapBase; } } - foreach(['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', + foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] as $expertSetting => $effectiveSetting) { $uuidOverride = $this->configuration->$expertSetting; - if(!empty($uuidOverride)) { + if (!empty($uuidOverride)) { $this->configuration->$effectiveSetting = $uuidOverride; } else { $uuidAttributes = Access::UUID_ATTRIBUTES; array_unshift($uuidAttributes, 'auto'); - if(!in_array($this->configuration->$effectiveSetting, + if (!in_array($this->configuration->$effectiveSetting, $uuidAttributes) && (!is_null($this->configID))) { $this->configuration->$effectiveSetting = 'auto'; @@ -383,7 +383,6 @@ class Connection extends LDAPUtility { $effectiveSetting.', '.'reset to '. 'autodetect.', ILogger::INFO); } - } } @@ -395,14 +394,14 @@ class Connection extends LDAPUtility { //make sure empty search attributes are saved as simple, empty array $saKeys = ['ldapAttributesForUserSearch', 'ldapAttributesForGroupSearch']; - foreach($saKeys as $key) { + foreach ($saKeys as $key) { $val = $this->configuration->$key; - if(is_array($val) && count($val) === 1 && empty($val[0])) { + if (is_array($val) && count($val) === 1 && empty($val[0])) { $this->configuration->$key = []; } } - if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) + if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0) && $this->configuration->ldapTLS) { $this->configuration->ldapTLS = false; \OCP\Util::writeLog( @@ -424,10 +423,10 @@ class Connection extends LDAPUtility { //options that shall not be empty $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName', 'ldapGroupDisplayName', 'ldapLoginFilter']; - foreach($options as $key) { + foreach ($options as $key) { $val = $this->configuration->$key; - if(empty($val)) { - switch($key) { + if (empty($val)) { + switch ($key) { case 'ldapHost': $subj = 'LDAP Host'; break; @@ -475,7 +474,7 @@ class Connection extends LDAPUtility { $baseUsers = $this->configuration->ldapBaseUsers; $baseGroups = $this->configuration->ldapBaseGroups; - if(empty($base) && empty($baseUsers) && empty($baseGroups)) { + if (empty($base) && empty($baseUsers) && empty($baseGroups)) { \OCP\Util::writeLog( 'user_ldap', $errorStr.'Not a single Base DN given.', @@ -484,7 +483,7 @@ class Connection extends LDAPUtility { $configurationOK = false; } - if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') + if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') === false) { \OCP\Util::writeLog( 'user_ldap', @@ -502,8 +501,7 @@ class Connection extends LDAPUtility { * @return bool true if configuration seems OK, false otherwise */ private function validateConfiguration() { - - if($this->doNotValidate) { + if ($this->doNotValidate) { //don't do a validation if it is a new configuration with pure //default values. Will be allowed on changes via __set or //setConfiguration @@ -526,14 +524,14 @@ class Connection extends LDAPUtility { * @throws ServerNotAvailableException */ private function establishConnection() { - if(!$this->configuration->ldapConfigurationActive) { + if (!$this->configuration->ldapConfigurationActive) { return null; } static $phpLDAPinstalled = true; - if(!$phpLDAPinstalled) { + if (!$phpLDAPinstalled) { return false; } - if(!$this->ignoreValidation && !$this->configured) { + if (!$this->ignoreValidation && !$this->configured) { \OCP\Util::writeLog( 'user_ldap', 'Configuration is invalid, cannot connect', @@ -541,8 +539,8 @@ class Connection extends LDAPUtility { ); return false; } - if(!$this->ldapConnectionRes) { - if(!$this->ldap->areLDAPFunctionsAvailable()) { + if (!$this->ldapConnectionRes) { + if (!$this->ldap->areLDAPFunctionsAvailable()) { $phpLDAPinstalled = false; \OCP\Util::writeLog( 'user_ldap', @@ -552,8 +550,8 @@ class Connection extends LDAPUtility { return false; } - if($this->configuration->turnOffCertCheck) { - if(putenv('LDAPTLS_REQCERT=never')) { + if ($this->configuration->turnOffCertCheck) { + if (putenv('LDAPTLS_REQCERT=never')) { \OCP\Util::writeLog('user_ldap', 'Turned off SSL certificate validation successfully.', ILogger::DEBUG); @@ -577,20 +575,20 @@ class Connection extends LDAPUtility { return $this->bind(); } } catch (ServerNotAvailableException $e) { - if(!$isBackupHost) { + if (!$isBackupHost) { throw $e; } } //if LDAP server is not reachable, try the Backup (Replica!) Server - if($isBackupHost || $isOverrideMainServer) { + if ($isBackupHost || $isOverrideMainServer) { $this->doConnect($this->configuration->ldapBackupHost, $this->configuration->ldapBackupPort); $this->bindResult = []; $bindStatus = $this->bind(); $error = $this->ldap->isResource($this->ldapConnectionRes) ? $this->ldap->errno($this->ldapConnectionRes) : -1; - if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { + if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { //when bind to backup server succeeded and failed to main server, //skip contacting him until next cache refresh $this->writeToCache('overrideMainServer', true); @@ -615,16 +613,16 @@ class Connection extends LDAPUtility { $this->ldapConnectionRes = $this->ldap->connect($host, $port); - if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { + if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); } - if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { + if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { throw new ServerNotAvailableException('Could not disable LDAP referrals.'); } - if($this->configuration->ldapTLS) { - if(!$this->ldap->startTls($this->ldapConnectionRes)) { + if ($this->configuration->ldapTLS) { + if (!$this->ldap->startTls($this->ldapConnectionRes)) { throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); } } @@ -636,15 +634,15 @@ class Connection extends LDAPUtility { * Binds to LDAP */ public function bind() { - if(!$this->configuration->ldapConfigurationActive) { + if (!$this->configuration->ldapConfigurationActive) { return false; } $cr = $this->ldapConnectionRes; - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { $cr = $this->getConnectionResource(); } - if( + if ( count($this->bindResult) !== 0 && $this->bindResult['dn'] === $this->configuration->ldapAgentName && \OC::$server->getHasher()->verify( @@ -668,7 +666,7 @@ class Connection extends LDAPUtility { 'result' => $ldapLogin, ]; - if(!$ldapLogin) { + if (!$ldapLogin) { $errno = $this->ldap->errno($cr); \OCP\Util::writeLog('user_ldap', @@ -677,7 +675,7 @@ class Connection extends LDAPUtility { // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS - if($errno !== 0 && $errno !== 49 && $errno !== 50) { + if ($errno !== 0 && $errno !== 49 && $errno !== 50) { $this->ldapConnectionRes = null; } @@ -685,5 +683,4 @@ class Connection extends LDAPUtility { } return true; } - } diff --git a/apps/user_ldap/lib/Controller/ConfigAPIController.php b/apps/user_ldap/lib/Controller/ConfigAPIController.php index fb8451287ef..ec056c651a7 100644 --- a/apps/user_ldap/lib/Controller/ConfigAPIController.php +++ b/apps/user_ldap/lib/Controller/ConfigAPIController.php @@ -151,12 +151,12 @@ class ConfigAPIController extends OCSController { public function delete($configID) { try { $this->ensureConfigIDExists($configID); - if(!$this->ldapHelper->deleteServerConfiguration($configID)) { + if (!$this->ldapHelper->deleteServerConfiguration($configID)) { throw new OCSException('Could not delete configuration'); } - } catch(OCSException $e) { + } catch (OCSException $e) { throw $e; - } catch(\Exception $e) { + } catch (\Exception $e) { $this->logger->logException($e); throw new OCSException('An issue occurred when deleting the config.'); } @@ -191,7 +191,7 @@ class ConfigAPIController extends OCSController { try { $this->ensureConfigIDExists($configID); - if(!is_array($configData)) { + if (!is_array($configData)) { throw new OCSBadRequestException('configData is not properly set'); } @@ -199,14 +199,14 @@ class ConfigAPIController extends OCSController { $configKeys = $configuration->getConfigTranslationArray(); foreach ($configKeys as $i => $key) { - if(isset($configData[$key])) { + if (isset($configData[$key])) { $configuration->$key = $configData[$key]; } } $configuration->saveConfiguration(); $this->connectionFactory->get($configID)->clearCache(); - } catch(OCSException $e) { + } catch (OCSException $e) { throw $e; } catch (\Exception $e) { $this->logger->logException($e); @@ -292,16 +292,16 @@ class ConfigAPIController extends OCSController { $config = new Configuration($configID); $data = $config->getConfiguration(); - if(!(int)$showPassword) { + if (!(int)$showPassword) { $data['ldapAgentPassword'] = '***'; } foreach ($data as $key => $value) { - if(is_array($value)) { + if (is_array($value)) { $value = implode(';', $value); $data[$key] = $value; } } - } catch(OCSException $e) { + } catch (OCSException $e) { throw $e; } catch (\Exception $e) { $this->logger->logException($e); @@ -319,7 +319,7 @@ class ConfigAPIController extends OCSController { */ private function ensureConfigIDExists($configID) { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(); - if(!in_array($configID, $prefixes, true)) { + if (!in_array($configID, $prefixes, true)) { throw new OCSNotFoundException('Config ID not found'); } } diff --git a/apps/user_ldap/lib/Controller/RenewPasswordController.php b/apps/user_ldap/lib/Controller/RenewPasswordController.php index cc58f79cbd0..499a25e0d28 100644 --- a/apps/user_ldap/lib/Controller/RenewPasswordController.php +++ b/apps/user_ldap/lib/Controller/RenewPasswordController.php @@ -84,7 +84,7 @@ class RenewPasswordController extends Controller { * @return TemplateResponse|RedirectResponse */ public function showRenewPasswordForm($user) { - if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { + if ($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm')); } $parameters = []; @@ -128,7 +128,7 @@ class RenewPasswordController extends Controller { * @return RedirectResponse */ public function tryRenewPassword($user, $oldPassword, $newPassword) { - if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { + if ($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') { return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm')); } $args = !is_null($user) ? ['user' => $user] : []; @@ -175,5 +175,4 @@ class RenewPasswordController extends Controller { ]); return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)); } - } diff --git a/apps/user_ldap/lib/Exceptions/AttributeNotSet.php b/apps/user_ldap/lib/Exceptions/AttributeNotSet.php index c05a0221849..5a4853d1e19 100644 --- a/apps/user_ldap/lib/Exceptions/AttributeNotSet.php +++ b/apps/user_ldap/lib/Exceptions/AttributeNotSet.php @@ -23,4 +23,5 @@ namespace OCA\User_LDAP\Exceptions; -class AttributeNotSet extends \RuntimeException {} +class AttributeNotSet extends \RuntimeException { +} diff --git a/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php b/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php index 2581de127d0..1a462b27781 100644 --- a/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php +++ b/apps/user_ldap/lib/Exceptions/ConstraintViolationException.php @@ -23,4 +23,5 @@ namespace OCA\User_LDAP\Exceptions; -class ConstraintViolationException extends \Exception {} +class ConstraintViolationException extends \Exception { +} diff --git a/apps/user_ldap/lib/Exceptions/NotOnLDAP.php b/apps/user_ldap/lib/Exceptions/NotOnLDAP.php index 8a9ce068b9b..e88fa3b840e 100644 --- a/apps/user_ldap/lib/Exceptions/NotOnLDAP.php +++ b/apps/user_ldap/lib/Exceptions/NotOnLDAP.php @@ -23,4 +23,5 @@ namespace OCA\User_LDAP\Exceptions; -class NotOnLDAP extends \Exception {} +class NotOnLDAP extends \Exception { +} diff --git a/apps/user_ldap/lib/GroupPluginManager.php b/apps/user_ldap/lib/GroupPluginManager.php index 799e290f852..56c4aab9f3b 100644 --- a/apps/user_ldap/lib/GroupPluginManager.php +++ b/apps/user_ldap/lib/GroupPluginManager.php @@ -27,7 +27,6 @@ namespace OCA\User_LDAP; use OCP\GroupInterface; class GroupPluginManager { - private $respondToActions = 0; private $which = [ @@ -54,7 +53,7 @@ class GroupPluginManager { $respondToActions = $plugin->respondToActions(); $this->respondToActions |= $respondToActions; - foreach($this->which as $action => $v) { + foreach ($this->which as $action => $v) { if ((bool)($respondToActions & $action)) { $this->which[$action] = $plugin; \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']); diff --git a/apps/user_ldap/lib/Group_LDAP.php b/apps/user_ldap/lib/Group_LDAP.php index 246b61b5202..85d9e38e03e 100644 --- a/apps/user_ldap/lib/Group_LDAP.php +++ b/apps/user_ldap/lib/Group_LDAP.php @@ -73,7 +73,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD parent::__construct($access); $filter = $this->access->connection->ldapGroupFilter; $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; - if(!empty($filter) && !empty($gassoc)) { + if (!empty($filter) && !empty($gassoc)) { $this->enabled = true; } @@ -92,25 +92,25 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * Checks whether the user is member of a group or not. */ public function inGroup($uid, $gid) { - if(!$this->enabled) { + if (!$this->enabled) { return false; } $cacheKey = 'inGroup'.$uid.':'.$gid; $inGroup = $this->access->connection->getFromCache($cacheKey); - if(!is_null($inGroup)) { + if (!is_null($inGroup)) { return (bool)$inGroup; } $userDN = $this->access->username2dn($uid); - if(isset($this->cachedGroupMembers[$gid])) { + if (isset($this->cachedGroupMembers[$gid])) { $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); return $isInGroup; } $cacheKeyMembers = 'inGroup-members:'.$gid; $members = $this->access->connection->getFromCache($cacheKeyMembers); - if(!is_null($members)) { + if (!is_null($members)) { $this->cachedGroupMembers[$gid] = $members; $isInGroup = in_array($userDN, $members, true); $this->access->connection->writeToCache($cacheKey, $isInGroup); @@ -119,34 +119,34 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $groupDN = $this->access->groupname2dn($gid); // just in case - if(!$groupDN || !$userDN) { + if (!$groupDN || !$userDN) { $this->access->connection->writeToCache($cacheKey, false); return false; } //check primary group first - if($gid === $this->getUserPrimaryGroup($userDN)) { + if ($gid === $this->getUserPrimaryGroup($userDN)) { $this->access->connection->writeToCache($cacheKey, true); return true; } //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. $members = $this->_groupMembers($groupDN); - if(!is_array($members) || count($members) === 0) { + if (!is_array($members) || count($members) === 0) { $this->access->connection->writeToCache($cacheKey, false); return false; } //extra work if we don't get back user DNs - if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { + if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { $dns = []; $filterParts = []; $bytes = 0; - foreach($members as $mid) { + foreach ($members as $mid) { $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); $filterParts[] = $filter; $bytes += strlen($filter); - if($bytes >= 9000000) { + if ($bytes >= 9000000) { // AD has a default input buffer of 10 MB, we do not want // to take even the chance to exceed it $filter = $this->access->combineFilterWithOr($filterParts); @@ -156,7 +156,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $dns = array_merge($dns, $users); } } - if(count($filterParts) > 0) { + if (count($filterParts) > 0) { $filter = $this->access->combineFilterWithOr($filterParts); $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); $dns = array_merge($dns, $users); @@ -201,7 +201,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $memberUrlFilter = substr($memberURLs[0], $pos); $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); $dynamicMembers = []; - foreach($foundMembers as $value) { + foreach ($foundMembers as $value) { $dynamicMembers[$value['dn'][0]] = 1; } } else { @@ -230,7 +230,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD // used extensively in cron job, caching makes sense for nested groups $cacheKey = '_groupMembers'.$dnGroup; $groupMembers = $this->access->connection->getFromCache($cacheKey); - if($groupMembers !== null) { + if ($groupMembers !== null) { return $groupMembers; } $seen[$dnGroup] = 1; @@ -290,10 +290,10 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); if ($nesting !== 1) { - if($recordMode) { + if ($recordMode) { // the keys are numeric, but should hold the DN return array_reduce($list, function ($transformed, $record) use ($dn) { - if($record['dn'][0] != $dn) { + if ($record['dn'][0] != $dn) { $transformed[$record['dn'][0]] = $record; } return $transformed; @@ -326,7 +326,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD public function gidNumber2Name($gid, $dn) { $cacheKey = 'gidNumberToName' . $gid; $groupName = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupName) && isset($groupName)) { + if (!is_null($groupName) && isset($groupName)) { return $groupName; } @@ -337,7 +337,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $this->access->connection->ldapGidNumber . '=' . $gid ]); $result = $this->access->searchGroups($filter, ['dn'], 1); - if(empty($result)) { + if (empty($result)) { return false; } $dn = $result[0]['dn'][0]; @@ -360,7 +360,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function getEntryGidNumber($dn, $attribute) { $value = $this->access->readAttribute($dn, $attribute); - if(is_array($value) && !empty($value)) { + if (is_array($value) && !empty($value)) { return $value[0]; } return false; @@ -382,9 +382,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserGidNumber($dn) { $gidNumber = false; - if($this->access->connection->hasGidNumber) { + if ($this->access->connection->hasGidNumber) { $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); - if($gidNumber === false) { + if ($gidNumber === false) { $this->access->connection->hasGidNumber = false; } } @@ -401,7 +401,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { $groupID = $this->getGroupGidNumber($groupDN); - if($groupID === false) { + if ($groupID === false) { throw new \Exception('Not a valid group'); } @@ -465,9 +465,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserGroupByGid($dn) { $groupID = $this->getUserGidNumber($dn); - if($groupID !== false) { + if ($groupID !== false) { $groupName = $this->gidNumber2Name($groupID, $dn); - if($groupName !== false) { + if ($groupName !== false) { return $groupName; } } @@ -484,12 +484,12 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD public function primaryGroupID2Name($gid, $dn) { $cacheKey = 'primaryGroupIDtoName'; $groupNames = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupNames) && isset($groupNames[$gid])) { + if (!is_null($groupNames) && isset($groupNames[$gid])) { return $groupNames[$gid]; } $domainObjectSid = $this->access->getSID($dn); - if($domainObjectSid === false) { + if ($domainObjectSid === false) { return false; } @@ -499,7 +499,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD 'objectsid=' . $domainObjectSid . '-' . $gid ]); $result = $this->access->searchGroups($filter, ['dn'], 1); - if(empty($result)) { + if (empty($result)) { return false; } $dn = $result[0]['dn'][0]; @@ -522,7 +522,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function getEntryGroupID($dn, $attribute) { $value = $this->access->readAttribute($dn, $attribute); - if(is_array($value) && !empty($value)) { + if (is_array($value) && !empty($value)) { return $value[0]; } return false; @@ -544,9 +544,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserPrimaryGroupIDs($dn) { $primaryGroupID = false; - if($this->access->connection->hasPrimaryGroups) { + if ($this->access->connection->hasPrimaryGroups) { $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); - if($primaryGroupID === false) { + if ($primaryGroupID === false) { $this->access->connection->hasPrimaryGroups = false; } } @@ -563,7 +563,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { $groupID = $this->getGroupPrimaryGroupID($groupDN); - if($groupID === false) { + if ($groupID === false) { throw new \Exception('Not a valid group'); } @@ -627,9 +627,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function getUserPrimaryGroup($dn) { $groupID = $this->getUserPrimaryGroupIDs($dn); - if($groupID !== false) { + if ($groupID !== false) { $groupName = $this->primaryGroupID2Name($groupID, $dn); - if($groupName !== false) { + if ($groupName !== false) { return $groupName; } } @@ -648,16 +648,16 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * This function includes groups based on dynamic group membership. */ public function getUserGroups($uid) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } $cacheKey = 'getUserGroups'.$uid; $userGroups = $this->access->connection->getFromCache($cacheKey); - if(!is_null($userGroups)) { + if (!is_null($userGroups)) { return $userGroups; } $userDN = $this->access->username2dn($uid); - if(!$userDN) { + if (!$userDN) { $this->access->connection->writeToCache($cacheKey, []); return []; } @@ -672,7 +672,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD // look through dynamic groups to add them to the result array if needed $groupsToMatch = $this->access->fetchListOfGroups( $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]); - foreach($groupsToMatch as $dynamicGroup) { + foreach ($groupsToMatch as $dynamicGroup) { if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { continue; } @@ -689,7 +689,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD if ($userMatch !== false) { // match found so this user is in this group $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); - if(is_string($groupName)) { + if (is_string($groupName)) { // be sure to never return false if the dn could not be // resolved to a name, for whatever reason. $groups[] = $groupName; @@ -705,7 +705,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD // if possible, read out membership via memberOf. It's far faster than // performing a search, which still is a fallback later. // memberof doesn't support memberuid, so skip it here. - if((int)$this->access->connection->hasMemberOfFilterSupport === 1 + if ((int)$this->access->connection->hasMemberOfFilterSupport === 1 && (int)$this->access->connection->useMemberOfToDetectMembership === 1 && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' ) { @@ -713,7 +713,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD if (is_array($groupDNs)) { foreach ($groupDNs as $dn) { $groupName = $this->access->dn2groupname($dn); - if(is_string($groupName)) { + if (is_string($groupName)) { // be sure to never return false if the dn could not be // resolved to a name, for whatever reason. $groups[] = $groupName; @@ -721,10 +721,10 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } } - if($primaryGroup !== false) { + if ($primaryGroup !== false) { $groups[] = $primaryGroup; } - if($gidGroupName !== false) { + if ($gidGroupName !== false) { $groups[] = $gidGroupName; } $this->access->connection->writeToCache($cacheKey, $groups); @@ -732,11 +732,11 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } //uniqueMember takes DN, memberuid the uid, so we need to distinguish - if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') + if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') ) { $uid = $userDN; - } elseif(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { + } elseif (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { $result = $this->access->readAttribute($userDN, 'uid'); if ($result === false) { \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. @@ -750,7 +750,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $uid = $userDN; } - if($uid !== false) { + if ($uid !== false) { if (isset($this->cachedGroupsByMember[$uid])) { $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); } else { @@ -761,10 +761,10 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } } - if($primaryGroup !== false) { + if ($primaryGroup !== false) { $groups[] = $primaryGroup; } - if($gidGroupName !== false) { + if ($gidGroupName !== false) { $groups[] = $gidGroupName; } @@ -794,7 +794,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD [$this->access->connection->ldapGroupDisplayName, 'dn']); if (is_array($groups)) { $fetcher = function ($dn, &$seen) { - if(is_array($dn) && isset($dn['dn'][0])) { + if (is_array($dn) && isset($dn['dn'][0])) { $dn = $dn['dn'][0]; } return $this->getGroupsByMember($dn, $seen); @@ -816,33 +816,33 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * @throws \Exception */ public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } - if(!$this->groupExists($gid)) { + if (!$this->groupExists($gid)) { return []; } $search = $this->access->escapeFilterPart($search, true); $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; // check for cache of the exact query $groupUsers = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupUsers)) { + if (!is_null($groupUsers)) { return $groupUsers; } // check for cache of the query without limit and offset $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); - if(!is_null($groupUsers)) { + if (!is_null($groupUsers)) { $groupUsers = array_slice($groupUsers, $offset, $limit); $this->access->connection->writeToCache($cacheKey, $groupUsers); return $groupUsers; } - if($limit === -1) { + if ($limit === -1) { $limit = null; } $groupDN = $this->access->groupname2dn($gid); - if(!$groupDN) { + if (!$groupDN) { // group couldn't be found, return empty resultset $this->access->connection->writeToCache($cacheKey, []); return []; @@ -851,7 +851,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); $members = $this->_groupMembers($groupDN); - if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { + if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) { //in case users could not be retrieved, return empty result set $this->access->connection->writeToCache($cacheKey, []); return []; @@ -860,8 +860,8 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $groupUsers = []; $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); $attrs = $this->access->userManager->getAttributes(true); - foreach($members as $member) { - if($isMemberUid) { + foreach ($members as $member) { + if ($isMemberUid) { //we got uids, need to get their DNs to 'translate' them to user names $filter = $this->access->combineFilterWithAnd([ str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), @@ -871,31 +871,30 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD ]) ]); $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); - if(count($ldap_users) < 1) { + if (count($ldap_users) < 1) { continue; } $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); } else { //we got DNs, check if we need to filter by search or we can give back all of them $uid = $this->access->dn2username($member); - if(!$uid) { + if (!$uid) { continue; } $cacheKey = 'userExistsOnLDAP' . $uid; $userExists = $this->access->connection->getFromCache($cacheKey); - if($userExists === false) { + if ($userExists === false) { continue; } - if($userExists === null || $search !== '') { + if ($userExists === null || $search !== '') { if (!$this->access->readAttribute($member, $this->access->connection->ldapUserDisplayName, $this->access->combineFilterWithAnd([ $this->access->getFilterPartForUserSearch($search), $this->access->connection->ldapUserFilter - ]))) - { - if($search === '') { + ]))) { + if ($search === '') { $this->access->connection->writeToCache($cacheKey, false); } continue; @@ -928,16 +927,16 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; - if(!$this->enabled || !$this->groupExists($gid)) { + if (!$this->enabled || !$this->groupExists($gid)) { return false; } $groupUsers = $this->access->connection->getFromCache($cacheKey); - if(!is_null($groupUsers)) { + if (!is_null($groupUsers)) { return $groupUsers; } $groupDN = $this->access->groupname2dn($gid); - if(!$groupDN) { + if (!$groupDN) { // group couldn't be found, return empty result set $this->access->connection->writeToCache($cacheKey, false); return false; @@ -945,7 +944,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD $members = $this->_groupMembers($groupDN); $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); - if(!$members && $primaryUserCount === 0) { + if (!$members && $primaryUserCount === 0) { //in case users could not be retrieved, return empty result set $this->access->connection->writeToCache($cacheKey, false); return false; @@ -970,27 +969,27 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD //For now this is not important, because the only use of this method //does not supply a search string $groupUsers = []; - foreach($members as $member) { - if($isMemberUid) { + foreach ($members as $member) { + if ($isMemberUid) { //we got uids, need to get their DNs to 'translate' them to user names $filter = $this->access->combineFilterWithAnd([ str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), $this->access->getFilterPartForUserSearch($search) ]); $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); - if(count($ldap_users) < 1) { + if (count($ldap_users) < 1) { continue; } $groupUsers[] = $this->access->dn2username($ldap_users[0]); } else { //we need to apply the search filter now - if(!$this->access->readAttribute($member, + if (!$this->access->readAttribute($member, $this->access->connection->ldapUserDisplayName, $this->access->getFilterPartForUserSearch($search))) { continue; } // dn2username will also check if the users belong to the allowed base - if($ocname = $this->access->dn2username($member)) { + if ($ocname = $this->access->dn2username($member)) { $groupUsers[] = $ocname; } } @@ -1013,7 +1012,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * Returns a list with all groups (used by getGroups) */ protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; @@ -1021,13 +1020,13 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD //Check cache before driving unnecessary searches \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); $ldap_groups = $this->access->connection->getFromCache($cacheKey); - if(!is_null($ldap_groups)) { + if (!is_null($ldap_groups)) { return $ldap_groups; } // if we'd pass -1 to LDAP search, we'd end up in a Protocol // error. With a limit of 0, we get 0 results. So we pass null. - if($limit <= 0) { + if ($limit <= 0) { $limit = null; } $filter = $this->access->combineFilterWithAnd([ @@ -1059,7 +1058,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD * (active directory has a limit of 1000 by default) */ public function getGroups($search = '', $limit = -1, $offset = 0) { - if(!$this->enabled) { + if (!$this->enabled) { return []; } $search = $this->access->escapeFilterPart($search, true); @@ -1069,9 +1068,9 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD } $maxGroups = 100000; // limit max results (just for safety reasons) if ($limit > -1) { - $overallLimit = min($limit + $offset, $maxGroups); + $overallLimit = min($limit + $offset, $maxGroups); } else { - $overallLimit = $maxGroups; + $overallLimit = $maxGroups; } $chunkOffset = $offset; $allGroups = []; @@ -1106,20 +1105,20 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD */ public function groupExists($gid) { $groupExists = $this->access->connection->getFromCache('groupExists'.$gid); - if(!is_null($groupExists)) { + if (!is_null($groupExists)) { return (bool)$groupExists; } //getting dn, if false the group does not exist. If dn, it may be mapped //only, requires more checking. $dn = $this->access->groupname2dn($gid); - if(!$dn) { + if (!$dn) { $this->access->connection->writeToCache('groupExists'.$gid, false); return false; } //if group really still exists, we will be able to read its objectclass - if(!is_array($this->access->readAttribute($dn, ''))) { + if (!is_array($this->access->readAttribute($dn, ''))) { $this->access->connection->writeToCache('groupExists'.$gid, false); return false; } @@ -1160,7 +1159,7 @@ class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLD if ($dn = $this->groupPluginManager->createGroup($gid)) { //updates group mapping $uuid = $this->access->getUUID($dn, false); - if(is_string($uuid)) { + if (is_string($uuid)) { $this->access->mapAndAnnounceIfApplicable( $this->access->getGroupMapper(), $dn, diff --git a/apps/user_ldap/lib/Group_Proxy.php b/apps/user_ldap/lib/Group_Proxy.php index b492e965307..3bd0cc4c400 100644 --- a/apps/user_ldap/lib/Group_Proxy.php +++ b/apps/user_ldap/lib/Group_Proxy.php @@ -40,10 +40,10 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet */ public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) { parent::__construct($ldap); - foreach($serverConfigPrefixes as $configPrefix) { + foreach ($serverConfigPrefixes as $configPrefix) { $this->backends[$configPrefix] = new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager); - if(is_null($this->refBackend)) { + if (is_null($this->refBackend)) { $this->refBackend = &$this->backends[$configPrefix]; } } @@ -58,8 +58,8 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet */ protected function walkBackends($gid, $method, $parameters) { $cacheKey = $this->getGroupCacheKey($gid); - foreach($this->backends as $configPrefix => $backend) { - if($result = call_user_func_array([$backend, $method], $parameters)) { + foreach ($this->backends as $configPrefix => $backend) { + if ($result = call_user_func_array([$backend, $method], $parameters)) { $this->writeToCache($cacheKey, $configPrefix); return $result; } @@ -79,17 +79,17 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet $cacheKey = $this->getGroupCacheKey($gid); $prefix = $this->getFromCache($cacheKey); //in case the uid has been found in the past, try this stored connection first - if(!is_null($prefix)) { - if(isset($this->backends[$prefix])) { + if (!is_null($prefix)) { + if (isset($this->backends[$prefix])) { $result = call_user_func_array([$this->backends[$prefix], $method], $parameters); - if($result === $passOnWhen) { + if ($result === $passOnWhen) { //not found here, reset cache to null if group vanished //because sometimes methods return false with a reason $groupExists = call_user_func_array( [$this->backends[$prefix], 'groupExists'], [$gid] ); - if(!$groupExists) { + if (!$groupExists) { $this->writeToCache($cacheKey, null); } } @@ -122,7 +122,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet public function getUserGroups($uid) { $groups = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendGroups = $backend->getUserGroups($uid); if (is_array($backendGroups)) { $groups = array_merge($groups, $backendGroups); @@ -139,7 +139,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { $users = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset); if (is_array($backendUsers)) { $users = array_merge($users, $backendUsers); @@ -224,7 +224,7 @@ class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGet public function getGroups($search = '', $limit = -1, $offset = 0) { $groups = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendGroups = $backend->getGroups($search, $limit, $offset); if (is_array($backendGroups)) { $groups = array_merge($groups, $backendGroups); diff --git a/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php b/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php index af9bc7aba84..13d20a42a17 100644 --- a/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php +++ b/apps/user_ldap/lib/Handler/ExtStorageConfigHandler.php @@ -42,22 +42,22 @@ class ExtStorageConfigHandler extends UserContext implements IConfigHandler { $this->placeholder = 'home'; $user = $this->getUser(); - if($user === null) { + if ($user === null) { return $optionValue; } $backend = $user->getBackend(); - if(!$backend instanceof User_Proxy) { + if (!$backend instanceof User_Proxy) { return $optionValue; } $access = $backend->getLDAPAccess($user->getUID()); - if(!$access) { + if (!$access) { return $optionValue; } $attribute = $access->connection->ldapExtStorageHomeAttribute; - if(empty($attribute)) { + if (empty($attribute)) { return $optionValue; } diff --git a/apps/user_ldap/lib/Helper.php b/apps/user_ldap/lib/Helper.php index 19797d8a98b..90fa3d05892 100644 --- a/apps/user_ldap/lib/Helper.php +++ b/apps/user_ldap/lib/Helper.php @@ -101,7 +101,7 @@ class Helper { $keys = $this->getServersConfig($referenceConfigkey); $result = []; - foreach($keys as $key) { + foreach ($keys as $key) { $len = strlen($key) - strlen($referenceConfigkey); $prefix = substr($key, 0, $len); $result[$prefix] = $this->config->getAppValue('user_ldap', $key); @@ -118,7 +118,7 @@ class Helper { public function getNextServerConfigurationPrefix() { $serverConnections = $this->getServerConfigurationPrefixes(); - if(count($serverConnections) === 0) { + if (count($serverConnections) === 0) { return 's01'; } @@ -148,12 +148,12 @@ class Helper { * @return bool true on success, false otherwise */ public function deleteServerConfiguration($prefix) { - if(!in_array($prefix, self::getServerConfigurationPrefixes())) { + if (!in_array($prefix, self::getServerConfigurationPrefixes())) { return false; } $saveOtherConfigurations = ''; - if(empty($prefix)) { + if (empty($prefix)) { $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; } @@ -167,11 +167,11 @@ class Helper { '); $delRows = $query->execute([$prefix.'%']); - if($delRows === null) { + if ($delRows === null) { return false; } - if($delRows === 0) { + if ($delRows === 0) { return false; } @@ -187,7 +187,7 @@ class Helper { $all = $this->getServerConfigurationPrefixes(false); $active = $this->getServerConfigurationPrefixes(true); - if(!is_array($all) || !is_array($active)) { + if (!is_array($all) || !is_array($active)) { throw new \Exception('Unexpected Return Value'); } @@ -201,14 +201,14 @@ class Helper { */ public function getDomainFromURL($url) { $uinfo = parse_url($url); - if(!is_array($uinfo)) { + if (!is_array($uinfo)) { return false; } $domain = false; - if(isset($uinfo['host'])) { + if (isset($uinfo['host'])) { $domain = $uinfo['host']; - } elseif(isset($uinfo['path'])) { + } elseif (isset($uinfo['path'])) { $domain = $uinfo['path']; } @@ -222,7 +222,7 @@ class Helper { */ public function setLDAPProvider() { $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); - if(is_null($current)) { + if (is_null($current)) { \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class); } } @@ -234,9 +234,9 @@ class Helper { */ public function sanitizeDN($dn) { //treating multiple base DNs - if(is_array($dn)) { + if (is_array($dn)) { $result = []; - foreach($dn as $singleDN) { + foreach ($dn as $singleDN) { $result[] = $this->sanitizeDN($singleDN); } return $result; @@ -287,7 +287,7 @@ class Helper { * @throws \Exception */ public static function loginName2UserName($param) { - if(!isset($param['uid'])) { + if (!isset($param['uid'])) { throw new \Exception('key uid is expected to be set in $param'); } @@ -306,7 +306,7 @@ class Helper { $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager ); $uid = $userBackend->loginName2UserName($param['uid']); - if($uid !== false) { + if ($uid !== false) { $param['uid'] = $uid; } } diff --git a/apps/user_ldap/lib/IGroupLDAP.php b/apps/user_ldap/lib/IGroupLDAP.php index 7b2b5301e29..c84b899f5c0 100644 --- a/apps/user_ldap/lib/IGroupLDAP.php +++ b/apps/user_ldap/lib/IGroupLDAP.php @@ -40,5 +40,4 @@ interface IGroupLDAP { * @return resource of the LDAP connection */ public function getNewLDAPConnection($gid); - } diff --git a/apps/user_ldap/lib/ILDAPGroupPlugin.php b/apps/user_ldap/lib/ILDAPGroupPlugin.php index 3a5accece26..3c9baeab65c 100644 --- a/apps/user_ldap/lib/ILDAPGroupPlugin.php +++ b/apps/user_ldap/lib/ILDAPGroupPlugin.php @@ -81,5 +81,4 @@ interface ILDAPGroupPlugin { * @return array|false */ public function getGroupDetails($gid); - } diff --git a/apps/user_ldap/lib/ILDAPUserPlugin.php b/apps/user_ldap/lib/ILDAPUserPlugin.php index 29397b6c205..e4858d0688f 100644 --- a/apps/user_ldap/lib/ILDAPUserPlugin.php +++ b/apps/user_ldap/lib/ILDAPUserPlugin.php @@ -89,5 +89,4 @@ interface ILDAPUserPlugin { * @return int|bool */ public function countUsers(); - } diff --git a/apps/user_ldap/lib/ILDAPWrapper.php b/apps/user_ldap/lib/ILDAPWrapper.php index 586cfa18f8d..aa67dd596f1 100644 --- a/apps/user_ldap/lib/ILDAPWrapper.php +++ b/apps/user_ldap/lib/ILDAPWrapper.php @@ -212,5 +212,4 @@ interface ILDAPWrapper { * @return bool true if it is a resource, false otherwise */ public function isResource($resource); - } diff --git a/apps/user_ldap/lib/Jobs/CleanUp.php b/apps/user_ldap/lib/Jobs/CleanUp.php index 052ae72b663..996df67b1d2 100644 --- a/apps/user_ldap/lib/Jobs/CleanUp.php +++ b/apps/user_ldap/lib/Jobs/CleanUp.php @@ -83,19 +83,19 @@ class CleanUp extends TimedJob { //pass in app.php we do add here, except something else is passed e.g. //in tests. - if(isset($arguments['helper'])) { + if (isset($arguments['helper'])) { $this->ldapHelper = $arguments['helper']; } else { $this->ldapHelper = new Helper(\OC::$server->getConfig()); } - if(isset($arguments['ocConfig'])) { + if (isset($arguments['ocConfig'])) { $this->ocConfig = $arguments['ocConfig']; } else { $this->ocConfig = \OC::$server->getConfig(); } - if(isset($arguments['userBackend'])) { + if (isset($arguments['userBackend'])) { $this->userBackend = $arguments['userBackend']; } else { $this->userBackend = new User_Proxy( @@ -108,19 +108,19 @@ class CleanUp extends TimedJob { ); } - if(isset($arguments['db'])) { + if (isset($arguments['db'])) { $this->db = $arguments['db']; } else { $this->db = \OC::$server->getDatabaseConnection(); } - if(isset($arguments['mapping'])) { + if (isset($arguments['mapping'])) { $this->mapping = $arguments['mapping']; } else { $this->mapping = new UserMapping($this->db); } - if(isset($arguments['deletedUsersIndex'])) { + if (isset($arguments['deletedUsersIndex'])) { $this->dui = $arguments['deletedUsersIndex']; } else { $this->dui = new DeletedUsersIndex( @@ -135,11 +135,11 @@ class CleanUp extends TimedJob { public function run($argument) { $this->setArguments($argument); - if(!$this->isCleanUpAllowed()) { + if (!$this->isCleanUpAllowed()) { return; } $users = $this->mapping->getList($this->getOffset(), $this->getChunkSize()); - if(!is_array($users)) { + if (!is_array($users)) { //something wrong? Let's start from the beginning next time and //abort $this->setOffset(true); @@ -165,7 +165,7 @@ class CleanUp extends TimedJob { */ public function isCleanUpAllowed() { try { - if($this->ldapHelper->haveDisabledConfigurations()) { + if ($this->ldapHelper->haveDisabledConfigurations()) { return false; } } catch (\Exception $e) { @@ -189,7 +189,7 @@ class CleanUp extends TimedJob { * @param array $users result from getMappedUsers() */ private function checkUsers(array $users) { - foreach($users as $user) { + foreach ($users as $user) { $this->checkUser($user); } } @@ -199,7 +199,7 @@ class CleanUp extends TimedJob { * @param string[] $user */ private function checkUser(array $user) { - if($this->userBackend->userExistsOnLDAP($user['name'])) { + if ($this->userBackend->userExistsOnLDAP($user['name'])) { //still available, all good return; @@ -231,10 +231,9 @@ class CleanUp extends TimedJob { * @return int */ public function getChunkSize() { - if($this->limit === null) { + if ($this->limit === null) { $this->limit = (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobChunkSize', 50); } return $this->limit; } - } diff --git a/apps/user_ldap/lib/Jobs/Sync.php b/apps/user_ldap/lib/Jobs/Sync.php index e095ba41bef..1ef2d16e7c2 100644 --- a/apps/user_ldap/lib/Jobs/Sync.php +++ b/apps/user_ldap/lib/Jobs/Sync.php @@ -122,20 +122,20 @@ class Sync extends TimedJob { $isBackgroundJobModeAjax = $this->config ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; - if($isBackgroundJobModeAjax) { + if ($isBackgroundJobModeAjax) { return; } $cycleData = $this->getCycle(); - if($cycleData === null) { + if ($cycleData === null) { $cycleData = $this->determineNextCycle(); - if($cycleData === null) { + if ($cycleData === null) { $this->updateInterval(); return; } } - if(!$this->qualifiesToRun($cycleData)) { + if (!$this->qualifiesToRun($cycleData)) { $this->updateInterval(); return; } @@ -175,7 +175,7 @@ class Sync extends TimedJob { true ); - if((int)$connection->ldapPagingSize === 0) { + if ((int)$connection->ldapPagingSize === 0) { return false; } return count($results) >= (int)$connection->ldapPagingSize; @@ -189,7 +189,7 @@ class Sync extends TimedJob { */ public function getCycle() { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); - if(count($prefixes) === 0) { + if (count($prefixes) === 0) { return null; } @@ -198,7 +198,7 @@ class Sync extends TimedJob { 'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0), ]; - if( + if ( $cycleData['prefix'] !== null && in_array($cycleData['prefix'], $prefixes) ) { @@ -227,14 +227,14 @@ class Sync extends TimedJob { */ public function determineNextCycle(array $cycleData = null) { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); - if(count($prefixes) === 0) { + if (count($prefixes) === 0) { return null; } // get the next prefix in line and remember it $oldPrefix = $cycleData === null ? null : $cycleData['prefix']; $prefix = $this->getNextPrefix($oldPrefix); - if($prefix === null) { + if ($prefix === null) { return null; } $cycleData['prefix'] = $prefix; @@ -253,7 +253,7 @@ class Sync extends TimedJob { */ public function qualifiesToRun($cycleData) { $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0); - if((time() - $lastChange) > 60 * 30) { + if ((time() - $lastChange) > 60 * 30) { return true; } return false; @@ -279,17 +279,17 @@ class Sync extends TimedJob { protected function getNextPrefix($lastPrefix) { $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true); $noOfPrefixes = count($prefixes); - if($noOfPrefixes === 0) { + if ($noOfPrefixes === 0) { return null; } $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true); - if($i === false) { + if ($i === false) { $i = -1; } else { $i++; } - if(!isset($prefixes[$i])) { + if (!isset($prefixes[$i])) { $i = 0; } return $prefixes[$i]; @@ -301,49 +301,49 @@ class Sync extends TimedJob { * @param array $argument */ public function setArgument($argument) { - if(isset($argument['config'])) { + if (isset($argument['config'])) { $this->config = $argument['config']; } else { $this->config = \OC::$server->getConfig(); } - if(isset($argument['helper'])) { + if (isset($argument['helper'])) { $this->ldapHelper = $argument['helper']; } else { $this->ldapHelper = new Helper($this->config); } - if(isset($argument['ldapWrapper'])) { + if (isset($argument['ldapWrapper'])) { $this->ldap = $argument['ldapWrapper']; } else { $this->ldap = new LDAP(); } - if(isset($argument['avatarManager'])) { + if (isset($argument['avatarManager'])) { $this->avatarManager = $argument['avatarManager']; } else { $this->avatarManager = \OC::$server->getAvatarManager(); } - if(isset($argument['dbc'])) { + if (isset($argument['dbc'])) { $this->dbc = $argument['dbc']; } else { $this->dbc = \OC::$server->getDatabaseConnection(); } - if(isset($argument['ncUserManager'])) { + if (isset($argument['ncUserManager'])) { $this->ncUserManager = $argument['ncUserManager']; } else { $this->ncUserManager = \OC::$server->getUserManager(); } - if(isset($argument['notificationManager'])) { + if (isset($argument['notificationManager'])) { $this->notificationManager = $argument['notificationManager']; } else { $this->notificationManager = \OC::$server->getNotificationManager(); } - if(isset($argument['userManager'])) { + if (isset($argument['userManager'])) { $this->userManager = $argument['userManager']; } else { $this->userManager = new Manager( @@ -358,19 +358,19 @@ class Sync extends TimedJob { ); } - if(isset($argument['mapper'])) { + if (isset($argument['mapper'])) { $this->mapper = $argument['mapper']; } else { $this->mapper = new UserMapping($this->dbc); } - if(isset($argument['connectionFactory'])) { + if (isset($argument['connectionFactory'])) { $this->connectionFactory = $argument['connectionFactory']; } else { $this->connectionFactory = new ConnectionFactory($this->ldap); } - if(isset($argument['accessFactory'])) { + if (isset($argument['accessFactory'])) { $this->accessFactory = $argument['accessFactory']; } else { $this->accessFactory = new AccessFactory( diff --git a/apps/user_ldap/lib/Jobs/UpdateGroups.php b/apps/user_ldap/lib/Jobs/UpdateGroups.php index 71a2ea8c69e..19981a69bd2 100644 --- a/apps/user_ldap/lib/Jobs/UpdateGroups.php +++ b/apps/user_ldap/lib/Jobs/UpdateGroups.php @@ -67,7 +67,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { $knownGroups = array_keys(self::getKnownGroups()); $actualGroups = self::getGroupBE()->getGroups(); - if(empty($actualGroups) && empty($knownGroups)) { + if (empty($actualGroups) && empty($knownGroups)) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', ILogger::INFO); @@ -99,26 +99,26 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { SET `owncloudusers` = ? WHERE `owncloudname` = ? '); - foreach($groups as $group) { + foreach ($groups as $group) { //we assume, that self::$groupsFromDB has been retrieved already $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); $actualUsers = self::getGroupBE()->usersInGroup($group); $hasChanged = false; - foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { + foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]); \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', ILogger::INFO); $hasChanged = true; } - foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { + foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { \OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]); \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', ILogger::INFO); $hasChanged = true; } - if($hasChanged) { + if ($hasChanged) { $query->execute([serialize($actualUsers), $group]); } } @@ -137,7 +137,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`) VALUES (?, ?) '); - foreach($createdGroups as $createdGroup) { + foreach ($createdGroups as $createdGroup) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', ILogger::INFO); @@ -159,7 +159,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { FROM `*PREFIX*ldap_group_members` WHERE `owncloudname` = ? '); - foreach($removedGroups as $removedGroup) { + foreach ($removedGroups as $removedGroup) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', ILogger::INFO); @@ -174,13 +174,13 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy */ static private function getGroupBE() { - if(!is_null(self::$groupBE)) { + if (!is_null(self::$groupBE)) { return self::$groupBE; } $helper = new Helper(\OC::$server->getConfig()); $configPrefixes = $helper->getServerConfigurationPrefixes(true); $ldapWrapper = new LDAP(); - if(count($configPrefixes) === 1) { + if (count($configPrefixes) === 1) { //avoid the proxy when there is only one LDAP server configured $dbc = \OC::$server->getDatabaseConnection(); $userManager = new Manager( @@ -210,7 +210,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { * @return array */ static private function getKnownGroups() { - if(is_array(self::$groupsFromDB)) { + if (is_array(self::$groupsFromDB)) { return self::$groupsFromDB; } $query = \OC_DB::prepare(' @@ -219,7 +219,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob { '); $result = $query->execute()->fetchAll(); self::$groupsFromDB = []; - foreach($result as $dataset) { + foreach ($result as $dataset) { self::$groupsFromDB[$dataset['owncloudname']] = $dataset; } diff --git a/apps/user_ldap/lib/LDAP.php b/apps/user_ldap/lib/LDAP.php index c4a30770566..409c6ab2b09 100644 --- a/apps/user_ldap/lib/LDAP.php +++ b/apps/user_ldap/lib/LDAP.php @@ -54,10 +54,10 @@ class LDAP implements ILDAPWrapper { * @return mixed */ public function connect($host, $port) { - if(strpos($host, '://') === false) { + if (strpos($host, '://') === false) { $host = 'ldap://' . $host; } - if(strpos($host, ':', strpos($host, '://') + 1) === false) { + if (strpos($host, ':', strpos($host, '://') + 1) === false) { //ldap_connect ignores port parameter when URLs are passed $host .= ':' . $port; } @@ -195,7 +195,7 @@ class LDAP implements ILDAPWrapper { */ public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) { $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) { - if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { + if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { return true; } $oldHandler($no, $message, $file, $line); @@ -285,13 +285,13 @@ class LDAP implements ILDAPWrapper { * @return bool */ protected function isResultFalse($result) { - if($result === false) { + if ($result === false) { return true; } - if($this->curFunc === 'ldap_search' && is_array($result)) { + if ($this->curFunc === 'ldap_search' && is_array($result)) { foreach ($result as $singleResult) { - if($singleResult === false) { + if ($singleResult === false) { return true; } } @@ -306,7 +306,7 @@ class LDAP implements ILDAPWrapper { protected function invokeLDAPMethod() { $arguments = func_get_args(); $func = 'ldap_' . array_shift($arguments); - if(function_exists($func)) { + if (function_exists($func)) { $this->preFunctionCall($func, $arguments); $result = call_user_func_array($func, $arguments); if ($this->isResultFalse($result)) { @@ -336,12 +336,12 @@ class LDAP implements ILDAPWrapper { */ private function processLDAPError($resource) { $errorCode = ldap_errno($resource); - if($errorCode === 0) { + if ($errorCode === 0) { return; } $errorMsg = ldap_error($resource); - if($this->curFunc === 'ldap_get_entries' + if ($this->curFunc === 'ldap_get_entries' && $errorCode === -4) { } elseif ($errorCode === 32) { //for now @@ -373,9 +373,9 @@ class LDAP implements ILDAPWrapper { * @throw \Exception */ private function postFunctionCall() { - if($this->isResource($this->curArgs[0])) { + if ($this->isResource($this->curArgs[0])) { $resource = $this->curArgs[0]; - } elseif( + } elseif ( $this->curFunc === 'ldap_search' && is_array($this->curArgs[0]) && $this->isResource($this->curArgs[0][0]) diff --git a/apps/user_ldap/lib/LDAPProvider.php b/apps/user_ldap/lib/LDAPProvider.php index 75267165cdf..5b91a52f546 100644 --- a/apps/user_ldap/lib/LDAPProvider.php +++ b/apps/user_ldap/lib/LDAPProvider.php @@ -37,7 +37,6 @@ use OCP\LDAP\ILDAPProvider; * LDAP provider for pulic access to the LDAP backend. */ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { - private $userBackend; private $groupBackend; private $logger; @@ -57,7 +56,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { $this->deletedUsersIndex = $deletedUsersIndex; $userBackendFound = false; $groupBackendFound = false; - foreach ($serverContainer->getUserManager()->getBackends() as $backend){ + foreach ($serverContainer->getUserManager()->getBackends() as $backend) { $this->logger->debug('instance '.get_class($backend).' user backend.', ['app' => 'user_ldap']); if ($backend instanceof IUserLDAP) { $this->userBackend = $backend; @@ -65,7 +64,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { break; } } - foreach ($serverContainer->getGroupManager()->getBackends() as $backend){ + foreach ($serverContainer->getGroupManager()->getBackends() as $backend) { $this->logger->debug('instance '.get_class($backend).' group backend.', ['app' => 'user_ldap']); if ($backend instanceof IGroupLDAP) { $this->groupBackend = $backend; @@ -86,11 +85,11 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if translation was unsuccessful */ public function getUserDN($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $result = $this->userBackend->getLDAPAccess($uid)->username2dn($uid); - if(!$result){ + if (!$result) { throw new \Exception('Translation to LDAP DN unsuccessful'); } return $result; @@ -103,11 +102,11 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception */ public function getGroupDN($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } $result = $this->groupBackend->getLDAPAccess($gid)->groupname2dn($gid); - if(!$result){ + if (!$result) { throw new \Exception('Translation to LDAP DN unsuccessful'); } return $result; @@ -122,7 +121,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { */ public function getUserName($dn) { $result = $this->userBackend->dn2UserName($dn); - if(!$result){ + if (!$result) { throw new \Exception('Translation to internal user name unsuccessful'); } return $result; @@ -154,7 +153,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPConnection($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } return $this->userBackend->getNewLDAPConnection($uid); @@ -168,7 +167,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if group id was not found in LDAP */ public function getGroupLDAPConnection($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } return $this->groupBackend->getNewLDAPConnection($gid); @@ -181,14 +180,14 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPBaseUsers($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $access = $this->userBackend->getLDAPAccess($uid); $bases = $access->getConnection()->ldapBaseUsers; $dn = $this->getUserDN($uid); foreach ($bases as $base) { - if($access->isDNPartOfBase($dn, [$base])) { + if ($access->isDNPartOfBase($dn, [$base])) { return $base; } } @@ -211,7 +210,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPBaseGroups($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $bases = $this->userBackend->getLDAPAccess($uid)->getConnection()->ldapBaseGroups; @@ -224,7 +223,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function clearCache($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } $this->userBackend->getLDAPAccess($uid)->getConnection()->clearCache(); @@ -237,7 +236,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function clearGroupCache($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } $this->groupBackend->getLDAPAccess($gid)->getConnection()->clearCache(); @@ -276,7 +275,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPDisplayNameField($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_display_name']; @@ -289,7 +288,7 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if user id was not found in LDAP */ public function getLDAPEmailField($uid) { - if(!$this->userBackend->userExists($uid)){ + if (!$this->userBackend->userExists($uid)) { throw new \Exception('User id not found in LDAP'); } return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_email_attr']; @@ -302,10 +301,9 @@ class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport { * @throws \Exception if group id was not found in LDAP */ public function getLDAPGroupMemberAssoc($gid) { - if(!$this->groupBackend->groupExists($gid)){ + if (!$this->groupBackend->groupExists($gid)) { throw new \Exception('Group id not found in LDAP'); } return $this->groupBackend->getLDAPAccess($gid)->getConnection()->getConfiguration()['ldap_group_member_assoc_attribute']; } - } diff --git a/apps/user_ldap/lib/Mapping/AbstractMapping.php b/apps/user_ldap/lib/Mapping/AbstractMapping.php index 5d445af6b7e..e14c9a572de 100644 --- a/apps/user_ldap/lib/Mapping/AbstractMapping.php +++ b/apps/user_ldap/lib/Mapping/AbstractMapping.php @@ -55,7 +55,7 @@ abstract class AbstractMapping { * @return bool */ public function isColNameValid($col) { - switch($col) { + switch ($col) { case 'ldap_dn': case 'owncloud_name': case 'directory_uuid': @@ -74,7 +74,7 @@ abstract class AbstractMapping { * @return string|false */ protected function getXbyY($fetchCol, $compareCol, $search) { - if(!$this->isColNameValid($fetchCol)) { + if (!$this->isColNameValid($fetchCol)) { //this is used internally only, but we don't want to risk //having SQL injection at all. throw new \Exception('Invalid Column Name'); @@ -86,7 +86,7 @@ abstract class AbstractMapping { '); $res = $query->execute([$search]); - if($res !== false) { + if ($res !== false) { return $query->fetchColumn(); } @@ -174,8 +174,8 @@ abstract class AbstractMapping { $res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]); $names = []; - if($res !== false) { - while($row = $query->fetch()) { + if ($res !== false) { + while ($row = $query->fetch()) { $names[] = $row['owncloud_name']; } } @@ -230,7 +230,7 @@ abstract class AbstractMapping { * @return bool */ public function map($fdn, $name, $uuid) { - if(mb_strlen($fdn) > 255) { + if (mb_strlen($fdn) > 255) { \OC::$server->getLogger()->error( 'Cannot map, because the DN exceeds 255 characters: {dn}', [ @@ -295,9 +295,9 @@ abstract class AbstractMapping { ->from($this->getTableName()); $cursor = $picker->execute(); $result = true; - while($id = $cursor->fetchColumn(0)) { + while ($id = $cursor->fetchColumn(0)) { $preCallback($id); - if($isUnmapped = $this->unmap($id)) { + if ($isUnmapped = $this->unmap($id)) { $postCallback($id); } $result &= $isUnmapped; diff --git a/apps/user_ldap/lib/Mapping/GroupMapping.php b/apps/user_ldap/lib/Mapping/GroupMapping.php index cc779817f1a..b2c1b9c99af 100644 --- a/apps/user_ldap/lib/Mapping/GroupMapping.php +++ b/apps/user_ldap/lib/Mapping/GroupMapping.php @@ -36,5 +36,4 @@ class GroupMapping extends AbstractMapping { protected function getTableName() { return '*PREFIX*ldap_group_mapping'; } - } diff --git a/apps/user_ldap/lib/Mapping/UserMapping.php b/apps/user_ldap/lib/Mapping/UserMapping.php index 31ac8a05326..556f7ecf1a4 100644 --- a/apps/user_ldap/lib/Mapping/UserMapping.php +++ b/apps/user_ldap/lib/Mapping/UserMapping.php @@ -36,5 +36,4 @@ class UserMapping extends AbstractMapping { protected function getTableName() { return '*PREFIX*ldap_user_mapping'; } - } diff --git a/apps/user_ldap/lib/Migration/UUIDFix.php b/apps/user_ldap/lib/Migration/UUIDFix.php index f6359c2e882..f7e399a51bd 100644 --- a/apps/user_ldap/lib/Migration/UUIDFix.php +++ b/apps/user_ldap/lib/Migration/UUIDFix.php @@ -37,14 +37,14 @@ abstract class UUIDFix extends QueuedJob { public function run($argument) { $isUser = $this->proxy instanceof User_Proxy; - foreach($argument['records'] as $record) { + foreach ($argument['records'] as $record) { $access = $this->proxy->getLDAPAccess($record['name']); $uuid = $access->getUUID($record['dn'], $isUser); - if($uuid === false) { + if ($uuid === false) { // record not found, no prob, continue with the next continue; } - if($uuid !== $record['uuid']) { + if ($uuid !== $record['uuid']) { $this->mapper->setUUIDbyDN($uuid, $record['dn']); } } diff --git a/apps/user_ldap/lib/Migration/UUIDFixInsert.php b/apps/user_ldap/lib/Migration/UUIDFixInsert.php index 1674882803a..873c8bcd98e 100644 --- a/apps/user_ldap/lib/Migration/UUIDFixInsert.php +++ b/apps/user_ldap/lib/Migration/UUIDFixInsert.php @@ -72,7 +72,7 @@ class UUIDFixInsert implements IRepairStep { */ public function run(IOutput $output) { $installedVersion = $this->config->getAppValue('user_ldap', 'installed_version', '1.2.1'); - if(version_compare($installedVersion, '1.2.1') !== -1) { + if (version_compare($installedVersion, '1.2.1') !== -1) { return; } @@ -83,20 +83,19 @@ class UUIDFixInsert implements IRepairStep { do { $retry = false; $records = $mapper->getList($offset, $batchSize); - if(count($records) === 0){ + if (count($records) === 0) { continue; } try { $this->jobList->add($jobClass, ['records' => $records]); $offset += $batchSize; } catch (\InvalidArgumentException $e) { - if(strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) { + if (strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) { $batchSize = (int)floor(count($records) * 0.8); $retry = true; } } } while (count($records) === $batchSize || $retry); } - } } diff --git a/apps/user_ldap/lib/Notification/Notifier.php b/apps/user_ldap/lib/Notification/Notifier.php index 167f282beb7..d380e38a486 100644 --- a/apps/user_ldap/lib/Notification/Notifier.php +++ b/apps/user_ldap/lib/Notification/Notifier.php @@ -37,7 +37,7 @@ class Notifier implements INotifier { /** * @param IFactory $l10nFactory */ - public function __construct(\OCP\L10N\IFactory $l10nFactory) { + public function __construct(\OCP\L10N\IFactory $l10nFactory) { $this->l10nFactory = $l10nFactory; } diff --git a/apps/user_ldap/lib/Proxy.php b/apps/user_ldap/lib/Proxy.php index b077b0d5a86..7698895eaf0 100644 --- a/apps/user_ldap/lib/Proxy.php +++ b/apps/user_ldap/lib/Proxy.php @@ -50,7 +50,7 @@ abstract class Proxy { public function __construct(ILDAPWrapper $ldap) { $this->ldap = $ldap; $memcache = \OC::$server->getMemCacheFactory(); - if($memcache->isAvailable()) { + if ($memcache->isAvailable()) { $this->cache = $memcache->createDistributed(); } } @@ -68,7 +68,7 @@ abstract class Proxy { static $db; static $coreUserManager; static $coreNotificationManager; - if($fs === null) { + if ($fs === null) { $ocConfig = \OC::$server->getConfig(); $fs = new FilesystemHelper(); $log = new LogWrapper(); @@ -94,7 +94,7 @@ abstract class Proxy { * @return mixed */ protected function getAccess($configPrefix) { - if(!isset(self::$accesses[$configPrefix])) { + if (!isset(self::$accesses[$configPrefix])) { $this->addAccess($configPrefix); } return self::$accesses[$configPrefix]; @@ -149,7 +149,7 @@ abstract class Proxy { */ protected function handleRequest($id, $method, $parameters, $passOnWhen = false) { $result = $this->callOnLastSeenOn($id, $method, $parameters, $passOnWhen); - if($result === $passOnWhen) { + if ($result === $passOnWhen) { $result = $this->walkBackends($id, $method, $parameters); } return $result; @@ -161,7 +161,7 @@ abstract class Proxy { */ private function getCacheKey($key) { $prefix = 'LDAP-Proxy-'; - if($key === null) { + if ($key === null) { return $prefix; } return $prefix.hash('sha256', $key); @@ -172,7 +172,7 @@ abstract class Proxy { * @return mixed|null */ public function getFromCache($key) { - if($this->cache === null) { + if ($this->cache === null) { return null; } @@ -190,7 +190,7 @@ abstract class Proxy { * @param mixed $value */ public function writeToCache($key, $value) { - if($this->cache === null) { + if ($this->cache === null) { return; } $key = $this->getCacheKey($key); @@ -199,7 +199,7 @@ abstract class Proxy { } public function clearCache() { - if($this->cache === null) { + if ($this->cache === null) { return; } $this->cache->clear($this->getCacheKey(null)); diff --git a/apps/user_ldap/lib/Settings/Admin.php b/apps/user_ldap/lib/Settings/Admin.php index e9c883bd20d..f043d179e80 100644 --- a/apps/user_ldap/lib/Settings/Admin.php +++ b/apps/user_ldap/lib/Settings/Admin.php @@ -49,7 +49,7 @@ class Admin implements ISettings { public function getForm() { $helper = new Helper(\OC::$server->getConfig()); $prefixes = $helper->getServerConfigurationPrefixes(); - if(count($prefixes) === 0) { + if (count($prefixes) === 0) { $newPrefix = $helper->getNextServerConfigurationPrefix(); $config = new Configuration($newPrefix, false); $config->setConfiguration($config->getDefaults()); @@ -70,11 +70,11 @@ class Admin implements ISettings { $parameters['wizardControls'] = $wControls; // assign default values - if(!isset($config)) { + if (!isset($config)) { $config = new Configuration('', false); } $defaults = $config->getDefaults(); - foreach($defaults as $key => $default) { + foreach ($defaults as $key => $default) { $parameters[$key.'_default'] = $default; } diff --git a/apps/user_ldap/lib/User/DeletedUsersIndex.php b/apps/user_ldap/lib/User/DeletedUsersIndex.php index 98de28b6925..fee2b02d2c3 100644 --- a/apps/user_ldap/lib/User/DeletedUsersIndex.php +++ b/apps/user_ldap/lib/User/DeletedUsersIndex.php @@ -71,7 +71,7 @@ class DeletedUsersIndex { 'user_ldap', 'isDeleted', '1'); $userObjects = []; - foreach($deletedUsers as $user) { + foreach ($deletedUsers as $user) { $userObjects[] = new OfflineUser($user, $this->config, $this->db, $this->mapping); } $this->deletedUsers = $userObjects; @@ -84,7 +84,7 @@ class DeletedUsersIndex { * @return \OCA\User_LDAP\User\OfflineUser[] */ public function getUsers() { - if(is_array($this->deletedUsers)) { + if (is_array($this->deletedUsers)) { return $this->deletedUsers; } return $this->fetchDeletedUsers(); @@ -95,7 +95,7 @@ class DeletedUsersIndex { * @return bool */ public function hasUsers() { - if(!is_array($this->deletedUsers)) { + if (!is_array($this->deletedUsers)) { $this->fetchDeletedUsers(); } return is_array($this->deletedUsers) && (count($this->deletedUsers) > 0); @@ -109,7 +109,7 @@ class DeletedUsersIndex { */ public function markUser($ocName) { $curValue = $this->config->getUserValue($ocName, 'user_ldap', 'isDeleted', '0'); - if($curValue === '1') { + if ($curValue === '1') { // the user is already marked, do not write to DB again return; } diff --git a/apps/user_ldap/lib/User/Manager.php b/apps/user_ldap/lib/User/Manager.php index f3729f2458e..a62aa3b39ac 100644 --- a/apps/user_ldap/lib/User/Manager.php +++ b/apps/user_ldap/lib/User/Manager.php @@ -97,7 +97,6 @@ class Manager { IAvatarManager $avatarManager, Image $image, IDBConnection $db, IUserManager $userManager, INotificationManager $notificationManager) { - $this->ocConfig = $ocConfig; $this->ocFilesystem = $ocFilesystem; $this->ocLog = $ocLog; @@ -142,7 +141,7 @@ class Manager { * @param $uid */ public function invalidate($uid) { - if(!isset($this->usersByUid[$uid])) { + if (!isset($this->usersByUid[$uid])) { return; } $dn = $this->usersByUid[$uid]->getDN(); @@ -156,7 +155,7 @@ class Manager { * @return null */ private function checkAccess() { - if(is_null($this->access)) { + if (is_null($this->access)) { throw new \Exception('LDAP Access instance must be set first'); } } @@ -181,11 +180,11 @@ class Manager { ]; $homeRule = $this->access->getConnection()->homeFolderNamingRule; - if(strpos($homeRule, 'attr:') === 0) { + if (strpos($homeRule, 'attr:') === 0) { $attributes[] = substr($homeRule, strlen('attr:')); } - if(!$minimal) { + if (!$minimal) { // attributes that are not really important but may come with big // payload. $attributes = array_merge( @@ -197,7 +196,7 @@ class Manager { $attributes = array_reduce($attributes, function ($list, $attribute) { $attribute = strtolower(trim((string)$attribute)); - if(!empty($attribute) && !in_array($attribute, $list)) { + if (!empty($attribute) && !in_array($attribute, $list)) { $list[] = $attribute; } @@ -240,11 +239,11 @@ class Manager { */ protected function createInstancyByUserName($id) { //most likely a uid. Check whether it is a deleted user - if($this->isDeletedUser($id)) { + if ($this->isDeletedUser($id)) { return $this->getDeletedUser($id); } $dn = $this->access->username2dn($id); - if($dn !== false) { + if ($dn !== false) { return $this->createAndCache($dn, $id); } return null; @@ -258,20 +257,19 @@ class Manager { */ public function get($id) { $this->checkAccess(); - if(isset($this->usersByDN[$id])) { + if (isset($this->usersByDN[$id])) { return $this->usersByDN[$id]; - } elseif(isset($this->usersByUid[$id])) { + } elseif (isset($this->usersByUid[$id])) { return $this->usersByUid[$id]; } - if($this->access->stringResemblesDN($id)) { + if ($this->access->stringResemblesDN($id)) { $uid = $this->access->dn2username($id); - if($uid !== false) { + if ($uid !== false) { return $this->createAndCache($id, $uid); } } return $this->createInstancyByUserName($id); } - } diff --git a/apps/user_ldap/lib/User/OfflineUser.php b/apps/user_ldap/lib/User/OfflineUser.php index 60a39e95022..72d29dd5441 100644 --- a/apps/user_ldap/lib/User/OfflineUser.php +++ b/apps/user_ldap/lib/User/OfflineUser.php @@ -203,7 +203,7 @@ class OfflineUser { 'email' => 'settings', 'lastLogin' => 'login', ]; - foreach($properties as $property => $app) { + foreach ($properties as $property => $app) { $this->$property = $this->config->getUserValue($this->ocName, $app, $property, ''); } @@ -226,7 +226,7 @@ class OfflineUser { ', 1); $query->execute([$this->ocName]); $sResult = $query->fetchColumn(0); - if((int)$sResult === 1) { + if ((int)$sResult === 1) { $this->hasActiveShares = true; return; } @@ -238,7 +238,7 @@ class OfflineUser { ', 1); $query->execute([$this->ocName]); $sResult = $query->fetchColumn(0); - if((int)$sResult === 1) { + if ((int)$sResult === 1) { $this->hasActiveShares = true; return; } diff --git a/apps/user_ldap/lib/User/User.php b/apps/user_ldap/lib/User/User.php index 28eeddccef0..724db063659 100644 --- a/apps/user_ldap/lib/User/User.php +++ b/apps/user_ldap/lib/User/User.php @@ -127,7 +127,6 @@ class User { IConfig $config, FilesystemHelper $fs, Image $image, LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager, INotificationManager $notificationManager) { - if ($username === null) { $log->log("uid for '$dn' must not be null!", ILogger::ERROR); throw new \InvalidArgumentException('uid must not be null!'); @@ -156,17 +155,17 @@ class User { * @return null */ public function update() { - if(is_null($this->dn)) { + if (is_null($this->dn)) { return null; } $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 0); - if($this->needsRefresh()) { + if ($this->needsRefresh()) { $this->updateEmail(); $this->updateQuota(); - if($hasLoggedIn !== 0) { + if ($hasLoggedIn !== 0) { //we do not need to try it, when the user has not been logged in //before, because the file system will not be ready. $this->updateAvatar(); @@ -184,7 +183,7 @@ class User { */ public function markUser() { $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0'); - if($curValue === '1') { + if ($curValue === '1') { // the user is already marked, do not write to DB again return; } @@ -200,7 +199,7 @@ class User { $this->markRefreshTime(); //Quota $attr = strtolower($this->connection->ldapQuotaAttribute); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->updateQuota($ldapEntry[$attr][0]); } else { if ($this->connection->ldapQuotaDefault !== '') { @@ -212,11 +211,11 @@ class User { //displayName $displayName = $displayName2 = ''; $attr = strtolower($this->connection->ldapUserDisplayName); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $displayName = (string)$ldapEntry[$attr][0]; } $attr = strtolower($this->connection->ldapUserDisplayName2); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $displayName2 = (string)$ldapEntry[$attr][0]; } if ($displayName !== '') { @@ -233,22 +232,22 @@ class User { //email must be stored after displayname, because it would cause a user //change event that will trigger fetching the display name again $attr = strtolower($this->connection->ldapEmailAttribute); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->updateEmail($ldapEntry[$attr][0]); } unset($attr); // LDAP Username, needed for s2s sharing - if(isset($ldapEntry['uid'])) { + if (isset($ldapEntry['uid'])) { $this->storeLDAPUserName($ldapEntry['uid'][0]); - } elseif(isset($ldapEntry['samaccountname'])) { + } elseif (isset($ldapEntry['samaccountname'])) { $this->storeLDAPUserName($ldapEntry['samaccountname'][0]); } //homePath - if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) { + if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) { $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:'))); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->access->cacheUserHome( $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0])); } @@ -257,14 +256,14 @@ class User { //memberOf groups $cacheKey = 'getMemberOf'.$this->getUsername(); $groups = false; - if(isset($ldapEntry['memberof'])) { + if (isset($ldapEntry['memberof'])) { $groups = $ldapEntry['memberof']; } $this->connection->writeToCache($cacheKey, $groups); //external storage var $attr = strtolower($this->connection->ldapExtStorageHomeAttribute); - if(isset($ldapEntry[$attr])) { + if (isset($ldapEntry[$attr])) { $this->updateExtStorageHome($ldapEntry[$attr][0]); } unset($attr); @@ -273,8 +272,8 @@ class User { /** @var Connection $connection */ $connection = $this->access->getConnection(); $attributes = $connection->resolveRule('avatar'); - foreach ($attributes as $attribute) { - if(isset($ldapEntry[$attribute])) { + foreach ($attributes as $attribute) { + if (isset($ldapEntry[$attribute])) { $this->avatarImage = $ldapEntry[$attribute][0]; // the call to the method that saves the avatar in the file // system must be postponed after the login. It is to ensure @@ -314,8 +313,7 @@ class User { if (is_null($valueFromLDAP) && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0 - && $this->access->connection->homeFolderNamingRule !== 'attr:') - { + && $this->access->connection->homeFolderNamingRule !== 'attr:') { $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:')); $homedir = $this->access->readAttribute( $this->access->username2dn($this->getUsername()), $attr); @@ -327,7 +325,7 @@ class User { if ($path !== '') { //if attribute's value is an absolute path take this, otherwise append it to data dir //check for / at the beginning or pattern c:\ resp. c:/ - if('/' !== $path[0] + if ('/' !== $path[0] && !(3 < strlen($path) && ctype_alpha($path[0]) && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2])) ) { @@ -342,7 +340,7 @@ class User { return $path; } - if(!is_null($attr) + if (!is_null($attr) && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true) ) { // a naming rule attribute is defined, but it doesn't exist for that LDAP user @@ -357,7 +355,7 @@ class User { public function getMemberOfGroups() { $cacheKey = 'getMemberOf'.$this->getUsername(); $memberOfGroups = $this->connection->getFromCache($cacheKey); - if(!is_null($memberOfGroups)) { + if (!is_null($memberOfGroups)) { return $memberOfGroups; } $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf'); @@ -370,7 +368,7 @@ class User { * @return string data (provided by LDAP) | false */ public function getAvatarImage() { - if(!is_null($this->avatarImage)) { + if (!is_null($this->avatarImage)) { return $this->avatarImage; } @@ -378,9 +376,9 @@ class User { /** @var Connection $connection */ $connection = $this->access->getConnection(); $attributes = $connection->resolveRule('avatar'); - foreach($attributes as $attribute) { + foreach ($attributes as $attribute) { $result = $this->access->readAttribute($this->dn, $attribute); - if($result !== false && is_array($result) && isset($result[0])) { + if ($result !== false && is_array($result) && isset($result[0])) { $this->avatarImage = $result[0]; break; } @@ -417,7 +415,7 @@ class User { $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, 0); - if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) { + if ((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) { return false; } return true; @@ -443,11 +441,11 @@ class User { */ public function composeAndStoreDisplayName($displayName, $displayName2 = '') { $displayName2 = (string)$displayName2; - if($displayName2 !== '') { + if ($displayName2 !== '') { $displayName .= ' (' . $displayName2 . ')'; } $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null); - if ($oldName !== $displayName) { + if ($oldName !== $displayName) { $this->store('displayName', $displayName); $user = $this->userManager->get($this->getUsername()); if (!empty($oldName) && $user instanceof \OC\User\User) { @@ -475,7 +473,7 @@ class User { * @return bool */ private function wasRefreshed($feature) { - if(isset($this->refreshedFeatures[$feature])) { + if (isset($this->refreshedFeatures[$feature])) { return true; } $this->refreshedFeatures[$feature] = 1; @@ -488,15 +486,15 @@ class User { * @return null */ public function updateEmail($valueFromLDAP = null) { - if($this->wasRefreshed('email')) { + if ($this->wasRefreshed('email')) { return; } $email = (string)$valueFromLDAP; - if(is_null($valueFromLDAP)) { + if (is_null($valueFromLDAP)) { $emailAttribute = $this->connection->ldapEmailAttribute; if ($emailAttribute !== '') { $aEmail = $this->access->readAttribute($this->dn, $emailAttribute); - if(is_array($aEmail) && (count($aEmail) > 0)) { + if (is_array($aEmail) && (count($aEmail) > 0)) { $email = (string)$aEmail[0]; } } @@ -533,22 +531,22 @@ class User { * @return null */ public function updateQuota($valueFromLDAP = null) { - if($this->wasRefreshed('quota')) { + if ($this->wasRefreshed('quota')) { return; } $quotaAttribute = $this->connection->ldapQuotaAttribute; $defaultQuota = $this->connection->ldapQuotaDefault; - if($quotaAttribute === '' && $defaultQuota === '') { + if ($quotaAttribute === '' && $defaultQuota === '') { return; } $quota = false; - if(is_null($valueFromLDAP) && $quotaAttribute !== '') { + if (is_null($valueFromLDAP) && $quotaAttribute !== '') { $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute); - if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) { + if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) { $quota = $aQuota[0]; - } elseif(is_array($aQuota) && isset($aQuota[0])) { + } elseif (is_array($aQuota) && isset($aQuota[0])) { $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG); } } elseif ($this->verifyQuotaValue($valueFromLDAP)) { @@ -560,7 +558,7 @@ class User { if ($quota === false && $this->verifyQuotaValue($defaultQuota)) { // quota not found using the LDAP attribute (or not parseable). Try the default quota $quota = $defaultQuota; - } elseif($quota === false) { + } elseif ($quota === false) { $this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG); return; } @@ -583,7 +581,7 @@ class User { * @param array $params */ public function updateAvatarPostLogin($params) { - if(isset($params['uid']) && $params['uid'] === $this->getUsername()) { + if (isset($params['uid']) && $params['uid'] === $this->getUsername()) { $this->updateAvatar(); } } @@ -593,29 +591,29 @@ class User { * @return bool */ public function updateAvatar($force = false) { - if(!$force && $this->wasRefreshed('avatar')) { + if (!$force && $this->wasRefreshed('avatar')) { return false; } $avatarImage = $this->getAvatarImage(); - if($avatarImage === false) { + if ($avatarImage === false) { //not set, nothing left to do; return false; } - if(!$this->image->loadFromBase64(base64_encode($avatarImage))) { + if (!$this->image->loadFromBase64(base64_encode($avatarImage))) { return false; } // use the checksum before modifications $checksum = md5($this->image->data()); - if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) { + if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) { return true; } $isSet = $this->setOwnCloudAvatar(); - if($isSet) { + if ($isSet) { // save checksum only after successful setting $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum); } @@ -628,7 +626,7 @@ class User { * @return bool */ private function setOwnCloudAvatar() { - if(!$this->image->valid()) { + if (!$this->image->valid()) { $this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR); return false; } @@ -636,12 +634,12 @@ class User { //make sure it is a square and not bigger than 128x128 $size = min([$this->image->width(), $this->image->height(), 128]); - if(!$this->image->centerCrop($size)) { + if (!$this->image->centerCrop($size)) { $this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR); return false; } - if(!$this->fs->isLoaded()) { + if (!$this->fs->isLoaded()) { $this->fs->setup($this->uid); } @@ -717,7 +715,7 @@ class User { if (array_key_exists('pwdpolicysubentry', $result[0])) { $pwdPolicySubentry = $result[0]['pwdpolicysubentry']; - if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){ + if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) { $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN } } @@ -729,7 +727,7 @@ class User { //retrieve relevant password policy attributes $cacheKey = 'ppolicyAttributes' . $ppolicyDN; $result = $this->connection->getFromCache($cacheKey); - if(is_null($result)) { + if (is_null($result)) { $result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']); $this->connection->writeToCache($cacheKey, $result); } @@ -764,7 +762,7 @@ class User { && !empty($pwdExpireWarning)) { $pwdMaxAgeInt = (int)$pwdMaxAge[0]; $pwdExpireWarningInt = (int)$pwdExpireWarning[0]; - if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){ + if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) { $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]); $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S')); $currentDateTime = new \DateTime(); diff --git a/apps/user_ldap/lib/UserPluginManager.php b/apps/user_ldap/lib/UserPluginManager.php index f240d4493c3..2d99d887604 100644 --- a/apps/user_ldap/lib/UserPluginManager.php +++ b/apps/user_ldap/lib/UserPluginManager.php @@ -28,7 +28,6 @@ namespace OCA\User_LDAP; use OC\User\Backend; class UserPluginManager { - public $test = false; private $respondToActions = 0; @@ -60,7 +59,7 @@ class UserPluginManager { $respondToActions = $plugin->respondToActions(); $this->respondToActions |= $respondToActions; - foreach($this->which as $action => $v) { + foreach ($this->which as $action => $v) { if (is_int($action) && (bool)($respondToActions & $action)) { $this->which[$action] = $plugin; \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']); diff --git a/apps/user_ldap/lib/User_LDAP.php b/apps/user_ldap/lib/User_LDAP.php index 08b0464cc50..4e5af690387 100644 --- a/apps/user_ldap/lib/User_LDAP.php +++ b/apps/user_ldap/lib/User_LDAP.php @@ -87,16 +87,16 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn return $this->userPluginManager->canChangeAvatar($uid); } - if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) { + if (!$this->implementsActions(Backend::PROVIDE_AVATAR)) { return true; } $user = $this->access->userManager->get($uid); - if(!$user instanceof User) { + if (!$user instanceof User) { return false; } $imageData = $user->getAvatarImage(); - if($imageData === false) { + if ($imageData === false) { return true; } return !$user->updateAvatar(true); @@ -156,7 +156,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn //find out dn of the user name $attrs = $this->access->userManager->getAttributes(); $users = $this->access->fetchUsersByLoginName($loginName, $attrs); - if(count($users) < 1) { + if (count($users) < 1) { throw new NotOnLDAP('No user available for the given login name on ' . $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort); } @@ -173,23 +173,23 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn public function checkPassword($uid, $password) { try { $ldapRecord = $this->getLDAPUserByLoginName($uid); - } catch(NotOnLDAP $e) { + } catch (NotOnLDAP $e) { \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]); return false; } $dn = $ldapRecord['dn'][0]; $user = $this->access->userManager->get($dn); - if(!$user instanceof User) { + if (!$user instanceof User) { Util::writeLog('user_ldap', 'LDAP Login: Could not get user object for DN ' . $dn . '. Maybe the LDAP entry has no set display name attribute?', ILogger::WARN); return false; } - if($user->getUsername() !== false) { + if ($user->getUsername() !== false) { //are the credentials OK? - if(!$this->access->areCredentialsValid($dn, $password)) { + if (!$this->access->areCredentialsValid($dn, $password)) { return false; } @@ -216,11 +216,11 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $user = $this->access->userManager->get($uid); - if(!$user instanceof User) { + if (!$user instanceof User) { throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid . '. Maybe the LDAP entry has no set display name attribute?'); } - if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) { + if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) { $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN; $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange; if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) { @@ -252,13 +252,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn //check if users are cached, if so return $ldap_users = $this->access->connection->getFromCache($cachekey); - if(!is_null($ldap_users)) { + if (!is_null($ldap_users)) { return $ldap_users; } // if we'd pass -1 to LDAP search, we'd end up in a Protocol // error. With a limit of 0, we get 0 results. So we pass null. - if($limit <= 0) { + if ($limit <= 0) { $limit = null; } $filter = $this->access->combineFilterWithAnd([ @@ -292,22 +292,22 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn * @throws \OC\ServerNotAvailableException */ public function userExistsOnLDAP($user) { - if(is_string($user)) { + if (is_string($user)) { $user = $this->access->userManager->get($user); } - if(is_null($user)) { + if (is_null($user)) { return false; } $uid = $user instanceof User ? $user->getUsername() : $user->getOCName(); $cacheKey = 'userExistsOnLDAP' . $uid; $userExists = $this->access->connection->getFromCache($cacheKey); - if(!is_null($userExists)) { + if (!is_null($userExists)) { return (bool)$userExists; } $dn = $user->getDN(); //check if user really still exists by reading its entry - if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) { + if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) { try { $uuid = $this->access->getUserMapper()->getUUIDByDN($dn); if (!$uuid) { @@ -331,7 +331,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn } } - if($user instanceof OfflineUser) { + if ($user instanceof OfflineUser) { $user->unmark(); } @@ -347,13 +347,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn */ public function userExists($uid) { $userExists = $this->access->connection->getFromCache('userExists'.$uid); - if(!is_null($userExists)) { + if (!is_null($userExists)) { return (bool)$userExists; } //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking. $user = $this->access->userManager->get($uid); - if(is_null($user)) { + if (is_null($user)) { Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '. $this->access->connection->ldapHost, ILogger::DEBUG); $this->access->connection->writeToCache('userExists'.$uid, false); @@ -373,13 +373,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn public function deleteUser($uid) { if ($this->userPluginManager->canDeleteUser()) { $status = $this->userPluginManager->deleteUser($uid); - if($status === false) { + if ($status === false) { return false; } } $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0); - if((int)$marked === 0) { + if ((int)$marked === 0) { \OC::$server->getLogger()->notice( 'User '.$uid . ' is not marked as deleted, not cleaning up.', ['app' => 'user_ldap']); @@ -403,7 +403,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn */ public function getHome($uid) { // user Exists check required as it is not done in user proxy! - if(!$this->userExists($uid)) { + if (!$this->userExists($uid)) { return false; } @@ -413,13 +413,13 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $cacheKey = 'getHome'.$uid; $path = $this->access->connection->getFromCache($cacheKey); - if(!is_null($path)) { + if (!is_null($path)) { return $path; } // early return path if it is a deleted user $user = $this->access->userManager->get($uid); - if($user instanceof User || $user instanceof OfflineUser) { + if ($user instanceof User || $user instanceof OfflineUser) { $path = $user->getHomePath() ?: false; } else { throw new NoUserException($uid . ' is not a valid user anymore'); @@ -439,12 +439,12 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn return $this->userPluginManager->getDisplayName($uid); } - if(!$this->userExists($uid)) { + if (!$this->userExists($uid)) { return false; } $cacheKey = 'getDisplayName'.$uid; - if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { + if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { return $displayName; } @@ -461,10 +461,10 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $this->access->username2dn($uid), $this->access->connection->ldapUserDisplayName); - if($displayName && (count($displayName) > 0)) { + if ($displayName && (count($displayName) > 0)) { $displayName = $displayName[0]; - if (is_array($displayName2)){ + if (is_array($displayName2)) { $displayName2 = count($displayName2) > 0 ? $displayName2[0] : ''; } @@ -508,7 +508,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn */ public function getDisplayNames($search = '', $limit = null, $offset = null) { $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset; - if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) { + if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) { return $displayNames; } @@ -559,7 +559,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn $filter = $this->access->getFilterForUserCount(); $cacheKey = 'countUsers-'.$filter; - if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) { + if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) { return $entries; } $entries = $this->access->countUsers($filter); @@ -609,7 +609,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn if (is_string($dn)) { // the NC user creation work flow requires a know user id up front $uuid = $this->access->getUUID($dn, true); - if(is_string($uuid)) { + if (is_string($uuid)) { $this->access->mapAndAnnounceIfApplicable( $this->access->getUserMapper(), $dn, @@ -635,5 +635,4 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn } return false; } - } diff --git a/apps/user_ldap/lib/User_Proxy.php b/apps/user_ldap/lib/User_Proxy.php index 27e8c42ae73..e9ff92d03eb 100644 --- a/apps/user_ldap/lib/User_Proxy.php +++ b/apps/user_ldap/lib/User_Proxy.php @@ -60,11 +60,11 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, UserPluginManager $userPluginManager ) { parent::__construct($ldap); - foreach($serverConfigPrefixes as $configPrefix) { + foreach ($serverConfigPrefixes as $configPrefix) { $this->backends[$configPrefix] = new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager); - if(is_null($this->refBackend)) { + if (is_null($this->refBackend)) { $this->refBackend = &$this->backends[$configPrefix]; } } @@ -79,13 +79,13 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, */ protected function walkBackends($uid, $method, $parameters) { $cacheKey = $this->getUserCacheKey($uid); - foreach($this->backends as $configPrefix => $backend) { + foreach ($this->backends as $configPrefix => $backend) { $instance = $backend; - if(!method_exists($instance, $method) + if (!method_exists($instance, $method) && method_exists($this->getAccess($configPrefix), $method)) { $instance = $this->getAccess($configPrefix); } - if($result = call_user_func_array([$instance, $method], $parameters)) { + if ($result = call_user_func_array([$instance, $method], $parameters)) { $this->writeToCache($cacheKey, $configPrefix); return $result; } @@ -105,22 +105,22 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, $cacheKey = $this->getUserCacheKey($uid); $prefix = $this->getFromCache($cacheKey); //in case the uid has been found in the past, try this stored connection first - if(!is_null($prefix)) { - if(isset($this->backends[$prefix])) { + if (!is_null($prefix)) { + if (isset($this->backends[$prefix])) { $instance = $this->backends[$prefix]; - if(!method_exists($instance, $method) + if (!method_exists($instance, $method) && method_exists($this->getAccess($prefix), $method)) { $instance = $this->getAccess($prefix); } $result = call_user_func_array([$instance, $method], $parameters); - if($result === $passOnWhen) { + if ($result === $passOnWhen) { //not found here, reset cache to null if user vanished //because sometimes methods return false with a reason $userExists = call_user_func_array( [$this->backends[$prefix], 'userExistsOnLDAP'], [$uid] ); - if(!$userExists) { + if (!$userExists) { $this->writeToCache($cacheKey, null); } } @@ -162,7 +162,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, public function getUsers($search = '', $limit = 10, $offset = 0) { //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends $users = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->getUsers($search, $limit, $offset); if (is_array($backendUsers)) { $users = array_merge($users, $backendUsers); @@ -179,13 +179,13 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, public function userExists($uid) { $existsOnLDAP = false; $existsLocally = $this->handleRequest($uid, 'userExists', [$uid]); - if($existsLocally) { + if ($existsLocally) { $existsOnLDAP = $this->userExistsOnLDAP($uid); } - if($existsLocally && !$existsOnLDAP) { + if ($existsLocally && !$existsOnLDAP) { try { $user = $this->getLDAPAccess($uid)->userManager->get($uid); - if($user instanceof User) { + if ($user instanceof User) { $user->markUser(); } } catch (\Exception $e) { @@ -288,7 +288,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, public function getDisplayNames($search = '', $limit = null, $offset = null) { //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends $users = []; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->getDisplayNames($search, $limit, $offset); if (is_array($backendUsers)) { $users = $users + $backendUsers; @@ -332,7 +332,7 @@ class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, */ public function countUsers() { $users = false; - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { $backendUsers = $backend->countUsers(); if ($backendUsers !== false) { $users += $backendUsers; diff --git a/apps/user_ldap/lib/Wizard.php b/apps/user_ldap/lib/Wizard.php index a0dcd0febbf..01a9e19076d 100644 --- a/apps/user_ldap/lib/Wizard.php +++ b/apps/user_ldap/lib/Wizard.php @@ -72,7 +72,7 @@ class Wizard extends LDAPUtility { public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) { parent::__construct($ldap); $this->configuration = $configuration; - if(is_null(Wizard::$l)) { + if (is_null(Wizard::$l)) { Wizard::$l = \OC::$server->getL10N('user_ldap'); } $this->access = $access; @@ -80,7 +80,7 @@ class Wizard extends LDAPUtility { } public function __destruct() { - if($this->result->hasChanges()) { + if ($this->result->hasChanges()) { $this->configuration->saveConfiguration(); } } @@ -95,18 +95,18 @@ class Wizard extends LDAPUtility { */ public function countEntries(string $filter, string $type): int { $reqs = ['ldapHost', 'ldapPort', 'ldapBase']; - if($type === 'users') { + if ($type === 'users') { $reqs[] = 'ldapUserFilter'; } - if(!$this->checkRequirements($reqs)) { + if (!$this->checkRequirements($reqs)) { throw new \Exception('Requirements not met', 400); } $attr = ['dn']; // default $limit = 1001; - if($type === 'groups') { + if ($type === 'groups') { $result = $this->access->countGroups($filter, $attr, $limit); - } elseif($type === 'users') { + } elseif ($type === 'users') { $result = $this->access->countUsers($filter, $attr, $limit); } elseif ($type === 'objects') { $result = $this->access->countObjects($limit); @@ -125,7 +125,7 @@ class Wizard extends LDAPUtility { * @return string */ private function formatCountResult(int $count): string { - if($count > 1000) { + if ($count > 1000) { return '> 1000'; } return (string)$count; @@ -134,7 +134,7 @@ class Wizard extends LDAPUtility { public function countGroups() { $filter = $this->configuration->ldapGroupFilter; - if(empty($filter)) { + if (empty($filter)) { $output = self::$l->n('%s group found', '%s groups found', 0, [0]); $this->result->addChange('ldap_group_count', $output); return $this->result; @@ -144,7 +144,7 @@ class Wizard extends LDAPUtility { $groupsTotal = $this->countEntries($filter, 'groups'); } catch (\Exception $e) { //400 can be ignored, 500 is forwarded - if($e->getCode() === 500) { + if ($e->getCode() === 500) { throw $e; } return false; @@ -186,7 +186,7 @@ class Wizard extends LDAPUtility { public function countInBaseDN() { // we don't need to provide a filter in this case $total = $this->countEntries('', 'objects'); - if($total === false) { + if ($total === false) { throw new \Exception('invalid results received'); } $this->result->addChange('ldap_test_base', $total); @@ -200,7 +200,7 @@ class Wizard extends LDAPUtility { * @return int|bool */ public function countUsersWithAttribute($attr, $existsCheck = false) { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -225,7 +225,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function detectUserDisplayNameAttribute() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -238,7 +238,7 @@ class Wizard extends LDAPUtility { // most likely not the default value with upper case N, // verify it still produces a result $count = (int)$this->countUsersWithAttribute($attr, true); - if($count > 0) { + if ($count > 0) { //no change, but we sent it back to make sure the user interface //is still correct, even if the ajax call was cancelled meanwhile $this->result->addChange('ldap_display_name', $attr); @@ -251,7 +251,7 @@ class Wizard extends LDAPUtility { foreach ($displayNameAttrs as $attr) { $count = (int)$this->countUsersWithAttribute($attr, true); - if($count > 0) { + if ($count > 0) { $this->applyFind('ldap_display_name', $attr); return $this->result; } @@ -267,7 +267,7 @@ class Wizard extends LDAPUtility { * @return WizardResult|bool */ public function detectEmailAttribute() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -278,7 +278,7 @@ class Wizard extends LDAPUtility { $attr = $this->configuration->ldapEmailAttribute; if ($attr !== '') { $count = (int)$this->countUsersWithAttribute($attr, true); - if($count > 0) { + if ($count > 0) { return false; } $writeLog = true; @@ -289,17 +289,17 @@ class Wizard extends LDAPUtility { $emailAttributes = ['mail', 'mailPrimaryAddress']; $winner = ''; $maxUsers = 0; - foreach($emailAttributes as $attr) { + foreach ($emailAttributes as $attr) { $count = $this->countUsersWithAttribute($attr); - if($count > $maxUsers) { + if ($count > $maxUsers) { $maxUsers = $count; $winner = $attr; } } - if($winner !== '') { + if ($winner !== '') { $this->applyFind('ldap_email_attr', $winner); - if($writeLog) { + if ($writeLog) { \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' . 'automatically been reset, because the original value ' . 'did not return any results.', ILogger::INFO); @@ -314,7 +314,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function determineAttributes() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -330,7 +330,7 @@ class Wizard extends LDAPUtility { $this->result->addOptions('ldap_loginfilter_attributes', $attributes); $selected = $this->configuration->ldapLoginFilterAttributes; - if(is_array($selected) && !empty($selected)) { + if (is_array($selected) && !empty($selected)) { $this->result->addChange('ldap_loginfilter_attributes', $selected); } @@ -343,7 +343,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ private function getUserAttributes() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -351,20 +351,20 @@ class Wizard extends LDAPUtility { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $base = $this->configuration->ldapBase[0]; $filter = $this->configuration->ldapUserFilter; $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { return false; } $er = $this->ldap->firstEntry($cr, $rr); $attributes = $this->ldap->getAttributes($cr, $er); $pureAttributes = []; - for($i = 0; $i < $attributes['count']; $i++) { + for ($i = 0; $i < $attributes['count']; $i++) { $pureAttributes[] = $attributes[$i]; } @@ -399,23 +399,23 @@ class Wizard extends LDAPUtility { * @throws \Exception */ private function determineGroups($dbKey, $confKey, $testMemberOf = true) { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $this->fetchGroups($dbKey, $confKey); - if($testMemberOf) { + if ($testMemberOf) { $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf(); $this->result->markChange(); - if(!$this->configuration->hasMemberOfFilterSupport) { + if (!$this->configuration->hasMemberOfFilterSupport) { throw new \Exception('memberOf is not supported by the server'); } } @@ -435,7 +435,7 @@ class Wizard extends LDAPUtility { $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames']; $filterParts = []; - foreach($obclasses as $obclass) { + foreach ($obclasses as $obclass) { $filterParts[] = 'objectclass='.$obclass; } //we filter for everything @@ -452,8 +452,8 @@ class Wizard extends LDAPUtility { // we need to request dn additionally here, otherwise memberOf // detection will fail later $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset); - foreach($result as $item) { - if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { + foreach ($result as $item) { + if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { // just in case - no issue known continue; } @@ -463,7 +463,7 @@ class Wizard extends LDAPUtility { $offset += $limit; } while ($this->access->hasMoreResults()); - if(count($groupNames) > 0) { + if (count($groupNames) > 0) { natsort($groupNames); $this->result->addOptions($dbKey, array_values($groupNames)); } else { @@ -471,7 +471,7 @@ class Wizard extends LDAPUtility { } $setFeatures = $this->configuration->$confKey; - if(is_array($setFeatures) && !empty($setFeatures)) { + if (is_array($setFeatures) && !empty($setFeatures)) { //something is already configured? pre-select it. $this->result->addChange($dbKey, $setFeatures); } @@ -479,14 +479,14 @@ class Wizard extends LDAPUtility { } public function determineGroupMemberAssoc() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapGroupFilter', ])) { return false; } $attribute = $this->detectGroupMemberAssoc(); - if($attribute === false) { + if ($attribute === false) { return false; } $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]); @@ -501,14 +501,14 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function determineGroupObjectClasses() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } @@ -528,14 +528,14 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function determineUserObjectClasses() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } @@ -558,7 +558,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function getGroupFilter() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { @@ -582,7 +582,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function getUserListFilter() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', ])) { @@ -595,7 +595,7 @@ class Wizard extends LDAPUtility { $this->applyFind('ldap_display_name', $d['ldap_display_name']); } $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST); - if(!$filter) { + if (!$filter) { throw new \Exception('Cannot create filter'); } @@ -608,7 +608,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function getUserLoginFilter() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapUserFilter', @@ -617,7 +617,7 @@ class Wizard extends LDAPUtility { } $filter = $this->composeLdapFilter(self::LFILTER_LOGIN); - if(!$filter) { + if (!$filter) { throw new \Exception('Cannot create filter'); } @@ -631,7 +631,7 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function testLoginName($loginName) { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', 'ldapBase', 'ldapLoginFilter', @@ -640,17 +640,17 @@ class Wizard extends LDAPUtility { } $cr = $this->access->connection->getConnectionResource(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { throw new \Exception('connection error'); } - if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') + if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') === false) { throw new \Exception('missing placeholder'); } $users = $this->access->countUsersByLoginName($loginName); - if($this->ldap->errno($cr) !== 0) { + if ($this->ldap->errno($cr) !== 0) { throw new \Exception($this->ldap->error($cr)); } $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter); @@ -665,19 +665,19 @@ class Wizard extends LDAPUtility { * @throws \Exception */ public function guessPortAndTLS() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', ])) { return false; } $this->checkHost(); $portSettings = $this->getPortSettingsToTry(); - if(!is_array($portSettings)) { + if (!is_array($portSettings)) { throw new \Exception(print_r($portSettings, true)); } //proceed from the best configuration and return on first success - foreach($portSettings as $setting) { + foreach ($portSettings as $setting) { $p = $setting['port']; $t = $setting['tls']; \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG); @@ -690,7 +690,7 @@ class Wizard extends LDAPUtility { // any reply other than -1 (= cannot connect) is already okay, // because then we found the server // unavailable startTLS returns -11 - if($e->getCode() > 0) { + if ($e->getCode() > 0) { $settingsFound = true; } else { throw $e; @@ -718,7 +718,7 @@ class Wizard extends LDAPUtility { * @return WizardResult|false WizardResult on success, false otherwise */ public function guessBaseDN() { - if(!$this->checkRequirements(['ldapHost', + if (!$this->checkRequirements(['ldapHost', 'ldapPort', ])) { return false; @@ -727,9 +727,9 @@ class Wizard extends LDAPUtility { //check whether a DN is given in the agent name (99.9% of all cases) $base = null; $i = stripos($this->configuration->ldapAgentName, 'dc='); - if($i !== false) { + if ($i !== false) { $base = substr($this->configuration->ldapAgentName, $i); - if($this->testBaseDN($base)) { + if ($this->testBaseDN($base)) { $this->applyFind('ldap_base', $base); return $this->result; } @@ -740,12 +740,12 @@ class Wizard extends LDAPUtility { //a base DN $helper = new Helper(\OC::$server->getConfig()); $domain = $helper->getDomainFromURL($this->configuration->ldapHost); - if(!$domain) { + if (!$domain) { return false; } $dparts = explode('.', $domain); - while(count($dparts) > 0) { + while (count($dparts) > 0) { $base2 = 'dc=' . implode(',dc=', $dparts); if ($base !== $base2 && $this->testBaseDN($base2)) { $this->applyFind('ldap_base', $base2); @@ -779,7 +779,7 @@ class Wizard extends LDAPUtility { $hostInfo = parse_url($host); //removes Port from Host - if(is_array($hostInfo) && isset($hostInfo['port'])) { + if (is_array($hostInfo) && isset($hostInfo['port'])) { $port = $hostInfo['port']; $host = str_replace(':'.$port, '', $host); $this->applyFind('ldap_host', $host); @@ -796,30 +796,30 @@ class Wizard extends LDAPUtility { private function detectGroupMemberAssoc() { $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber']; $filter = $this->configuration->ldapGroupFilter; - if(empty($filter)) { + if (empty($filter)) { return false; } $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0]; $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { return false; } $er = $this->ldap->firstEntry($cr, $rr); - while(is_resource($er)) { + while (is_resource($er)) { $this->ldap->getDN($cr, $er); $attrs = $this->ldap->getAttributes($cr, $er); $result = []; $possibleAttrsCount = count($possibleAttrs); - for($i = 0; $i < $possibleAttrsCount; $i++) { - if(isset($attrs[$possibleAttrs[$i]])) { + for ($i = 0; $i < $possibleAttrsCount; $i++) { + if (isset($attrs[$possibleAttrs[$i]])) { $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count']; } } - if(!empty($result)) { + if (!empty($result)) { natsort($result); return key($result); } @@ -838,14 +838,14 @@ class Wizard extends LDAPUtility { */ private function testBaseDN($base) { $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } //base is there, let's validate it. If we search for anything, we should //get a result set > 0 on a proper base $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { $errorNo = $this->ldap->errno($cr); $errorMsg = $this->ldap->error($cr); \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base. @@ -867,11 +867,11 @@ class Wizard extends LDAPUtility { */ private function testMemberOf() { $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1); - if(is_int($result) && $result > 0) { + if (is_int($result) && $result > 0) { return true; } return false; @@ -892,27 +892,27 @@ class Wizard extends LDAPUtility { case self::LFILTER_USER_LIST: $objcs = $this->configuration->ldapUserFilterObjectclass; //glue objectclasses - if(is_array($objcs) && count($objcs) > 0) { + if (is_array($objcs) && count($objcs) > 0) { $filter .= '(|'; - foreach($objcs as $objc) { + foreach ($objcs as $objc) { $filter .= '(objectclass=' . $objc . ')'; } $filter .= ')'; $parts++; } //glue group memberships - if($this->configuration->hasMemberOfFilterSupport) { + if ($this->configuration->hasMemberOfFilterSupport) { $cns = $this->configuration->ldapUserFilterGroups; - if(is_array($cns) && count($cns) > 0) { + if (is_array($cns) && count($cns) > 0) { $filter .= '(|'; $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $base = $this->configuration->ldapBase[0]; - foreach($cns as $cn) { + foreach ($cns as $cn) { $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { continue; } $er = $this->ldap->firstEntry($cr, $rr); @@ -922,7 +922,7 @@ class Wizard extends LDAPUtility { continue; } $filterPart = '(memberof=' . $dn . ')'; - if(isset($attrs['primaryGroupToken'])) { + if (isset($attrs['primaryGroupToken'])) { $pgt = $attrs['primaryGroupToken'][0]; $primaryFilterPart = '(primaryGroupID=' . $pgt .')'; $filterPart = '(|' . $filterPart . $primaryFilterPart . ')'; @@ -934,7 +934,7 @@ class Wizard extends LDAPUtility { $parts++; } //wrap parts in AND condition - if($parts > 1) { + if ($parts > 1) { $filter = '(&' . $filter . ')'; } if ($filter === '') { @@ -945,9 +945,9 @@ class Wizard extends LDAPUtility { case self::LFILTER_GROUP_LIST: $objcs = $this->configuration->ldapGroupFilterObjectclass; //glue objectclasses - if(is_array($objcs) && count($objcs) > 0) { + if (is_array($objcs) && count($objcs) > 0) { $filter .= '(|'; - foreach($objcs as $objc) { + foreach ($objcs as $objc) { $filter .= '(objectclass=' . $objc . ')'; } $filter .= ')'; @@ -955,16 +955,16 @@ class Wizard extends LDAPUtility { } //glue group memberships $cns = $this->configuration->ldapGroupFilterGroups; - if(is_array($cns) && count($cns) > 0) { + if (is_array($cns) && count($cns) > 0) { $filter .= '(|'; - foreach($cns as $cn) { + foreach ($cns as $cn) { $filter .= '(cn=' . $cn . ')'; } $filter .= ')'; } $parts++; //wrap parts in AND condition - if($parts > 1) { + if ($parts > 1) { $filter = '(&' . $filter . ')'; } break; @@ -977,13 +977,13 @@ class Wizard extends LDAPUtility { $userAttributes = array_change_key_case(array_flip($userAttributes)); $parts = 0; - if($this->configuration->ldapLoginFilterUsername === '1') { + if ($this->configuration->ldapLoginFilterUsername === '1') { $attr = ''; - if(isset($userAttributes['uid'])) { + if (isset($userAttributes['uid'])) { $attr = 'uid'; - } elseif(isset($userAttributes['samaccountname'])) { + } elseif (isset($userAttributes['samaccountname'])) { $attr = 'samaccountname'; - } elseif(isset($userAttributes['cn'])) { + } elseif (isset($userAttributes['cn'])) { //fallback $attr = 'cn'; } @@ -994,16 +994,16 @@ class Wizard extends LDAPUtility { } $filterEmail = ''; - if($this->configuration->ldapLoginFilterEmail === '1') { + if ($this->configuration->ldapLoginFilterEmail === '1') { $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))'; $parts++; } $filterAttributes = ''; $attrsToFilter = $this->configuration->ldapLoginFilterAttributes; - if(is_array($attrsToFilter) && count($attrsToFilter) > 0) { + if (is_array($attrsToFilter) && count($attrsToFilter) > 0) { $filterAttributes = '(|'; - foreach($attrsToFilter as $attribute) { + foreach ($attrsToFilter as $attribute) { $filterAttributes .= '(' . $attribute . $loginpart . ')'; } $filterAttributes .= ')'; @@ -1011,13 +1011,13 @@ class Wizard extends LDAPUtility { } $filterLogin = ''; - if($parts > 1) { + if ($parts > 1) { $filterLogin = '(|'; } $filterLogin .= $filterUsername; $filterLogin .= $filterEmail; $filterLogin .= $filterAttributes; - if($parts > 1) { + if ($parts > 1) { $filterLogin .= ')'; } @@ -1042,12 +1042,12 @@ class Wizard extends LDAPUtility { //connect, does not really trigger any server communication $host = $this->configuration->ldapHost; $hostInfo = parse_url($host); - if(!$hostInfo) { + if (!$hostInfo) { throw new \Exception(self::$l->t('Invalid Host')); } \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG); $cr = $this->ldap->connect($host, $port); - if(!is_resource($cr)) { + if (!is_resource($cr)) { throw new \Exception(self::$l->t('Invalid Host')); } @@ -1057,9 +1057,9 @@ class Wizard extends LDAPUtility { $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); try { - if($tls) { + if ($tls) { $isTlsWorking = @$this->ldap->startTls($cr); - if(!$isTlsWorking) { + if (!$isTlsWorking) { return false; } } @@ -1073,17 +1073,17 @@ class Wizard extends LDAPUtility { $errNo = $this->ldap->errno($cr); $error = ldap_error($cr); $this->ldap->unbind($cr); - } catch(ServerNotAvailableException $e) { + } catch (ServerNotAvailableException $e) { return false; } - if($login === true) { + if ($login === true) { $this->ldap->unbind($cr); \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG); return true; } - if($errNo === -1) { + if ($errNo === -1) { //host, port or TLS wrong return false; } @@ -1111,9 +1111,9 @@ class Wizard extends LDAPUtility { */ private function checkRequirements($reqs) { $this->checkAgentRequirements(); - foreach($reqs as $option) { + foreach ($reqs as $option) { $value = $this->configuration->$option; - if(empty($value)) { + if (empty($value)) { return false; } } @@ -1135,33 +1135,33 @@ class Wizard extends LDAPUtility { $dnRead = []; $foundItems = []; $maxEntries = 0; - if(!is_array($this->configuration->ldapBase) + if (!is_array($this->configuration->ldapBase) || !isset($this->configuration->ldapBase[0])) { return false; } $base = $this->configuration->ldapBase[0]; $cr = $this->getConnection(); - if(!$this->ldap->isResource($cr)) { + if (!$this->ldap->isResource($cr)) { return false; } $lastFilter = null; - if(isset($filters[count($filters)-1])) { + if (isset($filters[count($filters)-1])) { $lastFilter = $filters[count($filters)-1]; } - foreach($filters as $filter) { - if($lastFilter === $filter && count($foundItems) > 0) { + foreach ($filters as $filter) { + if ($lastFilter === $filter && count($foundItems) > 0) { //skip when the filter is a wildcard and results were found continue; } // 20k limit for performance and reason $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000); - if(!$this->ldap->isResource($rr)) { + if (!$this->ldap->isResource($rr)) { continue; } $entries = $this->ldap->countEntries($cr, $rr); $getEntryFunc = 'firstEntry'; - if(($entries !== false) && ($entries > 0)) { - if(!is_null($maxF) && $entries > $maxEntries) { + if (($entries !== false) && ($entries > 0)) { + if (!is_null($maxF) && $entries > $maxEntries) { $maxEntries = $entries; $maxF = $filter; } @@ -1169,13 +1169,13 @@ class Wizard extends LDAPUtility { do { $entry = $this->ldap->$getEntryFunc($cr, $rr); $getEntryFunc = 'nextEntry'; - if(!$this->ldap->isResource($entry)) { + if (!$this->ldap->isResource($entry)) { continue 2; } $rr = $entry; //will be expected by nextEntry next round $attributes = $this->ldap->getAttributes($cr, $entry); $dn = $this->ldap->getDN($cr, $entry); - if($dn === false || in_array($dn, $dnRead)) { + if ($dn === false || in_array($dn, $dnRead)) { continue; } $newItems = []; @@ -1186,7 +1186,7 @@ class Wizard extends LDAPUtility { $foundItems = array_merge($foundItems, $newItems); $this->resultCache[$dn][$attr] = $newItems; $dnRead[] = $dn; - } while(($state === self::LRESULT_PROCESSED_SKIP + } while (($state === self::LRESULT_PROCESSED_SKIP || $this->ldap->isResource($entry)) && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit)); } @@ -1209,11 +1209,11 @@ class Wizard extends LDAPUtility { */ private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) { $cr = $this->getConnection(); - if(!$cr) { + if (!$cr) { throw new \Exception('Could not connect to LDAP'); } $p = 'objectclass='; - foreach($objectclasses as $key => $value) { + foreach ($objectclasses as $key => $value) { $objectclasses[$key] = $p.$value; } $maxEntryObjC = ''; @@ -1225,7 +1225,7 @@ class Wizard extends LDAPUtility { $availableFeatures = $this->cumulativeSearchOnAttribute($objectclasses, $attr, $dig, $maxEntryObjC); - if(is_array($availableFeatures) + if (is_array($availableFeatures) && count($availableFeatures) > 0) { natcasesort($availableFeatures); //natcasesort keeps indices, but we must get rid of them for proper @@ -1236,7 +1236,7 @@ class Wizard extends LDAPUtility { } $setFeatures = $this->configuration->$confkey; - if(is_array($setFeatures) && !empty($setFeatures)) { + if (is_array($setFeatures) && !empty($setFeatures)) { //something is already configured? pre-select it. $this->result->addChange($dbkey, $setFeatures); } elseif ($po && $maxEntryObjC !== '') { @@ -1258,7 +1258,7 @@ class Wizard extends LDAPUtility { * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP */ private function getAttributeValuesFromEntry($result, $attribute, &$known) { - if(!is_array($result) + if (!is_array($result) || !isset($result['count']) || !$result['count'] > 0) { return self::LRESULT_PROCESSED_INVALID; @@ -1267,12 +1267,12 @@ class Wizard extends LDAPUtility { // strtolower on all keys for proper comparison $result = \OCP\Util::mb_array_change_key_case($result); $attribute = strtolower($attribute); - if(isset($result[$attribute])) { - foreach($result[$attribute] as $key => $val) { - if($key === 'count') { + if (isset($result[$attribute])) { + foreach ($result[$attribute] as $key => $val) { + if ($key === 'count') { continue; } - if(!in_array($val, $known)) { + if (!in_array($val, $known)) { $known[] = $val; } } @@ -1286,7 +1286,7 @@ class Wizard extends LDAPUtility { * @return bool|mixed */ private function getConnection() { - if(!is_null($this->cr)) { + if (!is_null($this->cr)) { return $this->cr; } @@ -1298,14 +1298,14 @@ class Wizard extends LDAPUtility { $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); - if($this->configuration->ldapTLS === 1) { + if ($this->configuration->ldapTLS === 1) { $this->ldap->startTls($cr); } $lo = @$this->ldap->bind($cr, $this->configuration->ldapAgentName, $this->configuration->ldapAgentPassword); - if($lo === true) { + if ($lo === true) { $this->$cr = $cr; return $cr; } @@ -1340,9 +1340,9 @@ class Wizard extends LDAPUtility { $portSettings = []; //In case the port is already provided, we will check this first - if($port > 0) { + if ($port > 0) { $hostInfo = parse_url($host); - if(!(is_array($hostInfo) + if (!(is_array($hostInfo) && isset($hostInfo['scheme']) && stripos($hostInfo['scheme'], 'ldaps') !== false)) { $portSettings[] = ['port' => $port, 'tls' => true]; @@ -1356,6 +1356,4 @@ class Wizard extends LDAPUtility { return $portSettings; } - - } diff --git a/apps/user_ldap/lib/WizardResult.php b/apps/user_ldap/lib/WizardResult.php index 4c0c555ca53..3c8f638736e 100644 --- a/apps/user_ldap/lib/WizardResult.php +++ b/apps/user_ldap/lib/WizardResult.php @@ -52,7 +52,7 @@ class WizardResult { * @param array|string $values */ public function addOptions($key, $values) { - if(!is_array($values)) { + if (!is_array($values)) { $values = [$values]; } $this->options[$key] = $values; @@ -71,7 +71,7 @@ class WizardResult { public function getResultArray() { $result = []; $result['changes'] = $this->changes; - if(count($this->options) > 0) { + if (count($this->options) > 0) { $result['options'] = $this->options; } return $result; diff --git a/apps/user_ldap/templates/part.wizard-server.php b/apps/user_ldap/templates/part.wizard-server.php index 56194bafecd..ff8630c62cd 100644 --- a/apps/user_ldap/templates/part.wizard-server.php +++ b/apps/user_ldap/templates/part.wizard-server.php @@ -4,9 +4,10 @@ - + diff --git a/apps/user_ldap/templates/renewpassword.php b/apps/user_ldap/templates/renewpassword.php index e07f2a21077..c3ea94fbf02 100644 --- a/apps/user_ldap/templates/renewpassword.php +++ b/apps/user_ldap/templates/renewpassword.php @@ -11,7 +11,7 @@ style('user_ldap', 'renewPassword');
        t('Please renew your password.')); ?>
        - +

        diff --git a/apps/user_ldap/templates/settings.php b/apps/user_ldap/templates/settings.php index bbc809481ac..6b0221f0935 100644 --- a/apps/user_ldap/templates/settings.php +++ b/apps/user_ldap/templates/settings.php @@ -67,7 +67,7 @@ style('user_ldap', 'settings');
      • t('Advanced'));?>
      • '.$l->t('Warning: The PHP LDAP module is not installed, the backend will not work. Please ask your system administrator to install it.').'

        '); } ?> @@ -95,7 +95,15 @@ style('user_ldap', 'settings');

        -

        +

        t('(New password is sent as plain text to LDAP)'));?> diff --git a/apps/user_ldap/tests/AccessTest.php b/apps/user_ldap/tests/AccessTest.php index a805f387086..73fd35b8960 100644 --- a/apps/user_ldap/tests/AccessTest.php +++ b/apps/user_ldap/tests/AccessTest.php @@ -238,7 +238,7 @@ class AccessTest extends TestCase { $lw->expects($this->exactly(1)) ->method('explodeDN') ->willReturnCallback(function ($dn) use ($case) { - if($dn === $case['input']) { + if ($dn === $case['input']) { return $case['interResult']; } return null; @@ -258,7 +258,7 @@ class AccessTest extends TestCase { $lw = new LDAP(); $access = new Access($con, $lw, $um, $helper, $config, $this->ncUserManager); - if(!function_exists('ldap_explode_dn')) { + if (!function_exists('ldap_explode_dn')) { $this->markTestSkipped('LDAP Module not available'); } @@ -539,7 +539,7 @@ class AccessTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($key) use ($base) { - if(stripos($key, 'base') !== false) { + if (stripos($key, 'base') !== false) { return $base; } return null; @@ -661,7 +661,7 @@ class AccessTest extends TestCase { * @param $expected */ public function testSanitizeUsername($name, $expected) { - if($expected === null) { + if ($expected === null) { $this->expectException(\InvalidArgumentException::class); } $sanitizedName = $this->access->sanitizeUsername($name); @@ -703,5 +703,4 @@ class AccessTest extends TestCase { ]; $this->access->nextcloudUserNames($records); } - } diff --git a/apps/user_ldap/tests/ConfigurationTest.php b/apps/user_ldap/tests/ConfigurationTest.php index fee92a523c9..db119eb3bfe 100644 --- a/apps/user_ldap/tests/ConfigurationTest.php +++ b/apps/user_ldap/tests/ConfigurationTest.php @@ -139,5 +139,4 @@ class ConfigurationTest extends \Test\TestCase { // so far the only thing that can get resolved :) $this->assertSame($expected, $this->configuration->resolveRule('avatar')); } - } diff --git a/apps/user_ldap/tests/ConnectionTest.php b/apps/user_ldap/tests/ConnectionTest.php index 8a4ec38e4bd..721966025f0 100644 --- a/apps/user_ldap/tests/ConnectionTest.php +++ b/apps/user_ldap/tests/ConnectionTest.php @@ -135,7 +135,7 @@ class ConnectionTest extends \Test\TestCase { $this->ldap->expects($this->exactly(3)) ->method('bind') ->willReturnCallback(function () use (&$isThrown) { - if(!$isThrown) { + if (!$isThrown) { $isThrown = true; throw new \OC\ServerNotAvailableException(); } @@ -288,5 +288,4 @@ class ConnectionTest extends \Test\TestCase { $this->connection->init(); } - } diff --git a/apps/user_ldap/tests/Group_LDAPTest.php b/apps/user_ldap/tests/Group_LDAPTest.php index 305df690358..ae637e0e584 100644 --- a/apps/user_ldap/tests/Group_LDAPTest.php +++ b/apps/user_ldap/tests/Group_LDAPTest.php @@ -57,7 +57,7 @@ class Group_LDAPTest extends TestCase { static $conMethods; static $accMethods; - if(is_null($conMethods) || is_null($accMethods)) { + if (is_null($conMethods) || is_null($accMethods)) { $conMethods = get_class_methods('\OCA\User_LDAP\Connection'); $accMethods = get_class_methods('\OCA\User_LDAP\Access'); } @@ -89,7 +89,7 @@ class Group_LDAPTest extends TestCase { $access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapDynamicGroupMemberURL') { + if ($name === 'ldapDynamicGroupMemberURL') { return ''; } return 1; @@ -110,7 +110,7 @@ class Group_LDAPTest extends TestCase { $access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn) use ($groupDN) { - if($dn === $groupDN) { + if ($dn === $groupDN) { return [ 'uid=u11,ou=users,dc=foo,dc=bar', 'uid=u22,ou=users,dc=foo,dc=bar', @@ -154,7 +154,7 @@ class Group_LDAPTest extends TestCase { //something that is neither null or false, but once an array //with the users in the group – so we do so all other times for //simplicicity. - if(strpos($name, 'u') === 0) { + if (strpos($name, 'u') === 0) { return strpos($name, '3'); } return ['u11', 'u22', 'u33', 'u34']; @@ -521,9 +521,9 @@ class Group_LDAPTest extends TestCase { $access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($attr === 'primaryGroupToken') { + if ($attr === 'primaryGroupToken') { return [1337]; - } elseif($attr === 'gidNumber') { + } elseif ($attr === 'gidNumber') { return [4211]; } return []; @@ -558,7 +558,7 @@ class Group_LDAPTest extends TestCase { $access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($attr === 'primaryGroupToken') { + if ($attr === 'primaryGroupToken') { return [1337]; } return []; @@ -594,7 +594,7 @@ class Group_LDAPTest extends TestCase { $access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($attr === 'primaryGroupToken') { + if ($attr === 'primaryGroupToken') { return [1337]; } return []; @@ -655,9 +655,9 @@ class Group_LDAPTest extends TestCase { $access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'useMemberOfToDetectMembership') { + if ($name === 'useMemberOfToDetectMembership') { return 0; - } elseif($name === 'ldapDynamicGroupMemberURL') { + } elseif ($name === 'ldapDynamicGroupMemberURL') { return ''; } return 1; @@ -693,7 +693,7 @@ class Group_LDAPTest extends TestCase { $access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - switch($name) { + switch ($name) { case 'useMemberOfToDetectMembership': return 0; case 'ldapDynamicGroupMemberURL': @@ -1031,18 +1031,18 @@ class Group_LDAPTest extends TestCase { $access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($group) use ($groupDN, $expectedMembers, $groupsInfo) { - if(isset($groupsInfo[$group])) { + if (isset($groupsInfo[$group])) { return $groupsInfo[$group]; } return []; }); $access->connection = $this->createMock(Connection::class); - if(count($groupsInfo) > 1) { + if (count($groupsInfo) > 1) { $access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapNestedGroups') { + if ($name === 'ldapNestedGroups') { return 1; } return null; @@ -1080,11 +1080,11 @@ class Group_LDAPTest extends TestCase { $access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapGroupMemberAssocAttr') { + if ($name === 'ldapGroupMemberAssocAttr') { return 'member'; - } elseif($name === 'ldapGroupFilter') { + } elseif ($name === 'ldapGroupFilter') { return 'objectclass=nextcloudGroup'; - } elseif($name === 'ldapGroupDisplayName') { + } elseif ($name === 'ldapGroupDisplayName') { return 'cn'; } return null; @@ -1096,5 +1096,4 @@ class Group_LDAPTest extends TestCase { $ldap = new GroupLDAP($access, $pluginManager); $this->assertSame($expected, $ldap->getDisplayName($gid)); } - } diff --git a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php index 77aeddf94f5..e6d9ddece55 100644 --- a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php +++ b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php @@ -83,7 +83,6 @@ abstract class AbstractIntegrationTest { $this->initUserManager(); $this->initHelper(); $this->initAccess(); - } /** @@ -151,23 +150,23 @@ abstract class AbstractIntegrationTest { public function run() { $methods = get_class_methods($this); $atLeastOneCaseRan = false; - foreach($methods as $method) { - if(strpos($method, 'case') === 0) { + foreach ($methods as $method) { + if (strpos($method, 'case') === 0) { print("running $method " . PHP_EOL); try { - if(!$this->$method()) { + if (!$this->$method()) { print(PHP_EOL . '>>> !!! Test ' . $method . ' FAILED !!! <<<' . PHP_EOL . PHP_EOL); exit(1); } $atLeastOneCaseRan = true; - } catch(\Exception $e) { + } catch (\Exception $e) { print(PHP_EOL . '>>> !!! Test ' . $method . ' RAISED AN EXCEPTION !!! <<<' . PHP_EOL); print($e->getMessage() . PHP_EOL . PHP_EOL); exit(1); } } } - if($atLeastOneCaseRan) { + if ($atLeastOneCaseRan) { print('Tests succeeded' . PHP_EOL); } else { print('No Test was available.' . PHP_EOL); diff --git a/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php b/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php index 33eb1c70d6f..e78208e579c 100644 --- a/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php +++ b/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php @@ -113,7 +113,7 @@ class ExceptionOnLostConnection { * restores original state of the LDAP proxy, if necessary */ public function cleanUp() { - if($this->originalProxyState === true) { + if ($this->originalProxyState === true) { $this->setProxyState(true); } } @@ -123,7 +123,7 @@ class ExceptionOnLostConnection { * fail */ public function run() { - if($this->originalProxyState === false) { + if ($this->originalProxyState === false) { $this->setProxyState(true); } //host contains port, 2nd parameter will be ignored @@ -152,7 +152,7 @@ class ExceptionOnLostConnection { * @throws \Exception */ private function checkCurlResult($ch, $result) { - if($result === false) { + if ($result === false) { $error = curl_error($ch); curl_close($ch); throw new \Exception($error); @@ -166,7 +166,7 @@ class ExceptionOnLostConnection { * @throws \Exception */ private function setProxyState($isEnabled) { - if(!is_bool($isEnabled)) { + if (!is_bool($isEnabled)) { throw new \InvalidArgumentException('Bool expected'); } $postData = json_encode(['enabled' => $isEnabled]); diff --git a/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php index 6048d42a4a6..01ac243729b 100644 --- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php +++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php @@ -73,7 +73,6 @@ class IntegrationTestFetchUsersByLoginName extends AbstractIntegrationTest { $result = $this->access->fetchUsersByLoginName('alice'); return count($result) === 1; } - } /** @var string $host */ diff --git a/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php index 893efeaf495..ba8a3657edc 100644 --- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php +++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php @@ -74,12 +74,12 @@ class IntegrationTestPaging extends AbstractIntegrationTest { // the result will be 4, because the highest possible paging size // is 2 (as configured). // But also with more than one search base, the limit can be outpaced. - if(count($result) !== 4) { + if (count($result) !== 4) { return false; } $result = $this->access->searchUsers($filter, $attributes); - if(count($result) !== 7) { + if (count($result) !== 7) { return false; } diff --git a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php index 87f25b19394..d1065337816 100644 --- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php +++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php @@ -77,7 +77,7 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest { \OC_Util::setupFS($username); \OC::$server->getUserFolder($username); \OC::$server->getConfig()->deleteUserValue($username, 'user_ldap', User::USER_PREFKEY_LASTREFRESH); - if(\OC::$server->getAvatarManager()->getAvatar($username)->exists()) { + if (\OC::$server->getAvatarManager()->getAvatar($username)->exists()) { \OC::$server->getAvatarManager()->getAvatar($username)->remove(); } diff --git a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php index b656b50ef50..84920d5950d 100644 --- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php +++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php @@ -84,7 +84,7 @@ class IntegrationTestUserCleanUp extends AbstractIntegrationTest { // it is deleted from the LDAP server. The instance will be returned // from cache and may false-positively confirm the correctness. $user = \OC::$server->getUserManager()->get($username); - if($user === null) { + if ($user === null) { return false; } $user->delete(); diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php index ebfbd339654..ac5346fe025 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php @@ -20,7 +20,7 @@ * along with this program. If not, see * */ -if(php_sapi_name() !== 'cli') { +if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); exit(1); } diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php index 74783bff251..4bf26b81a4b 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php @@ -20,7 +20,7 @@ * along with this program. If not, see * */ -if(php_sapi_name() !== 'cli') { +if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); exit(1); } diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php index aaba2d0bf85..f2cfad251de 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php @@ -20,7 +20,7 @@ * along with this program. If not, see * */ -if(php_sapi_name() !== 'cli') { +if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); exit(1); } diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php b/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php index 42ada041457..6ef4c745c26 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php @@ -19,7 +19,7 @@ * along with this program. If not, see * */ -if(php_sapi_name() !== 'cli') { +if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); exit(1); } diff --git a/apps/user_ldap/tests/Jobs/CleanUpTest.php b/apps/user_ldap/tests/Jobs/CleanUpTest.php index bf4c8b75bac..73d246ac4e2 100644 --- a/apps/user_ldap/tests/Jobs/CleanUpTest.php +++ b/apps/user_ldap/tests/Jobs/CleanUpTest.php @@ -152,5 +152,4 @@ class CleanUpTest extends \Test\TestCase { $result = $bgJob->isOffsetResetNecessary($bgJob->getChunkSize()); $this->assertSame(false, $result); } - } diff --git a/apps/user_ldap/tests/Jobs/SyncTest.php b/apps/user_ldap/tests/Jobs/SyncTest.php index 1cdbefb289c..e79fa58e019 100644 --- a/apps/user_ldap/tests/Jobs/SyncTest.php +++ b/apps/user_ldap/tests/Jobs/SyncTest.php @@ -175,7 +175,7 @@ class SyncTest extends TestCase { $connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($key) use ($pagingSize) { - if($key === 'ldapPagingSize') { + if ($key === 'ldapPagingSize') { return $pagingSize; } return null; @@ -221,7 +221,7 @@ class SyncTest extends TestCase { ->with(true) ->willReturn($prefixes); - if(is_array($expectedCycle)) { + if (is_array($expectedCycle)) { $this->config->expects($this->exactly(2)) ->method('setAppValue') ->withConsecutive( @@ -236,7 +236,7 @@ class SyncTest extends TestCase { $this->sync->setArgument($this->arguments); $nextCycle = $this->sync->determineNextCycle($cycleData); - if($expectedCycle === null) { + if ($expectedCycle === null) { $this->assertNull($nextCycle); } else { $this->assertSame($expectedCycle['prefix'], $nextCycle['prefix']); @@ -295,23 +295,23 @@ class SyncTest extends TestCase { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback(function ($app, $key, $default) use ($runData) { - if($app === 'core' && $key === 'backgroundjobs_mode') { + if ($app === 'core' && $key === 'backgroundjobs_mode') { return 'cron'; } - if($app = 'user_ldap') { + if ($app = 'user_ldap') { // for getCycle() - if($key === 'background_sync_prefix') { + if ($key === 'background_sync_prefix') { return $runData['scheduledCycle']['prefix']; } - if($key === 'background_sync_offset') { + if ($key === 'background_sync_offset') { return $runData['scheduledCycle']['offset']; } // for qualifiesToRun() - if($key === $runData['scheduledCycle']['prefix'] . '_lastChange') { + if ($key === $runData['scheduledCycle']['prefix'] . '_lastChange') { return time() - 60*40; } // for getMinPagingSize - if($key === $runData['scheduledCycle']['prefix'] . 'ldap_paging_size') { + if ($key === $runData['scheduledCycle']['prefix'] . 'ldap_paging_size') { return $runData['pagingSize']; } } @@ -342,7 +342,7 @@ class SyncTest extends TestCase { $connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($key) use ($runData) { - if($key === 'ldapPagingSize') { + if ($key === 'ldapPagingSize') { return $runData['pagingSize']; } return null; @@ -367,5 +367,4 @@ class SyncTest extends TestCase { $this->sync->run($this->arguments); } - } diff --git a/apps/user_ldap/tests/LDAPGroupPluginDummy.php b/apps/user_ldap/tests/LDAPGroupPluginDummy.php index 996f6f4a3f0..7ff5cd8ac69 100644 --- a/apps/user_ldap/tests/LDAPGroupPluginDummy.php +++ b/apps/user_ldap/tests/LDAPGroupPluginDummy.php @@ -26,8 +26,6 @@ namespace OCA\User_LDAP\Tests; use OCA\User_LDAP\ILDAPGroupPlugin; class LDAPGroupPluginDummy implements ILDAPGroupPlugin { - - public function respondToActions() { return null; } diff --git a/apps/user_ldap/tests/LDAPProviderTest.php b/apps/user_ldap/tests/LDAPProviderTest.php index 4433ed08baa..a8910c4a272 100644 --- a/apps/user_ldap/tests/LDAPProviderTest.php +++ b/apps/user_ldap/tests/LDAPProviderTest.php @@ -47,7 +47,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; * @package OCA\User_LDAP\Tests */ class LDAPProviderTest extends \Test\TestCase { - protected function setUp(): void { parent::setUp(); } @@ -358,7 +357,7 @@ class LDAPProviderTest extends \Test\TestCase { $connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($key) use ($bases) { - switch($key) { + switch ($key) { case 'ldapBaseUsers': return $bases; } @@ -420,7 +419,7 @@ class LDAPProviderTest extends \Test\TestCase { $connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($key) use ($bases) { - switch($key) { + switch ($key) { case 'ldapBaseGroups': return $bases; } @@ -697,5 +696,4 @@ class LDAPProviderTest extends \Test\TestCase { $ldapProvider = $this->getLDAPProvider($server); $this->assertEquals('assoc_type', $ldapProvider->getLDAPGroupMemberAssoc('existing_group')); } - } diff --git a/apps/user_ldap/tests/LDAPTest.php b/apps/user_ldap/tests/LDAPTest.php index 8dd7122b4e1..5df6b118487 100644 --- a/apps/user_ldap/tests/LDAPTest.php +++ b/apps/user_ldap/tests/LDAPTest.php @@ -29,7 +29,7 @@ namespace OCA\User_LDAP\Tests; use OCA\User_LDAP\LDAP; use Test\TestCase; -class LDAPTest extends TestCase { +class LDAPTest extends TestCase { /** @var LDAP|\PHPUnit_Framework_MockObject_MockObject */ private $ldap; @@ -58,7 +58,6 @@ class LDAPTest extends TestCase { * @dataProvider errorProvider */ public function testSearchWithErrorHandler(string $errorMessage, bool $passThrough) { - $wasErrorHandlerCalled = false; $errorHandler = function ($number, $message, $file, $line) use (&$wasErrorHandlerCalled) { $wasErrorHandlerCalled = true; diff --git a/apps/user_ldap/tests/LDAPUserPluginDummy.php b/apps/user_ldap/tests/LDAPUserPluginDummy.php index 609742d872d..a3bcc252fbe 100644 --- a/apps/user_ldap/tests/LDAPUserPluginDummy.php +++ b/apps/user_ldap/tests/LDAPUserPluginDummy.php @@ -26,7 +26,6 @@ namespace OCA\User_LDAP\Tests; use OCA\User_LDAP\ILDAPUserPlugin; class LDAPUserPluginDummy implements ILDAPUserPlugin { - public function respondToActions() { return null; } @@ -58,5 +57,4 @@ class LDAPUserPluginDummy implements ILDAPUserPlugin { public function countUsers() { return null; } - } diff --git a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php b/apps/user_ldap/tests/Mapping/AbstractMappingTest.php index a298c8b4bce..079c2e21b10 100644 --- a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php +++ b/apps/user_ldap/tests/Mapping/AbstractMappingTest.php @@ -77,7 +77,7 @@ abstract class AbstractMappingTest extends \Test\TestCase { * @param array $data */ protected function mapEntries($mapper, $data) { - foreach($data as $entry) { + foreach ($data as $entry) { $done = $mapper->map($entry['dn'], $entry['name'], $entry['uuid']); $this->assertTrue($done); } @@ -111,9 +111,9 @@ abstract class AbstractMappingTest extends \Test\TestCase { // test that mapping will not happen when it shall not $tooLongDN = 'uid=joann,ou=Secret Small Specialized Department,ou=Some Tremendously Important Department,ou=Another Very Important Department,ou=Pretty Meaningful Derpartment,ou=Quite Broad And General Department,ou=The Topmost Department,dc=hugelysuccessfulcompany,dc=com'; $paramKeys = ['', 'dn', 'name', 'uuid', $tooLongDN]; - foreach($paramKeys as $key) { + foreach ($paramKeys as $key) { $failEntry = $data[0]; - if(!empty($key)) { + if (!empty($key)) { $failEntry[$key] = 'do-not-get-mapped'; } $isMapped = $mapper->map($failEntry['dn'], $failEntry['name'], $failEntry['uuid']); @@ -128,7 +128,7 @@ abstract class AbstractMappingTest extends \Test\TestCase { public function testUnmap() { list($mapper, $data) = $this->initTest(); - foreach($data as $entry) { + foreach ($data as $entry) { $result = $mapper->unmap($entry['name']); $this->assertTrue($result); } @@ -144,21 +144,21 @@ abstract class AbstractMappingTest extends \Test\TestCase { public function testGetMethods() { list($mapper, $data) = $this->initTest(); - foreach($data as $entry) { + foreach ($data as $entry) { $fdn = $mapper->getDNByName($entry['name']); $this->assertSame($fdn, $entry['dn']); } $fdn = $mapper->getDNByName('nosuchname'); $this->assertFalse($fdn); - foreach($data as $entry) { + foreach ($data as $entry) { $name = $mapper->getNameByDN($entry['dn']); $this->assertSame($name, $entry['name']); } $name = $mapper->getNameByDN('nosuchdn'); $this->assertFalse($name); - foreach($data as $entry) { + foreach ($data as $entry) { $name = $mapper->getNameByUUID($entry['uuid']); $this->assertSame($name, $entry['name']); } @@ -229,7 +229,7 @@ abstract class AbstractMappingTest extends \Test\TestCase { $done = $mapper->clear(); $this->assertTrue($done); - foreach($data as $entry) { + foreach ($data as $entry) { $name = $mapper->getNameByUUID($entry['uuid']); $this->assertFalse($name); } @@ -252,7 +252,7 @@ abstract class AbstractMappingTest extends \Test\TestCase { $done = $mapper->clearCb($callback, $callback); $this->assertTrue($done); $this->assertSame(count($data) * 2, $callbackCalls); - foreach($data as $entry) { + foreach ($data as $entry) { $name = $mapper->getNameByUUID($entry['uuid']); $this->assertFalse($name); } diff --git a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php b/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php index 47a6a091ae2..a1048609e69 100644 --- a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php +++ b/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php @@ -194,5 +194,4 @@ abstract class AbstractUUIDFixTest extends TestCase { $this->job->run($args); } - } diff --git a/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php b/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php index 82afd8f19d8..a1f04d44670 100644 --- a/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php +++ b/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php @@ -47,5 +47,4 @@ class UUIDFixGroupTest extends AbstractUUIDFixTest { $this->mockProxy(Group_Proxy::class); $this->instantiateJob(UUIDFixGroup::class); } - } diff --git a/apps/user_ldap/tests/Settings/AdminTest.php b/apps/user_ldap/tests/Settings/AdminTest.php index 8f3a699af5d..c9119cffae4 100644 --- a/apps/user_ldap/tests/Settings/AdminTest.php +++ b/apps/user_ldap/tests/Settings/AdminTest.php @@ -72,7 +72,7 @@ class AdminTest extends TestCase { // assign default values $config = new Configuration('', false); $defaults = $config->getDefaults(); - foreach($defaults as $key => $default) { + foreach ($defaults as $key => $default) { $parameters[$key.'_default'] = $default; } diff --git a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php index 57abbf2bf62..af1d86c6df7 100644 --- a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php +++ b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php @@ -88,7 +88,7 @@ class DeletedUsersIndexTest extends \Test\TestCase { $this->assertSame(2, count($deletedUsers)); // ensure the different uids were used - foreach($deletedUsers as $deletedUser) { + foreach ($deletedUsers as $deletedUser) { $this->assertTrue(in_array($deletedUser->getOCName(), $uids)); $i = array_search($deletedUser->getOCName(), $uids); $this->assertNotFalse($i); @@ -117,6 +117,4 @@ class DeletedUsersIndexTest extends \Test\TestCase { $this->assertNotSame($testUser->getOCName(), $deletedUser->getOCName()); } } - - } diff --git a/apps/user_ldap/tests/User/ManagerTest.php b/apps/user_ldap/tests/User/ManagerTest.php index f71f50377fb..98365bbfdb5 100644 --- a/apps/user_ldap/tests/User/ManagerTest.php +++ b/apps/user_ldap/tests/User/ManagerTest.php @@ -251,5 +251,4 @@ class ManagerTest extends \Test\TestCase { $valueCounts = array_count_values($attributes); $this->assertSame(1, $valueCounts['mail']); } - } diff --git a/apps/user_ldap/tests/User/UserTest.php b/apps/user_ldap/tests/User/UserTest.php index 7453b31e338..8de71b182ba 100644 --- a/apps/user_ldap/tests/User/UserTest.php +++ b/apps/user_ldap/tests/User/UserTest.php @@ -607,13 +607,11 @@ class UserTest extends \Test\TestCase { $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($dn === $this->dn - && $attr === 'jpegphoto') - { + if ($dn === $this->dn + && $attr === 'jpegphoto') { return false; - } elseif($dn === $this->dn - && $attr === 'thumbnailphoto') - { + } elseif ($dn === $this->dn + && $attr === 'thumbnailphoto') { return ['this is a photo']; } return null; @@ -672,13 +670,11 @@ class UserTest extends \Test\TestCase { $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($dn === $this->dn - && $attr === 'jpegphoto') - { + if ($dn === $this->dn + && $attr === 'jpegphoto') { return false; - } elseif($dn === $this->dn - && $attr === 'thumbnailphoto') - { + } elseif ($dn === $this->dn + && $attr === 'thumbnailphoto') { return ['this is a photo']; } return null; @@ -725,13 +721,11 @@ class UserTest extends \Test\TestCase { $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($dn === $this->dn - && $attr === 'jpegphoto') - { + if ($dn === $this->dn + && $attr === 'jpegphoto') { return false; - } elseif($dn === $this->dn - && $attr === 'thumbnailphoto') - { + } elseif ($dn === $this->dn + && $attr === 'thumbnailphoto') { return ['this is a photo']; } return null; @@ -790,13 +784,11 @@ class UserTest extends \Test\TestCase { $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - if($dn === $this->dn - && $attr === 'jpegPhoto') - { + if ($dn === $this->dn + && $attr === 'jpegPhoto') { return false; - } elseif($dn === $this->dn - && $attr === 'thumbnailPhoto') - { + } elseif ($dn === $this->dn + && $attr === 'thumbnailPhoto') { return false; } return null; @@ -895,7 +887,7 @@ class UserTest extends \Test\TestCase { * @dataProvider extStorageHomeDataProvider */ public function testUpdateExtStorageHome(string $expected, string $valueFromLDAP = null, bool $isSet = true) { - if($valueFromLDAP === null) { + if ($valueFromLDAP === null) { $this->connection->expects($this->once()) ->method('__get') ->willReturnMap([ @@ -903,7 +895,7 @@ class UserTest extends \Test\TestCase { ]); $return = []; - if($isSet) { + if ($isSet) { $return[] = $expected; } $this->access->expects($this->once()) @@ -912,7 +904,7 @@ class UserTest extends \Test\TestCase { ->willReturn($return); } - if($expected !== '') { + if ($expected !== '') { $this->config->expects($this->once()) ->method('setUserValue') ->with($this->uid, 'user_ldap', 'extStorageHome', $expected); @@ -924,7 +916,6 @@ class UserTest extends \Test\TestCase { $actual = $this->user->updateExtStorageHome($valueFromLDAP); $this->assertSame($expected, $actual); - } public function testUpdateNoRefresh() { @@ -1039,7 +1030,7 @@ class UserTest extends \Test\TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'homeFolderNamingRule') { + if ($name === 'homeFolderNamingRule') { return 'attr:homeDirectory'; } return $name; @@ -1060,7 +1051,7 @@ class UserTest extends \Test\TestCase { 'jpegphoto' => ['here be an image'] ]; - foreach($requiredMethods as $method) { + foreach ($requiredMethods as $method) { $userMock->expects($this->once()) ->method($method); } @@ -1194,10 +1185,10 @@ class UserTest extends \Test\TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapDefaultPPolicyDN') { + if ($name === 'ldapDefaultPPolicyDN') { return 'cn=default,ou=policies,dc=foo,dc=bar'; } - if($name === 'turnOnPasswordChange') { + if ($name === 'turnOnPasswordChange') { return '1'; } return $name; @@ -1206,7 +1197,7 @@ class UserTest extends \Test\TestCase { $this->access->expects($this->any()) ->method('search') ->willReturnCallback(function ($filter, $base) { - if($base === [$this->dn]) { + if ($base === [$this->dn]) { return [ [ 'pwdchangedtime' => [(new \DateTime())->sub(new \DateInterval('P28D'))->format('Ymdhis').'Z'], @@ -1214,7 +1205,7 @@ class UserTest extends \Test\TestCase { ], ]; } - if($base === ['cn=default,ou=policies,dc=foo,dc=bar']) { + if ($base === ['cn=default,ou=policies,dc=foo,dc=bar']) { return [ [ 'pwdmaxage' => ['2592000'], @@ -1257,10 +1248,10 @@ class UserTest extends \Test\TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapDefaultPPolicyDN') { + if ($name === 'ldapDefaultPPolicyDN') { return 'cn=default,ou=policies,dc=foo,dc=bar'; } - if($name === 'turnOnPasswordChange') { + if ($name === 'turnOnPasswordChange') { return '1'; } return $name; @@ -1269,7 +1260,7 @@ class UserTest extends \Test\TestCase { $this->access->expects($this->any()) ->method('search') ->willReturnCallback(function ($filter, $base) { - if($base === [$this->dn]) { + if ($base === [$this->dn]) { return [ [ 'pwdpolicysubentry' => ['cn=custom,ou=policies,dc=foo,dc=bar'], @@ -1278,7 +1269,7 @@ class UserTest extends \Test\TestCase { ] ]; } - if($base === ['cn=custom,ou=policies,dc=foo,dc=bar']) { + if ($base === ['cn=custom,ou=policies,dc=foo,dc=bar']) { return [ [ 'pwdmaxage' => ['2592000'], diff --git a/apps/user_ldap/tests/User_LDAPTest.php b/apps/user_ldap/tests/User_LDAPTest.php index 2b0fcd681f9..00ca6737175 100644 --- a/apps/user_ldap/tests/User_LDAPTest.php +++ b/apps/user_ldap/tests/User_LDAPTest.php @@ -109,7 +109,7 @@ class User_LDAPTest extends TestCase { $this->access->expects($this->any()) ->method('username2dn') ->willReturnCallback(function ($uid) { - switch ($uid) { + switch ($uid) { case 'gunslinger': return 'dnOfRoland,dc=test'; break; @@ -140,31 +140,31 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapLoginFilter') { - return '%uid'; - } - return null; + if ($name === 'ldapLoginFilter') { + return '%uid'; + } + return null; }); $this->access->expects($this->any()) ->method('fetchListOfUsers') ->willReturnCallback(function ($filter) { - if($filter === 'roland') { - return [['dn' => ['dnOfRoland,dc=test']]]; - } - return []; + if ($filter === 'roland') { + return [['dn' => ['dnOfRoland,dc=test']]]; + } + return []; }); $this->access->expects($this->any()) ->method('fetchUsersByLoginName') ->willReturnCallback(function ($uid) { - if($uid === 'roland') { + if ($uid === 'roland') { return [['dn' => ['dnOfRoland,dc=test']]]; } return []; }); $retVal = 'gunslinger'; - if($noDisplayName === true) { + if ($noDisplayName === true) { $retVal = false; } $this->access->expects($this->any()) @@ -178,10 +178,10 @@ class User_LDAPTest extends TestCase { $this->access->expects($this->any()) ->method('areCredentialsValid') ->willReturnCallback(function ($dn, $pwd) { - if($pwd === 'dt19') { - return true; - } - return false; + if ($pwd === 'dt19') { + return true; + } + return false; }); } @@ -364,36 +364,36 @@ class User_LDAPTest extends TestCase { $this->access->expects($this->once()) ->method('escapeFilterPart') ->willReturnCallback(function ($search) { - return $search; + return $search; }); $this->access->expects($this->any()) ->method('getFilterPartForUserSearch') ->willReturnCallback(function ($search) { - return $search; + return $search; }); $this->access->expects($this->any()) ->method('combineFilterWithAnd') ->willReturnCallback(function ($param) { - return $param[2]; + return $param[2]; }); $this->access->expects($this->any()) ->method('fetchListOfUsers') ->willReturnCallback(function ($search, $a, $l, $o) { - $users = ['gunslinger', 'newyorker', 'ladyofshadows']; - if(empty($search)) { - $result = $users; - } else { - $result = []; - foreach($users as $user) { - if(stripos($user, $search) !== false) { - $result[] = $user; - } - } - } - if(!is_null($l) || !is_null($o)) { - $result = array_slice($result, $o, $l); - } - return $result; + $users = ['gunslinger', 'newyorker', 'ladyofshadows']; + if (empty($search)) { + $result = $users; + } else { + $result = []; + foreach ($users as $user) { + if (stripos($user, $search) !== false) { + $result[] = $user; + } + } + } + if (!is_null($l) || !is_null($o)) { + $result = array_slice($result, $o, $l); + } + return $result; }); $this->access->expects($this->any()) ->method('nextcloudUserNames') @@ -545,7 +545,7 @@ class User_LDAPTest extends TestCase { $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn) { - if($dn === 'dnOfRoland,dc=test') { + if ($dn === 'dnOfRoland,dc=test') { return []; } return false; @@ -570,7 +570,7 @@ class User_LDAPTest extends TestCase { $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn) { - if($dn === 'dnOfRoland,dc=test') { + if ($dn === 'dnOfRoland,dc=test') { return []; } return false; @@ -602,7 +602,7 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'homeFolderNamingRule') { + if ($name === 'homeFolderNamingRule') { return 'attr:testAttribute'; } return null; @@ -613,7 +613,7 @@ class User_LDAPTest extends TestCase { ->willReturnCallback(function ($dn, $attr) { switch ($dn) { case 'dnOfRoland,dc=test': - if($attr === 'testAttribute') { + if ($attr === 'testAttribute') { return ['/tmp/rolandshome/']; } return []; @@ -654,7 +654,7 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'homeFolderNamingRule') { + if ($name === 'homeFolderNamingRule') { return 'attr:testAttribute'; } return null; @@ -665,7 +665,7 @@ class User_LDAPTest extends TestCase { ->willReturnCallback(function ($dn, $attr) { switch ($dn) { case 'dnOfLadyOfShadows,dc=test': - if($attr === 'testAttribute') { + if ($attr === 'testAttribute') { return ['susannah/']; } return []; @@ -705,7 +705,7 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'homeFolderNamingRule') { + if ($name === 'homeFolderNamingRule') { return 'attr:testAttribute'; } return null; @@ -721,7 +721,7 @@ class User_LDAPTest extends TestCase { $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturnCallback(function ($key) { - if($key === 'userExistsnewyorker') { + if ($key === 'userExistsnewyorker') { return true; } return null; @@ -753,7 +753,7 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'homeFolderNamingRule') { + if ($name === 'homeFolderNamingRule') { return 'attr:testAttribute'; } return null; @@ -810,18 +810,18 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapUserDisplayName') { - return 'displayname'; - } - return null; + if ($name === 'ldapUserDisplayName') { + return 'displayname'; + } + return null; }); $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { - switch ($dn) { + switch ($dn) { case 'dnOfRoland,dc=test': - if($attr === 'displayname') { + if ($attr === 'displayname') { return ['Roland Deschain']; } return []; @@ -864,14 +864,16 @@ class User_LDAPTest extends TestCase { $mapper = $this->createMock(UserMapping::class); $mapper->expects($this->any()) ->method('getUUIDByDN') - ->willReturnCallback(function ($dn) { return $dn; }); + ->willReturnCallback(function ($dn) { + return $dn; + }); $this->userManager->expects($this->any()) ->method('get') ->willReturnCallback(function ($uid) use ($user1, $user2) { - if($uid === 'gunslinger') { + if ($uid === 'gunslinger') { return $user1; - } elseif($uid === 'newyorker') { + } elseif ($uid === 'newyorker') { return $user2; } return null; @@ -881,7 +883,9 @@ class User_LDAPTest extends TestCase { ->willReturn($mapper); $this->access->expects($this->any()) ->method('getUserDnByUuid') - ->willReturnCallback(function ($uuid) { return $uuid . '1'; }); + ->willReturnCallback(function ($uuid) { + return $uuid . '1'; + }); //with displayName $result = $backend->getDisplayName('gunslinger'); @@ -943,14 +947,16 @@ class User_LDAPTest extends TestCase { $mapper = $this->createMock(UserMapping::class); $mapper->expects($this->any()) ->method('getUUIDByDN') - ->willReturnCallback(function ($dn) { return $dn; }); + ->willReturnCallback(function ($dn) { + return $dn; + }); $this->userManager->expects($this->any()) ->method('get') ->willReturnCallback(function ($uid) use ($user1, $user2) { - if($uid === 'gunslinger') { + if ($uid === 'gunslinger') { return $user1; - } elseif($uid === 'newyorker') { + } elseif ($uid === 'newyorker') { return $user2; } return null; @@ -960,7 +966,9 @@ class User_LDAPTest extends TestCase { ->willReturn($mapper); $this->access->expects($this->any()) ->method('getUserDnByUuid') - ->willReturnCallback(function ($uuid) { return $uuid . '1'; }); + ->willReturnCallback(function ($uuid) { + return $uuid . '1'; + }); //with displayName $result = \OC::$server->getUserManager()->get('gunslinger')->getDisplayName(); @@ -1136,35 +1144,35 @@ class User_LDAPTest extends TestCase { $this->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) use (&$enablePasswordChange) { - if($name === 'ldapLoginFilter') { - return '%uid'; - } - if($name === 'turnOnPasswordChange') { - return $enablePasswordChange?1:0; - } - return null; + if ($name === 'ldapLoginFilter') { + return '%uid'; + } + if ($name === 'turnOnPasswordChange') { + return $enablePasswordChange?1:0; + } + return null; }); $this->connection->expects($this->any()) ->method('getFromCache') ->willReturnCallback(function ($uid) { - if($uid === 'userExists'.'roland') { - return true; - } - return null; + if ($uid === 'userExists'.'roland') { + return true; + } + return null; }); $this->access->expects($this->any()) ->method('fetchListOfUsers') ->willReturnCallback(function ($filter) { - if($filter === 'roland') { - return [['dn' => ['dnOfRoland,dc=test']]]; - } - return []; + if ($filter === 'roland') { + return [['dn' => ['dnOfRoland,dc=test']]]; + } + return []; }); $this->access->expects($this->any()) ->method('fetchUsersByLoginName') ->willReturnCallback(function ($uid) { - if($uid === 'roland') { + if ($uid === 'roland') { return [['dn' => ['dnOfRoland,dc=test']]]; } return []; @@ -1180,10 +1188,10 @@ class User_LDAPTest extends TestCase { $this->access->expects($this->any()) ->method('setPassword') ->willReturnCallback(function ($uid, $password) { - if(strlen($password) <= 5) { - throw new HintException('Password fails quality checking policy', '', 19); - } - return true; + if (strlen($password) <= 5) { + throw new HintException('Password fails quality checking policy', '', 19); + } + return true; }); } diff --git a/apps/user_ldap/tests/User_ProxyTest.php b/apps/user_ldap/tests/User_ProxyTest.php index 0a073b3948e..83755abe078 100644 --- a/apps/user_ldap/tests/User_ProxyTest.php +++ b/apps/user_ldap/tests/User_ProxyTest.php @@ -35,7 +35,7 @@ use OCP\IUserSession; use OCP\Notification\IManager as INotificationManager; use Test\TestCase; -class User_ProxyTest extends TestCase { +class User_ProxyTest extends TestCase { /** @var ILDAPWrapper|\PHPUnit_Framework_MockObject_MockObject */ private $ldapWrapper; /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ @@ -87,7 +87,8 @@ class User_ProxyTest extends TestCase { ->with('MyUid', 'setDisplayName', ['MyUid', 'MyPassword']) ->willReturn(true); - $this->assertTrue($this->proxy->setDisplayName('MyUid', 'MyPassword')); } + $this->assertTrue($this->proxy->setDisplayName('MyUid', 'MyPassword')); + } public function testCreateUser() { $this->proxy diff --git a/apps/user_ldap/tests/WizardTest.php b/apps/user_ldap/tests/WizardTest.php index 67af7e9b177..5595ff30440 100644 --- a/apps/user_ldap/tests/WizardTest.php +++ b/apps/user_ldap/tests/WizardTest.php @@ -50,8 +50,8 @@ class WizardTest extends TestCase { //on systems without php5_ldap $ldapConsts = ['LDAP_OPT_PROTOCOL_VERSION', 'LDAP_OPT_REFERRALS', 'LDAP_OPT_NETWORK_TIMEOUT']; - foreach($ldapConsts as $const) { - if(!defined($const)) { + foreach ($ldapConsts as $const) { + if (!defined($const)) { define($const, 42); } } @@ -62,7 +62,7 @@ class WizardTest extends TestCase { static $connMethods; static $accMethods; - if(is_null($confMethods)) { + if (is_null($confMethods)) { $confMethods = get_class_methods('\OCA\User_LDAP\Configuration'); $connMethods = get_class_methods('\OCA\User_LDAP\Connection'); $accMethods = get_class_methods('\OCA\User_LDAP\Access'); @@ -95,7 +95,6 @@ class WizardTest extends TestCase { $ldap->expects($this->once()) ->method('bind') ->willReturn(true); - } public function testCumulativeSearchOnAttributeLimited() { @@ -104,11 +103,11 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapBase') { - return ['base']; - } - return null; - }); + if ($name === 'ldapBase') { + return ['base']; + } + return null; + }); $this->prepareLdapWrapperForConnections($ldap); @@ -164,21 +163,21 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapBase') { - return ['base']; - } - return null; - }); + if ($name === 'ldapBase') { + return ['base']; + } + return null; + }); $this->prepareLdapWrapperForConnections($ldap); $ldap->expects($this->any()) ->method('isResource') ->willReturnCallback(function ($r) { - if($r === true) { + if ($r === true) { return true; } - if($r % 24 === 0) { + if ($r % 24 === 0) { global $uidnumber; $uidnumber++; return false; @@ -241,7 +240,7 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapEmailAttribute') { + if ($name === 'ldapEmailAttribute') { return 'myEmailAttribute'; } else { //for requirement checks @@ -263,7 +262,7 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapEmailAttribute') { + if ($name === 'ldapEmailAttribute') { return 'myEmailAttribute'; } else { //for requirement checks @@ -280,11 +279,11 @@ class WizardTest extends TestCase { $access->expects($this->exactly(3)) ->method('countUsers') ->willReturnCallback(function ($filter) { - if($filter === 'myEmailAttribute') { + if ($filter === 'myEmailAttribute') { return 0; - } elseif($filter === 'mail') { + } elseif ($filter === 'mail') { return 3; - } elseif($filter === 'mailPrimaryAddress') { + } elseif ($filter === 'mailPrimaryAddress') { return 17; } throw new \Exception('Untested filter: ' . $filter); @@ -302,7 +301,7 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapEmailAttribute') { + if ($name === 'ldapEmailAttribute') { return ''; } else { //for requirement checks @@ -319,11 +318,11 @@ class WizardTest extends TestCase { $access->expects($this->exactly(2)) ->method('countUsers') ->willReturnCallback(function ($filter) { - if($filter === 'myEmailAttribute') { + if ($filter === 'myEmailAttribute') { return 0; - } elseif($filter === 'mail') { + } elseif ($filter === 'mail') { return 3; - } elseif($filter === 'mailPrimaryAddress') { + } elseif ($filter === 'mailPrimaryAddress') { return 17; } throw new \Exception('Untested filter: ' . $filter); @@ -341,7 +340,7 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapEmailAttribute') { + if ($name === 'ldapEmailAttribute') { return 'myEmailAttribute'; } else { //for requirement checks @@ -358,11 +357,11 @@ class WizardTest extends TestCase { $access->expects($this->exactly(3)) ->method('countUsers') ->willReturnCallback(function ($filter) { - if($filter === 'myEmailAttribute') { + if ($filter === 'myEmailAttribute') { return 0; - } elseif($filter === 'mail') { + } elseif ($filter === 'mail') { return 0; - } elseif($filter === 'mailPrimaryAddress') { + } elseif ($filter === 'mailPrimaryAddress') { return 0; } throw new \Exception('Untested filter: ' . $filter); @@ -380,11 +379,11 @@ class WizardTest extends TestCase { $configuration->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { - if($name === 'ldapBase') { - return ['base']; - } - return null; - }); + if ($name === 'ldapBase') { + return ['base']; + } + return null; + }); $this->prepareLdapWrapperForConnections($ldap); @@ -418,11 +417,11 @@ class WizardTest extends TestCase { //dummy value, usually invalid ->willReturnCallback(function ($a, $prev) { $current = $prev + 1; - if($current === 7) { + if ($current === 7) { return false; } global $mark; - if($prev === 4 && !$mark) { + if ($prev === 4 && !$mark) { $mark = true; return 4; } @@ -449,5 +448,4 @@ class WizardTest extends TestCase { $this->assertSame(6, count($resultArray)); unset($mark); } - } diff --git a/apps/workflowengine/lib/AppInfo/Application.php b/apps/workflowengine/lib/AppInfo/Application.php index d75b025b3f4..c9e982a311f 100644 --- a/apps/workflowengine/lib/AppInfo/Application.php +++ b/apps/workflowengine/lib/AppInfo/Application.php @@ -35,7 +35,6 @@ use OCP\WorkflowEngine\IOperationCompat; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class Application extends \OCP\AppFramework\App { - const APP_ID = 'workflowengine'; /** @var EventDispatcherInterface */ @@ -130,7 +129,6 @@ class Application extends \OCP\AppFramework\App { ); } $flowLogger->logEventDone($ctx); - } catch (QueryException $e) { // Ignore query exceptions since they might occur when an entity/operation were setup before by an app that is disabled now } @@ -139,7 +137,5 @@ class Application extends \OCP\AppFramework\App { }, $eventNames ?? []); } } - - } } diff --git a/apps/workflowengine/lib/BackgroundJobs/Rotate.php b/apps/workflowengine/lib/BackgroundJobs/Rotate.php index 1602e5a72da..aee817e3cc8 100644 --- a/apps/workflowengine/lib/BackgroundJobs/Rotate.php +++ b/apps/workflowengine/lib/BackgroundJobs/Rotate.php @@ -39,14 +39,14 @@ class Rotate extends TimedJob { $default = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/flow.log'; $this->filePath = trim((string)$config->getAppValue(Application::APP_ID, 'logfile', $default)); - if($this->filePath === '') { + if ($this->filePath === '') { // disabled, nothing to do return; } $this->maxSize = $config->getSystemValue('log_rotate_size', 100 * 1024 * 1024); - if($this->shouldRotateBySize()) { + if ($this->shouldRotateBySize()) { $this->rotate(); } } diff --git a/apps/workflowengine/lib/Check/FileMimeType.php b/apps/workflowengine/lib/Check/FileMimeType.php index 9d378379e5e..0e02c405126 100644 --- a/apps/workflowengine/lib/Check/FileMimeType.php +++ b/apps/workflowengine/lib/Check/FileMimeType.php @@ -62,7 +62,6 @@ class FileMimeType extends AbstractStringCheck implements IFileCheck { $this->_setFileInfo($storage, $path, $isDir); if (!isset($this->mimeType[$this->storage->getId()][$this->path]) || $this->mimeType[$this->storage->getId()][$this->path] === '') { - if ($isDir) { $this->mimeType[$this->storage->getId()][$this->path] = 'httpd/unix-directory'; } else { diff --git a/apps/workflowengine/lib/Check/RequestTime.php b/apps/workflowengine/lib/Check/RequestTime.php index aa35e8b84c9..9729129104f 100644 --- a/apps/workflowengine/lib/Check/RequestTime.php +++ b/apps/workflowengine/lib/Check/RequestTime.php @@ -26,7 +26,6 @@ use OCP\IL10N; use OCP\WorkflowEngine\ICheck; class RequestTime implements ICheck { - const REGEX_TIME = '([0-1][0-9]|2[0-3]):([0-5][0-9])'; const REGEX_TIMEZONE = '([a-zA-Z]+(?:\\/[a-zA-Z\-\_]+)+)'; diff --git a/apps/workflowengine/lib/Check/RequestUserAgent.php b/apps/workflowengine/lib/Check/RequestUserAgent.php index 24dfb1b906e..9679f631897 100644 --- a/apps/workflowengine/lib/Check/RequestUserAgent.php +++ b/apps/workflowengine/lib/Check/RequestUserAgent.php @@ -82,5 +82,4 @@ class RequestUserAgent extends AbstractStringCheck { public function isAvailableForScope(int $scope): bool { return true; } - } diff --git a/apps/workflowengine/lib/Controller/AWorkflowController.php b/apps/workflowengine/lib/Controller/AWorkflowController.php index 767ae79c5fd..6d109f7dccf 100644 --- a/apps/workflowengine/lib/Controller/AWorkflowController.php +++ b/apps/workflowengine/lib/Controller/AWorkflowController.php @@ -112,7 +112,7 @@ abstract class AWorkflowController extends OCSController { throw new OCSBadRequestException($e->getMessage(), $e); } catch (\DomainException $e) { throw new OCSForbiddenException($e->getMessage(), $e); - } catch(DBALException $e) { + } catch (DBALException $e) { throw new OCSException('An internal error occurred', $e->getCode(), $e); } } @@ -139,7 +139,7 @@ abstract class AWorkflowController extends OCSController { throw new OCSBadRequestException($e->getMessage(), $e); } catch (\DomainException $e) { throw new OCSForbiddenException($e->getMessage(), $e); - } catch(DBALException $e) { + } catch (DBALException $e) { throw new OCSException('An internal error occurred', $e->getCode(), $e); } } @@ -157,7 +157,7 @@ abstract class AWorkflowController extends OCSController { throw new OCSBadRequestException($e->getMessage(), $e); } catch (\DomainException $e) { throw new OCSForbiddenException($e->getMessage(), $e); - } catch(DBALException $e) { + } catch (DBALException $e) { throw new OCSException('An internal error occurred', $e->getCode(), $e); } } diff --git a/apps/workflowengine/lib/Controller/GlobalWorkflowsController.php b/apps/workflowengine/lib/Controller/GlobalWorkflowsController.php index 45930c34c5b..6641155f032 100644 --- a/apps/workflowengine/lib/Controller/GlobalWorkflowsController.php +++ b/apps/workflowengine/lib/Controller/GlobalWorkflowsController.php @@ -34,7 +34,7 @@ class GlobalWorkflowsController extends AWorkflowController { private $scopeContext; protected function getScopeContext(): ScopeContext { - if($this->scopeContext === null) { + if ($this->scopeContext === null) { $this->scopeContext = new ScopeContext(IManager::SCOPE_ADMIN); } return $this->scopeContext; diff --git a/apps/workflowengine/lib/Controller/UserWorkflowsController.php b/apps/workflowengine/lib/Controller/UserWorkflowsController.php index 226746a2264..c3884b61979 100644 --- a/apps/workflowengine/lib/Controller/UserWorkflowsController.php +++ b/apps/workflowengine/lib/Controller/UserWorkflowsController.php @@ -105,14 +105,13 @@ class UserWorkflowsController extends AWorkflowController { * @throws OCSForbiddenException */ protected function getScopeContext(): ScopeContext { - if($this->scopeContext === null) { + if ($this->scopeContext === null) { $user = $this->session->getUser(); - if(!$user || !$this->manager->isUserScopeEnabled()) { + if (!$user || !$this->manager->isUserScopeEnabled()) { throw new OCSForbiddenException('User not logged in'); } $this->scopeContext = new ScopeContext(IManager::SCOPE_USER, $user->getUID()); } return $this->scopeContext; } - } diff --git a/apps/workflowengine/lib/Entity/File.php b/apps/workflowengine/lib/Entity/File.php index 78178ff759d..4f98a3e5cad 100644 --- a/apps/workflowengine/lib/Entity/File.php +++ b/apps/workflowengine/lib/Entity/File.php @@ -46,7 +46,6 @@ use OCP\WorkflowEngine\IEntity; use OCP\WorkflowEngine\IRuleMatcher; class File implements IEntity, IDisplayText, IUrl { - private const EVENT_NAMESPACE = '\OCP\Files::'; /** @var IL10N */ @@ -125,7 +124,7 @@ class File implements IEntity, IDisplayText, IUrl { public function isLegitimatedForUserId(string $uid): bool { try { $node = $this->getNode(); - if($node->getOwner()->getUID() === $uid) { + if ($node->getOwner()->getUID() === $uid) { return true; } $acl = $this->shareManager->getAccessList($node, true, true); @@ -192,19 +191,19 @@ class File implements IEntity, IDisplayText, IUrl { return $this->l10n->t('%s copied %s', $options); case MapperEvent::EVENT_ASSIGN: $tagNames = []; - if($this->event instanceof MapperEvent) { + if ($this->event instanceof MapperEvent) { $tagIDs = $this->event->getTags(); $tagObjects = $this->tagManager->getTagsByIds($tagIDs); foreach ($tagObjects as $systemTag) { /** @var ISystemTag $systemTag */ - if($systemTag->isUserVisible()) { + if ($systemTag->isUserVisible()) { $tagNames[] = $systemTag->getName(); } } } $filename = array_pop($options); $tagString = implode(', ', $tagNames); - if($tagString === '') { + if ($tagString === '') { return ''; } array_push($options, $tagString, $filename); diff --git a/apps/workflowengine/lib/Helper/LogContext.php b/apps/workflowengine/lib/Helper/LogContext.php index 231294d8c74..405d8ceb4ee 100644 --- a/apps/workflowengine/lib/Helper/LogContext.php +++ b/apps/workflowengine/lib/Helper/LogContext.php @@ -41,8 +41,8 @@ class LogContext { public function setScopes(array $scopes): LogContext { $this->details['scopes'] = []; foreach ($scopes as $scope) { - if($scope instanceof ScopeContext) { - switch($scope->getScope()) { + if ($scope instanceof ScopeContext) { + switch ($scope->getScope()) { case IManager::SCOPE_ADMIN: $this->details['scopes'][] = ['scope' => 'admin']; break; @@ -61,7 +61,7 @@ class LogContext { } public function setOperation(?IOperation $operation): LogContext { - if($operation instanceof IOperation) { + if ($operation instanceof IOperation) { $this->details['operation'] = [ 'class' => get_class($operation), 'name' => $operation->getDisplayName(), @@ -71,7 +71,7 @@ class LogContext { } public function setEntity(?IEntity $entity): LogContext { - if($entity instanceof IEntity) { + if ($entity instanceof IEntity) { $this->details['entity'] = [ 'class' => get_class($entity), 'name' => $entity->getName(), diff --git a/apps/workflowengine/lib/Helper/ScopeContext.php b/apps/workflowengine/lib/Helper/ScopeContext.php index e0251131a01..2ddea398f6b 100644 --- a/apps/workflowengine/lib/Helper/ScopeContext.php +++ b/apps/workflowengine/lib/Helper/ScopeContext.php @@ -41,16 +41,15 @@ class ScopeContext { } private function evaluateScope(int $scope): int { - if(in_array($scope, [IManager::SCOPE_ADMIN, IManager::SCOPE_USER], true)) { + if (in_array($scope, [IManager::SCOPE_ADMIN, IManager::SCOPE_USER], true)) { return $scope; } throw new \InvalidArgumentException('Invalid scope'); } private function evaluateScopeId(string $scopeId = null): string { - if($this->scope === IManager::SCOPE_USER - && trim((string)$scopeId) === '') - { + if ($this->scope === IManager::SCOPE_USER + && trim((string)$scopeId) === '') { throw new \InvalidArgumentException('user scope requires a user id'); } return trim((string)$scopeId); @@ -71,7 +70,7 @@ class ScopeContext { } public function getHash(): string { - if($this->hash === null) { + if ($this->hash === null) { $this->hash = \hash('sha256', $this->getScope() . '::' . $this->getScopeId()); } return $this->hash; diff --git a/apps/workflowengine/lib/Manager.php b/apps/workflowengine/lib/Manager.php index fbcf3a48493..b583b190070 100644 --- a/apps/workflowengine/lib/Manager.php +++ b/apps/workflowengine/lib/Manager.php @@ -154,7 +154,7 @@ class Manager implements IManager { $result = $query->execute(); $operations = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $eventNames = \json_decode($row['events']); $operation = $row['class']; @@ -201,7 +201,7 @@ class Manager implements IManager { } public function getAllOperations(ScopeContext $scopeContext): array { - if(isset($this->operations[$scopeContext->getHash()])) { + if (isset($this->operations[$scopeContext->getHash()])) { return $this->operations[$scopeContext->getHash()]; } @@ -214,7 +214,7 @@ class Manager implements IManager { ->leftJoin('o', 'flow_operations_scope', 's', $query->expr()->eq('o.id', 's.operation_id')) ->where($query->expr()->eq('s.type', $query->createParameter('scope'))); - if($scopeContext->getScope() === IManager::SCOPE_USER) { + if ($scopeContext->getScope() === IManager::SCOPE_USER) { $query->andWhere($query->expr()->eq('s.value', $query->createParameter('scopeId'))); } @@ -223,7 +223,7 @@ class Manager implements IManager { $this->operations[$scopeContext->getHash()] = []; while ($row = $result->fetch()) { - if(!isset($this->operations[$scopeContext->getHash()][$row['class']])) { + if (!isset($this->operations[$scopeContext->getHash()][$row['class']])) { $this->operations[$scopeContext->getHash()][$row['class']] = []; } $this->operations[$scopeContext->getHash()][$row['class']][] = $row; @@ -324,7 +324,7 @@ class Manager implements IManager { } protected function canModify(int $id, ScopeContext $scopeContext):bool { - if(isset($this->operationsByScope[$scopeContext->getHash()])) { + if (isset($this->operationsByScope[$scopeContext->getHash()])) { return in_array($id, $this->operationsByScope[$scopeContext->getHash()], true); } @@ -334,7 +334,7 @@ class Manager implements IManager { ->leftJoin('o', 'flow_operations_scope', 's', $qb->expr()->eq('o.id', 's.operation_id')) ->where($qb->expr()->eq('s.type', $qb->createParameter('scope'))); - if($scopeContext->getScope() !== IManager::SCOPE_ADMIN) { + if ($scopeContext->getScope() !== IManager::SCOPE_ADMIN) { $qb->where($qb->expr()->eq('s.value', $qb->createParameter('scopeId'))); } @@ -342,7 +342,7 @@ class Manager implements IManager { $result = $qb->execute(); $this->operationsByScope[$scopeContext->getHash()] = []; - while($opId = $result->fetchColumn(0)) { + while ($opId = $result->fetchColumn(0)) { $this->operationsByScope[$scopeContext->getHash()][] = (int)$opId; } $result->closeCursor(); @@ -369,7 +369,7 @@ class Manager implements IManager { string $entity, array $events ): array { - if(!$this->canModify($id, $scopeContext)) { + if (!$this->canModify($id, $scopeContext)) { throw new \DomainException('Target operation not within scope'); }; $row = $this->getOperation($id); @@ -409,7 +409,7 @@ class Manager implements IManager { * @throws \DomainException */ public function deleteOperation($id, ScopeContext $scopeContext) { - if(!$this->canModify($id, $scopeContext)) { + if (!$this->canModify($id, $scopeContext)) { throw new \DomainException('Target operation not within scope'); }; $query = $this->connection->getQueryBuilder(); @@ -418,7 +418,7 @@ class Manager implements IManager { $result = (bool)$query->delete('flow_operations') ->where($query->expr()->eq('id', $query->createNamedParameter($id))) ->execute(); - if($result) { + if ($result) { $qb = $this->connection->getQueryBuilder(); $result &= (bool)$qb->delete('flow_operations_scope') ->where($qb->expr()->eq('operation_id', $qb->createNamedParameter($id))) @@ -430,7 +430,7 @@ class Manager implements IManager { throw $e; } - if(isset($this->operations[$scopeContext->getHash()])) { + if (isset($this->operations[$scopeContext->getHash()])) { unset($this->operations[$scopeContext->getHash()]); } @@ -445,12 +445,12 @@ class Manager implements IManager { throw new \UnexpectedValueException($this->l->t('Entity %s does not exist', [$entity])); } - if(!$instance instanceof IEntity) { + if (!$instance instanceof IEntity) { throw new \UnexpectedValueException($this->l->t('Entity %s is invalid', [$entity])); } - if(empty($events)) { - if(!$operation instanceof IComplexOperation) { + if (empty($events)) { + if (!$operation instanceof IComplexOperation) { throw new \UnexpectedValueException($this->l->t('No events are chosen.')); } return; @@ -463,7 +463,7 @@ class Manager implements IManager { } $diff = array_diff($events, $availableEvents); - if(!empty($diff)) { + if (!empty($diff)) { throw new \UnexpectedValueException($this->l->t('Entity %s has no event %s', [$entity, array_shift($diff)])); } } diff --git a/apps/workflowengine/lib/Migration/PopulateNewlyIntroducedDatabaseFields.php b/apps/workflowengine/lib/Migration/PopulateNewlyIntroducedDatabaseFields.php index 3c8d4ce81f8..6f344c2ee2d 100644 --- a/apps/workflowengine/lib/Migration/PopulateNewlyIntroducedDatabaseFields.php +++ b/apps/workflowengine/lib/Migration/PopulateNewlyIntroducedDatabaseFields.php @@ -62,14 +62,13 @@ class PopulateNewlyIntroducedDatabaseFields implements IRepairStep { ->set('entity', $qb->createNamedParameter(File::class)) ->where($qb->expr()->emptyString('entity')) ->execute(); - } protected function populateScopeTable(Statement $ids): void { $qb = $this->dbc->getQueryBuilder(); $insertQuery = $qb->insert('flow_operations_scope'); - while($id = $ids->fetchColumn(0)) { + while ($id = $ids->fetchColumn(0)) { $insertQuery->values(['operation_id' => $qb->createNamedParameter($id), 'type' => IManager::SCOPE_ADMIN]); $insertQuery->execute(); } @@ -86,5 +85,4 @@ class PopulateNewlyIntroducedDatabaseFields implements IRepairStep { return $selectQuery->execute(); } - } diff --git a/apps/workflowengine/lib/Migration/Version2000Date20190808074233.php b/apps/workflowengine/lib/Migration/Version2000Date20190808074233.php index 787cd06bfa1..cfbd852d49f 100644 --- a/apps/workflowengine/lib/Migration/Version2000Date20190808074233.php +++ b/apps/workflowengine/lib/Migration/Version2000Date20190808074233.php @@ -112,14 +112,14 @@ class Version2000Date20190808074233 extends SimpleMigrationStep { } protected function ensureEntityColumns(Table $table) { - if(!$table->hasColumn('entity')) { + if (!$table->hasColumn('entity')) { $table->addColumn('entity', Type::STRING, [ 'notnull' => true, 'length' => 256, 'default' => '', ]); } - if(!$table->hasColumn('events')) { + if (!$table->hasColumn('events')) { $table->addColumn('events', Type::TEXT, [ 'notnull' => true, 'default' => '[]', diff --git a/apps/workflowengine/lib/Service/Logger.php b/apps/workflowengine/lib/Service/Logger.php index f369a304e9c..d5aca8f84b7 100644 --- a/apps/workflowengine/lib/Service/Logger.php +++ b/apps/workflowengine/lib/Service/Logger.php @@ -53,7 +53,7 @@ class Logger { protected function initLogger() { $default = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/flow.log'; $logFile = trim((string)$this->config->getAppValue(Application::APP_ID, 'logfile', $default)); - if($logFile !== '') { + if ($logFile !== '') { $this->flowLogger = $this->logFactory->getCustomLogger($logFile); } } @@ -152,17 +152,16 @@ class Logger { string $message, array $context, LogContext $logContext - ): void - { - if(!isset($context['app'])) { + ): void { + if (!isset($context['app'])) { $context['app'] = Application::APP_ID; } - if(!isset($context['level'])) { + if (!isset($context['level'])) { $context['level'] = ILogger::INFO; } $this->generalLogger->log($context['level'], $message, $context); - if(!$this->flowLogger instanceof IDataLogger) { + if (!$this->flowLogger instanceof IDataLogger) { return; } diff --git a/apps/workflowengine/lib/Service/RuleMatcher.php b/apps/workflowengine/lib/Service/RuleMatcher.php index b022bafb11a..f02c28fa27e 100644 --- a/apps/workflowengine/lib/Service/RuleMatcher.php +++ b/apps/workflowengine/lib/Service/RuleMatcher.php @@ -88,28 +88,28 @@ class RuleMatcher implements IRuleMatcher { } public function setOperation(IOperation $operation): void { - if($this->operation !== null) { + if ($this->operation !== null) { throw new RuntimeException('This method must not be called more than once'); } $this->operation = $operation; } public function setEntity(IEntity $entity): void { - if($this->entity !== null) { + if ($this->entity !== null) { throw new RuntimeException('This method must not be called more than once'); } $this->entity = $entity; } public function getEntity(): IEntity { - if($this->entity === null) { + if ($this->entity === null) { throw new \LogicException('Entity was not set yet'); } return $this->entity; } public function getFlows(bool $returnFirstMatchingOperationOnly = true): array { - if(!$this->operation) { + if (!$this->operation) { throw new RuntimeException('Operation is not set'); } return $this->getMatchingOperations(get_class($this->operation), $returnFirstMatchingOperationOnly); @@ -118,7 +118,7 @@ class RuleMatcher implements IRuleMatcher { public function getMatchingOperations(string $class, bool $returnFirstMatchingOperationOnly = true): array { $scopes[] = new ScopeContext(IManager::SCOPE_ADMIN); $user = $this->session->getUser(); - if($user !== null && $this->manager->isUserScopeEnabled()) { + if ($user !== null && $this->manager->isUserScopeEnabled()) { $scopes[] = new ScopeContext(IManager::SCOPE_USER, $user->getUID()); } @@ -134,7 +134,7 @@ class RuleMatcher implements IRuleMatcher { $operations = array_merge($operations, $this->manager->getOperations($class, $scope)); } - if($this->entity instanceof IEntity) { + if ($this->entity instanceof IEntity) { /** @var ScopeContext[] $additionalScopes */ $additionalScopes = $this->manager->getAllConfiguredScopesForOperation($class); foreach ($additionalScopes as $hash => $scopeCandidate) { @@ -188,7 +188,7 @@ class RuleMatcher implements IRuleMatcher { $ctx ->setEntity($this->entity) ->setOperation($this->operation); - if(!empty($matches)) { + if (!empty($matches)) { $ctx->setConfiguration($matches); $this->logger->logRunAll($ctx); } else { @@ -216,11 +216,11 @@ class RuleMatcher implements IRuleMatcher { } $checkInstance->setFileInfo($this->fileInfo['storage'], $this->fileInfo['path'], $this->fileInfo['isDir']); } elseif ($checkInstance instanceof IEntityCheck) { - foreach($this->contexts as $entityInfo) { + foreach ($this->contexts as $entityInfo) { list($entity, $subject) = $entityInfo; $checkInstance->setEntitySubject($entity, $subject); } - } elseif(!$checkInstance instanceof ICheck) { + } elseif (!$checkInstance instanceof ICheck) { // Check is invalid throw new \UnexpectedValueException($this->l->t('Check %s is invalid or does not exist', $check['class'])); } diff --git a/apps/workflowengine/lib/Settings/Admin.php b/apps/workflowengine/lib/Settings/Admin.php index 3f8cb00982e..11e9096bc56 100644 --- a/apps/workflowengine/lib/Settings/Admin.php +++ b/apps/workflowengine/lib/Settings/Admin.php @@ -28,7 +28,6 @@ namespace OCA\WorkflowEngine\Settings; use OCP\WorkflowEngine\IManager; class Admin extends ASettings { - function getScope(): int { return IManager::SCOPE_ADMIN; } diff --git a/apps/workflowengine/lib/Settings/Personal.php b/apps/workflowengine/lib/Settings/Personal.php index 15f4df3c7e6..af922726121 100644 --- a/apps/workflowengine/lib/Settings/Personal.php +++ b/apps/workflowengine/lib/Settings/Personal.php @@ -28,7 +28,6 @@ namespace OCA\WorkflowEngine\Settings; use OCP\WorkflowEngine\IManager; class Personal extends ASettings { - function getScope(): int { return IManager::SCOPE_USER; } diff --git a/apps/workflowengine/tests/Check/AbstractStringCheckTest.php b/apps/workflowengine/tests/Check/AbstractStringCheckTest.php index f9fc57a5331..083876268f1 100644 --- a/apps/workflowengine/tests/Check/AbstractStringCheckTest.php +++ b/apps/workflowengine/tests/Check/AbstractStringCheckTest.php @@ -24,7 +24,6 @@ namespace OCA\WorkflowEngine\Tests\Check; use OCP\IL10N; class AbstractStringCheckTest extends \Test\TestCase { - protected function getCheckMock() { $l = $this->getMockBuilder(IL10N::class) ->disableOriginalConstructor() @@ -32,8 +31,8 @@ class AbstractStringCheckTest extends \Test\TestCase { $l->expects($this->any()) ->method('t') ->willReturnCallback(function ($string, $args) { - return sprintf($string, $args); - }); + return sprintf($string, $args); + }); $check = $this->getMockBuilder('OCA\WorkflowEngine\Check\AbstractStringCheck') ->setConstructorArgs([ diff --git a/apps/workflowengine/tests/ManagerTest.php b/apps/workflowengine/tests/ManagerTest.php index 191e7bfec84..512d5dc1f61 100644 --- a/apps/workflowengine/tests/ManagerTest.php +++ b/apps/workflowengine/tests/ManagerTest.php @@ -126,7 +126,7 @@ class ManagerTest extends TestCase { public function clearTables() { $query = $this->db->getQueryBuilder(); - foreach(['flow_checks', 'flow_operations', 'flow_operations_scope'] as $table) { + foreach (['flow_checks', 'flow_operations', 'flow_operations_scope'] as $table) { $query->delete($table) ->execute(); } @@ -274,7 +274,6 @@ class ManagerTest extends TestCase { array_walk($userOps, function ($op) { $this->assertTrue($op['class'] === 'OCA\WFE\TestOp'); }); - } public function testUpdateOperation() { @@ -285,9 +284,9 @@ class ManagerTest extends TestCase { $this->container->expects($this->any()) ->method('query') ->willReturnCallback(function ($class) { - if(substr($class, -2) === 'Op') { + if (substr($class, -2) === 'Op') { return $this->createMock(IOperation::class); - } elseif($class === File::class) { + } elseif ($class === File::class) { return $this->getMockBuilder(File::class) ->setConstructorArgs([ $this->l, @@ -331,7 +330,7 @@ class ManagerTest extends TestCase { $this->assertSame('Test02a', $op['name']); $this->assertSame('barfoo', $op['operation']); - foreach([[$adminScope, $opId2], [$userScope, $opId1]] as $run) { + foreach ([[$adminScope, $opId2], [$userScope, $opId1]] as $run) { try { /** @noinspection PhpUnhandledExceptionInspection */ $this->manager->updateOperation($run[1], 'Evil', [$check2], 'hackx0r', $run[0], $entity, []); @@ -361,7 +360,7 @@ class ManagerTest extends TestCase { ); $this->invokePrivate($this->manager, 'addScope', [$opId2, $userScope]); - foreach([[$adminScope, $opId2], [$userScope, $opId1]] as $run) { + foreach ([[$adminScope, $opId2], [$userScope, $opId1]] as $run) { try { /** @noinspection PhpUnhandledExceptionInspection */ $this->manager->deleteOperation($run[1], $run[0]); @@ -376,11 +375,11 @@ class ManagerTest extends TestCase { /** @noinspection PhpUnhandledExceptionInspection */ $this->manager->deleteOperation($opId2, $userScope); - foreach([$opId1, $opId2] as $opId) { + foreach ([$opId1, $opId2] as $opId) { try { $this->invokePrivate($this->manager, 'getOperation', [$opId]); $this->assertTrue(false, 'UnexpectedValueException not thrown'); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->assertInstanceOf(\UnexpectedValueException::class, $e); } } @@ -423,13 +422,15 @@ class ManagerTest extends TestCase { $this->assertCount(2, $entities); $entityTypeCounts = array_reduce($entities, function (array $carry, IEntity $entity) { - if($entity instanceof File) $carry[0]++; - elseif($entity instanceof IEntity) $carry[1]++; + if ($entity instanceof File) { + $carry[0]++; + } elseif ($entity instanceof IEntity) { + $carry[1]++; + } return $carry; }, [0, 0]); $this->assertSame(1, $entityTypeCounts[0]); $this->assertSame(1, $entityTypeCounts[1]); } - } diff --git a/build/OCPSinceChecker.php b/build/OCPSinceChecker.php index 13f58fe2550..ff314170149 100644 --- a/build/OCPSinceChecker.php +++ b/build/OCPSinceChecker.php @@ -40,51 +40,51 @@ class SinceTagCheckVisitor extends \PhpParser\NodeVisitorAbstract { protected $errors = []; public function enterNode(\PhpParser\Node $node) { - if($this->deprecatedClass) { + if ($this->deprecatedClass) { return; } - if($node instanceof \PhpParser\Node\Stmt\Namespace_) { + if ($node instanceof \PhpParser\Node\Stmt\Namespace_) { $this->namespace = $node->name; } - if($node instanceof \PhpParser\Node\Stmt\Interface_ or + if ($node instanceof \PhpParser\Node\Stmt\Interface_ or $node instanceof \PhpParser\Node\Stmt\Class_) { $this->className = $node->name; /** @var \PhpParser\Comment\Doc[] $comments */ $comments = $node->getAttribute('comments'); - if(count($comments) === 0) { + if (count($comments) === 0) { $this->errors[] = 'PHPDoc is needed for ' . $this->namespace . '\\' . $this->className . '::' . $node->name; return; } $comment = $comments[count($comments) - 1]; $text = $comment->getText(); - if(strpos($text, '@deprecated') !== false) { + if (strpos($text, '@deprecated') !== false) { $this->deprecatedClass = true; } - if($this->deprecatedClass === false && strpos($text, '@since') === false && strpos($text, '@deprecated') === false) { + if ($this->deprecatedClass === false && strpos($text, '@since') === false && strpos($text, '@deprecated') === false) { $type = $node instanceof \PhpParser\Node\Stmt\Interface_ ? 'interface' : 'class'; $this->errors[] = '@since or @deprecated tag is needed in PHPDoc for ' . $type . ' ' . $this->namespace . '\\' . $this->className; return; } } - if($node instanceof \PhpParser\Node\Stmt\ClassMethod) { + if ($node instanceof \PhpParser\Node\Stmt\ClassMethod) { /** @var \PhpParser\Node\Stmt\ClassMethod $node */ /** @var \PhpParser\Comment\Doc[] $comments */ $comments = $node->getAttribute('comments'); - if(count($comments) === 0) { + if (count($comments) === 0) { $this->errors[] = 'PHPDoc is needed for ' . $this->namespace . '\\' . $this->className . '::' . $node->name; return; } $comment = $comments[count($comments) - 1]; $text = $comment->getText(); - if(strpos($text, '@since') === false && strpos($text, '@deprecated') === false) { + if (strpos($text, '@since') === false && strpos($text, '@deprecated') === false) { $this->errors[] = '@since or @deprecated tag is needed in PHPDoc for ' . $this->namespace . '\\' . $this->className . '::' . $node->name; return; } @@ -108,7 +108,7 @@ $Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GE $errors = []; -foreach($Regex as $file) { +foreach ($Regex as $file) { $stmts = $parser->parse(file_get_contents($file[0])); $visitor = new SinceTagCheckVisitor(); @@ -119,7 +119,7 @@ foreach($Regex as $file) { $errors = array_merge($errors, $visitor->getErrors()); } -if(count($errors)) { +if (count($errors)) { echo join(PHP_EOL, $errors) . PHP_EOL . PHP_EOL; exit(1); } diff --git a/build/gen-coverage-badge.php b/build/gen-coverage-badge.php index b610b2748d6..0164951fc1c 100644 --- a/build/gen-coverage-badge.php +++ b/build/gen-coverage-badge.php @@ -52,7 +52,7 @@ try { } $content = file_get_contents("https://img.shields.io/badge/coverage-$percent%-$color.svg"); file_put_contents('coverage.svg', $content); -} catch(Exception $ex) { +} catch (Exception $ex) { echo $ex->getMessage() . PHP_EOL; $content = file_get_contents("https://img.shields.io/badge/coverage-ERROR-red.svg"); file_put_contents('coverage.svg', $content); diff --git a/build/htaccess-checker.php b/build/htaccess-checker.php index b6932d6543a..950735463c9 100644 --- a/build/htaccess-checker.php +++ b/build/htaccess-checker.php @@ -27,7 +27,7 @@ */ $htaccess = file_get_contents(__DIR__ . '/../.htaccess'); -if(strpos($htaccess, 'DO NOT CHANGE ANYTHING') !== false) { +if (strpos($htaccess, 'DO NOT CHANGE ANYTHING') !== false) { echo(".htaccess file has invalid changes!\n"); exit(1); } else { diff --git a/build/integration/features/bootstrap/Auth.php b/build/integration/features/bootstrap/Auth.php index e48c0967cee..c621ef3572d 100644 --- a/build/integration/features/bootstrap/Auth.php +++ b/build/integration/features/bootstrap/Auth.php @@ -270,5 +270,4 @@ trait Auth { public function whenTheSessionCookieExpires() { $this->cookieJar->clearSessionCookies(); } - } diff --git a/build/integration/features/bootstrap/BasicStructure.php b/build/integration/features/bootstrap/BasicStructure.php index 6a42cc1915d..438a6418f07 100644 --- a/build/integration/features/bootstrap/BasicStructure.php +++ b/build/integration/features/bootstrap/BasicStructure.php @@ -43,7 +43,6 @@ use Psr\Http\Message\ResponseInterface; require __DIR__ . '/../../vendor/autoload.php'; trait BasicStructure { - use Auth; use Download; use Trashbin; @@ -516,11 +515,11 @@ trait BasicStructure { * @throws \Exception */ public function theFollowingHeadersShouldBeSet(TableNode $table) { - foreach($table->getTable() as $header) { + foreach ($table->getTable() as $header) { $headerName = $header[0]; $expectedHeaderValue = $header[1]; $returnedHeader = $this->response->getHeader($headerName)[0]; - if($returnedHeader !== $expectedHeaderValue) { + if ($returnedHeader !== $expectedHeaderValue) { throw new \Exception( sprintf( "Expected value '%s' for header '%s', got '%s'", diff --git a/build/integration/features/bootstrap/CalDavContext.php b/build/integration/features/bootstrap/CalDavContext.php index b7b099b9850..76fe0576704 100644 --- a/build/integration/features/bootstrap/CalDavContext.php +++ b/build/integration/features/bootstrap/CalDavContext.php @@ -71,7 +71,8 @@ class CalDavContext implements \Behat\Behat\Context\Context { ], ] ); - } catch (\GuzzleHttp\Exception\ClientException $e) {} + } catch (\GuzzleHttp\Exception\ClientException $e) { + } } /** @@ -106,7 +107,7 @@ class CalDavContext implements \Behat\Behat\Context\Context { * @throws \Exception */ public function theCaldavHttpStatusCodeShouldBe($code) { - if((int)$code !== $this->response->getStatusCode()) { + if ((int)$code !== $this->response->getStatusCode()) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -117,7 +118,7 @@ class CalDavContext implements \Behat\Behat\Context\Context { } $body = $this->response->getBody()->getContents(); - if($body && substr($body, 0, 1) === '<') { + if ($body && substr($body, 0, 1) === '<') { $reader = new Sabre\Xml\Reader(); $reader->xml($body); $this->responseXml = $reader->parse(); @@ -132,7 +133,7 @@ class CalDavContext implements \Behat\Behat\Context\Context { public function theExceptionIs($message) { $result = $this->responseXml['value'][0]['value']; - if($message !== $result) { + if ($message !== $result) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -151,7 +152,7 @@ class CalDavContext implements \Behat\Behat\Context\Context { public function theErrorMessageIs($message) { $result = $this->responseXml['value'][1]['value']; - if($message !== $result) { + if ($message !== $result) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -219,7 +220,7 @@ class CalDavContext implements \Behat\Behat\Context\Context { $jsonEncoded = json_encode($this->responseXml); $arrayElement = json_decode($jsonEncoded, true); $actual = count($arrayElement['value']) - 1; - if($actual !== (int)$amount) { + if ($actual !== (int)$amount) { throw new InvalidArgumentException( sprintf( 'Expected %s got %s', diff --git a/build/integration/features/bootstrap/CapabilitiesContext.php b/build/integration/features/bootstrap/CapabilitiesContext.php index 9f778ea5b5a..427e115605c 100644 --- a/build/integration/features/bootstrap/CapabilitiesContext.php +++ b/build/integration/features/bootstrap/CapabilitiesContext.php @@ -34,7 +34,6 @@ require __DIR__ . '/../../vendor/autoload.php'; * Capabilities context. */ class CapabilitiesContext implements Context, SnippetAcceptingContext { - use BasicStructure; use AppConfiguration; @@ -48,7 +47,7 @@ class CapabilitiesContext implements Context, SnippetAcceptingContext { foreach ($formData->getHash() as $row) { $path_to_element = explode('@@@', $row['path_to_element']); $answeredValue = $capabilitiesXML->{$row['capability']}; - for ($i = 0; $i < count($path_to_element); $i++){ + for ($i = 0; $i < count($path_to_element); $i++) { $answeredValue = $answeredValue->{$path_to_element[$i]}; } $answeredValue = (string)$answeredValue; @@ -57,7 +56,6 @@ class CapabilitiesContext implements Context, SnippetAcceptingContext { $answeredValue, "Failed field " . $row['capability'] . " " . $row['path_to_element'] ); - } } diff --git a/build/integration/features/bootstrap/CardDavContext.php b/build/integration/features/bootstrap/CardDavContext.php index 3e79c41fd13..c6d12c0f980 100644 --- a/build/integration/features/bootstrap/CardDavContext.php +++ b/build/integration/features/bootstrap/CardDavContext.php @@ -71,7 +71,8 @@ class CardDavContext implements \Behat\Behat\Context\Context { ], ] ); - } catch (\GuzzleHttp\Exception\ClientException $e) {} + } catch (\GuzzleHttp\Exception\ClientException $e) { + } } /** @@ -101,7 +102,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { $this->response = $e->getResponse(); } - if((int)$statusCode !== $this->response->getStatusCode()) { + if ((int)$statusCode !== $this->response->getStatusCode()) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -112,7 +113,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { } $body = $this->response->getBody()->getContents(); - if(substr($body, 0, 1) === '<') { + if (substr($body, 0, 1) === '<') { $reader = new Sabre\Xml\Reader(); $reader->xml($body); $this->responseXml = $reader->parse(); @@ -154,7 +155,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { ] ); - if($this->response->getStatusCode() !== (int)$statusCode) { + if ($this->response->getStatusCode() !== (int)$statusCode) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -173,7 +174,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { public function theCarddavExceptionIs($message) { $result = $this->responseXml['value'][0]['value']; - if($message !== $result) { + if ($message !== $result) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -192,7 +193,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { public function theCarddavErrorMessageIs($message) { $result = $this->responseXml['value'][1]['value']; - if($message !== $result) { + if ($message !== $result) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -225,7 +226,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { ] ); - if($this->response->getStatusCode() !== 201) { + if ($this->response->getStatusCode() !== 201) { throw new \Exception( sprintf( 'Expected %s got %s', @@ -284,7 +285,7 @@ class CardDavContext implements \Behat\Behat\Context\Context { ] ); } catch (\GuzzleHttp\Exception\ClientException $e) { - $this->response = $e->getResponse(); + $this->response = $e->getResponse(); } } @@ -294,11 +295,11 @@ class CardDavContext implements \Behat\Behat\Context\Context { * @throws \Exception */ public function theFollowingHttpHeadersShouldBeSet(\Behat\Gherkin\Node\TableNode $table) { - foreach($table->getTable() as $header) { + foreach ($table->getTable() as $header) { $headerName = $header[0]; $expectedHeaderValue = $header[1]; $returnedHeader = $this->response->getHeader($headerName)[0]; - if($returnedHeader !== $expectedHeaderValue) { + if ($returnedHeader !== $expectedHeaderValue) { throw new \Exception( sprintf( "Expected value '%s' for header '%s', got '%s'", diff --git a/build/integration/features/bootstrap/ChecksumsContext.php b/build/integration/features/bootstrap/ChecksumsContext.php index f6587b53d41..be9059cb710 100644 --- a/build/integration/features/bootstrap/ChecksumsContext.php +++ b/build/integration/features/bootstrap/ChecksumsContext.php @@ -64,7 +64,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @return string */ private function getPasswordForUser($userName) { - if($userName === 'admin') { + if ($userName === 'admin') { return 'admin'; } return '123456'; @@ -77,8 +77,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $destination * @param string $checksum */ - public function userUploadsFileToWithChecksum($user, $source, $destination, $checksum) - { + public function userUploadsFileToWithChecksum($user, $source, $destination, $checksum) { $file = \GuzzleHttp\Psr7\stream_for(fopen($source, 'r')); try { $this->response = $this->client->put( @@ -106,7 +105,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @throws \Exception */ public function theWebdavResponseShouldHaveAStatusCode($statusCode) { - if((int)$statusCode !== $this->response->getStatusCode()) { + if ((int)$statusCode !== $this->response->getStatusCode()) { throw new \Exception("Expected $statusCode, got ".$this->response->getStatusCode()); } } @@ -116,8 +115,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $user * @param string $path */ - public function userRequestTheChecksumOfViaPropfind($user, $path) - { + public function userRequestTheChecksumOfViaPropfind($user, $path) { $this->response = $this->client->request( 'PROPFIND', $this->baseUrl . '/remote.php/webdav' . $path, @@ -141,8 +139,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $checksum * @throws \Exception */ - public function theWebdavChecksumShouldMatch($checksum) - { + public function theWebdavChecksumShouldMatch($checksum) { $service = new Sabre\Xml\Service(); $parsed = $service->parse($this->response->getBody()->getContents()); @@ -162,8 +159,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $user * @param string $path */ - public function userDownloadsTheFile($user, $path) - { + public function userDownloadsTheFile($user, $path) { $this->response = $this->client->get( $this->baseUrl . '/remote.php/webdav' . $path, [ @@ -180,8 +176,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $checksum * @throws \Exception */ - public function theHeaderChecksumShouldMatch($checksum) - { + public function theHeaderChecksumShouldMatch($checksum) { if ($this->response->getHeader('OC-Checksum')[0] !== $checksum) { throw new \Exception("Expected $checksum, got ".$this->response->getHeader('OC-Checksum')[0]); } @@ -193,8 +188,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $source * @param string $destination */ - public function userCopiedFileTo($user, $source, $destination) - { + public function userCopiedFileTo($user, $source, $destination) { $this->response = $this->client->request( 'MOVE', $this->baseUrl . '/remote.php/webdav' . $source, @@ -213,8 +207,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { /** * @Then The webdav checksum should be empty */ - public function theWebdavChecksumShouldBeEmpty() - { + public function theWebdavChecksumShouldBeEmpty() { $service = new Sabre\Xml\Service(); $parsed = $service->parse($this->response->getBody()->getContents()); @@ -232,8 +225,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { /** * @Then The OC-Checksum header should not be there */ - public function theOcChecksumHeaderShouldNotBeThere() - { + public function theOcChecksumHeaderShouldNotBeThere() { if ($this->response->hasHeader('OC-Checksum')) { throw new \Exception("Expected no checksum header but got ".$this->response->getHeader('OC-Checksum')[0]); } @@ -248,8 +240,7 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { * @param string $destination * @param string $checksum */ - public function userUploadsChunkFileOfWithToWithChecksum($user, $num, $total, $data, $destination, $checksum) - { + public function userUploadsChunkFileOfWithToWithChecksum($user, $num, $total, $data, $destination, $checksum) { $num -= 1; $this->response = $this->client->put( $this->baseUrl . '/remote.php/webdav' . $destination . '-chunking-42-'.$total.'-'.$num, @@ -265,6 +256,5 @@ class ChecksumsContext implements \Behat\Behat\Context\Context { ] ] ); - } } diff --git a/build/integration/features/bootstrap/CommandLineContext.php b/build/integration/features/bootstrap/CommandLineContext.php index 678cf40351f..d233353262d 100644 --- a/build/integration/features/bootstrap/CommandLineContext.php +++ b/build/integration/features/bootstrap/CommandLineContext.php @@ -110,7 +110,7 @@ class CommandLineContext implements \Behat\Behat\Context\Context { */ public function transferingOwnershipPath($path, $user1, $user2) { $path = '--path=' . $path; - if($this->runOcc(['files:transfer-ownership', $path, $user1, $user2]) === 0) { + if ($this->runOcc(['files:transfer-ownership', $path, $user1, $user2]) === 0) { $this->lastTransferPath = $this->findLastTransferFolderForUser($user1, $user2); } else { // failure diff --git a/build/integration/features/bootstrap/CommentsContext.php b/build/integration/features/bootstrap/CommentsContext.php index c3577658f0c..ebd7d5697e5 100644 --- a/build/integration/features/bootstrap/CommentsContext.php +++ b/build/integration/features/bootstrap/CommentsContext.php @@ -297,6 +297,4 @@ class CommentsContext implements \Behat\Behat\Context\Context { throw new \Exception("Response status code was not $statusCode (" . $res->getStatusCode() . ")"); } } - - } diff --git a/build/integration/features/bootstrap/FederationContext.php b/build/integration/features/bootstrap/FederationContext.php index dce62b16c0d..ca1869c10ac 100644 --- a/build/integration/features/bootstrap/FederationContext.php +++ b/build/integration/features/bootstrap/FederationContext.php @@ -33,7 +33,6 @@ require __DIR__ . '/../../vendor/autoload.php'; * Federation context. */ class FederationContext implements Context, SnippetAcceptingContext { - use WebDav; use AppConfiguration; @@ -47,7 +46,7 @@ class FederationContext implements Context, SnippetAcceptingContext { * @param string $shareeServer "LOCAL" or "REMOTE" */ public function federateSharing($sharerUser, $sharerServer, $sharerPath, $shareeUser, $shareeServer) { - if ($shareeServer == "REMOTE"){ + if ($shareeServer == "REMOTE") { $shareWith = "$shareeUser@" . substr($this->remoteBaseUrl, 0, -4); } else { $shareWith = "$shareeUser@" . substr($this->localBaseUrl, 0, -4); @@ -68,7 +67,7 @@ class FederationContext implements Context, SnippetAcceptingContext { * @param string $shareeServer "LOCAL" or "REMOTE" */ public function federateGroupSharing($sharerUser, $sharerServer, $sharerPath, $shareeGroup, $shareeServer) { - if ($shareeServer == "REMOTE"){ + if ($shareeServer == "REMOTE") { $shareWith = "$shareeGroup@" . substr($this->remoteBaseUrl, 0, -4); } else { $shareWith = "$shareeGroup@" . substr($this->localBaseUrl, 0, -4); diff --git a/build/integration/features/bootstrap/FilesDropContext.php b/build/integration/features/bootstrap/FilesDropContext.php index 8f522d6f2ce..d1fd2e8d0c9 100644 --- a/build/integration/features/bootstrap/FilesDropContext.php +++ b/build/integration/features/bootstrap/FilesDropContext.php @@ -37,7 +37,7 @@ class FilesDropContext implements Context, SnippetAcceptingContext { public function droppingFileWith($path, $content) { $client = new Client(); $options = []; - if (count($this->lastShareData->data->element) > 0){ + if (count($this->lastShareData->data->element) > 0) { $token = $this->lastShareData->data[0]->token; } else { $token = $this->lastShareData->data[0]->token; @@ -65,7 +65,7 @@ class FilesDropContext implements Context, SnippetAcceptingContext { public function creatingFolderInDrop($folder) { $client = new Client(); $options = []; - if (count($this->lastShareData->data->element) > 0){ + if (count($this->lastShareData->data->element) > 0) { $token = $this->lastShareData->data[0]->token; } else { $token = $this->lastShareData->data[0]->token; diff --git a/build/integration/features/bootstrap/LDAPContext.php b/build/integration/features/bootstrap/LDAPContext.php index 306b1e3c517..4217bc640c9 100644 --- a/build/integration/features/bootstrap/LDAPContext.php +++ b/build/integration/features/bootstrap/LDAPContext.php @@ -38,7 +38,7 @@ class LDAPContext implements Context { /** @AfterScenario */ public function teardown() { - if($this->configID === null) { + if ($this->configID === null) { return; } $this->disableLDAPConfiguration(); # via occ in case of big config issues @@ -140,7 +140,7 @@ class LDAPContext implements Context { $originalAsAn = $this->currentUser; $this->asAn('admin'); $configData = $table->getRows(); - foreach($configData as &$row) { + foreach ($configData as &$row) { $row[0] = 'configData[' . $row[0] . ']'; } $this->settingTheLDAPConfigurationTo(new TableNode($configData)); @@ -153,8 +153,8 @@ class LDAPContext implements Context { public function theGroupResultShouldMatch(string $type, TableNode $expectations) { $listReturnedElements = simplexml_load_string($this->response->getBody())->data[0]->$type[0]->element; $extractedIDsArray = json_decode(json_encode($listReturnedElements), 1); - foreach($expectations->getRows() as $expectation) { - if((int)$expectation[1] === 1) { + foreach ($expectations->getRows() as $expectation) { + if ((int)$expectation[1] === 1) { Assert::assertContains($expectation[0], $extractedIDsArray); } else { Assert::assertNotContains($expectation[0], $extractedIDsArray); @@ -182,8 +182,8 @@ class LDAPContext implements Context { $listReturnedElements = simplexml_load_string($this->response->getBody())->data[0]->$type[0]->element; $extractedIDsArray = json_decode(json_encode($listReturnedElements), 1); $uidsFound = 0; - foreach($expectations->getRows() as $expectation) { - if(in_array($expectation[0], $extractedIDsArray)) { + foreach ($expectations->getRows() as $expectation) { + if (in_array($expectation[0], $extractedIDsArray)) { $uidsFound++; } } @@ -194,7 +194,7 @@ class LDAPContext implements Context { * @Given /^the record's fields should match$/ */ public function theRecordFieldsShouldMatch(TableNode $expectations) { - foreach($expectations->getRowsHash() as $k => $v) { + foreach ($expectations->getRowsHash() as $k => $v) { $value = (string)simplexml_load_string($this->response->getBody())->data[0]->$k; Assert::assertEquals($v, $value, "got $value"); } diff --git a/build/integration/features/bootstrap/Provisioning.php b/build/integration/features/bootstrap/Provisioning.php index 1301d5551f6..c6cfa881fb5 100644 --- a/build/integration/features/bootstrap/Provisioning.php +++ b/build/integration/features/bootstrap/Provisioning.php @@ -380,7 +380,6 @@ trait Provisioning { $this->userExists($user); $this->groupExists($group); $this->addingUserToGroup($user, $group); - } /** @@ -539,7 +538,6 @@ trait Provisioning { $respondedArray = $this->getArrayOfUsersResponded($this->response); Assert::assertEquals($usersSimplified, $respondedArray, "", 0.0, 10, true); } - } /** @@ -553,7 +551,6 @@ trait Provisioning { $respondedArray = $this->getArrayOfGroupsResponded($this->response); Assert::assertEquals($groupsSimplified, $respondedArray, "", 0.0, 10, true); } - } /** @@ -567,7 +564,6 @@ trait Provisioning { $respondedArray = $this->getArrayOfSubadminsResponded($this->response); Assert::assertEquals($groupsSimplified, $respondedArray, "", 0.0, 10, true); } - } /** @@ -581,7 +577,6 @@ trait Provisioning { $respondedArray = $this->getArrayOfAppsResponded($this->response); Assert::assertEquals($appsSimplified, $respondedArray, "", 0.0, 10, true); } - } /** @@ -817,5 +812,4 @@ trait Provisioning { } $this->usingServer($previousServer); } - } diff --git a/build/integration/features/bootstrap/Search.php b/build/integration/features/bootstrap/Search.php index 6d6d9c3ecda..72a20a08ce8 100644 --- a/build/integration/features/bootstrap/Search.php +++ b/build/integration/features/bootstrap/Search.php @@ -86,5 +86,4 @@ trait Search { Assert::assertEquals($expectedValue, $searchResult[$expectedField], "Field '$expectedField' does not match ({$searchResult[$expectedField]})"); } } - } diff --git a/build/integration/features/bootstrap/Sharing.php b/build/integration/features/bootstrap/Sharing.php index 854ce552e6e..22c9fef9f7f 100644 --- a/build/integration/features/bootstrap/Sharing.php +++ b/build/integration/features/bootstrap/Sharing.php @@ -79,7 +79,7 @@ trait Sharing { if ($body instanceof TableNode) { $fd = $body->getRowsHash(); - if (array_key_exists('expireDate', $fd)){ + if (array_key_exists('expireDate', $fd)) { $dateModification = $fd['expireDate']; $fd['expireDate'] = date('Y-m-d', strtotime($dateModification)); } @@ -106,7 +106,7 @@ trait Sharing { * @When /^restore the last share data from "([^"]*)"$/ */ public function restoreLastShareData($name) { - $this->lastShareData = $this->storedShareData[$name]; + $this->lastShareData = $this->storedShareData[$name]; } /** @@ -156,10 +156,9 @@ trait Sharing { public function checkPublicSharedFile($filename) { $client = new Client(); $options = []; - if (count($this->lastShareData->data->element) > 0){ + if (count($this->lastShareData->data->element) > 0) { $url = $this->lastShareData->data[0]->url; - } - else{ + } else { $url = $this->lastShareData->data->url; } $fullUrl = $url . "/download"; @@ -171,10 +170,9 @@ trait Sharing { */ public function checkPublicSharedFileWithPassword($filename, $password) { $options = []; - if (count($this->lastShareData->data->element) > 0){ + if (count($this->lastShareData->data->element) > 0) { $token = $this->lastShareData->data[0]->token; - } - else{ + } else { $token = $this->lastShareData->data->token; } @@ -246,7 +244,7 @@ trait Sharing { if ($body instanceof TableNode) { $fd = $body->getRowsHash(); - if (array_key_exists('expireDate', $fd)){ + if (array_key_exists('expireDate', $fd)) { $dateModification = $fd['expireDate']; $fd['expireDate'] = date('Y-m-d', strtotime($dateModification)); } @@ -281,22 +279,22 @@ trait Sharing { $options['auth'] = [$user, $this->regularUser]; } $body = []; - if (!is_null($path)){ + if (!is_null($path)) { $body['path'] = $path; } - if (!is_null($shareType)){ + if (!is_null($shareType)) { $body['shareType'] = $shareType; } - if (!is_null($shareWith)){ + if (!is_null($shareWith)) { $body['shareWith'] = $shareWith; } - if (!is_null($publicUpload)){ + if (!is_null($publicUpload)) { $body['publicUpload'] = $publicUpload; } - if (!is_null($password)){ + if (!is_null($password)) { $body['password'] = $password; } - if (!is_null($permissions)){ + if (!is_null($permissions)) { $body['permissions'] = $permissions; } @@ -313,41 +311,34 @@ trait Sharing { public function isFieldInResponse($field, $contentExpected) { $data = simplexml_load_string($this->response->getBody())->data[0]; - if ((string)$field == 'expiration'){ + if ((string)$field == 'expiration') { $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00"; } - if (count($data->element) > 0){ - foreach($data as $element) { - if ($contentExpected == "A_TOKEN"){ + if (count($data->element) > 0) { + foreach ($data as $element) { + if ($contentExpected == "A_TOKEN") { return (strlen((string)$element->$field) == 15); - } - elseif ($contentExpected == "A_NUMBER"){ + } elseif ($contentExpected == "A_NUMBER") { return is_numeric((string)$element->$field); - } - elseif($contentExpected == "AN_URL"){ + } elseif ($contentExpected == "AN_URL") { return $this->isExpectedUrl((string)$element->$field, "index.php/s/"); - } - elseif ((string)$element->$field == $contentExpected){ + } elseif ((string)$element->$field == $contentExpected) { return true; - } - else{ + } else { print($element->$field); } } return false; } else { - if ($contentExpected == "A_TOKEN"){ - return (strlen((string)$data->$field) == 15); - } - elseif ($contentExpected == "A_NUMBER"){ - return is_numeric((string)$data->$field); - } - elseif($contentExpected == "AN_URL"){ - return $this->isExpectedUrl((string)$data->$field, "index.php/s/"); - } - elseif ($data->$field == $contentExpected){ - return true; + if ($contentExpected == "A_TOKEN") { + return (strlen((string)$data->$field) == 15); + } elseif ($contentExpected == "A_NUMBER") { + return is_numeric((string)$data->$field); + } elseif ($contentExpected == "AN_URL") { + return $this->isExpectedUrl((string)$data->$field, "index.php/s/"); + } elseif ($data->$field == $contentExpected) { + return true; } return false; } @@ -391,8 +382,8 @@ trait Sharing { public function isUserOrGroupInSharedData($userOrGroup, $permissions = null) { $data = simplexml_load_string($this->response->getBody())->data[0]; - foreach($data as $element) { - if ($element->share_with == $userOrGroup && ($permissions === null || $permissions == $element->permissions)){ + foreach ($data as $element) { + if ($element->share_with == $userOrGroup && ($permissions === null || $permissions == $element->permissions)) { return true; } } @@ -419,7 +410,7 @@ trait Sharing { 'OCS-APIREQUEST' => 'true', ]; $this->response = $client->get($fullUrl, $options); - if ($this->isUserOrGroupInSharedData($user2, $permissions)){ + if ($this->isUserOrGroupInSharedData($user2, $permissions)) { return; } else { $this->createShare($user1, $filepath, 0, $user2, null, null, $permissions); @@ -448,7 +439,7 @@ trait Sharing { 'OCS-APIREQUEST' => 'true', ]; $this->response = $client->get($fullUrl, $options); - if ($this->isUserOrGroupInSharedData($group, $permissions)){ + if ($this->isUserOrGroupInSharedData($group, $permissions)) { return; } else { $this->createShare($user, $filepath, 1, $group, null, null, $permissions); @@ -480,7 +471,7 @@ trait Sharing { */ public function checkingLastShareIDIsIncluded() { $share_id = $this->lastShareData->data[0]->id; - if (!$this->isFieldInResponse('id', $share_id)){ + if (!$this->isFieldInResponse('id', $share_id)) { Assert::fail("Share id $share_id not found in response"); } } @@ -490,7 +481,7 @@ trait Sharing { */ public function checkingLastShareIDIsNotIncluded() { $share_id = $this->lastShareData->data[0]->id; - if ($this->isFieldInResponse('id', $share_id)){ + if ($this->isFieldInResponse('id', $share_id)) { Assert::fail("Share id $share_id has been found in response"); } } @@ -503,16 +494,16 @@ trait Sharing { if ($body instanceof TableNode) { $fd = $body->getRowsHash(); - foreach($fd as $field => $value) { - if (substr($field, 0, 10) === "share_with"){ + foreach ($fd as $field => $value) { + if (substr($field, 0, 10) === "share_with") { $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -5), $value); $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -5), $value); } - if (substr($field, 0, 6) === "remote"){ + if (substr($field, 0, 6) === "remote") { $value = str_replace("REMOTE", substr($this->remoteBaseUrl, 0, -4), $value); $value = str_replace("LOCAL", substr($this->localBaseUrl, 0, -4), $value); } - if (!$this->isFieldInResponse($field, $value)){ + if (!$this->isFieldInResponse($field, $value)) { Assert::fail("$field" . " doesn't have value " . "$value"); } } @@ -610,7 +601,7 @@ trait Sharing { Assert::fail("$field was not found in response"); } - if ($field === 'expiration' && !empty($contentExpected)){ + if ($field === 'expiration' && !empty($contentExpected)) { $contentExpected = date('Y-m-d', strtotime($contentExpected)) . " 00:00:00"; } @@ -648,7 +639,7 @@ trait Sharing { ); $json = json_decode($res->getBody()->getContents(), true); $deleted = false; - foreach($json['ocs']['data'] as $data) { + foreach ($json['ocs']['data'] as $data) { if (stripslashes($data['path']) === $fileName) { $id = $data['id']; $client->delete( @@ -668,7 +659,7 @@ trait Sharing { } } - if($deleted === false) { + if ($deleted === false) { throw new \Exception("Could not delete file $fileName"); } } @@ -676,16 +667,14 @@ trait Sharing { /** * @When save last share id */ - public function saveLastShareId() - { + public function saveLastShareId() { $this->savedShareId = $this->lastShareData['data']['id']; } /** * @Then share ids should match */ - public function shareIdsShouldMatch() - { + public function shareIdsShouldMatch() { if ($this->savedShareId !== $this->lastShareData['data']['id']) { throw new \Exception('Expected the same link share to be returned'); } diff --git a/build/integration/features/bootstrap/SharingContext.php b/build/integration/features/bootstrap/SharingContext.php index ec03283de5a..584defda603 100644 --- a/build/integration/features/bootstrap/SharingContext.php +++ b/build/integration/features/bootstrap/SharingContext.php @@ -33,5 +33,6 @@ class SharingContext implements Context, SnippetAcceptingContext { use Sharing; use AppConfiguration; - protected function resetAppConfigs() {} + protected function resetAppConfigs() { + } } diff --git a/build/license.php b/build/license.php index ecb7bbd5051..9e2b5f94df4 100644 --- a/build/license.php +++ b/build/license.php @@ -19,8 +19,7 @@ * along with this program. If not, see * */ -class Licenses -{ +class Licenses { protected $paths = []; protected $mailMap = []; protected $checkFiles = []; @@ -80,9 +79,8 @@ EOD; * @param string|bool $gitRoot */ function exec($folder, $gitRoot = false) { - if (is_array($folder)) { - foreach($folder as $f) { + foreach ($folder as $f) { $this->exec($f, $gitRoot); } return; @@ -105,7 +103,7 @@ EOD; $iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($folder, $excludes) { /** @var SplFileInfo $item */ - foreach($excludes as $exclude) { + foreach ($excludes as $exclude) { if (substr($item->getPath(), 0, strlen($exclude)) === $exclude) { return false; } @@ -178,7 +176,7 @@ With help from many libraries and frameworks including: */ private function isMITLicensed($source) { $lines = explode(PHP_EOL, $source); - while(!empty($lines)) { + while (!empty($lines)) { $line = $lines[0]; array_shift($lines); if (strpos($line, 'The MIT License') !== false) { @@ -191,7 +189,7 @@ With help from many libraries and frameworks including: private function isOwnCloudLicensed($source) { $lines = explode(PHP_EOL, $source); - while(!empty($lines)) { + while (!empty($lines)) { $line = $lines[0]; array_shift($lines); if (strpos($line, 'ownCloud, Inc') !== false || strpos($line, 'ownCloud GmbH') !== false) { @@ -209,7 +207,7 @@ With help from many libraries and frameworks including: private function eatOldLicense($source) { $lines = explode(PHP_EOL, $source); $isStrict = false; - while(!empty($lines)) { + while (!empty($lines)) { $line = $lines[0]; if (trim($line) === 'checkFiles[] = $path; - } private function printFilesToCheck() { diff --git a/build/signed-off-checker.php b/build/signed-off-checker.php index 43cf4529476..9620309932a 100644 --- a/build/signed-off-checker.php +++ b/build/signed-off-checker.php @@ -33,27 +33,27 @@ $repoName = getenv('DRONE_REPO_NAME'); $droneEvent = getenv('DRONE_BUILD_EVENT'); $githubToken = getenv('GITHUB_TOKEN'); -if(is_string($droneEvent) && $droneEvent === 'push') { +if (is_string($droneEvent) && $droneEvent === 'push') { echo("Push event - no signed-off check required.\n"); exit(0); } -if(!is_string($pullRequestNumber) || $pullRequestNumber === '') { +if (!is_string($pullRequestNumber) || $pullRequestNumber === '') { echo("The environment variable DRONE_PULL_REQUEST has no proper value.\n"); exit(1); } -if(!is_string($repoOwner) || $repoOwner === '') { +if (!is_string($repoOwner) || $repoOwner === '') { echo("The environment variable DRONE_REPO_OWNER has no proper value.\n"); exit(1); } -if(!is_string($repoName) || $repoName === '') { +if (!is_string($repoName) || $repoName === '') { echo("The environment variable DRONE_REPO_NAME has no proper value.\n"); exit(1); } -if(!is_string($githubToken) || $githubToken === '') { +if (!is_string($githubToken) || $githubToken === '') { echo("The environment variable GITHUB_TOKEN has no proper value.\n"); exit(1); } @@ -67,7 +67,7 @@ $response = curl_exec($ch); curl_close($ch); $decodedResponse = json_decode($response, true); -if(!is_array($decodedResponse) || count($decodedResponse) === 0) { +if (!is_array($decodedResponse) || count($decodedResponse) === 0) { echo("Could not decode JSON response from GitHub API.\n"); exit(1); } @@ -75,47 +75,47 @@ if(!is_array($decodedResponse) || count($decodedResponse) === 0) { // Get all commits SHAs $commits = []; -foreach($decodedResponse as $commit) { - if(!isset($commit['sha'])) { +foreach ($decodedResponse as $commit) { + if (!isset($commit['sha'])) { echo("No SHA specified in $commit\n"); exit(1); } - if(!isset($commit['commit']['message'])) { + if (!isset($commit['commit']['message'])) { echo("No commit message specified in $commit\n"); exit(1); } $commits[$commit['sha']] = $commit['commit']['message']; } -if(count($commits) < 1) { +if (count($commits) < 1) { echo("Could not read commits.\n"); exit(1); } $notSignedCommits = []; -foreach($commits as $commit => $message) { - if($commit === '') { +foreach ($commits as $commit => $message) { + if ($commit === '') { continue; } $signOffMessage = false; $commitMessageLines = explode("\n", $message); - foreach($commitMessageLines as $line) { - if(preg_match('/^Signed-off-by: .* <.*@.*>$/', $line)) { + foreach ($commitMessageLines as $line) { + if (preg_match('/^Signed-off-by: .* <.*@.*>$/', $line)) { echo "$commit is signed-off with \"$line\"\n"; $signOffMessage = true; continue; } } - if($signOffMessage === true) { + if ($signOffMessage === true) { continue; } $notSignedCommits[] = $commit; } -if($notSignedCommits !== []) { +if ($notSignedCommits !== []) { echo("\n"); echo("Some commits were not signed off!\n"); echo("Missing signatures on:\n"); diff --git a/core/Application.php b/core/Application.php index 15246c9c76c..55f3b68c26e 100644 --- a/core/Application.php +++ b/core/Application.php @@ -55,7 +55,6 @@ use Symfony\Component\EventDispatcher\GenericEvent; * @package OC\Core */ class Application extends App { - public function __construct() { parent::__construct('core'); @@ -193,5 +192,4 @@ class Application extends App { $eventDispatcher->addServiceListener(RemoteWipeFinished::class, RemoteWipeEmailListener::class); $eventDispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedStoreCleanupListener::class); } - } diff --git a/core/BackgroundJobs/BackgroundCleanupUpdaterBackupsJob.php b/core/BackgroundJobs/BackgroundCleanupUpdaterBackupsJob.php index 4489afe1f02..c24c8aa05a3 100644 --- a/core/BackgroundJobs/BackgroundCleanupUpdaterBackupsJob.php +++ b/core/BackgroundJobs/BackgroundCleanupUpdaterBackupsJob.php @@ -48,18 +48,18 @@ class BackgroundCleanupUpdaterBackupsJob extends QueuedJob { $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); $instanceId = $this->config->getSystemValue('instanceid', null); - if(!is_string($instanceId) || empty($instanceId)) { + if (!is_string($instanceId) || empty($instanceId)) { return; } $updaterFolderPath = $dataDir . '/updater-' . $instanceId; $backupFolderPath = $updaterFolderPath . '/backups'; - if(file_exists($backupFolderPath)) { + if (file_exists($backupFolderPath)) { $this->log->info("$backupFolderPath exists - start to clean it up"); $dirList = []; $dirs = new \DirectoryIterator($backupFolderPath); - foreach($dirs as $dir) { + foreach ($dirs as $dir) { // skip files and dot dirs if ($dir->isFile() || $dir->isDot()) { continue; @@ -80,7 +80,7 @@ class BackgroundCleanupUpdaterBackupsJob extends QueuedJob { $dirList = array_slice($dirList, 0, -3); $this->log->info("List of all directories that will be deleted: " . json_encode($dirList)); - foreach($dirList as $dir) { + foreach ($dirList as $dir) { $this->log->info("Removing $dir ..."); \OC_Helper::rmdirr($dir); } diff --git a/core/Command/App/CheckCode.php b/core/Command/App/CheckCode.php index d37211d3add..185ec0e64a3 100644 --- a/core/Command/App/CheckCode.php +++ b/core/Command/App/CheckCode.php @@ -42,8 +42,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -class CheckCode extends Command implements CompletionAwareInterface { - +class CheckCode extends Command implements CompletionAwareInterface { protected $checkers = [ 'private' => PrivateCheck::class, 'deprecation' => DeprecationCheck::class, @@ -95,7 +94,7 @@ class CheckCode extends Command implements CompletionAwareInterface { $codeChecker = new CodeChecker($checkList, !$input->getOption('skip-validate-info')); $codeChecker->listen('CodeChecker', 'analyseFileBegin', function ($params) use ($output) { - if(OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln("Analysing {$params}"); } }); @@ -103,29 +102,29 @@ class CheckCode extends Command implements CompletionAwareInterface { $count = count($errors); // show filename if the verbosity is low, but there are errors in a file - if($count > 0 && OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) { + if ($count > 0 && OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) { $output->writeln("Analysing {$filename}"); } // show error count if there are errors present or the verbosity is high - if($count > 0 || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + if ($count > 0 || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln(" {$count} errors"); } usort($errors, function ($a, $b) { return $a['line'] >$b['line']; }); - foreach($errors as $p) { + foreach ($errors as $p) { $line = sprintf("%' 4d", $p['line']); $output->writeln(" line $line: {$p['disallowedToken']} - {$p['reason']}"); } }); $errors = []; - if(!$input->getOption('skip-checkers')) { + if (!$input->getOption('skip-checkers')) { $errors = $codeChecker->analyse($appId); } - if(!$input->getOption('skip-validate-info')) { + if (!$input->getOption('skip-validate-info')) { $infoChecker = new InfoChecker(); $infoChecker->listen('InfoChecker', 'parseError', function ($error) use ($output) { $output->writeln("Invalid appinfo.xml file found: $error"); diff --git a/core/Command/App/Install.php b/core/Command/App/Install.php index 7248ec1e425..49f4f0b804e 100644 --- a/core/Command/App/Install.php +++ b/core/Command/App/Install.php @@ -32,7 +32,6 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class Install extends Command { - protected function configure() { $this ->setName('app:install') @@ -64,12 +63,12 @@ class Install extends Command { $installer = \OC::$server->query(Installer::class); $installer->downloadApp($appId); $result = $installer->installApp($appId); - } catch(\Exception $e) { + } catch (\Exception $e) { $output->writeln('Error: ' . $e->getMessage()); return 1; } - if($result === false) { + if ($result === false) { $output->writeln($appId . ' couldn\'t be installed'); return 1; } diff --git a/core/Command/App/ListApps.php b/core/Command/App/ListApps.php index 84fdf7f8f41..0765ab39a24 100644 --- a/core/Command/App/ListApps.php +++ b/core/Command/App/ListApps.php @@ -62,7 +62,7 @@ class ListApps extends Base { } protected function execute(InputInterface $input, OutputInterface $output) { - if ($input->getOption('shipped') === 'true' || $input->getOption('shipped') === 'false'){ + if ($input->getOption('shipped') === 'true' || $input->getOption('shipped') === 'false') { $shippedFilter = $input->getOption('shipped') === 'true'; } else { $shippedFilter = null; @@ -74,7 +74,7 @@ class ListApps extends Base { //sort enabled apps above disabled apps foreach ($apps as $app) { - if ($shippedFilter !== null && $this->manager->isShipped($app) !== $shippedFilter){ + if ($shippedFilter !== null && $this->manager->isShipped($app) !== $shippedFilter) { continue; } if ($this->manager->isInstalled($app)) { diff --git a/core/Command/App/Remove.php b/core/Command/App/Remove.php index bb264e77e5f..d3e91332d77 100644 --- a/core/Command/App/Remove.php +++ b/core/Command/App/Remove.php @@ -96,7 +96,7 @@ class Remove extends Command implements CompletionAwareInterface { try { $this->manager->disableApp($appId); $output->writeln($appId . ' disabled'); - } catch(Throwable $e) { + } catch (Throwable $e) { $output->writeln('Error: ' . $e->getMessage() . ''); $this->logger->logException($e, [ 'app' => 'CLI', @@ -109,7 +109,7 @@ class Remove extends Command implements CompletionAwareInterface { // Let's try to remove the app... try { $result = $this->installer->removeApp($appId); - } catch(Throwable $e) { + } catch (Throwable $e) { $output->writeln('Error: ' . $e->getMessage() . ''); $this->logger->logException($e, [ 'app' => 'CLI', @@ -118,7 +118,7 @@ class Remove extends Command implements CompletionAwareInterface { return 1; } - if($result === false) { + if ($result === false) { $output->writeln($appId . ' could not be removed'); return 1; } diff --git a/core/Command/App/Update.php b/core/Command/App/Update.php index 4be2f4639ef..417d1915d05 100644 --- a/core/Command/App/Update.php +++ b/core/Command/App/Update.php @@ -91,7 +91,6 @@ class Update extends Command { $output->writeln($singleAppId . ' not installed'); return 1; } - } elseif ($input->getOption('all') || $input->getOption('showonly')) { $apps = \OC_App::getAllApps(); } else { @@ -108,7 +107,7 @@ class Update extends Command { if (!$input->getOption('showonly')) { try { $result = $this->installer->updateAppstoreApp($appId); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->logger->logException($e, ['message' => 'Failure during update of app "' . $appId . '"','app' => 'app:update']); $output->writeln('Error: ' . $e->getMessage()); $return = 1; @@ -117,7 +116,7 @@ class Update extends Command { if ($result === false) { $output->writeln($appId . ' couldn\'t be updated'); $return = 1; - } elseif($result === true) { + } elseif ($result === true) { $output->writeln($appId . ' updated'); } } diff --git a/core/Command/Background/Ajax.php b/core/Command/Background/Ajax.php index 3eb00655ead..5dc94d939d7 100644 --- a/core/Command/Background/Ajax.php +++ b/core/Command/Background/Ajax.php @@ -26,7 +26,6 @@ namespace OC\Core\Command\Background; class Ajax extends Base { - protected function getMode() { return 'ajax'; } diff --git a/core/Command/Background/Base.php b/core/Command/Background/Base.php index a00a8fe4c51..41466660000 100644 --- a/core/Command/Background/Base.php +++ b/core/Command/Background/Base.php @@ -37,8 +37,6 @@ use Symfony\Component\Console\Output\OutputInterface; * Subclasses will override the getMode() function to specify the mode to configure. */ abstract class Base extends Command { - - abstract protected function getMode(); /** diff --git a/core/Command/Background/Cron.php b/core/Command/Background/Cron.php index 27253a355b2..9dbb4f855e5 100644 --- a/core/Command/Background/Cron.php +++ b/core/Command/Background/Cron.php @@ -26,7 +26,6 @@ namespace OC\Core\Command\Background; class Cron extends Base { - protected function getMode() { return 'cron'; } diff --git a/core/Command/Background/WebCron.php b/core/Command/Background/WebCron.php index 76bcf83a304..7da379b6a53 100644 --- a/core/Command/Background/WebCron.php +++ b/core/Command/Background/WebCron.php @@ -26,7 +26,6 @@ namespace OC\Core\Command\Background; class WebCron extends Base { - protected function getMode() { return 'webcron'; } diff --git a/core/Command/Broadcast/Test.php b/core/Command/Broadcast/Test.php index 08fcd1f0d92..93734369ace 100644 --- a/core/Command/Broadcast/Test.php +++ b/core/Command/Broadcast/Test.php @@ -98,5 +98,4 @@ class Test extends Command { return 0; } - } diff --git a/core/Command/Config/Import.php b/core/Command/Config/Import.php index a6e57e92052..7918ef620ab 100644 --- a/core/Command/Config/Import.php +++ b/core/Command/Config/Import.php @@ -33,7 +33,7 @@ use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class Import extends Command implements CompletionAwareInterface { +class Import extends Command implements CompletionAwareInterface { protected $validRootKeys = ['system', 'apps']; /** @var IConfig */ diff --git a/core/Command/Config/System/DeleteConfig.php b/core/Command/Config/System/DeleteConfig.php index 85531c4c4bf..9ddad641e38 100644 --- a/core/Command/Config/System/DeleteConfig.php +++ b/core/Command/Config/System/DeleteConfig.php @@ -75,8 +75,7 @@ class DeleteConfig extends Base { try { $value = $this->removeSubValue(array_slice($configNames, 1), $value, $input->hasParameterOption('--error-if-not-exists')); - } - catch (\UnexpectedValueException $e) { + } catch (\UnexpectedValueException $e) { $output->writeln('System config ' . implode(' => ', $configNames) . ' could not be deleted because it did not exist'); return 1; } diff --git a/core/Command/Db/AddMissingColumns.php b/core/Command/Db/AddMissingColumns.php index 4672770c6af..5794b95b76f 100644 --- a/core/Command/Db/AddMissingColumns.php +++ b/core/Command/Db/AddMissingColumns.php @@ -78,7 +78,6 @@ class AddMissingColumns extends Command { * @throws \Doctrine\DBAL\Schema\SchemaException */ private function addCoreColumns(OutputInterface $output) { - $output->writeln('Check columns of the comments table.'); $schema = new SchemaWrapper($this->connection); diff --git a/core/Command/Db/AddMissingIndices.php b/core/Command/Db/AddMissingIndices.php index 924c2af05c0..506fef94a63 100644 --- a/core/Command/Db/AddMissingIndices.php +++ b/core/Command/Db/AddMissingIndices.php @@ -83,7 +83,6 @@ class AddMissingIndices extends Command { * @throws \Doctrine\DBAL\Schema\SchemaException */ private function addCoreIndexes(OutputInterface $output) { - $output->writeln('Check indices of the share table.'); $schema = new SchemaWrapper($this->connection); diff --git a/core/Command/Db/ConvertFilecacheBigInt.php b/core/Command/Db/ConvertFilecacheBigInt.php index 16971e20b6c..4a833fbbede 100644 --- a/core/Command/Db/ConvertFilecacheBigInt.php +++ b/core/Command/Db/ConvertFilecacheBigInt.php @@ -72,7 +72,6 @@ class ConvertFilecacheBigInt extends Command { } protected function execute(InputInterface $input, OutputInterface $output) { - $schema = new SchemaWrapper($this->connection); $isSqlite = $this->connection->getDatabasePlatform() instanceof SqlitePlatform; $updates = []; diff --git a/core/Command/Db/ConvertType.php b/core/Command/Db/ConvertType.php index c79ece79915..2929fea3764 100644 --- a/core/Command/Db/ConvertType.php +++ b/core/Command/Db/ConvertType.php @@ -239,7 +239,7 @@ class ConvertType extends Command implements CompletionAwareInterface { $schemaManager = new \OC\DB\MDB2SchemaManager($toDB); $apps = $input->getOption('all-apps') ? \OC_App::getAllApps() : \OC_App::getEnabledApps(); - foreach($apps as $app) { + foreach ($apps as $app) { if (file_exists(\OC_App::getAppPath($app).'/appinfo/database.xml')) { $schemaManager->createDbFromStructure(\OC_App::getAppPath($app).'/appinfo/database.xml'); } else { @@ -275,7 +275,7 @@ class ConvertType extends Command implements CompletionAwareInterface { if (!empty($toTables)) { $output->writeln('Clearing schema in new database'); } - foreach($toTables as $table) { + foreach ($toTables as $table) { $db->getSchemaManager()->dropTable($table); } } @@ -403,7 +403,7 @@ class ConvertType extends Command implements CompletionAwareInterface { try { // copy table rows - foreach($tables as $table) { + foreach ($tables as $table) { $output->writeln($table); $this->copyTable($fromDB, $toDB, $schema->getTable($table), $input, $output); } @@ -413,7 +413,7 @@ class ConvertType extends Command implements CompletionAwareInterface { } // save new database config $this->saveDBInfo($input); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->config->setSystemValue('maintenance', false); throw $e; } diff --git a/core/Command/Db/Migrations/ExecuteCommand.php b/core/Command/Db/Migrations/ExecuteCommand.php index 0f2709646ba..149ca8904b7 100644 --- a/core/Command/Db/Migrations/ExecuteCommand.php +++ b/core/Command/Db/Migrations/ExecuteCommand.php @@ -127,5 +127,4 @@ class ExecuteCommand extends Command implements CompletionAwareInterface { return []; } - } diff --git a/core/Command/Db/Migrations/GenerateCommand.php b/core/Command/Db/Migrations/GenerateCommand.php index a40cd800dff..6d554a57858 100644 --- a/core/Command/Db/Migrations/GenerateCommand.php +++ b/core/Command/Db/Migrations/GenerateCommand.php @@ -38,7 +38,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class GenerateCommand extends Command implements CompletionAwareInterface { - protected static $_templateSimple = 'getMigratedVersions(); $availableMigrations = $ms->getAvailableVersions(); $executedUnavailableMigrations = array_diff($executedMigrations, array_keys($availableMigrations)); @@ -145,6 +144,4 @@ class StatusCommand extends Command implements CompletionAwareInterface { return $migration; } - - } diff --git a/core/Command/Encryption/ChangeKeyStorageRoot.php b/core/Command/Encryption/ChangeKeyStorageRoot.php index 05626715781..bdc2857dd18 100644 --- a/core/Command/Encryption/ChangeKeyStorageRoot.php +++ b/core/Command/Encryption/ChangeKeyStorageRoot.php @@ -116,7 +116,6 @@ class ChangeKeyStorageRoot extends Command { * @throws \Exception */ protected function moveAllKeys($oldRoot, $newRoot, OutputInterface $output) { - $output->writeln("Start to move keys:"); if ($this->rootView->is_dir($oldRoot) === false) { @@ -150,7 +149,6 @@ class ChangeKeyStorageRoot extends Command { if (!$result) { throw new \Exception("Can't access the new root folder. Please check the permissions and make sure that the folder is in your data folder"); } - } @@ -189,12 +187,11 @@ class ChangeKeyStorageRoot extends Command { * @param OutputInterface $output */ protected function moveUserKeys($oldRoot, $newRoot, OutputInterface $output) { - $progress = new ProgressBar($output); $progress->start(); - foreach($this->userManager->getBackends() as $backend) { + foreach ($this->userManager->getBackends() as $backend) { $limit = 500; $offset = 0; do { @@ -205,7 +202,7 @@ class ChangeKeyStorageRoot extends Command { $this->moveUserEncryptionFolder($user, $oldRoot, $newRoot); } $offset += $limit; - } while(count($users) >= $limit); + } while (count($users) >= $limit); } $progress->finish(); } @@ -219,9 +216,7 @@ class ChangeKeyStorageRoot extends Command { * @throws \Exception */ protected function moveUserEncryptionFolder($user, $oldRoot, $newRoot) { - if ($this->userManager->userExists($user)) { - $source = $oldRoot . '/' . $user . '/files_encryption'; $target = $newRoot . '/' . $user . '/files_encryption'; if ( @@ -268,5 +263,4 @@ class ChangeKeyStorageRoot extends Command { return false; } - } diff --git a/core/Command/Encryption/DecryptAll.php b/core/Command/Encryption/DecryptAll.php index af1aa4c792c..e631f97cdaa 100644 --- a/core/Command/Encryption/DecryptAll.php +++ b/core/Command/Encryption/DecryptAll.php @@ -192,6 +192,5 @@ class DecryptAll extends Command { $this->resetMaintenanceAndTrashbin(); throw $e; } - } } diff --git a/core/Command/Encryption/EncryptAll.php b/core/Command/Encryption/EncryptAll.php index 77c2cb31204..7c6cad41a37 100644 --- a/core/Command/Encryption/EncryptAll.php +++ b/core/Command/Encryption/EncryptAll.php @@ -142,5 +142,4 @@ class EncryptAll extends Command { $output->writeln('aborted'); } } - } diff --git a/core/Command/Encryption/ShowKeyStorageRoot.php b/core/Command/Encryption/ShowKeyStorageRoot.php index a1ab9c2915c..c877d1fcdd3 100644 --- a/core/Command/Encryption/ShowKeyStorageRoot.php +++ b/core/Command/Encryption/ShowKeyStorageRoot.php @@ -27,7 +27,7 @@ use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class ShowKeyStorageRoot extends Command{ +class ShowKeyStorageRoot extends Command { /** @var Util */ protected $util; @@ -54,5 +54,4 @@ class ShowKeyStorageRoot extends Command{ $output->writeln("Current key storage root: $rootDescription"); } - } diff --git a/core/Command/Integrity/CheckApp.php b/core/Command/Integrity/CheckApp.php index d62c13deffb..affe137c67d 100644 --- a/core/Command/Integrity/CheckApp.php +++ b/core/Command/Integrity/CheckApp.php @@ -70,9 +70,8 @@ class CheckApp extends Base { $path = (string)$input->getOption('path'); $result = $this->checker->verifyAppSignature($appid, $path); $this->writeArrayInOutputFormat($input, $output, $result); - if (count($result)>0){ + if (count($result)>0) { return 1; } } - } diff --git a/core/Command/Integrity/CheckCore.php b/core/Command/Integrity/CheckCore.php index bebfbea560e..665e0079b44 100644 --- a/core/Command/Integrity/CheckCore.php +++ b/core/Command/Integrity/CheckCore.php @@ -61,7 +61,7 @@ class CheckCore extends Base { protected function execute(InputInterface $input, OutputInterface $output) { $result = $this->checker->verifyCoreSignature(); $this->writeArrayInOutputFormat($input, $output, $result); - if (count($result)>0){ + if (count($result)>0) { return 1; } } diff --git a/core/Command/Integrity/SignApp.php b/core/Command/Integrity/SignApp.php index 6e750d4af10..7657c2975af 100644 --- a/core/Command/Integrity/SignApp.php +++ b/core/Command/Integrity/SignApp.php @@ -76,7 +76,7 @@ class SignApp extends Command { $path = $input->getOption('path'); $privateKeyPath = $input->getOption('privateKey'); $keyBundlePath = $input->getOption('certificate'); - if(is_null($path) || is_null($privateKeyPath) || is_null($keyBundlePath)) { + if (is_null($path) || is_null($privateKeyPath) || is_null($keyBundlePath)) { $documentationUrl = $this->urlGenerator->linkToDocs('developer-code-integrity'); $output->writeln('This command requires the --path, --privateKey and --certificate.'); $output->writeln('Example: ./occ integrity:sign-app --path="/Users/lukasreschke/Programming/myapp/" --privateKey="/Users/lukasreschke/private/myapp.key" --certificate="/Users/lukasreschke/public/mycert.crt"'); @@ -87,12 +87,12 @@ class SignApp extends Command { $privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath); $keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath); - if($privateKey === false) { + if ($privateKey === false) { $output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath)); return null; } - if($keyBundle === false) { + if ($keyBundle === false) { $output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath)); return null; } @@ -105,7 +105,7 @@ class SignApp extends Command { try { $this->checker->writeAppSignature($path, $x509, $rsa); $output->writeln('Successfully signed "'.$path.'"'); - } catch (\Exception $e){ + } catch (\Exception $e) { $output->writeln('Error: ' . $e->getMessage()); return 1; } diff --git a/core/Command/Integrity/SignCore.php b/core/Command/Integrity/SignCore.php index b825a942d80..7f871b08298 100644 --- a/core/Command/Integrity/SignCore.php +++ b/core/Command/Integrity/SignCore.php @@ -70,7 +70,7 @@ class SignCore extends Command { $privateKeyPath = $input->getOption('privateKey'); $keyBundlePath = $input->getOption('certificate'); $path = $input->getOption('path'); - if(is_null($privateKeyPath) || is_null($keyBundlePath) || is_null($path)) { + if (is_null($privateKeyPath) || is_null($keyBundlePath) || is_null($path)) { $output->writeln('--privateKey, --certificate and --path are required.'); return null; } @@ -78,12 +78,12 @@ class SignCore extends Command { $privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath); $keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath); - if($privateKey === false) { + if ($privateKey === false) { $output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath)); return null; } - if($keyBundle === false) { + if ($keyBundle === false) { $output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath)); return null; } @@ -97,7 +97,7 @@ class SignCore extends Command { try { $this->checker->writeCoreSignature($x509, $rsa, $path); $output->writeln('Successfully signed "core"'); - } catch (\Exception $e){ + } catch (\Exception $e) { $output->writeln('Error: ' . $e->getMessage()); return 1; } diff --git a/core/Command/InterruptedException.php b/core/Command/InterruptedException.php index 3ca2f1572a0..509656f2dae 100644 --- a/core/Command/InterruptedException.php +++ b/core/Command/InterruptedException.php @@ -26,4 +26,5 @@ namespace OC\Core\Command; /** * Exception for when the user hit ctrl-c */ -class InterruptedException extends \Exception {} +class InterruptedException extends \Exception { +} diff --git a/core/Command/L10n/CreateJs.php b/core/Command/L10n/CreateJs.php index fd337994e86..05d58ec231d 100644 --- a/core/Command/L10n/CreateJs.php +++ b/core/Command/L10n/CreateJs.php @@ -36,7 +36,6 @@ use Symfony\Component\Console\Output\OutputInterface; use UnexpectedValueException; class CreateJs extends Command implements CompletionAwareInterface { - protected function configure() { $this ->setName('l10n:createjs') @@ -67,7 +66,7 @@ class CreateJs extends Command implements CompletionAwareInterface { $languages= $this->getAllLanguages($path); } - foreach($languages as $lang) { + foreach ($languages as $lang) { $this->writeFiles($app, $path, $lang, $output); } } @@ -75,13 +74,13 @@ class CreateJs extends Command implements CompletionAwareInterface { private function getAllLanguages($path) { $result = []; foreach (new DirectoryIterator("$path/l10n") as $fileInfo) { - if($fileInfo->isDot()) { + if ($fileInfo->isDot()) { continue; } - if($fileInfo->isDir()) { + if ($fileInfo->isDir()) { continue; } - if($fileInfo->getExtension() !== 'php') { + if ($fileInfo->getExtension() !== 'php') { continue; } $result[]= substr($fileInfo->getBasename(), 0, -4); diff --git a/core/Command/Log/Manage.php b/core/Command/Log/Manage.php index 062bc866cc9..2d7eaf9e2e6 100644 --- a/core/Command/Log/Manage.php +++ b/core/Command/Log/Manage.php @@ -36,7 +36,6 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class Manage extends Command implements CompletionAwareInterface { - const DEFAULT_BACKEND = 'file'; const DEFAULT_LOG_LEVEL = 2; const DEFAULT_TIMEZONE = 'UTC'; diff --git a/core/Command/Maintenance/Install.php b/core/Command/Maintenance/Install.php index fa18ef721b2..b7557b55e81 100644 --- a/core/Command/Maintenance/Install.php +++ b/core/Command/Maintenance/Install.php @@ -92,7 +92,7 @@ class Install extends Command { $this->printErrors($output, $errors); // ignore the OS X setup warning - if(count($errors) !== 1 || + if (count($errors) !== 1 || (string)$errors[0]['error'] !== 'Mac OS X is not supported and Nextcloud will not work properly on this platform. Use it at your own risk! ') { return 1; } diff --git a/core/Command/Maintenance/Mimetype/GenerateMimetypeFileBuilder.php b/core/Command/Maintenance/Mimetype/GenerateMimetypeFileBuilder.php index 249b899173e..01bac261cd4 100644 --- a/core/Command/Maintenance/Mimetype/GenerateMimetypeFileBuilder.php +++ b/core/Command/Maintenance/Mimetype/GenerateMimetypeFileBuilder.php @@ -27,8 +27,7 @@ declare(strict_types=1); namespace OC\Core\Command\Maintenance\Mimetype; -class GenerateMimetypeFileBuilder -{ +class GenerateMimetypeFileBuilder { /** * Generate mime type list file * @param $aliases @@ -39,7 +38,7 @@ class GenerateMimetypeFileBuilder $keys = array_filter(array_keys($aliases), function ($k) { return $k[0] === '_'; }); - foreach($keys as $key) { + foreach ($keys as $key) { unset($aliases[$key]); } @@ -47,7 +46,7 @@ class GenerateMimetypeFileBuilder $dir = new \DirectoryIterator(\OC::$SERVERROOT.'/core/img/filetypes'); $files = []; - foreach($dir as $fileInfo) { + foreach ($dir as $fileInfo) { if ($fileInfo->isFile()) { $file = preg_replace('/.[^.]*$/', '', $fileInfo->getFilename()); $files[] = $file; @@ -61,7 +60,7 @@ class GenerateMimetypeFileBuilder // Fetch all themes! $themes = []; $dirs = new \DirectoryIterator(\OC::$SERVERROOT.'/themes/'); - foreach($dirs as $dir) { + foreach ($dirs as $dir) { //Valid theme dir if ($dir->isFile() || $dir->isDot()) { continue; @@ -105,5 +104,4 @@ OC.MimeTypeList={ }; '; } - } diff --git a/core/Command/Maintenance/Mimetype/UpdateDB.php b/core/Command/Maintenance/Mimetype/UpdateDB.php index 5bb78d9a3f3..47b0b600777 100644 --- a/core/Command/Maintenance/Mimetype/UpdateDB.php +++ b/core/Command/Maintenance/Mimetype/UpdateDB.php @@ -32,7 +32,6 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class UpdateDB extends Command { - const DEFAULT_MIMETYPE = 'application/octet-stream'; /** @var IMimeTypeDetector */ diff --git a/core/Command/Maintenance/UpdateHtaccess.php b/core/Command/Maintenance/UpdateHtaccess.php index 6397ed7aec4..7f143536bfa 100644 --- a/core/Command/Maintenance/UpdateHtaccess.php +++ b/core/Command/Maintenance/UpdateHtaccess.php @@ -30,7 +30,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class UpdateHtaccess extends Command { - protected function configure() { $this ->setName('maintenance:update:htaccess') diff --git a/core/Command/TwoFactorAuth/Cleanup.php b/core/Command/TwoFactorAuth/Cleanup.php index a8576b15384..ac9dceef343 100644 --- a/core/Command/TwoFactorAuth/Cleanup.php +++ b/core/Command/TwoFactorAuth/Cleanup.php @@ -57,5 +57,4 @@ class Cleanup extends Base { $output->writeln("All user-provider associations for provider $providerId have been removed."); } - } diff --git a/core/Command/TwoFactorAuth/Disable.php b/core/Command/TwoFactorAuth/Disable.php index 1dd3a2cf64d..128699a3970 100644 --- a/core/Command/TwoFactorAuth/Disable.php +++ b/core/Command/TwoFactorAuth/Disable.php @@ -68,5 +68,4 @@ class Disable extends Base { return 2; } } - } diff --git a/core/Command/TwoFactorAuth/Enable.php b/core/Command/TwoFactorAuth/Enable.php index 0c2aef540e9..d979768f182 100644 --- a/core/Command/TwoFactorAuth/Enable.php +++ b/core/Command/TwoFactorAuth/Enable.php @@ -68,5 +68,4 @@ class Enable extends Base { return 2; } } - } diff --git a/core/Command/TwoFactorAuth/Enforce.php b/core/Command/TwoFactorAuth/Enforce.php index e99c584384c..7f3ceb9694c 100644 --- a/core/Command/TwoFactorAuth/Enforce.php +++ b/core/Command/TwoFactorAuth/Enforce.php @@ -112,5 +112,4 @@ class Enforce extends Command { protected function writeNotEnforced(OutputInterface $output) { $output->writeln('Two-factor authentication is not enforced'); } - } diff --git a/core/Command/TwoFactorAuth/State.php b/core/Command/TwoFactorAuth/State.php index 3ae1884d343..438a272223f 100644 --- a/core/Command/TwoFactorAuth/State.php +++ b/core/Command/TwoFactorAuth/State.php @@ -104,5 +104,4 @@ class State extends Base { $output->writeln("- " . $provider); } } - } diff --git a/core/Command/Upgrade.php b/core/Command/Upgrade.php index 761a6fb55c0..461884fabe4 100644 --- a/core/Command/Upgrade.php +++ b/core/Command/Upgrade.php @@ -47,7 +47,6 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\GenericEvent; class Upgrade extends Command { - const ERROR_SUCCESS = 0; const ERROR_NOT_INSTALLED = 1; const ERROR_MAINTENANCE_MODE = 2; @@ -86,8 +85,7 @@ class Upgrade extends Command { * @param OutputInterface $output output interface */ protected function execute(InputInterface $input, OutputInterface $output) { - - if(Util::needUpgrade()) { + if (Util::needUpgrade()) { if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) { // Prepend each line with a little timestamp $timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter()); @@ -153,12 +151,12 @@ class Upgrade extends Command { $output->writeln(''); break; case '\OC\Repair::step': - if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) { + if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) { $output->writeln('Repair step: ' . $event->getArgument(0) . ''); } break; case '\OC\Repair::info': - if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) { + if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) { $output->writeln('Repair info: ' . $event->getArgument(0) . ''); } break; @@ -259,12 +257,12 @@ class Upgrade extends Command { $this->postUpgradeCheck($input, $output); - if(!$success) { + if (!$success) { return self::ERROR_FAILURE; } return self::ERROR_SUCCESS; - } elseif($this->config->getSystemValueBool('maintenance')) { + } elseif ($this->config->getSystemValueBool('maintenance')) { //Possible scenario: Nextcloud core is updated but an app failed $output->writeln('Nextcloud is in maintenance mode'); $output->write('Maybe an upgrade is already in process. Please check the ' diff --git a/core/Command/User/Add.php b/core/Command/User/Add.php index 208fb1dceb5..2fe4de83f60 100644 --- a/core/Command/User/Add.php +++ b/core/Command/User/Add.php @@ -154,11 +154,11 @@ class Add extends Command { if (!$group) { $this->groupManager->createGroup($groupName); $group = $this->groupManager->get($groupName); - if($group instanceof IGroup) { + if ($group instanceof IGroup) { $output->writeln('Created group "' . $group->getGID() . '"'); } } - if($group instanceof IGroup) { + if ($group instanceof IGroup) { $group->addUser($user); $output->writeln('User "' . $user->getUID() . '" added to group "' . $group->getGID() . '"'); } diff --git a/core/Command/User/LastSeen.php b/core/Command/User/LastSeen.php index 37cad457015..5a1e5f3b4e5 100644 --- a/core/Command/User/LastSeen.php +++ b/core/Command/User/LastSeen.php @@ -57,13 +57,13 @@ class LastSeen extends Command { protected function execute(InputInterface $input, OutputInterface $output) { $user = $this->userManager->get($input->getArgument('uid')); - if(is_null($user)) { + if (is_null($user)) { $output->writeln('User does not exist'); return; } $lastLogin = $user->getLastLogin(); - if($lastLogin === 0) { + if ($lastLogin === 0) { $output->writeln('User ' . $user->getUID() . ' has never logged in, yet.'); } else { diff --git a/core/Command/User/Report.php b/core/Command/User/Report.php index 7f4562fc426..fff3924d324 100644 --- a/core/Command/User/Report.php +++ b/core/Command/User/Report.php @@ -55,10 +55,10 @@ class Report extends Command { $table = new Table($output); $table->setHeaders(['User Report', '']); $userCountArray = $this->countUsers(); - if(!empty($userCountArray)) { + if (!empty($userCountArray)) { $total = 0; $rows = []; - foreach($userCountArray as $classname => $users) { + foreach ($userCountArray as $classname => $users) { $total += $users; $rows[] = [$classname, $users]; } diff --git a/core/Command/User/Setting.php b/core/Command/User/Setting.php index e084b94cc8a..71509d4eb6e 100644 --- a/core/Command/User/Setting.php +++ b/core/Command/User/Setting.php @@ -187,7 +187,6 @@ class Setting extends Base { $this->config->setUserValue($uid, $app, $key, $input->getArgument('value')); return 0; - } elseif ($input->hasParameterOption('--delete')) { if ($input->hasParameterOption('--error-if-not-exists') && $value === null) { $output->writeln('The setting does not exist for user "' . $uid . '".'); @@ -204,7 +203,6 @@ class Setting extends Base { $this->config->deleteUserValue($uid, $app, $key); return 0; - } elseif ($value !== null) { $output->writeln($value); return 0; diff --git a/core/Controller/AutoCompleteController.php b/core/Controller/AutoCompleteController.php index 12414b50f30..31d0a7ab7b3 100644 --- a/core/Controller/AutoCompleteController.php +++ b/core/Controller/AutoCompleteController.php @@ -91,7 +91,7 @@ class AutoCompleteController extends Controller { unset($results['exact']); $results = array_merge_recursive($exactMatches, $results); - if($sorter !== null) { + if ($sorter !== null) { $sorters = array_reverse(explode('|', $sorter)); $this->autoCompleteManager->runSorters($sorters, $results, [ 'itemType' => $itemType, diff --git a/core/Controller/CSRFTokenController.php b/core/Controller/CSRFTokenController.php index b120acbcd5f..9ff389140bd 100644 --- a/core/Controller/CSRFTokenController.php +++ b/core/Controller/CSRFTokenController.php @@ -66,5 +66,4 @@ class CSRFTokenController extends Controller { 'token' => $requestToken->getEncryptedValue(), ]); } - } diff --git a/core/Controller/ClientFlowLoginController.php b/core/Controller/ClientFlowLoginController.php index 5df6ce5c7b6..dad43fc837a 100644 --- a/core/Controller/ClientFlowLoginController.php +++ b/core/Controller/ClientFlowLoginController.php @@ -135,7 +135,7 @@ class ClientFlowLoginController extends Controller { */ private function isValidToken($stateToken) { $currentToken = $this->session->get(self::stateName); - if(!is_string($stateToken) || !is_string($currentToken)) { + if (!is_string($stateToken) || !is_string($currentToken)) { return false; } return hash_equals($currentToken, $stateToken); @@ -169,7 +169,7 @@ class ClientFlowLoginController extends Controller { public function showAuthPickerPage($clientIdentifier = '') { $clientName = $this->getClientName(); $client = null; - if($clientIdentifier !== '') { + if ($clientIdentifier !== '') { $client = $this->clientMapper->getByIdentifier($clientIdentifier); $clientName = $client->getName(); } @@ -237,13 +237,13 @@ class ClientFlowLoginController extends Controller { */ public function grantPage($stateToken = '', $clientIdentifier = '') { - if(!$this->isValidToken($stateToken)) { + if (!$this->isValidToken($stateToken)) { return $this->stateTokenForbiddenResponse(); } $clientName = $this->getClientName(); $client = null; - if($clientIdentifier !== '') { + if ($clientIdentifier !== '') { $client = $this->clientMapper->getByIdentifier($clientIdentifier); $clientName = $client->getName(); } @@ -284,7 +284,7 @@ class ClientFlowLoginController extends Controller { */ public function generateAppPassword($stateToken, $clientIdentifier = '') { - if(!$this->isValidToken($stateToken)) { + if (!$this->isValidToken($stateToken)) { $this->session->remove(self::stateName); return $this->stateTokenForbiddenResponse(); } @@ -315,7 +315,7 @@ class ClientFlowLoginController extends Controller { $clientName = $this->getClientName(); $client = false; - if($clientIdentifier !== '') { + if ($clientIdentifier !== '') { $client = $this->clientMapper->getByIdentifier($clientIdentifier); $clientName = $client->getName(); } @@ -332,7 +332,7 @@ class ClientFlowLoginController extends Controller { IToken::DO_NOT_REMEMBER ); - if($client) { + if ($client) { $code = $this->random->generate(128, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS); $accessToken = new AccessToken(); $accessToken->setClientId($client->getId()); diff --git a/core/Controller/ClientFlowLoginV2Controller.php b/core/Controller/ClientFlowLoginV2Controller.php index b5b69972832..43e17c77dde 100644 --- a/core/Controller/ClientFlowLoginV2Controller.php +++ b/core/Controller/ClientFlowLoginV2Controller.php @@ -43,7 +43,6 @@ use OCP\IURLGenerator; use OCP\Security\ISecureRandom; class ClientFlowLoginV2Controller extends Controller { - private const tokenName = 'client.flow.v2.login.token'; private const stateName = 'client.flow.v2.state.token'; @@ -150,7 +149,7 @@ class ClientFlowLoginV2Controller extends Controller { * @NoSameSiteCookieRequired */ public function grantPage(string $stateToken): StandaloneTemplateResponse { - if(!$this->isValidStateToken($stateToken)) { + if (!$this->isValidStateToken($stateToken)) { return $this->stateTokenForbiddenResponse(); } @@ -178,7 +177,7 @@ class ClientFlowLoginV2Controller extends Controller { * @UseSession */ public function generateAppPassword(string $stateToken): Response { - if(!$this->isValidStateToken($stateToken)) { + if (!$this->isValidStateToken($stateToken)) { return $this->stateTokenForbiddenResponse(); } @@ -241,7 +240,7 @@ class ClientFlowLoginV2Controller extends Controller { private function isValidStateToken(string $stateToken): bool { $currentToken = $this->session->get(self::stateName); - if(!is_string($stateToken) || !is_string($currentToken)) { + if (!is_string($stateToken) || !is_string($currentToken)) { return false; } return hash_equals($currentToken, $stateToken); @@ -266,7 +265,7 @@ class ClientFlowLoginV2Controller extends Controller { */ private function getFlowByLoginToken(): LoginFlowV2 { $currentToken = $this->session->get(self::tokenName); - if(!is_string($currentToken)) { + if (!is_string($currentToken)) { throw new LoginFlowV2NotFoundException('Login token not set in session'); } diff --git a/core/Controller/CssController.php b/core/Controller/CssController.php index 741d4431578..f7368003d55 100644 --- a/core/Controller/CssController.php +++ b/core/Controller/CssController.php @@ -75,7 +75,7 @@ class CssController extends Controller { $folder = $this->appData->getFolder($appName); $gzip = false; $file = $this->getFile($folder, $fileName, $gzip); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { return new NotFoundResponse(); } diff --git a/core/Controller/JsController.php b/core/Controller/JsController.php index 05e7bce3368..730a1cf0cb8 100644 --- a/core/Controller/JsController.php +++ b/core/Controller/JsController.php @@ -72,7 +72,7 @@ class JsController extends Controller { $folder = $this->appData->getFolder($appName); $gzip = false; $file = $this->getFile($folder, $fileName, $gzip); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { return new NotFoundResponse(); } diff --git a/core/Controller/LoginController.php b/core/Controller/LoginController.php index b3f7bb310ba..4813f15f1c5 100644 --- a/core/Controller/LoginController.php +++ b/core/Controller/LoginController.php @@ -57,7 +57,6 @@ use OCP\IUserSession; use OCP\Util; class LoginController extends Controller { - const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword'; const LOGIN_MSG_USERDISABLED = 'userdisabled'; diff --git a/core/Controller/LostController.php b/core/Controller/LostController.php index e3d59951d4e..0a2e8d6b73d 100644 --- a/core/Controller/LostController.php +++ b/core/Controller/LostController.php @@ -195,7 +195,7 @@ class LostController extends Controller { */ protected function checkPasswordResetToken($token, $userId) { $user = $this->userManager->get($userId); - if($user === null || !$user->isEnabled()) { + if ($user === null || !$user->isEnabled()) { throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid')); } @@ -212,7 +212,7 @@ class LostController extends Controller { } $splittedToken = explode(':', $decryptedToken); - if(count($splittedToken) !== 2) { + if (count($splittedToken) !== 2) { throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid')); } @@ -318,9 +318,9 @@ class LostController extends Controller { $this->config->deleteUserValue($userId, 'core', 'lostpassword'); @\OC::$server->getUserSession()->unsetMagicInCookie(); - } catch (HintException $e){ + } catch (HintException $e) { return $this->error($e->getHint()); - } catch (\Exception $e){ + } catch (\Exception $e) { return $this->error($e->getMessage()); } diff --git a/core/Controller/OCSController.php b/core/Controller/OCSController.php index 2ae2e0ee64e..7ed43fc6003 100644 --- a/core/Controller/OCSController.php +++ b/core/Controller/OCSController.php @@ -102,7 +102,7 @@ class OCSController extends \OCP\AppFramework\OCSController { 'extendedSupport' => \OCP\Util::hasExtendedSupport() ]; - if($this->userSession->isLoggedIn()) { + if ($this->userSession->isLoggedIn()) { $result['capabilities'] = $this->capabilitiesManager->getCapabilities(); } else { $result['capabilities'] = $this->capabilitiesManager->getCapabilities(true); @@ -145,7 +145,7 @@ class OCSController extends \OCP\AppFramework\OCSController { public function getIdentityProof($cloudId) { $userObject = $this->userManager->get($cloudId); - if($userObject !== null) { + if ($userObject !== null) { $key = $this->keyManager->getKey($userObject); $data = [ 'public' => $key->getPublic(), diff --git a/core/Controller/PreviewController.php b/core/Controller/PreviewController.php index b92a82028cd..f47104bc533 100644 --- a/core/Controller/PreviewController.php +++ b/core/Controller/PreviewController.php @@ -92,7 +92,6 @@ class PreviewController extends Controller { bool $a = false, bool $forceIcon = true, string $mode = 'fill'): Http\Response { - if ($file === '' || $x === 0 || $y === 0) { return new DataResponse([], Http::STATUS_BAD_REQUEST); } @@ -127,7 +126,6 @@ class PreviewController extends Controller { bool $a = false, bool $forceIcon = true, string $mode = 'fill') { - if ($fileId === -1 || $x === 0 || $y === 0) { return new DataResponse([], Http::STATUS_BAD_REQUEST); } @@ -160,7 +158,6 @@ class PreviewController extends Controller { bool $a = false, bool $forceIcon = true, string $mode) : Http\Response { - if (!($node instanceof File) || (!$forceIcon && !$this->preview->isAvailable($node))) { return new DataResponse([], Http::STATUS_NOT_FOUND); } @@ -178,6 +175,5 @@ class PreviewController extends Controller { } catch (\InvalidArgumentException $e) { return new DataResponse([], Http::STATUS_BAD_REQUEST); } - } } diff --git a/core/Controller/RecommendedAppsController.php b/core/Controller/RecommendedAppsController.php index fe3435d9be8..6240aecf43c 100644 --- a/core/Controller/RecommendedAppsController.php +++ b/core/Controller/RecommendedAppsController.php @@ -51,5 +51,4 @@ class RecommendedAppsController extends Controller { $this->initialStateService->provideInitialState('core', 'defaultPageUrl', \OC_Util::getDefaultPageUrl()); return new StandaloneTemplateResponse($this->appName, 'recommendedapps', [], 'guest'); } - } diff --git a/core/Controller/SetupController.php b/core/Controller/SetupController.php index d77f6982f3d..b57b991884c 100644 --- a/core/Controller/SetupController.php +++ b/core/Controller/SetupController.php @@ -70,12 +70,12 @@ class SetupController { return; } - if(isset($post['install']) and $post['install']=='true') { + if (isset($post['install']) and $post['install']=='true') { // We have to launch the installation process : $e = $this->setupHelper->install($post); $errors = ['errors' => $e]; - if(count($e) > 0) { + if (count($e) > 0) { $options = array_merge($opts, $post, $errors); $this->display($options); } else { @@ -109,7 +109,7 @@ class SetupController { } private function finishSetup(bool $installRecommended) { - if(file_exists($this->autoConfigFile)) { + if (file_exists($this->autoConfigFile)) { unlink($this->autoConfigFile); } \OC::$server->getIntegrityCodeChecker()->runInstanceVerification(); @@ -130,7 +130,7 @@ class SetupController { } public function loadAutoConfig($post) { - if(file_exists($this->autoConfigFile)) { + if (file_exists($this->autoConfigFile)) { \OCP\Util::writeLog('core', 'Autoconfig file found, setting up Nextcloud…', ILogger::INFO); $AUTOCONFIG = []; include $this->autoConfigFile; diff --git a/core/Controller/TwoFactorChallengeController.php b/core/Controller/TwoFactorChallengeController.php index 4209e48e648..251ae85b3f7 100644 --- a/core/Controller/TwoFactorChallengeController.php +++ b/core/Controller/TwoFactorChallengeController.php @@ -278,5 +278,4 @@ class TwoFactorChallengeController extends Controller { ] )); } - } diff --git a/core/Controller/UserController.php b/core/Controller/UserController.php index 2b78ba1aaea..638e4e00e46 100644 --- a/core/Controller/UserController.php +++ b/core/Controller/UserController.php @@ -71,6 +71,5 @@ class UserController extends Controller { ]; return new JSONResponse($json); - } } diff --git a/core/Controller/WebAuthnController.php b/core/Controller/WebAuthnController.php index 1d667311ff7..7315053f12d 100644 --- a/core/Controller/WebAuthnController.php +++ b/core/Controller/WebAuthnController.php @@ -38,7 +38,6 @@ use OCP\Util; use Webauthn\PublicKeyCredentialRequestOptions; class WebAuthnController extends Controller { - private const WEBAUTHN_LOGIN = 'webauthn_login'; private const WEBAUTHN_LOGIN_UID = 'webauthn_login_uid'; diff --git a/core/Controller/WhatsNewController.php b/core/Controller/WhatsNewController.php index 159e88e1474..3a72486b26a 100644 --- a/core/Controller/WhatsNewController.php +++ b/core/Controller/WhatsNewController.php @@ -74,13 +74,13 @@ class WhatsNewController extends OCSController { */ public function get():DataResponse { $user = $this->userSession->getUser(); - if($user === null) { + if ($user === null) { throw new \RuntimeException("Acting user cannot be resolved"); } $lastRead = $this->config->getUserValue($user->getUID(), 'core', 'whatsNewLastRead', 0); $currentVersion = $this->whatsNewService->normalizeVersion($this->config->getSystemValue('version')); - if(version_compare($lastRead, $currentVersion, '>=')) { + if (version_compare($lastRead, $currentVersion, '>=')) { return new DataResponse([], Http::STATUS_NO_CONTENT); } @@ -94,7 +94,7 @@ class WhatsNewController extends OCSController { ]; do { $lang = $iterator->current(); - if(isset($whatsNew['whatsNew'][$lang])) { + if (isset($whatsNew['whatsNew'][$lang])) { $resultData['whatsNew'] = $whatsNew['whatsNew'][$lang]; break; } @@ -114,7 +114,7 @@ class WhatsNewController extends OCSController { */ public function dismiss(string $version):DataResponse { $user = $this->userSession->getUser(); - if($user === null) { + if ($user === null) { throw new \RuntimeException("Acting user cannot be resolved"); } $version = $this->whatsNewService->normalizeVersion($version); diff --git a/core/Controller/WipeController.php b/core/Controller/WipeController.php index 378fb112850..bc3cc7ba063 100644 --- a/core/Controller/WipeController.php +++ b/core/Controller/WipeController.php @@ -94,5 +94,4 @@ class WipeController extends Controller { return new JSONResponse([], Http::STATUS_NOT_FOUND); } } - } diff --git a/core/Data/LoginFlowV2Credentials.php b/core/Data/LoginFlowV2Credentials.php index 61f1cdd795f..4dd3cba2e9c 100644 --- a/core/Data/LoginFlowV2Credentials.php +++ b/core/Data/LoginFlowV2Credentials.php @@ -68,6 +68,4 @@ class LoginFlowV2Credentials implements \JsonSerializable { 'appPassword' => $this->appPassword, ]; } - - } diff --git a/core/Data/LoginFlowV2Tokens.php b/core/Data/LoginFlowV2Tokens.php index c7438430c3f..5d9b39069b7 100644 --- a/core/Data/LoginFlowV2Tokens.php +++ b/core/Data/LoginFlowV2Tokens.php @@ -40,7 +40,6 @@ class LoginFlowV2Tokens { public function getPollToken(): string { return $this->pollToken; - } public function getLoginToken(): string { diff --git a/core/Exception/LoginFlowV2NotFoundException.php b/core/Exception/LoginFlowV2NotFoundException.php index 6c41fd10a04..ed06801acff 100644 --- a/core/Exception/LoginFlowV2NotFoundException.php +++ b/core/Exception/LoginFlowV2NotFoundException.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Core\Exception; class LoginFlowV2NotFoundException extends \Exception { - } diff --git a/core/Exception/ResetPasswordException.php b/core/Exception/ResetPasswordException.php index 9f2028068f5..2dfd2058395 100644 --- a/core/Exception/ResetPasswordException.php +++ b/core/Exception/ResetPasswordException.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Core\Exception; class ResetPasswordException extends \Exception { - } diff --git a/core/Middleware/TwoFactorMiddleware.php b/core/Middleware/TwoFactorMiddleware.php index 392ae7ca1ca..fb856ce8938 100644 --- a/core/Middleware/TwoFactorMiddleware.php +++ b/core/Middleware/TwoFactorMiddleware.php @@ -155,5 +155,4 @@ class TwoFactorMiddleware extends Middleware { throw $exception; } - } diff --git a/core/Migrations/Version13000Date20170718121200.php b/core/Migrations/Version13000Date20170718121200.php index 4df2f4cbdab..7907313f1e3 100644 --- a/core/Migrations/Version13000Date20170718121200.php +++ b/core/Migrations/Version13000Date20170718121200.php @@ -931,5 +931,4 @@ class Version13000Date20170718121200 extends SimpleMigrationStep { } return $schema; } - } diff --git a/core/Migrations/Version13000Date20170926101637.php b/core/Migrations/Version13000Date20170926101637.php index 1dd295e383f..1e42dc9b044 100644 --- a/core/Migrations/Version13000Date20170926101637.php +++ b/core/Migrations/Version13000Date20170926101637.php @@ -59,5 +59,4 @@ class Version13000Date20170926101637 extends BigIntMigration { 'vcategory_to_object' => ['objid', 'categoryid'], ]; } - } diff --git a/core/Migrations/Version14000Date20180518120534.php b/core/Migrations/Version14000Date20180518120534.php index 1e025f88ed1..565a7fab707 100644 --- a/core/Migrations/Version14000Date20180518120534.php +++ b/core/Migrations/Version14000Date20180518120534.php @@ -31,7 +31,6 @@ use OCP\Migration\IOutput; use OCP\Migration\SimpleMigrationStep; class Version14000Date20180518120534 extends SimpleMigrationStep { - public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/core/Migrations/Version14000Date20180522074438.php b/core/Migrations/Version14000Date20180522074438.php index 140d220d69a..4afd98d9fbb 100644 --- a/core/Migrations/Version14000Date20180522074438.php +++ b/core/Migrations/Version14000Date20180522074438.php @@ -33,10 +33,8 @@ use OCP\Migration\IOutput; use OCP\Migration\SimpleMigrationStep; class Version14000Date20180522074438 extends SimpleMigrationStep { - public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ISchemaWrapper { - $schema = $schemaClosure(); if (!$schema->hasTable('twofactor_providers')) { @@ -62,5 +60,4 @@ class Version14000Date20180522074438 extends SimpleMigrationStep { return $schema; } - } diff --git a/core/Migrations/Version14000Date20180626223656.php b/core/Migrations/Version14000Date20180626223656.php index 70f0eaafd36..0e679a9972e 100644 --- a/core/Migrations/Version14000Date20180626223656.php +++ b/core/Migrations/Version14000Date20180626223656.php @@ -31,7 +31,7 @@ class Version14000Date20180626223656 extends SimpleMigrationStep { public function changeSchema(\OCP\Migration\IOutput $output, \Closure $schemaClosure, array $options) { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); - if(!$schema->hasTable('whats_new')) { + if (!$schema->hasTable('whats_new')) { $table = $schema->createTable('whats_new'); $table->addColumn('id', 'integer', [ 'autoincrement' => true, diff --git a/core/Migrations/Version14000Date20180710092004.php b/core/Migrations/Version14000Date20180710092004.php index 31daa4f9d47..f44dbf42401 100644 --- a/core/Migrations/Version14000Date20180710092004.php +++ b/core/Migrations/Version14000Date20180710092004.php @@ -33,7 +33,6 @@ use OCP\Migration\IOutput; use OCP\Migration\SimpleMigrationStep; class Version14000Date20180710092004 extends SimpleMigrationStep { - public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/core/Migrations/Version15000Date20180926101451.php b/core/Migrations/Version15000Date20180926101451.php index fff8b31c6ee..a5f37cc9125 100644 --- a/core/Migrations/Version15000Date20180926101451.php +++ b/core/Migrations/Version15000Date20180926101451.php @@ -51,5 +51,4 @@ class Version15000Date20180926101451 extends SimpleMigrationStep { return $schema; } - } diff --git a/core/Migrations/Version15000Date20181029084625.php b/core/Migrations/Version15000Date20181029084625.php index 0af1b4a6502..607ef054f3a 100644 --- a/core/Migrations/Version15000Date20181029084625.php +++ b/core/Migrations/Version15000Date20181029084625.php @@ -52,5 +52,4 @@ class Version15000Date20181029084625 extends SimpleMigrationStep { return $schema; } - } diff --git a/core/Migrations/Version16000Date20190207141427.php b/core/Migrations/Version16000Date20190207141427.php index 028bd1fcb17..1b5777a9212 100644 --- a/core/Migrations/Version16000Date20190207141427.php +++ b/core/Migrations/Version16000Date20190207141427.php @@ -112,5 +112,4 @@ class Version16000Date20190207141427 extends SimpleMigrationStep { return $schema; } - } diff --git a/core/Migrations/Version17000Date20190514105811.php b/core/Migrations/Version17000Date20190514105811.php index d5d7d63cd77..b435172d5f3 100644 --- a/core/Migrations/Version17000Date20190514105811.php +++ b/core/Migrations/Version17000Date20190514105811.php @@ -45,7 +45,7 @@ class Version17000Date20190514105811 extends SimpleMigrationStep { public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); - if(!$schema->hasTable('filecache_extended')) { + if (!$schema->hasTable('filecache_extended')) { $table = $schema->createTable('filecache_extended'); $table->addColumn('fileid', Type::BIGINT, [ 'notnull' => true, diff --git a/core/Migrations/Version18000Date20191014105105.php b/core/Migrations/Version18000Date20191014105105.php index c36972c556f..62a8e2cc37f 100644 --- a/core/Migrations/Version18000Date20191014105105.php +++ b/core/Migrations/Version18000Date20191014105105.php @@ -90,5 +90,4 @@ class Version18000Date20191014105105 extends SimpleMigrationStep { return $schema; } - } diff --git a/core/Migrations/Version18000Date20191204114856.php b/core/Migrations/Version18000Date20191204114856.php index 256b42f9597..e9bf1221dbf 100644 --- a/core/Migrations/Version18000Date20191204114856.php +++ b/core/Migrations/Version18000Date20191204114856.php @@ -61,5 +61,4 @@ class Version18000Date20191204114856 extends SimpleMigrationStep { return $schema; } - } diff --git a/core/Migrations/Version19000Date20200211083441.php b/core/Migrations/Version19000Date20200211083441.php index 72bb26b02fe..07eb04df14e 100644 --- a/core/Migrations/Version19000Date20200211083441.php +++ b/core/Migrations/Version19000Date20200211083441.php @@ -10,7 +10,6 @@ use OCP\Migration\IOutput; use OCP\Migration\SimpleMigrationStep; class Version19000Date20200211083441 extends SimpleMigrationStep { - public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/core/Notification/RemoveLinkSharesNotifier.php b/core/Notification/RemoveLinkSharesNotifier.php index 3976dfb91c5..d4afe7239f1 100644 --- a/core/Notification/RemoveLinkSharesNotifier.php +++ b/core/Notification/RemoveLinkSharesNotifier.php @@ -60,7 +60,7 @@ class RemoveLinkSharesNotifier implements INotifier { } public function prepare(INotification $notification, string $languageCode): INotification { - if($notification->getApp() !== 'core') { + if ($notification->getApp() !== 'core') { throw new \InvalidArgumentException(); } $l = $this->l10nFactory->get('core', $languageCode); diff --git a/core/ajax/update.php b/core/ajax/update.php index 34c65b56c58..58d64347a36 100644 --- a/core/ajax/update.php +++ b/core/ajax/update.php @@ -105,7 +105,6 @@ class FeedBackHandler { } if (\OCP\Util::needUpgrade()) { - $config = \OC::$server->getSystemConfig(); if ($config->getValue('upgrade.disable-web', false)) { $eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.')); diff --git a/core/templates/403.php b/core/templates/403.php index d56a63bfe53..1ee3569ed03 100644 --- a/core/templates/403.php +++ b/core/templates/403.php @@ -1,6 +1,6 @@ getURLGenerator(); @@ -12,6 +12,8 @@ if(!isset($_)) {//standalone page is not supported anymore - redirect to /

        • t('Access forbidden')); ?>
          -

          +

        diff --git a/core/templates/404.php b/core/templates/404.php index 925059d4750..85ddb4c4b17 100644 --- a/core/templates/404.php +++ b/core/templates/404.php @@ -3,7 +3,7 @@ /** @var $l \OCP\IL10N */ /** @var $theme OCP\Defaults */ // @codeCoverageIgnoreStart -if(!isset($_)) {//standalone page is not supported anymore - redirect to / +if (!isset($_)) {//standalone page is not supported anymore - redirect to / require_once '../../lib/base.php'; $urlGenerator = \OC::$server->getURLGenerator(); diff --git a/core/templates/error.php b/core/templates/error.php index 929e8dd3984..c6f7706edc1 100644 --- a/core/templates/error.php +++ b/core/templates/error.php @@ -1,10 +1,10 @@

        t('Error')) ?>

          - +
        • - +

        • diff --git a/core/templates/exception.php b/core/templates/exception.php index fcfa8687710..a2b019b3289 100644 --- a/core/templates/exception.php +++ b/core/templates/exception.php @@ -14,7 +14,7 @@ style('core', ['styles', 'header']);
          • t('Remote Address: %s', [$_['remoteAddr']])) ?>
          • t('Request ID: %s', [$_['requestID']])) ?>
          • - +
          • t('Type: %s', [$_['errorClass']])) ?>
          • t('Code: %s', [$_['errorCode']])) ?>
          • t('Message: %s', [$_['errorMsg']])) ?>
          • @@ -23,7 +23,7 @@ style('core', ['styles', 'header']);
          - +

          t('Trace')) ?>

          diff --git a/core/templates/installation.php b/core/templates/installation.php index d65d0adb1cb..a7808a0103c 100644 --- a/core/templates/installation.php +++ b/core/templates/installation.php @@ -9,12 +9,12 @@ script('core', [ '>
          - 0): ?> + 0): ?>
          t('Error'));?> - +

          - + @@ -24,7 +24,7 @@ script('core', [

          - +
          t('Security warning'));?>

          t('Your data directory and files are probably accessible from the internet because the .htaccess file does not work.'));?>
          @@ -54,13 +54,13 @@ script('core', [

          - 0): ?> + 0): ?>
          t('Storage & database')); ?>
          - 0): ?> + 0): ?>
          @@ -72,14 +72,17 @@ script('core', [
          - 0): ?> + 0): ?>
          - + t('Configure the database')); ?>
          - $label): ?> - + $label): ?> +

          t('Only %s is available.', [$label])); ?> t('Install and activate additional PHP modules to choose other database types.')); ?>
          @@ -96,7 +99,7 @@ script('core', [

          - +

          @@ -123,7 +126,7 @@ script('core', [ autocomplete="off" autocapitalize="none" autocorrect="off" pattern="[0-9a-zA-Z$_-]+">

          - +

          @@ -149,7 +152,7 @@ script('core', [ - 0): ?> + 0): ?>

          t('Performance warning'));?>

          t('You chose SQLite as database.'));?>

          diff --git a/core/templates/layout.guest.php b/core/templates/layout.guest.php index 6bb6e1c74bd..e74f2d8ebbf 100644 --- a/core/templates/layout.guest.php +++ b/core/templates/layout.guest.php @@ -37,7 +37,7 @@

          getName()); ?>

          - getConfig()->getSystemValue('installed', false) + getConfig()->getSystemValue('installed', false) && \OC::$server->getConfig()->getAppValue('theming', 'logoMime', false)): ?> diff --git a/core/templates/layout.public.php b/core/templates/layout.public.php index 996b78a922b..73e3e0f0b46 100644 --- a/core/templates/layout.public.php +++ b/core/templates/layout.public.php @@ -39,34 +39,41 @@

          - getHeaderTitle()); } else { p($theme->getName());} ?> + getHeaderTitle()); + } else { + p($theme->getName()); + } ?>

          - getHeaderDetails()); } ?> + getHeaderDetails()); + } ?>
          getActionCount() !== 0) { + if (isset($template) && $template->getActionCount() !== 0) { $primary = $template->getPrimaryAction(); - $others = $template->getOtherActions(); - ?> + $others = $template->getOtherActions(); ?>
          - + getLabel()) ?> - getActionCount() > 1) { ?> + getActionCount() > 1) { ?>
            render()); } ?> @@ -75,12 +82,13 @@
          - +
          - getFooterVisible()) { ?> + getFooterVisible()) { ?>

          getLongFooter()); ?>

          t('More apps menu')); ?>">
            - +
          • class="active" + class="active" aria-label=""> @@ -123,7 +123,11 @@
            -
            +
              - +
            • class="active"> + class="active"> diff --git a/core/templates/login.php b/core/templates/login.php index 9c6a81fe1ea..124a62f0646 100644 --- a/core/templates/login.php +++ b/core/templates/login.php @@ -7,7 +7,7 @@ script('core', 'dist/login');
              - + diff --git a/core/templates/loginflow/authpicker.php b/core/templates/loginflow/authpicker.php index 5946eb78400..3a471525d80 100644 --- a/core/templates/loginflow/authpicker.php +++ b/core/templates/loginflow/authpicker.php @@ -59,6 +59,6 @@ $urlGenerator = $_['urlGenerator'];
              - + t('Alternative log in using app token')) ?> diff --git a/core/templates/twofactorselectchallenge.php b/core/templates/twofactorselectchallenge.php index 830b82b0415..e815fa16631 100644 --- a/core/templates/twofactorselectchallenge.php +++ b/core/templates/twofactorselectchallenge.php @@ -61,7 +61,7 @@ $noProviders = empty($_['providers']);

              - button primary two-factor-primarytwo-factor-secondary" href="getURLGenerator()->linkToRoute('core.TwoFactorChallenge.showChallenge', [ 'challengeProviderId' => $_['backupProvider']->getId(), 'redirect_url' => $_['redirect_url'], diff --git a/core/templates/twofactorshowchallenge.php b/core/templates/twofactorshowchallenge.php index 3e789c7490d..481cea06eb0 100644 --- a/core/templates/twofactorshowchallenge.php +++ b/core/templates/twofactorshowchallenge.php @@ -14,7 +14,7 @@ $template = $_['template'];

              getDisplayName()); ?>

              - +

              t('Error while validating your second factor')); ?>

              diff --git a/core/templates/update.use-cli.php b/core/templates/update.use-cli.php index 8cd7e37ffce..6e6d19483db 100644 --- a/core/templates/update.use-cli.php +++ b/core/templates/update.use-cli.php @@ -3,10 +3,10 @@

              t('Update needed')) ?>

              t('Please use the command line updater because you have a big instance with more than 50 users.')); - } else { - p($l->t('Please use the command line updater because automatic updating is disabled in the config.php.')); - } ?>

              + p($l->t('Please use the command line updater because you have a big instance with more than 50 users.')); +} else { + p($l->t('Please use the command line updater because automatic updating is disabled in the config.php.')); +} ?>

              t('For help, see the
              documentation.', [link_to_docs('admin-cli-upgrade')])); ?>

              diff --git a/cron.php b/cron.php index bef8b134f2d..74ba5775ec8 100644 --- a/cron.php +++ b/cron.php @@ -40,7 +40,6 @@ require_once __DIR__ . '/lib/versioncheck.php'; try { - require_once __DIR__ . '/lib/base.php'; if (\OCP\Util::needUpgrade()) { @@ -137,7 +136,6 @@ try { break; } } - } else { // We call cron.php from some website if ($appMode === 'cron') { @@ -158,7 +156,6 @@ try { // Log the successful cron execution $config->setAppValue('core', 'lastcron', time()); exit(); - } catch (Exception $ex) { \OC::$server->getLogger()->logException($ex, ['app' => 'cron']); } catch (Error $ex) { diff --git a/index.php b/index.php index f94a153b2c5..92c6ca3b932 100644 --- a/index.php +++ b/index.php @@ -32,12 +32,10 @@ require_once __DIR__ . '/lib/versioncheck.php'; try { - require_once __DIR__ . '/lib/base.php'; OC::handleRequest(); - -} catch(\OC\ServiceUnavailableException $ex) { +} catch (\OC\ServiceUnavailableException $ex) { \OC::$server->getLogger()->logException($ex, ['app' => 'index']); //show the user a detailed error page diff --git a/lib/autoloader.php b/lib/autoloader.php index a89cba4f6c5..f1bd613b52d 100644 --- a/lib/autoloader.php +++ b/lib/autoloader.php @@ -153,7 +153,7 @@ class Autoloader { $pathsToRequire = $this->memoryCache->get($class); } - if(class_exists($class, false)) { + if (class_exists($class, false)) { return false; } diff --git a/lib/base.php b/lib/base.php index a86dccd0822..f6eb79ab270 100644 --- a/lib/base.php +++ b/lib/base.php @@ -135,11 +135,11 @@ class OC { * the app path list is empty or contains an invalid path */ public static function initPaths() { - if(defined('PHPUNIT_CONFIG_DIR')) { + if (defined('PHPUNIT_CONFIG_DIR')) { self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; - } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { + } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { self::$configDir = OC::$SERVERROOT . '/tests/config/'; - } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { + } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { self::$configDir = rtrim($dir, '/') . '/'; } else { self::$configDir = OC::$SERVERROOT . '/config/'; @@ -242,7 +242,7 @@ class OC { // Create config if it does not already exist $configFilePath = self::$configDir .'/config.php'; - if(!file_exists($configFilePath)) { + if (!file_exists($configFilePath)) { @touch($configFilePath); } @@ -250,7 +250,6 @@ class OC { $configFileWritable = is_writable($configFilePath); if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() || !$configFileWritable && \OCP\Util::needUpgrade()) { - $urlGenerator = \OC::$server->getURLGenerator(); if (self::$CLI) { @@ -405,7 +404,7 @@ class OC { } public static function initSession() { - if(self::$server->getRequest()->getServerProtocol() === 'https') { + if (self::$server->getRequest()->getServerProtocol() === 'https') { ini_set('session.cookie_secure', true); } @@ -482,11 +481,11 @@ class OC { // Append __Host to the cookie if it meets the requirements $cookiePrefix = ''; - if($cookieParams['secure'] === true && $cookieParams['path'] === '/') { + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { $cookiePrefix = '__Host-'; } - foreach($policies as $policy) { + foreach ($policies as $policy) { header( sprintf( 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', @@ -528,31 +527,31 @@ class OC { ]; } - if($request->isUserAgent($incompatibleUserAgents)) { + if ($request->isUserAgent($incompatibleUserAgents)) { return; } - if(count($_COOKIE) > 0) { + if (count($_COOKIE) > 0) { $requestUri = $request->getScriptName(); $processingScript = explode('/', $requestUri); $processingScript = $processingScript[count($processingScript)-1]; // index.php routes are handled in the middleware - if($processingScript === 'index.php') { + if ($processingScript === 'index.php') { return; } // All other endpoints require the lax and the strict cookie - if(!$request->passesStrictCookieCheck()) { + if (!$request->passesStrictCookieCheck()) { self::sendSameSiteCookies(); // Debug mode gets access to the resources without strict cookie // due to the fact that the SabreDAV browser also lives there. - if(!\OC::$server->getConfig()->getSystemValue('debug', false)) { + if (!\OC::$server->getConfig()->getSystemValue('debug', false)) { http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); exit(); } } - } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { + } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { self::sendSameSiteCookies(); } } @@ -586,7 +585,6 @@ class OC { throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); } require_once $vendorAutoLoad; - } catch (\RuntimeException $e) { if (!self::$CLI) { http_response_code(503); @@ -611,7 +609,7 @@ class OC { @ini_set('display_errors', '0'); @ini_set('log_errors', '1'); - if(!date_default_timezone_set('UTC')) { + if (!date_default_timezone_set('UTC')) { throw new \RuntimeException('Could not set timezone to UTC'); } @@ -747,7 +745,7 @@ class OC { register_shutdown_function([$lockProvider, 'releaseAll']); // Check whether the sample configuration has been copied - if($systemConfig->getValue('copied_sample_config', false)) { + if ($systemConfig->getValue('copied_sample_config', false)) { $l = \OC::$server->getL10N('lib'); OC_Template::printErrorPage( $l->t('Sample configuration detected'), @@ -769,11 +767,11 @@ class OC { ) { // Allow access to CSS resources $isScssRequest = false; - if(strpos($request->getPathInfo(), '/css/') === 0) { + if (strpos($request->getPathInfo(), '/css/') === 0) { $isScssRequest = true; } - if(substr($request->getRequestUri(), -11) === '/status.php') { + if (substr($request->getRequestUri(), -11) === '/status.php') { http_response_code(400); header('Content-Type: application/json'); echo '{"error": "Trusted domain error.", "code": 15}'; @@ -876,11 +874,9 @@ class OC { $restrictions = array_values($restrictions); if (empty($restrictions)) { $appManager->disableApp($appId); - } - else{ + } else { $appManager->enableAppForGroups($appId, $restrictions); } - } }); } @@ -930,7 +926,6 @@ class OC { * Handle the request */ public static function handleRequest() { - \OC::$server->getEventLogger()->start('handle_request', 'Handle request'); $systemConfig = \OC::$server->getSystemConfig(); @@ -978,7 +973,7 @@ class OC { \OC_JSON::callCheck(); \OC_JSON::checkAdminUser(); $appIds = (array)$request->getParam('appid'); - foreach($appIds as $appId) { + foreach ($appIds as $appId) { $appId = \OC_App::cleanAppId($appId); \OC::$server->getAppManager()->disableApp($appId); } @@ -993,7 +988,7 @@ class OC { if (!\OCP\Util::needUpgrade() && !((bool) $systemConfig->getValue('maintenance', false))) { // For logged-in users: Load everything - if(\OC::$server->getUserSession()->isLoggedIn()) { + if (\OC::$server->getUserSession()->isLoggedIn()) { OC_App::loadApps(); } else { // For guests: Load only filesystem and logging diff --git a/lib/private/Accounts/AccountManager.php b/lib/private/Accounts/AccountManager.php index 5f2ea465ed7..8b0cb972c59 100644 --- a/lib/private/Accounts/AccountManager.php +++ b/lib/private/Accounts/AccountManager.php @@ -191,7 +191,6 @@ class AccountManager implements IAccountManager { * @return array */ protected function addMissingDefaultValues(array $userData) { - foreach ($userData as $key => $value) { if (!isset($userData[$key]['verified'])) { $userData[$key]['verified'] = self::NOT_VERIFIED; @@ -216,45 +215,44 @@ class AccountManager implements IAccountManager { $emailVerified = isset($oldData[self::PROPERTY_EMAIL]['verified']) && $oldData[self::PROPERTY_EMAIL]['verified'] === self::VERIFIED; // keep old verification status if we don't have a new one - if(!isset($newData[self::PROPERTY_TWITTER]['verified'])) { + if (!isset($newData[self::PROPERTY_TWITTER]['verified'])) { // keep old verification status if value didn't changed and an old value exists $keepOldStatus = $newData[self::PROPERTY_TWITTER]['value'] === $oldData[self::PROPERTY_TWITTER]['value'] && isset($oldData[self::PROPERTY_TWITTER]['verified']); $newData[self::PROPERTY_TWITTER]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_TWITTER]['verified'] : self::NOT_VERIFIED; } - if(!isset($newData[self::PROPERTY_WEBSITE]['verified'])) { + if (!isset($newData[self::PROPERTY_WEBSITE]['verified'])) { // keep old verification status if value didn't changed and an old value exists $keepOldStatus = $newData[self::PROPERTY_WEBSITE]['value'] === $oldData[self::PROPERTY_WEBSITE]['value'] && isset($oldData[self::PROPERTY_WEBSITE]['verified']); $newData[self::PROPERTY_WEBSITE]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_WEBSITE]['verified'] : self::NOT_VERIFIED; } - if(!isset($newData[self::PROPERTY_EMAIL]['verified'])) { + if (!isset($newData[self::PROPERTY_EMAIL]['verified'])) { // keep old verification status if value didn't changed and an old value exists $keepOldStatus = $newData[self::PROPERTY_EMAIL]['value'] === $oldData[self::PROPERTY_EMAIL]['value'] && isset($oldData[self::PROPERTY_EMAIL]['verified']); $newData[self::PROPERTY_EMAIL]['verified'] = $keepOldStatus ? $oldData[self::PROPERTY_EMAIL]['verified'] : self::VERIFICATION_IN_PROGRESS; } // reset verification status if a value from a previously verified data was changed - if($twitterVerified && + if ($twitterVerified && $oldData[self::PROPERTY_TWITTER]['value'] !== $newData[self::PROPERTY_TWITTER]['value'] ) { $newData[self::PROPERTY_TWITTER]['verified'] = self::NOT_VERIFIED; } - if($websiteVerified && + if ($websiteVerified && $oldData[self::PROPERTY_WEBSITE]['value'] !== $newData[self::PROPERTY_WEBSITE]['value'] ) { $newData[self::PROPERTY_WEBSITE]['verified'] = self::NOT_VERIFIED; } - if($emailVerified && + if ($emailVerified && $oldData[self::PROPERTY_EMAIL]['value'] !== $newData[self::PROPERTY_EMAIL]['value'] ) { $newData[self::PROPERTY_EMAIL]['verified'] = self::NOT_VERIFIED; } return $newData; - } /** @@ -346,7 +344,7 @@ class AccountManager implements IAccountManager { private function parseAccountData(IUser $user, $data): Account { $account = new Account($user); - foreach($data as $property => $accountData) { + foreach ($data as $property => $accountData) { $account->setProperty($property, $accountData['value'] ?? '', $accountData['scope'] ?? self::VISIBILITY_PRIVATE, $accountData['verified'] ?? self::NOT_VERIFIED); } return $account; @@ -355,5 +353,4 @@ class AccountManager implements IAccountManager { public function getAccount(IUser $user): IAccount { return $this->parseAccountData($user, $this->getUser($user)); } - } diff --git a/lib/private/Accounts/Hooks.php b/lib/private/Accounts/Hooks.php index 17eb7a3cf5a..2288b884c5c 100644 --- a/lib/private/Accounts/Hooks.php +++ b/lib/private/Accounts/Hooks.php @@ -50,7 +50,6 @@ class Hooks { * @param array $params */ public function changeUserHook($params) { - $accountManager = $this->getAccountManager(); /** @var IUser $user */ @@ -79,7 +78,6 @@ class Hooks { } break; } - } /** @@ -93,5 +91,4 @@ class Hooks { } return $this->accountManager; } - } diff --git a/lib/private/Activity/Manager.php b/lib/private/Activity/Manager.php index fc1c32a475f..ffe6c335b27 100644 --- a/lib/private/Activity/Manager.php +++ b/lib/private/Activity/Manager.php @@ -90,7 +90,7 @@ class Manager implements IManager { } $this->consumers = []; - foreach($this->consumersClosures as $consumer) { + foreach ($this->consumersClosures as $consumer) { $c = $consumer(); if ($c instanceof IConsumer) { $this->consumers[] = $c; @@ -385,5 +385,4 @@ class Manager implements IManager { // Token found login as that user return array_shift($users); } - } diff --git a/lib/private/AllConfig.php b/lib/private/AllConfig.php index e1517440b46..8834ac9b592 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -90,7 +90,7 @@ class AllConfig implements \OCP\IConfig { * because the database connection was created with an uninitialized config */ private function fixDIInit() { - if($this->connection === null) { + if ($this->connection === null) { $this->connection = \OC::$server->getDatabaseConnection(); } } @@ -485,7 +485,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . 'WHERE `appid` = ? AND `configkey` = ? '; - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { //oracle hack: need to explicitly cast CLOB to CHAR for comparison $sql .= 'AND to_char(`configvalue`) = ?'; } else { @@ -517,7 +517,7 @@ class AllConfig implements \OCP\IConfig { $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . 'WHERE `appid` = ? AND `configkey` = ? '; - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { //oracle hack: need to explicitly cast CLOB to CHAR for comparison $sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)'; } else { diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index bf1e8492aa3..f756664e457 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -136,7 +136,7 @@ class AppManager implements IAppManager { $values = $this->appConfig->getValues(false, 'enabled'); $alwaysEnabledApps = $this->getAlwaysEnabledApps(); - foreach($alwaysEnabledApps as $appId) { + foreach ($alwaysEnabledApps as $appId) { $values[$appId] = 'yes'; } @@ -241,7 +241,7 @@ class AppManager implements IAppManager { } elseif ($user === null) { return false; } else { - if(empty($enabled)){ + if (empty($enabled)) { return false; } @@ -385,7 +385,6 @@ class AppManager implements IAppManager { ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups )); $this->clearAppsCache(); - } /** @@ -428,7 +427,7 @@ class AppManager implements IAppManager { */ public function getAppPath($appId) { $appPath = \OC_App::getAppPath($appId); - if($appPath === false) { + if ($appPath === false) { throw new AppPathNotFoundException('Could not find path for ' . $appId); } return $appPath; @@ -443,7 +442,7 @@ class AppManager implements IAppManager { */ public function getAppWebPath(string $appId): string { $appWebPath = \OC_App::getAppWebPath($appId); - if($appWebPath === false) { + if ($appWebPath === false) { throw new AppPathNotFoundException('Could not find web path for ' . $appId); } return $appWebPath; @@ -523,7 +522,7 @@ class AppManager implements IAppManager { } public function getAppVersion(string $appId, bool $useCache = true): string { - if(!$useCache || !isset($this->appVersions[$appId])) { + if (!$useCache || !isset($this->appVersions[$appId])) { $appInfo = $this->getAppInfo($appId); $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0'; } diff --git a/lib/private/App/AppStore/Bundles/BundleFetcher.php b/lib/private/App/AppStore/Bundles/BundleFetcher.php index 3925042a09e..cff3368d042 100644 --- a/lib/private/App/AppStore/Bundles/BundleFetcher.php +++ b/lib/private/App/AppStore/Bundles/BundleFetcher.php @@ -74,8 +74,8 @@ class BundleFetcher { $this->getBundles(), $this->getDefaultInstallationBundle() ); - foreach($bundles as $bundle) { - if($bundle->getIdentifier() === $identifier) { + foreach ($bundles as $bundle) { + if ($bundle->getIdentifier() === $identifier) { return $bundle; } } diff --git a/lib/private/App/AppStore/Bundles/CoreBundle.php b/lib/private/App/AppStore/Bundles/CoreBundle.php index 6dcaedab3e1..4e28d673883 100644 --- a/lib/private/App/AppStore/Bundles/CoreBundle.php +++ b/lib/private/App/AppStore/Bundles/CoreBundle.php @@ -40,5 +40,4 @@ class CoreBundle extends Bundle { 'bruteforcesettings', ]; } - } diff --git a/lib/private/App/AppStore/Bundles/EducationBundle.php b/lib/private/App/AppStore/Bundles/EducationBundle.php index 2d1968772d4..01296cd0536 100644 --- a/lib/private/App/AppStore/Bundles/EducationBundle.php +++ b/lib/private/App/AppStore/Bundles/EducationBundle.php @@ -47,5 +47,4 @@ class EducationBundle extends Bundle { 'user_saml', ]; } - } diff --git a/lib/private/App/AppStore/Bundles/EnterpriseBundle.php b/lib/private/App/AppStore/Bundles/EnterpriseBundle.php index 63faaf8e308..37213fe5a39 100644 --- a/lib/private/App/AppStore/Bundles/EnterpriseBundle.php +++ b/lib/private/App/AppStore/Bundles/EnterpriseBundle.php @@ -47,5 +47,4 @@ class EnterpriseBundle extends Bundle { 'terms_of_service', ]; } - } diff --git a/lib/private/App/AppStore/Bundles/GroupwareBundle.php b/lib/private/App/AppStore/Bundles/GroupwareBundle.php index d1726c7fa5f..49ae1068b10 100644 --- a/lib/private/App/AppStore/Bundles/GroupwareBundle.php +++ b/lib/private/App/AppStore/Bundles/GroupwareBundle.php @@ -44,5 +44,4 @@ class GroupwareBundle extends Bundle { 'mail' ]; } - } diff --git a/lib/private/App/AppStore/Bundles/HubBundle.php b/lib/private/App/AppStore/Bundles/HubBundle.php index cf2f44b7ea4..18dd9093623 100644 --- a/lib/private/App/AppStore/Bundles/HubBundle.php +++ b/lib/private/App/AppStore/Bundles/HubBundle.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\App\AppStore\Bundles; class HubBundle extends Bundle { - public function getName() { return $this->l10n->t('Hub bundle'); } diff --git a/lib/private/App/AppStore/Bundles/SocialSharingBundle.php b/lib/private/App/AppStore/Bundles/SocialSharingBundle.php index 860f983eaa1..8ce4d1080ff 100644 --- a/lib/private/App/AppStore/Bundles/SocialSharingBundle.php +++ b/lib/private/App/AppStore/Bundles/SocialSharingBundle.php @@ -43,5 +43,4 @@ class SocialSharingBundle extends Bundle { 'socialsharing_diaspora', ]; } - } diff --git a/lib/private/App/AppStore/Fetcher/AppFetcher.php b/lib/private/App/AppStore/Fetcher/AppFetcher.php index 889facb3709..e4c2ba4e85e 100644 --- a/lib/private/App/AppStore/Fetcher/AppFetcher.php +++ b/lib/private/App/AppStore/Fetcher/AppFetcher.php @@ -88,11 +88,11 @@ class AppFetcher extends Fetcher { $allowPreReleases = $this->getChannel() === 'beta' || $this->getChannel() === 'daily'; $allowNightly = $this->getChannel() === 'daily'; - foreach($response['data'] as $dataKey => $app) { + foreach ($response['data'] as $dataKey => $app) { $releases = []; // Filter all compatible releases - foreach($app['releases'] as $release) { + foreach ($app['releases'] as $release) { // Exclude all nightly and pre-releases if required if (($allowNightly || $release['isNightly'] === false) && ($allowPreReleases || strpos($release['version'], '-') === false)) { @@ -123,12 +123,12 @@ class AppFetcher extends Fetcher { // Get the highest version $versions = []; - foreach($releases as $release) { + foreach ($releases as $release) { $versions[] = $release['version']; } usort($versions, 'version_compare'); $versions = array_reverse($versions); - if(isset($versions[0])) { + if (isset($versions[0])) { $highestVersion = $versions[0]; foreach ($releases as $release) { if ((string)$release['version'] === (string)$highestVersion) { diff --git a/lib/private/App/AppStore/Version/VersionParser.php b/lib/private/App/AppStore/Version/VersionParser.php index 36bc255175c..e851ecc31d1 100644 --- a/lib/private/App/AppStore/Version/VersionParser.php +++ b/lib/private/App/AppStore/Version/VersionParser.php @@ -47,7 +47,7 @@ class VersionParser { */ public function getVersion($versionSpec) { // * indicates that the version is compatible with all versions - if($versionSpec === '*') { + if ($versionSpec === '*') { return new Version('', ''); } @@ -59,17 +59,17 @@ class VersionParser { $secondVersion = isset($versionElements[1]) ? $versionElements[1] : ''; $secondVersionNumber = substr($secondVersion, 2); - switch(count($versionElements)) { + switch (count($versionElements)) { case 1: - if(!$this->isValidVersionString($firstVersionNumber)) { + if (!$this->isValidVersionString($firstVersionNumber)) { break; } - if(strpos($firstVersion, '>') === 0) { + if (strpos($firstVersion, '>') === 0) { return new Version($firstVersionNumber, ''); } return new Version('', $firstVersionNumber); case 2: - if(!$this->isValidVersionString($firstVersionNumber) || !$this->isValidVersionString($secondVersionNumber)) { + if (!$this->isValidVersionString($firstVersionNumber) || !$this->isValidVersionString($secondVersionNumber)) { break; } return new Version($firstVersionNumber, $secondVersionNumber); diff --git a/lib/private/App/CodeChecker/CodeChecker.php b/lib/private/App/CodeChecker/CodeChecker.php index 60276d5bfcc..aa8f43e6af2 100644 --- a/lib/private/App/CodeChecker/CodeChecker.php +++ b/lib/private/App/CodeChecker/CodeChecker.php @@ -37,7 +37,6 @@ use RegexIterator; use SplFileInfo; class CodeChecker extends BasicEmitter { - const CLASS_EXTENDS_NOT_ALLOWED = 1000; const CLASS_IMPLEMENTS_NOT_ALLOWED = 1001; const STATIC_CALL_NOT_ALLOWED = 1002; @@ -96,7 +95,7 @@ class CodeChecker extends BasicEmitter { $iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($excludes) { /** @var SplFileInfo $item */ - foreach($excludes as $exclude) { + foreach ($excludes as $exclude) { if (substr($item->getPath(), 0, strlen($exclude)) === $exclude) { return false; } diff --git a/lib/private/App/CodeChecker/MigrationSchemaChecker.php b/lib/private/App/CodeChecker/MigrationSchemaChecker.php index 63e35e0647c..778bbfc2f31 100644 --- a/lib/private/App/CodeChecker/MigrationSchemaChecker.php +++ b/lib/private/App/CodeChecker/MigrationSchemaChecker.php @@ -53,7 +53,6 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { $node->expr instanceof Node\Expr\MethodCall && $node->expr->var instanceof Node\Expr\Variable && $node->expr->var->name === $this->schemaVariableName) { - if ($node->expr->name === 'createTable') { if (isset($node->expr->args[0]) && $node->expr->args[0]->value instanceof Node\Scalar\String_) { if (!$this->checkNameLength($node->expr->args[0]->value->value)) { @@ -75,7 +74,6 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { $node instanceof Node\Expr\MethodCall && $node->var instanceof Node\Expr\Variable && $node->var->name === $this->schemaVariableName) { - if ($node->name === 'renameTable') { $this->errors[] = [ 'line' => $node->getLine(), @@ -87,14 +85,13 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { ]; } - /** - * Check columns and Indexes - */ + /** + * Check columns and Indexes + */ } elseif (!empty($this->tableVariableNames) && $node instanceof Node\Expr\MethodCall && $node->var instanceof Node\Expr\Variable && isset($this->tableVariableNames[$node->var->name])) { - if ($node->name === 'addColumn' || $node->name === 'changeColumn') { if (isset($node->args[0]) && $node->args[0]->value instanceof Node\Scalar\String_) { if (!$this->checkNameLength($node->args[0]->value->value)) { @@ -163,9 +160,9 @@ class MigrationSchemaChecker extends NodeVisitorAbstract { ]; } - /** - * Find the schema - */ + /** + * Find the schema + */ } elseif ($node instanceof Node\Expr\Assign && $node->expr instanceof Node\Expr\FuncCall && $node->var instanceof Node\Expr\Variable && diff --git a/lib/private/App/CompareVersion.php b/lib/private/App/CompareVersion.php index 314db1eadd6..12cd7615769 100644 --- a/lib/private/App/CompareVersion.php +++ b/lib/private/App/CompareVersion.php @@ -26,7 +26,6 @@ namespace OC\App; use InvalidArgumentException; class CompareVersion { - const REGEX_MAJOR = '/^\d+$/'; const REGEX_MAJOR_MINOR = '/^\d+.\d+$/'; const REGEX_MAJOR_MINOR_PATCH = '/^\d+.\d+.\d+$/'; @@ -46,7 +45,6 @@ class CompareVersion { */ public function isCompatible(string $actual, string $required, string $comparator = '>='): bool { - if (!preg_match(self::REGEX_SERVER, $actual)) { throw new InvalidArgumentException('server version is invalid'); } @@ -92,5 +90,4 @@ class CompareVersion { return version_compare("$actualMajor.$actualMinor.$actualPatch", "$requiredMajor.$requiredMinor.$requiredPatch", $comparator); } - } diff --git a/lib/private/App/InfoParser.php b/lib/private/App/InfoParser.php index 3d5bec2e829..6a56259a3f5 100644 --- a/lib/private/App/InfoParser.php +++ b/lib/private/App/InfoParser.php @@ -246,7 +246,7 @@ class InfoParser { $data = [ '@attributes' => [], ]; - if (!count($node->children())){ + if (!count($node->children())) { $value = (string)$node; if (!empty($value)) { $data['@value'] = (string)$node; diff --git a/lib/private/AppFramework/App.php b/lib/private/AppFramework/App.php index 382425ad046..c250a6e2d5d 100644 --- a/lib/private/AppFramework/App.php +++ b/lib/private/AppFramework/App.php @@ -107,7 +107,7 @@ class App { // first try $controllerName then go for \OCA\AppName\Controller\$controllerName try { $controller = $container->query($controllerName); - } catch(QueryException $e) { + } catch (QueryException $e) { if (strpos($controllerName, '\\Controller\\') !== false) { // This is from a global registered app route that is not enabled. [/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3); @@ -137,17 +137,17 @@ class App { $io = $container[IOutput::class]; - if(!is_null($httpHeaders)) { + if (!is_null($httpHeaders)) { $io->setHeader($httpHeaders); } - foreach($responseHeaders as $name => $value) { + foreach ($responseHeaders as $name => $value) { $io->setHeader($name . ': ' . $value); } - foreach($responseCookies as $name => $value) { + foreach ($responseCookies as $name => $value) { $expireDate = null; - if($value['expireDate'] instanceof \DateTime) { + if ($value['expireDate'] instanceof \DateTime) { $expireDate = $value['expireDate']->getTimestamp(); } $io->setCookie( @@ -183,7 +183,6 @@ class App { $io->setOutput($output); } } - } /** @@ -200,7 +199,6 @@ class App { */ public static function part(string $controllerName, string $methodName, array $urlParams, DIContainer $container) { - $container['urlParams'] = $urlParams; $controller = $container[$controllerName]; @@ -209,5 +207,4 @@ class App { list(, , $output) = $dispatcher->dispatch($controller, $methodName); return $output; } - } diff --git a/lib/private/AppFramework/DependencyInjection/DIContainer.php b/lib/private/AppFramework/DependencyInjection/DIContainer.php index 2ce504304dc..6654d3849b2 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -278,7 +278,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { $c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class) ); - foreach($this->middleWares as $middleWare) { + foreach ($this->middleWares as $middleWare) { $dispatcher->registerMiddleware($c->query($middleWare)); } @@ -298,8 +298,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { /** * @return \OCP\IServerContainer */ - public function getServer() - { + public function getServer() { return $this->server; } @@ -350,7 +349,7 @@ class DIContainer extends SimpleContainer implements IAppContainer { * @return mixed */ public function log($message, $level) { - switch($level){ + switch ($level) { case 'debug': $level = ILogger::DEBUG; break; diff --git a/lib/private/AppFramework/Http.php b/lib/private/AppFramework/Http.php index 4b08812b6cf..3c4a52fe37c 100644 --- a/lib/private/AppFramework/Http.php +++ b/lib/private/AppFramework/Http.php @@ -33,7 +33,6 @@ namespace OC\AppFramework; use OCP\AppFramework\Http as BaseHttp; class Http extends BaseHttp { - private $server; private $protocolVersion; protected $headers; @@ -119,8 +118,7 @@ class Http extends BaseHttp { */ public function getStatusHeader($status, \DateTime $lastModified=null, $ETag=null) { - - if(!is_null($lastModified)) { + if (!is_null($lastModified)) { $lastModified = $lastModified->format(\DateTime::RFC2822); } @@ -133,22 +131,18 @@ class Http extends BaseHttp { (isset($this->server['HTTP_IF_MODIFIED_SINCE']) && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === $lastModified)) { - $status = self::STATUS_NOT_MODIFIED; } // we have one change currently for the http 1.0 header that differs // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND // if this differs any more, we want to create childclasses for this - if($status === self::STATUS_TEMPORARY_REDIRECT + if ($status === self::STATUS_TEMPORARY_REDIRECT && $this->protocolVersion === 'HTTP/1.0') { - $status = self::STATUS_FOUND; } return $this->protocolVersion . ' ' . $status . ' ' . $this->headers[$status]; } - - } diff --git a/lib/private/AppFramework/Http/Dispatcher.php b/lib/private/AppFramework/Http/Dispatcher.php index 33ce8741acf..f1871e84c08 100644 --- a/lib/private/AppFramework/Http/Dispatcher.php +++ b/lib/private/AppFramework/Http/Dispatcher.php @@ -102,10 +102,10 @@ class Dispatcher { // exception and creates a response. If no response is created, it is // assumed that theres no middleware who can handle it and the error is // thrown again - } catch(\Exception $exception){ + } catch (\Exception $exception) { $response = $this->middlewareDispatcher->afterException( $controller, $methodName, $exception); - } catch(\Throwable $throwable) { + } catch (\Throwable $throwable) { $exception = new \Exception($throwable->getMessage(), $throwable->getCode(), $throwable); $response = $this->middlewareDispatcher->afterException( $controller, $methodName, $exception); @@ -141,7 +141,7 @@ class Dispatcher { // valid types that will be casted $types = ['int', 'integer', 'bool', 'boolean', 'float']; - foreach($this->reflector->getParameters() as $param => $default) { + foreach ($this->reflector->getParameters() as $param => $default) { // try to get the parameter from the request object and cast // it to the type annotated in the @param annotation @@ -150,7 +150,7 @@ class Dispatcher { // if this is submitted using GET or a POST form, 'false' should be // converted to false - if(($type === 'bool' || $type === 'boolean') && + if (($type === 'bool' || $type === 'boolean') && $value === 'false' && ( $this->request->method === 'GET' || @@ -159,8 +159,7 @@ class Dispatcher { ) ) { $value = false; - - } elseif($value !== null && \in_array($type, $types, true)) { + } elseif ($value !== null && \in_array($type, $types, true)) { settype($value, $type); } @@ -170,13 +169,13 @@ class Dispatcher { $response = \call_user_func_array([$controller, $methodName], $arguments); // format response - if($response instanceof DataResponse || !($response instanceof Response)) { + if ($response instanceof DataResponse || !($response instanceof Response)) { // get format from the url format or request format parameter $format = $this->request->getParam('format'); // if none is given try the first Accept header - if($format === null) { + if ($format === null) { $headers = $this->request->getHeader('Accept'); $format = $controller->getResponderByHTTPHeader($headers, null); } @@ -190,5 +189,4 @@ class Dispatcher { return $response; } - } diff --git a/lib/private/AppFramework/Http/Output.php b/lib/private/AppFramework/Http/Output.php index d96898b2521..fd95f370360 100644 --- a/lib/private/AppFramework/Http/Output.php +++ b/lib/private/AppFramework/Http/Output.php @@ -96,5 +96,4 @@ class Output implements IOutput { $path = $this->webRoot ? : '/'; setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly); } - } diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index 5430d1ae922..1dcec3c3b98 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -64,7 +64,6 @@ use OCP\Security\ISecureRandom; * @property mixed[] server */ class Request implements \ArrayAccess, \Countable, IRequest { - const USER_AGENT_IE = '/(MSIE)|(Trident)/'; // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/'; @@ -149,11 +148,11 @@ class Request implements \ArrayAccess, \Countable, IRequest { $this->config = $config; $this->csrfTokenManager = $csrfTokenManager; - if(!array_key_exists('method', $vars)) { + if (!array_key_exists('method', $vars)) { $vars['method'] = 'GET'; } - foreach($this->allowedKeys as $name) { + foreach ($this->allowedKeys as $name) { $this->items[$name] = isset($vars[$name]) ? $vars[$name] : []; @@ -165,7 +164,6 @@ class Request implements \ArrayAccess, \Countable, IRequest { $this->items['urlParams'], $this->items['params'] ); - } /** * @param array $parameters @@ -263,12 +261,12 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return mixed|null */ public function __get($name) { - switch($name) { + switch ($name) { case 'put': case 'patch': case 'get': case 'post': - if($this->method !== strtoupper($name)) { + if ($this->method !== strtoupper($name)) { throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method)); } return $this->getContent(); @@ -318,7 +316,6 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return string */ public function getHeader(string $name): string { - $name = strtoupper(str_replace('-', '_',$name)); if (isset($this->server['HTTP_' . $name])) { return $this->server['HTTP_' . $name]; @@ -447,21 +444,20 @@ class Request implements \ArrayAccess, \Countable, IRequest { // 'application/json' must be decoded manually. if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) { $params = json_decode(file_get_contents($this->inputStream), true); - if($params !== null && \count($params) > 0) { + if ($params !== null && \count($params) > 0) { $this->items['params'] = $params; - if($this->method === 'POST') { + if ($this->method === 'POST') { $this->items['post'] = $params; } } - // Handle application/x-www-form-urlencoded for methods other than GET + // Handle application/x-www-form-urlencoded for methods other than GET // or post correctly - } elseif($this->method !== 'GET' + } elseif ($this->method !== 'GET' && $this->method !== 'POST' && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) { - parse_str(file_get_contents($this->inputStream), $params); - if(\is_array($params)) { + if (\is_array($params)) { $this->items['params'] = $params; } } @@ -478,11 +474,11 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return bool true if CSRF check passed */ public function passesCSRFCheck(): bool { - if($this->csrfTokenManager === null) { + if ($this->csrfTokenManager === null) { return false; } - if(!$this->passesStrictCookieCheck()) { + if (!$this->passesStrictCookieCheck()) { return false; } @@ -510,7 +506,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { if ($this->getHeader('OCS-APIREQUEST')) { return false; } - if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) { + if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) { return false; } @@ -535,7 +531,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { protected function getProtectedCookieName(string $name): string { $cookieParams = $this->getCookieParams(); $prefix = ''; - if($cookieParams['secure'] === true && $cookieParams['path'] === '/') { + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { $prefix = '__Host-'; } @@ -550,12 +546,12 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @since 9.1.0 */ public function passesStrictCookieCheck(): bool { - if(!$this->cookieCheckRequired()) { + if (!$this->cookieCheckRequired()) { return true; } $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict'); - if($this->getCookie($cookieName) === 'true' + if ($this->getCookie($cookieName) === 'true' && $this->passesLaxCookieCheck()) { return true; } @@ -570,12 +566,12 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @since 9.1.0 */ public function passesLaxCookieCheck(): bool { - if(!$this->cookieCheckRequired()) { + if (!$this->cookieCheckRequired()) { return true; } $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax'); - if($this->getCookie($cookieName) === 'true') { + if ($this->getCookie($cookieName) === 'true') { return true; } return false; @@ -588,11 +584,11 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return string */ public function getId(): string { - if(isset($this->server['UNIQUE_ID'])) { + if (isset($this->server['UNIQUE_ID'])) { return $this->server['UNIQUE_ID']; } - if(empty($this->requestId)) { + if (empty($this->requestId)) { $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS; $this->requestId = $this->secureRandom->generate(20, $validChars); } @@ -649,15 +645,15 @@ class Request implements \ArrayAccess, \Countable, IRequest { $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : ''; $trustedProxies = $this->config->getSystemValue('trusted_proxies', []); - if(\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) { + if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) { $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [ 'HTTP_X_FORWARDED_FOR' // only have one default, so we cannot ship an insecure product out of the box ]); - foreach($forwardedForHeaders as $header) { - if(isset($this->server[$header])) { - foreach(explode(',', $this->server[$header]) as $IP) { + foreach ($forwardedForHeaders as $header) { + if (isset($this->server[$header])) { + foreach (explode(',', $this->server[$header]) as $IP) { $IP = trim($IP); if (filter_var($IP, FILTER_VALIDATE_IP) !== false) { return $IP; @@ -688,7 +684,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @return string Server protocol (http or https) */ public function getServerProtocol(): string { - if($this->config->getSystemValue('overwriteprotocol') !== '' + if ($this->config->getSystemValue('overwriteprotocol') !== '' && $this->isOverwriteCondition('protocol')) { return $this->config->getSystemValue('overwriteprotocol'); } @@ -734,7 +730,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { 'HTTP/2', ]; - if(\in_array($claimedProtocol, $validProtocols, true)) { + if (\in_array($claimedProtocol, $validProtocols, true)) { return $claimedProtocol; } @@ -748,7 +744,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { */ public function getRequestUri(): string { $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; - if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) { + if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) { $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME'])); } return $uri; @@ -776,7 +772,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { // FIXME: Sabre does not really belong here list($path, $name) = \Sabre\Uri\split($scriptName); if (!empty($path)) { - if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) { + if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) { $pathInfo = substr($pathInfo, \strlen($path)); } else { throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')"); @@ -792,7 +788,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { if ($name !== '' && strpos($pathInfo, $name) === 0) { $pathInfo = substr($pathInfo, \strlen($name)); } - if($pathInfo === false || $pathInfo === '/'){ + if ($pathInfo === false || $pathInfo === '/') { return ''; } else { return $pathInfo; @@ -810,7 +806,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { $pathInfo = rawurldecode($pathInfo); $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']); - switch($encoding) { + switch ($encoding) { case 'ISO-8859-1': $pathInfo = utf8_encode($pathInfo); } @@ -921,7 +917,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { * isn't met */ private function getOverwriteHost() { - if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) { + if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) { return $this->config->getSystemValue('overwritehost'); } return null; diff --git a/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php b/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php index 605422ffefe..b9f238eecb3 100644 --- a/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php +++ b/lib/private/AppFramework/Middleware/AdditionalScriptsMiddleware.php @@ -66,5 +66,4 @@ class AdditionalScriptsMiddleware extends Middleware { return $response; } - } diff --git a/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php b/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php index 47b9a62af81..388e86c1e15 100644 --- a/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php +++ b/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php @@ -91,7 +91,7 @@ class MiddlewareDispatcher { // we need to count so that we know which middlewares we have to ask in // case there is an exception $middlewareCount = \count($this->middlewares); - for($i = 0; $i < $middlewareCount; $i++){ + for ($i = 0; $i < $middlewareCount; $i++) { $this->middlewareCounter++; $middleware = $this->middlewares[$i]; $middleware->beforeController($controller, $methodName); @@ -115,11 +115,11 @@ class MiddlewareDispatcher { * @throws \Exception the passed in exception if it can't handle it */ public function afterException(Controller $controller, string $methodName, \Exception $exception): Response { - for($i=$this->middlewareCounter-1; $i>=0; $i--){ + for ($i=$this->middlewareCounter-1; $i>=0; $i--) { $middleware = $this->middlewares[$i]; try { return $middleware->afterException($controller, $methodName, $exception); - } catch(\Exception $exception){ + } catch (\Exception $exception) { continue; } } @@ -138,7 +138,7 @@ class MiddlewareDispatcher { * @return Response a Response object */ public function afterController(Controller $controller, string $methodName, Response $response): Response { - for($i= \count($this->middlewares)-1; $i>=0; $i--){ + for ($i= \count($this->middlewares)-1; $i>=0; $i--) { $middleware = $this->middlewares[$i]; $response = $middleware->afterController($controller, $methodName, $response); } @@ -157,11 +157,10 @@ class MiddlewareDispatcher { * @return string the output that should be printed */ public function beforeOutput(Controller $controller, string $methodName, string $output): string { - for($i= \count($this->middlewares)-1; $i>=0; $i--){ + for ($i= \count($this->middlewares)-1; $i>=0; $i--) { $middleware = $this->middlewares[$i]; $output = $middleware->beforeOutput($controller, $methodName, $output); } return $output; } - } diff --git a/lib/private/AppFramework/Middleware/OCSMiddleware.php b/lib/private/AppFramework/Middleware/OCSMiddleware.php index fe0f58c1ab5..875c743e972 100644 --- a/lib/private/AppFramework/Middleware/OCSMiddleware.php +++ b/lib/private/AppFramework/Middleware/OCSMiddleware.php @@ -102,7 +102,6 @@ class OCSMiddleware extends Middleware { if ($controller instanceof OCSController && !($response instanceof BaseResponse)) { if ($response->getStatus() === Http::STATUS_UNAUTHORIZED || $response->getStatus() === Http::STATUS_FORBIDDEN) { - $message = ''; if ($response instanceof JSONResponse) { /** @var DataResponse $response */ @@ -145,7 +144,7 @@ class OCSMiddleware extends Middleware { $format = $this->request->getParam('format'); // if none is given try the first Accept header - if($format === null) { + if ($format === null) { $headers = $this->request->getHeader('Accept'); $format = $controller->getResponderByHTTPHeader($headers, 'xml'); } diff --git a/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php b/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php index cd6337470b9..b362a38bc74 100644 --- a/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php +++ b/lib/private/AppFramework/Middleware/PublicShare/Exceptions/NeedAuthenticationException.php @@ -24,5 +24,4 @@ namespace OC\AppFramework\Middleware\PublicShare\Exceptions; class NeedAuthenticationException extends \Exception { - } diff --git a/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php b/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php index b6e2611179f..4b2dd25a257 100644 --- a/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php +++ b/lib/private/AppFramework/Middleware/PublicShare/PublicShareMiddleware.php @@ -89,7 +89,6 @@ class PublicShareMiddleware extends Middleware { } throw new NotFoundException(); - } public function afterException($controller, $methodName, \Exception $exception) { @@ -123,7 +122,7 @@ class PublicShareMiddleware extends Middleware { } // Check whether public sharing is enabled - if($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { + if ($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { return false; } diff --git a/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php b/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php index 46c33083e42..c2d1d7783ed 100644 --- a/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php @@ -63,7 +63,7 @@ class BruteForceMiddleware extends Middleware { public function beforeController($controller, $methodName) { parent::beforeController($controller, $methodName); - if($this->reflector->hasAnnotation('BruteForceProtection')) { + if ($this->reflector->hasAnnotation('BruteForceProtection')) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $this->throttler->sleepDelay($this->request->getRemoteAddress(), $action); } @@ -73,7 +73,7 @@ class BruteForceMiddleware extends Middleware { * {@inheritDoc} */ public function afterController($controller, $methodName, Response $response) { - if($this->reflector->hasAnnotation('BruteForceProtection') && $response->isThrottled()) { + if ($this->reflector->hasAnnotation('BruteForceProtection') && $response->isThrottled()) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $ip = $this->request->getRemoteAddress(); $this->throttler->sleepDelay($ip, $action); diff --git a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php index acfbab25ed4..af6d3de6570 100644 --- a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php @@ -84,7 +84,7 @@ class CORSMiddleware extends Middleware { // ensure that @CORS annotated API routes are not used in conjunction // with session authentication since this enables CSRF attack vectors if ($this->reflector->hasAnnotation('CORS') && - !$this->reflector->hasAnnotation('PublicPage')) { + !$this->reflector->hasAnnotation('PublicPage')) { $user = $this->request->server['PHP_AUTH_USER']; $pass = $this->request->server['PHP_AUTH_PW']; @@ -113,13 +113,13 @@ class CORSMiddleware extends Middleware { public function afterController($controller, $methodName, Response $response) { // only react if its a CORS request and if the request sends origin and - if(isset($this->request->server['HTTP_ORIGIN']) && + if (isset($this->request->server['HTTP_ORIGIN']) && $this->reflector->hasAnnotation('CORS')) { // allow credentials headers must not be true or CSRF is possible // otherwise - foreach($response->getHeaders() as $header => $value) { - if(strtolower($header) === 'access-control-allow-credentials' && + foreach ($response->getHeaders() as $header => $value) { + if (strtolower($header) === 'access-control-allow-credentials' && strtolower(trim($value)) === 'true') { $msg = 'Access-Control-Allow-Credentials must not be '. 'set to true in order to prevent CSRF'; @@ -144,9 +144,9 @@ class CORSMiddleware extends Middleware { * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception) { - if($exception instanceof SecurityException){ + if ($exception instanceof SecurityException) { $response = new JSONResponse(['message' => $exception->getMessage()]); - if($exception->getCode() !== 0) { + if ($exception->getCode() !== 0) { $response->setStatus($exception->getCode()); } else { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); @@ -156,5 +156,4 @@ class CORSMiddleware extends Middleware { throw $exception; } - } diff --git a/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php b/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php index 3b9723cb6b9..057aa1529dc 100644 --- a/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/CSPMiddleware.php @@ -71,7 +71,7 @@ class CSPMiddleware extends Middleware { $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy(); $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy); - if($this->cspNonceManager->browserSupportsCspV3()) { + if ($this->cspNonceManager->browserSupportsCspV3()) { $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue()); } diff --git a/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php b/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php index 46673a7e5ee..934cae991b4 100644 --- a/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php +++ b/lib/private/AppFramework/Middleware/Security/Exceptions/ReloadExecutionException.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\AppFramework\Middleware\Security\Exceptions; class ReloadExecutionException extends SecurityException { - } diff --git a/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php b/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php index e55f8e3f50a..bfa4116d12e 100644 --- a/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php +++ b/lib/private/AppFramework/Middleware/Security/Exceptions/SecurityException.php @@ -30,4 +30,5 @@ namespace OC\AppFramework\Middleware\Security\Exceptions; * * @package OC\AppFramework\Middleware\Security\Exceptions */ -class SecurityException extends \Exception {} +class SecurityException extends \Exception { +} diff --git a/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php b/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php index c7bf8e2c947..2a7cf982ff8 100644 --- a/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php @@ -86,7 +86,7 @@ class RateLimitingMiddleware extends Middleware { $userLimit = $this->reflector->getAnnotationParameter('UserRateThrottle', 'limit'); $userPeriod = $this->reflector->getAnnotationParameter('UserRateThrottle', 'period'); $rateLimitIdentifier = get_class($controller) . '::' . $methodName; - if($userLimit !== '' && $userPeriod !== '' && $this->userSession->isLoggedIn()) { + if ($userLimit !== '' && $userPeriod !== '' && $this->userSession->isLoggedIn()) { $this->limiter->registerUserRequest( $rateLimitIdentifier, $userLimit, @@ -107,7 +107,7 @@ class RateLimitingMiddleware extends Middleware { * {@inheritDoc} */ public function afterException($controller, $methodName, \Exception $exception) { - if($exception instanceof RateLimitExceededException) { + if ($exception instanceof RateLimitExceededException) { if (stripos($this->request->getHeader('Accept'),'html') === false) { $response = new JSONResponse( [ @@ -116,7 +116,7 @@ class RateLimitingMiddleware extends Middleware { $exception->getCode() ); } else { - $response = new TemplateResponse( + $response = new TemplateResponse( 'core', '403', [ @@ -124,7 +124,7 @@ class RateLimitingMiddleware extends Middleware { ], 'guest' ); - $response->setStatus($exception->getCode()); + $response->setStatus($exception->getCode()); } return $response; diff --git a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php index af34ed57182..12b0ef4e27a 100644 --- a/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php @@ -65,6 +65,4 @@ class ReloadExecutionMiddleware extends Middleware { return parent::afterException($controller, $methodName, $exception); } - - } diff --git a/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php b/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php index 5519b8705d9..70d4d4b88df 100644 --- a/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SameSiteCookieMiddleware.php @@ -87,11 +87,11 @@ class SameSiteCookieMiddleware extends Middleware { // Append __Host to the cookie if it meets the requirements $cookiePrefix = ''; - if($cookieParams['secure'] === true && $cookieParams['path'] === '/') { + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { $cookiePrefix = '__Host-'; } - foreach($policies as $policy) { + foreach ($policies as $policy) { header( sprintf( 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', diff --git a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php index 0ae2d37b374..5eb1d7f30be 100644 --- a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php @@ -137,17 +137,17 @@ class SecurityMiddleware extends Middleware { // security checks $isPublicPage = $this->reflector->hasAnnotation('PublicPage'); - if(!$isPublicPage) { - if(!$this->isLoggedIn) { + if (!$isPublicPage) { + if (!$this->isLoggedIn) { throw new NotLoggedInException(); } - if($this->reflector->hasAnnotation('SubAdminRequired') + if ($this->reflector->hasAnnotation('SubAdminRequired') && !$this->isSubAdmin && !$this->isAdminUser) { throw new NotAdminException($this->l10n->t('Logged in user must be an admin or sub admin')); } - if(!$this->reflector->hasAnnotation('SubAdminRequired') + if (!$this->reflector->hasAnnotation('SubAdminRequired') && !$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) { throw new NotAdminException($this->l10n->t('Logged in user must be an admin')); @@ -155,14 +155,14 @@ class SecurityMiddleware extends Middleware { } // Check for strict cookie requirement - if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) { - if(!$this->request->passesStrictCookieCheck()) { + if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) { + if (!$this->request->passesStrictCookieCheck()) { throw new StrictCookieMissingException(); } } // CSRF check - also registers the CSRF token since the session may be closed later Util::callRegister(); - if(!$this->reflector->hasAnnotation('NoCSRFRequired')) { + if (!$this->reflector->hasAnnotation('NoCSRFRequired')) { /* * Only allow the CSRF check to fail on OCS Requests. This kind of * hacks around that we have no full token auth in place yet and we @@ -171,7 +171,7 @@ class SecurityMiddleware extends Middleware { * Additionally we allow Bearer authenticated requests to pass on OCS routes. * This allows oauth apps (e.g. moodle) to use the OCS endpoints */ - if(!$this->request->passesCSRFCheck() && !( + if (!$this->request->passesCSRFCheck() && !( $controller instanceof OCSController && ( $this->request->getHeader('OCS-APIREQUEST') === 'true' || strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0 @@ -209,8 +209,8 @@ class SecurityMiddleware extends Middleware { * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception): Response { - if($exception instanceof SecurityException) { - if($exception instanceof StrictCookieMissingException) { + if ($exception instanceof SecurityException) { + if ($exception instanceof StrictCookieMissingException) { return new RedirectResponse(\OC::$WEBROOT); } if (stripos($this->request->getHeader('Accept'),'html') === false) { @@ -219,7 +219,7 @@ class SecurityMiddleware extends Middleware { $exception->getCode() ); } else { - if($exception instanceof NotLoggedInException) { + if ($exception instanceof NotLoggedInException) { $params = []; if (isset($this->request->server['REQUEST_URI'])) { $params['redirect_url'] = $this->request->server['REQUEST_URI']; @@ -241,5 +241,4 @@ class SecurityMiddleware extends Middleware { throw $exception; } - } diff --git a/lib/private/AppFramework/Middleware/SessionMiddleware.php b/lib/private/AppFramework/Middleware/SessionMiddleware.php index d2787dde745..88b85468252 100644 --- a/lib/private/AppFramework/Middleware/SessionMiddleware.php +++ b/lib/private/AppFramework/Middleware/SessionMiddleware.php @@ -69,5 +69,4 @@ class SessionMiddleware extends Middleware { } return $response; } - } diff --git a/lib/private/AppFramework/OCS/BaseResponse.php b/lib/private/AppFramework/OCS/BaseResponse.php index 6c49a685985..55410c8910b 100644 --- a/lib/private/AppFramework/OCS/BaseResponse.php +++ b/lib/private/AppFramework/OCS/BaseResponse.php @@ -30,7 +30,7 @@ use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\Response; -abstract class BaseResponse extends Response { +abstract class BaseResponse extends Response { /** @var array */ protected $data; @@ -118,7 +118,6 @@ abstract class BaseResponse extends Response { $this->toXML($response, $writer); $writer->endDocument(); return $writer->outputMemory(true); - } /** diff --git a/lib/private/AppFramework/OCS/V2Response.php b/lib/private/AppFramework/OCS/V2Response.php index 693d58a4d43..1d4eb741210 100644 --- a/lib/private/AppFramework/OCS/V2Response.php +++ b/lib/private/AppFramework/OCS/V2Response.php @@ -35,7 +35,6 @@ class V2Response extends BaseResponse { * @return int */ public function getStatus() { - $status = parent::getStatus(); if ($status === API::RESPOND_UNAUTHORISED) { return Http::STATUS_UNAUTHORIZED; diff --git a/lib/private/AppFramework/Routing/RouteConfig.php b/lib/private/AppFramework/Routing/RouteConfig.php index 999412979b0..eb9991fbe69 100644 --- a/lib/private/AppFramework/Routing/RouteConfig.php +++ b/lib/private/AppFramework/Routing/RouteConfig.php @@ -125,13 +125,13 @@ class RouteConfig { // optionally register requirements for route. This is used to // tell the route parser how url parameters should be matched - if(array_key_exists('requirements', $ocsRoute)) { + if (array_key_exists('requirements', $ocsRoute)) { $router->requirements($ocsRoute['requirements']); } // optionally register defaults for route. This is used to // tell the route parser how url parameters should be default valued - if(array_key_exists('defaults', $ocsRoute)) { + if (array_key_exists('defaults', $ocsRoute)) { $router->defaults($ocsRoute['defaults']); } } @@ -183,13 +183,13 @@ class RouteConfig { // optionally register requirements for route. This is used to // tell the route parser how url parameters should be matched - if(array_key_exists('requirements', $simpleRoute)) { + if (array_key_exists('requirements', $simpleRoute)) { $router->requirements($simpleRoute['requirements']); } // optionally register defaults for route. This is used to // tell the route parser how url parameters should be default valued - if(array_key_exists('defaults', $simpleRoute)) { + if (array_key_exists('defaults', $simpleRoute)) { $router->defaults($simpleRoute['defaults']); } } @@ -220,7 +220,7 @@ class RouteConfig { $root = $config['root'] ?? '/apps/' . $this->appName; // the url parameter used as id to the resource - foreach($actions as $action) { + foreach ($actions as $action) { $url = $root . $config['url']; $method = $action['name']; $verb = strtoupper($action['verb'] ?? 'GET'); @@ -270,7 +270,7 @@ class RouteConfig { foreach ($resources as $resource => $config) { // the url parameter used as id to the resource - foreach($actions as $action) { + foreach ($actions as $action) { $url = $config['url']; $method = $action['name']; $verb = strtoupper($action['verb'] ?? 'GET'); diff --git a/lib/private/AppFramework/Utility/ControllerMethodReflector.php b/lib/private/AppFramework/Utility/ControllerMethodReflector.php index 31f1892772f..2b7420cd41b 100644 --- a/lib/private/AppFramework/Utility/ControllerMethodReflector.php +++ b/lib/private/AppFramework/Utility/ControllerMethodReflector.php @@ -82,7 +82,7 @@ class ControllerMethodReflector implements IControllerMethodReflector { } $default = null; - if($param->isOptional()) { + if ($param->isOptional()) { $default = $param->getDefaultValue(); } $this->parameters[$param->name] = $default; @@ -97,7 +97,7 @@ class ControllerMethodReflector implements IControllerMethodReflector { * would return int or null if not existing */ public function getType(string $parameter) { - if(array_key_exists($parameter, $this->types)) { + if (array_key_exists($parameter, $this->types)) { return $this->types[$parameter]; } @@ -128,7 +128,7 @@ class ControllerMethodReflector implements IControllerMethodReflector { * @return string */ public function getAnnotationParameter(string $name, string $key): string { - if(isset($this->annotations[$name][$key])) { + if (isset($this->annotations[$name][$key])) { return $this->annotations[$name][$key]; } diff --git a/lib/private/AppFramework/Utility/SimpleContainer.php b/lib/private/AppFramework/Utility/SimpleContainer.php index 1703df3ea73..44bda1c3e6b 100644 --- a/lib/private/AppFramework/Utility/SimpleContainer.php +++ b/lib/private/AppFramework/Utility/SimpleContainer.php @@ -102,7 +102,7 @@ class SimpleContainer extends Container implements IContainer { throw new QueryException($baseMsg . ' Class can not be instantiated'); } - } catch(ReflectionException $e) { + } catch (ReflectionException $e) { throw new QueryException($baseMsg . ' ' . $e->getMessage()); } } @@ -140,7 +140,7 @@ class SimpleContainer extends Container implements IContainer { */ public function registerService($name, Closure $closure, $shared = true) { $name = $this->sanitizeName($name); - if (isset($this[$name])) { + if (isset($this[$name])) { unset($this[$name]); } if ($shared) { diff --git a/lib/private/AppFramework/Utility/TimeFactory.php b/lib/private/AppFramework/Utility/TimeFactory.php index b3d5ec831d1..30ab9bd3098 100644 --- a/lib/private/AppFramework/Utility/TimeFactory.php +++ b/lib/private/AppFramework/Utility/TimeFactory.php @@ -52,5 +52,4 @@ class TimeFactory implements ITimeFactory { public function getDateTime(string $time = 'now', \DateTimeZone $timezone = null): \DateTime { return new \DateTime($time, $timezone); } - } diff --git a/lib/private/Archive/Archive.php b/lib/private/Archive/Archive.php index 94956561c3e..5150e6ddee3 100644 --- a/lib/private/Archive/Archive.php +++ b/lib/private/Archive/Archive.php @@ -123,15 +123,15 @@ abstract class Archive { */ public function addRecursive($path, $source) { $dh = opendir($source); - if(is_resource($dh)) { + if (is_resource($dh)) { $this->addFolder($path); while (($file = readdir($dh)) !== false) { - if($file === '.' || $file === '..') { + if ($file === '.' || $file === '..') { continue; } - if(is_dir($source.'/'.$file)) { + if (is_dir($source.'/'.$file)) { $this->addRecursive($path.'/'.$file, $source.'/'.$file); - }else{ + } else { $this->addFile($path.'/'.$file, $source.'/'.$file); } } diff --git a/lib/private/Archive/ZIP.php b/lib/private/Archive/ZIP.php index cca6fd68c4e..31aea420a3d 100644 --- a/lib/private/Archive/ZIP.php +++ b/lib/private/Archive/ZIP.php @@ -35,7 +35,7 @@ namespace OC\Archive; use Icewind\Streams\CallbackWrapper; use OCP\ILogger; -class ZIP extends Archive{ +class ZIP extends Archive { /** * @var \ZipArchive zip */ @@ -48,8 +48,8 @@ class ZIP extends Archive{ public function __construct($source) { $this->path=$source; $this->zip=new \ZipArchive(); - if($this->zip->open($source, \ZipArchive::CREATE)) { - }else{ + if ($this->zip->open($source, \ZipArchive::CREATE)) { + } else { \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN); } } @@ -68,12 +68,12 @@ class ZIP extends Archive{ * @return bool */ public function addFile($path, $source='') { - if($source and $source[0]=='/' and file_exists($source)) { + if ($source and $source[0]=='/' and file_exists($source)) { $result=$this->zip->addFile($source, $path); - }else{ + } else { $result=$this->zip->addFromString($path, $source); } - if($result) { + if ($result) { $this->zip->close();//close and reopen to save the zip $this->zip->open($this->path); } @@ -116,9 +116,9 @@ class ZIP extends Archive{ $files=$this->getFiles(); $folderContent=[]; $pathLength=strlen($path); - foreach($files as $file) { - if(substr($file, 0, $pathLength)==$path and $file!=$path) { - if(strrpos(substr($file, 0, -1), '/')<=$pathLength) { + foreach ($files as $file) { + if (substr($file, 0, $pathLength)==$path and $file!=$path) { + if (strrpos(substr($file, 0, -1), '/')<=$pathLength) { $folderContent[]=substr($file, $pathLength); } } @@ -132,7 +132,7 @@ class ZIP extends Archive{ public function getFiles() { $fileCount=$this->zip->numFiles; $files=[]; - for($i=0;$i<$fileCount;$i++) { + for ($i=0;$i<$fileCount;$i++) { $files[]=$this->zip->getNameIndex($i); } return $files; @@ -177,9 +177,9 @@ class ZIP extends Archive{ * @return bool */ public function remove($path) { - if($this->fileExists($path.'/')) { + if ($this->fileExists($path.'/')) { return $this->zip->deleteName($path.'/'); - }else{ + } else { return $this->zip->deleteName($path); } } @@ -190,19 +190,19 @@ class ZIP extends Archive{ * @return resource */ public function getStream($path, $mode) { - if($mode=='r' or $mode=='rb') { + if ($mode=='r' or $mode=='rb') { return $this->zip->getStream($path); } else { //since we can't directly get a writable stream, //make a temp copy of the file and put it back //in the archive when the stream is closed - if(strrpos($path, '.')!==false) { + if (strrpos($path, '.')!==false) { $ext=substr($path, strrpos($path, '.')); - }else{ + } else { $ext=''; } $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext); - if($this->fileExists($path)) { + if ($this->fileExists($path)) { $this->extractFile($path, $tmpFile); } $handle = fopen($tmpFile, $mode); @@ -225,9 +225,9 @@ class ZIP extends Archive{ * @return string */ private function stripPath($path) { - if(!$path || $path[0]=='/') { + if (!$path || $path[0]=='/') { return substr($path, 1); - }else{ + } else { return $path; } } diff --git a/lib/private/Authentication/Events/ARemoteWipeEvent.php b/lib/private/Authentication/Events/ARemoteWipeEvent.php index 111c6cfeeef..8d28cc5c783 100644 --- a/lib/private/Authentication/Events/ARemoteWipeEvent.php +++ b/lib/private/Authentication/Events/ARemoteWipeEvent.php @@ -42,5 +42,4 @@ abstract class ARemoteWipeEvent extends Event { public function getToken(): IToken { return $this->token; } - } diff --git a/lib/private/Authentication/Events/RemoteWipeFinished.php b/lib/private/Authentication/Events/RemoteWipeFinished.php index 0a33ebf635f..d50b7d28077 100644 --- a/lib/private/Authentication/Events/RemoteWipeFinished.php +++ b/lib/private/Authentication/Events/RemoteWipeFinished.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Authentication\Events; class RemoteWipeFinished extends ARemoteWipeEvent { - } diff --git a/lib/private/Authentication/Events/RemoteWipeStarted.php b/lib/private/Authentication/Events/RemoteWipeStarted.php index 565c9660de6..89b560511a7 100644 --- a/lib/private/Authentication/Events/RemoteWipeStarted.php +++ b/lib/private/Authentication/Events/RemoteWipeStarted.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Authentication\Events; class RemoteWipeStarted extends ARemoteWipeEvent { - } diff --git a/lib/private/Authentication/Exceptions/InvalidProviderException.php b/lib/private/Authentication/Exceptions/InvalidProviderException.php index 090150e4a33..970096540c4 100644 --- a/lib/private/Authentication/Exceptions/InvalidProviderException.php +++ b/lib/private/Authentication/Exceptions/InvalidProviderException.php @@ -30,9 +30,7 @@ use Exception; use Throwable; class InvalidProviderException extends Exception { - public function __construct(string $providerId, Throwable $previous = null) { parent::__construct("The provider '$providerId' does not exist'", 0, $previous); } - } diff --git a/lib/private/Authentication/Exceptions/InvalidTokenException.php b/lib/private/Authentication/Exceptions/InvalidTokenException.php index badcbba28e2..efc6096da88 100644 --- a/lib/private/Authentication/Exceptions/InvalidTokenException.php +++ b/lib/private/Authentication/Exceptions/InvalidTokenException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class InvalidTokenException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/LoginRequiredException.php b/lib/private/Authentication/Exceptions/LoginRequiredException.php index 1c55e122d01..9d9ce055788 100644 --- a/lib/private/Authentication/Exceptions/LoginRequiredException.php +++ b/lib/private/Authentication/Exceptions/LoginRequiredException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class LoginRequiredException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php b/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php index 05815cab9f4..02ddd06020d 100644 --- a/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php +++ b/lib/private/Authentication/Exceptions/PasswordLoginForbiddenException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class PasswordLoginForbiddenException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/PasswordlessTokenException.php b/lib/private/Authentication/Exceptions/PasswordlessTokenException.php index e5ba5d87ad5..5c59dd35366 100644 --- a/lib/private/Authentication/Exceptions/PasswordlessTokenException.php +++ b/lib/private/Authentication/Exceptions/PasswordlessTokenException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class PasswordlessTokenException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php b/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php index b4691a7a0c4..2850d3de7e1 100644 --- a/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php +++ b/lib/private/Authentication/Exceptions/TokenPasswordExpiredException.php @@ -27,5 +27,4 @@ declare(strict_types=1); namespace OC\Authentication\Exceptions; class TokenPasswordExpiredException extends ExpiredTokenException { - } diff --git a/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php b/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php index c9c5a03e021..6db87b3516c 100644 --- a/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php +++ b/lib/private/Authentication/Exceptions/TwoFactorAuthRequiredException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class TwoFactorAuthRequiredException extends Exception { - } diff --git a/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php b/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php index 9c1c2a9a441..878bf59e4e9 100644 --- a/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php +++ b/lib/private/Authentication/Exceptions/UserAlreadyLoggedInException.php @@ -25,5 +25,4 @@ namespace OC\Authentication\Exceptions; use Exception; class UserAlreadyLoggedInException extends Exception { - } diff --git a/lib/private/Authentication/Listeners/LoginFailedListener.php b/lib/private/Authentication/Listeners/LoginFailedListener.php index 8086194eab3..d56e24cce70 100644 --- a/lib/private/Authentication/Listeners/LoginFailedListener.php +++ b/lib/private/Authentication/Listeners/LoginFailedListener.php @@ -57,9 +57,8 @@ class LoginFailedListener implements IEventListener { 'preLoginNameUsedAsUserName', ['uid' => &$uid] ); - if($this->userManager->userExists($uid)) { + if ($this->userManager->userExists($uid)) { $this->dispatcher->dispatchTyped(new LoginFailedEvent($uid)); } } - } diff --git a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php index 5acd228b133..0ab2dcf4837 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeActivityListener.php @@ -76,5 +76,4 @@ class RemoteWipeActivityListener implements IEventListener { ]); } } - } diff --git a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php index 6c0ca16859b..799c4ea4cf5 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeEmailListener.php @@ -170,5 +170,4 @@ class RemoteWipeEmailListener implements IEventListener { return $message; } - } diff --git a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php index 4b021d67c75..831107a05cd 100644 --- a/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php +++ b/lib/private/Authentication/Listeners/RemoteWipeNotificationsListener.php @@ -68,5 +68,4 @@ class RemoteWipeNotificationsListener implements IEventListener { ]); $this->notificationManager->notify($notification); } - } diff --git a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php index dc0be4e2e9b..c8f2da82db6 100644 --- a/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php +++ b/lib/private/Authentication/Listeners/UserDeletedStoreCleanupListener.php @@ -47,5 +47,4 @@ class UserDeletedStoreCleanupListener implements IEventListener { $this->registry->deleteUserData($event->getUser()); } - } diff --git a/lib/private/Authentication/Login/ALoginCommand.php b/lib/private/Authentication/Login/ALoginCommand.php index e27b0db173e..8ad162842bf 100644 --- a/lib/private/Authentication/Login/ALoginCommand.php +++ b/lib/private/Authentication/Login/ALoginCommand.php @@ -44,5 +44,4 @@ abstract class ALoginCommand { } public abstract function process(LoginData $loginData): LoginResult; - } diff --git a/lib/private/Authentication/Login/Chain.php b/lib/private/Authentication/Login/Chain.php index c86a932d6b6..1fc94fe9637 100644 --- a/lib/private/Authentication/Login/Chain.php +++ b/lib/private/Authentication/Login/Chain.php @@ -107,5 +107,4 @@ class Chain { return $chain->process($loginData); } - } diff --git a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php index 9f4e970c9cc..f4e1ad11dd0 100644 --- a/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php +++ b/lib/private/Authentication/Login/ClearLostPasswordTokensCommand.php @@ -48,5 +48,4 @@ class ClearLostPasswordTokensCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/CompleteLoginCommand.php b/lib/private/Authentication/Login/CompleteLoginCommand.php index 210b3ba9a88..d0cddba595c 100644 --- a/lib/private/Authentication/Login/CompleteLoginCommand.php +++ b/lib/private/Authentication/Login/CompleteLoginCommand.php @@ -47,5 +47,4 @@ class CompleteLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/EmailLoginCommand.php b/lib/private/Authentication/Login/EmailLoginCommand.php index c281ddc6737..24b5a00196b 100644 --- a/lib/private/Authentication/Login/EmailLoginCommand.php +++ b/lib/private/Authentication/Login/EmailLoginCommand.php @@ -57,5 +57,4 @@ class EmailLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php index 4c4b37b0801..1d33f103fdf 100644 --- a/lib/private/Authentication/Login/FinishRememberedLoginCommand.php +++ b/lib/private/Authentication/Login/FinishRememberedLoginCommand.php @@ -43,5 +43,4 @@ class FinishRememberedLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/LoggedInCheckCommand.php b/lib/private/Authentication/Login/LoggedInCheckCommand.php index 5701f2970a8..5fd1f1af4ba 100644 --- a/lib/private/Authentication/Login/LoggedInCheckCommand.php +++ b/lib/private/Authentication/Login/LoggedInCheckCommand.php @@ -59,5 +59,4 @@ class LoggedInCheckCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/LoginData.php b/lib/private/Authentication/Login/LoginData.php index ec8ebdbab46..162e0f362d8 100644 --- a/lib/private/Authentication/Login/LoginData.php +++ b/lib/private/Authentication/Login/LoginData.php @@ -117,5 +117,4 @@ class LoginData { public function isRememberLogin(): bool { return $this->rememberLogin; } - } diff --git a/lib/private/Authentication/Login/LoginResult.php b/lib/private/Authentication/Login/LoginResult.php index 273e0ee8d5c..60228307135 100644 --- a/lib/private/Authentication/Login/LoginResult.php +++ b/lib/private/Authentication/Login/LoginResult.php @@ -79,5 +79,4 @@ class LoginResult { public function getErrorMessage(): ?string { return $this->errorMessage; } - } diff --git a/lib/private/Authentication/Login/SetUserTimezoneCommand.php b/lib/private/Authentication/Login/SetUserTimezoneCommand.php index d3599880228..0029f2f1677 100644 --- a/lib/private/Authentication/Login/SetUserTimezoneCommand.php +++ b/lib/private/Authentication/Login/SetUserTimezoneCommand.php @@ -58,5 +58,4 @@ class SetUserTimezoneCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/TwoFactorCommand.php b/lib/private/Authentication/Login/TwoFactorCommand.php index 2c3d2fbf2c4..86b85c83fd0 100644 --- a/lib/private/Authentication/Login/TwoFactorCommand.php +++ b/lib/private/Authentication/Login/TwoFactorCommand.php @@ -91,5 +91,4 @@ class TwoFactorCommand extends ALoginCommand { $this->urlGenerator->linkToRoute($url, $urlParams) ); } - } diff --git a/lib/private/Authentication/Login/UidLoginCommand.php b/lib/private/Authentication/Login/UidLoginCommand.php index 76e06fb3e4f..8c9a516c735 100644 --- a/lib/private/Authentication/Login/UidLoginCommand.php +++ b/lib/private/Authentication/Login/UidLoginCommand.php @@ -53,5 +53,4 @@ class UidLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php index 9e89aa086db..efaf5554c21 100644 --- a/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php +++ b/lib/private/Authentication/Login/UpdateLastPasswordConfirmCommand.php @@ -44,5 +44,4 @@ class UpdateLastPasswordConfirmCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/UserDisabledCheckCommand.php b/lib/private/Authentication/Login/UserDisabledCheckCommand.php index 11f2d5f3a90..e33853ef5bd 100644 --- a/lib/private/Authentication/Login/UserDisabledCheckCommand.php +++ b/lib/private/Authentication/Login/UserDisabledCheckCommand.php @@ -56,5 +56,4 @@ class UserDisabledCheckCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/Login/WebAuthnLoginCommand.php b/lib/private/Authentication/Login/WebAuthnLoginCommand.php index d2f613c59be..6aa35d43f93 100644 --- a/lib/private/Authentication/Login/WebAuthnLoginCommand.php +++ b/lib/private/Authentication/Login/WebAuthnLoginCommand.php @@ -45,5 +45,4 @@ class WebAuthnLoginCommand extends ALoginCommand { return $this->processNextOrFinishSuccessfully($loginData); } - } diff --git a/lib/private/Authentication/LoginCredentials/Credentials.php b/lib/private/Authentication/LoginCredentials/Credentials.php index b9542aed354..e4cbdccec50 100644 --- a/lib/private/Authentication/LoginCredentials/Credentials.php +++ b/lib/private/Authentication/LoginCredentials/Credentials.php @@ -67,5 +67,4 @@ class Credentials implements ICredentials { public function getPassword() { return $this->password; } - } diff --git a/lib/private/Authentication/LoginCredentials/Store.php b/lib/private/Authentication/LoginCredentials/Store.php index a16b291f5f5..f4bedd88a18 100644 --- a/lib/private/Authentication/LoginCredentials/Store.php +++ b/lib/private/Authentication/LoginCredentials/Store.php @@ -118,5 +118,4 @@ class Store implements IStore { // If we reach this line, an exception was thrown. throw new CredentialsUnavailableException(); } - } diff --git a/lib/private/Authentication/Token/DefaultToken.php b/lib/private/Authentication/Token/DefaultToken.php index 4af42d07813..7ca05849635 100644 --- a/lib/private/Authentication/Token/DefaultToken.php +++ b/lib/private/Authentication/Token/DefaultToken.php @@ -43,7 +43,6 @@ use OCP\AppFramework\Db\Entity; * @method void setVersion(int $version) */ class DefaultToken extends Entity implements INamedToken { - const VERSION = 1; /** @var string user UID */ diff --git a/lib/private/Authentication/Token/DefaultTokenCleanupJob.php b/lib/private/Authentication/Token/DefaultTokenCleanupJob.php index 25b4aa59a92..0686f40e82f 100644 --- a/lib/private/Authentication/Token/DefaultTokenCleanupJob.php +++ b/lib/private/Authentication/Token/DefaultTokenCleanupJob.php @@ -27,11 +27,9 @@ use OC; use OC\BackgroundJob\Job; class DefaultTokenCleanupJob extends Job { - protected function run($argument) { /* @var $provider IProvider */ $provider = OC::$server->query(IProvider::class); $provider->invalidateOldTokens(); } - } diff --git a/lib/private/Authentication/Token/DefaultTokenMapper.php b/lib/private/Authentication/Token/DefaultTokenMapper.php index 3f11e02d5cd..e51033ed1df 100644 --- a/lib/private/Authentication/Token/DefaultTokenMapper.php +++ b/lib/private/Authentication/Token/DefaultTokenMapper.php @@ -36,7 +36,6 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; class DefaultTokenMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'authtoken'); } @@ -168,5 +167,4 @@ class DefaultTokenMapper extends QBMapper { ->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(DefaultToken::VERSION, IQueryBuilder::PARAM_INT))); $qb->execute(); } - } diff --git a/lib/private/Authentication/Token/DefaultTokenProvider.php b/lib/private/Authentication/Token/DefaultTokenProvider.php index 05e601d78a7..3556cfd24b0 100644 --- a/lib/private/Authentication/Token/DefaultTokenProvider.php +++ b/lib/private/Authentication/Token/DefaultTokenProvider.php @@ -286,7 +286,6 @@ class DefaultTokenProvider implements IProvider { $password = $this->getPassword($token, $oldTokenId); $token->setPassword($this->encryptPassword($password, $newTokenId)); } catch (PasswordlessTokenException $e) { - } $token->setToken($this->hashToken($newTokenId)); diff --git a/lib/private/Authentication/Token/IToken.php b/lib/private/Authentication/Token/IToken.php index e2de2b5fbbd..1f7c736f86b 100644 --- a/lib/private/Authentication/Token/IToken.php +++ b/lib/private/Authentication/Token/IToken.php @@ -30,7 +30,6 @@ namespace OC\Authentication\Token; use JsonSerializable; interface IToken extends JsonSerializable { - const TEMPORARY_TOKEN = 0; const PERMANENT_TOKEN = 1; const WIPE_TOKEN = 2; diff --git a/lib/private/Authentication/Token/IWipeableToken.php b/lib/private/Authentication/Token/IWipeableToken.php index 62293e6933b..efc542faa69 100644 --- a/lib/private/Authentication/Token/IWipeableToken.php +++ b/lib/private/Authentication/Token/IWipeableToken.php @@ -33,5 +33,4 @@ interface IWipeableToken extends IToken { * Mark the token for remote wipe */ public function wipe(): void; - } diff --git a/lib/private/Authentication/Token/Manager.php b/lib/private/Authentication/Token/Manager.php index dddc675a428..073569de0cf 100644 --- a/lib/private/Authentication/Token/Manager.php +++ b/lib/private/Authentication/Token/Manager.php @@ -139,7 +139,7 @@ class Manager implements IProvider { throw $e; } catch (ExpiredTokenException $e) { throw $e; - } catch(InvalidTokenException $e) { + } catch (InvalidTokenException $e) { // No worries we try to convert it to a PublicKey Token } @@ -272,6 +272,4 @@ class Manager implements IProvider { $this->defaultTokenProvider->updatePasswords($uid, $password); $this->publicKeyTokenProvider->updatePasswords($uid, $password); } - - } diff --git a/lib/private/Authentication/Token/PublicKeyToken.php b/lib/private/Authentication/Token/PublicKeyToken.php index 221f286ae05..27eda0b6889 100644 --- a/lib/private/Authentication/Token/PublicKeyToken.php +++ b/lib/private/Authentication/Token/PublicKeyToken.php @@ -47,7 +47,6 @@ use OCP\AppFramework\Db\Entity; * @method bool getPasswordInvalid() */ class PublicKeyToken extends Entity implements INamedToken, IWipeableToken { - const VERSION = 2; /** @var string user UID */ diff --git a/lib/private/Authentication/Token/PublicKeyTokenMapper.php b/lib/private/Authentication/Token/PublicKeyTokenMapper.php index 15a161aef64..e05325fec30 100644 --- a/lib/private/Authentication/Token/PublicKeyTokenMapper.php +++ b/lib/private/Authentication/Token/PublicKeyTokenMapper.php @@ -33,7 +33,6 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; class PublicKeyTokenMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'authtoken'); } diff --git a/lib/private/Authentication/Token/RemoteWipe.php b/lib/private/Authentication/Token/RemoteWipe.php index b1fc757f744..cab68357a01 100644 --- a/lib/private/Authentication/Token/RemoteWipe.php +++ b/lib/private/Authentication/Token/RemoteWipe.php @@ -152,5 +152,4 @@ class RemoteWipe { return true; } - } diff --git a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php index 4e8f9731d94..a5ddad47e01 100644 --- a/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php +++ b/lib/private/Authentication/TwoFactorAuth/Db/ProviderUserAssignmentDao.php @@ -35,7 +35,6 @@ use OCP\IDBConnection; * 2FA providers */ class ProviderUserAssignmentDao { - const TABLE_NAME = 'twofactor_providers'; /** @var IDBConnection */ @@ -90,7 +89,6 @@ class ProviderUserAssignmentDao { ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid))); $updateQuery->execute(); } - } public function deleteByUser(string $uid) { @@ -110,5 +108,4 @@ class ProviderUserAssignmentDao { $deleteQuery->execute(); } - } diff --git a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php index abd0ec7f2e7..c244843454b 100644 --- a/lib/private/Authentication/TwoFactorAuth/EnforcementState.php +++ b/lib/private/Authentication/TwoFactorAuth/EnforcementState.php @@ -82,5 +82,4 @@ class EnforcementState implements JsonSerializable { 'excludedGroups' => $this->excludedGroups, ]; } - } diff --git a/lib/private/Authentication/TwoFactorAuth/Manager.php b/lib/private/Authentication/TwoFactorAuth/Manager.php index 40e6e4082e1..ec414e67938 100644 --- a/lib/private/Authentication/TwoFactorAuth/Manager.php +++ b/lib/private/Authentication/TwoFactorAuth/Manager.php @@ -46,7 +46,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; class Manager { - const SESSION_UID_KEY = 'two_factor_auth_uid'; const SESSION_UID_DONE = 'two_factor_auth_passed'; const REMEMBER_LOGIN = 'two_factor_remember_login'; @@ -158,7 +157,6 @@ class Manager { */ private function fixMissingProviderStates(array $providerStates, array $providers, IUser $user): array { - foreach ($providers as $provider) { if (isset($providerStates[$provider->getId()])) { // All good @@ -384,5 +382,4 @@ class Manager { $this->tokenProvider->invalidateTokenById($userId, $tokenId); } } - } diff --git a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php index 42e5def80de..b06a517ef80 100644 --- a/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php +++ b/lib/private/Authentication/TwoFactorAuth/MandatoryTwoFactor.php @@ -110,6 +110,4 @@ class MandatoryTwoFactor { */ return true; } - - } diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php index b287072dde3..0754679adf1 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderLoader.php @@ -35,7 +35,6 @@ use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\IUser; class ProviderLoader { - const BACKUP_CODES_APP_ID = 'twofactor_backupcodes'; /** @var IAppManager */ @@ -86,5 +85,4 @@ class ProviderLoader { OC_App::loadApp($appId); } } - } diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php index 26c1af0ae17..4d3171e96f7 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderManager.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderManager.php @@ -93,5 +93,4 @@ class ProviderManager { return false; } } - } diff --git a/lib/private/Authentication/TwoFactorAuth/ProviderSet.php b/lib/private/Authentication/TwoFactorAuth/ProviderSet.php index 5b5ac60fd82..c27681c6036 100644 --- a/lib/private/Authentication/TwoFactorAuth/ProviderSet.php +++ b/lib/private/Authentication/TwoFactorAuth/ProviderSet.php @@ -80,5 +80,4 @@ class ProviderSet { public function isProviderMissing(): bool { return $this->providerMissing; } - } diff --git a/lib/private/Authentication/WebAuthn/CredentialRepository.php b/lib/private/Authentication/WebAuthn/CredentialRepository.php index c57af15d2e4..da552b120bf 100644 --- a/lib/private/Authentication/WebAuthn/CredentialRepository.php +++ b/lib/private/Authentication/WebAuthn/CredentialRepository.php @@ -68,7 +68,6 @@ class CredentialRepository implements PublicKeyCredentialSourceRepository { try { $oldEntity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialSource->getPublicKeyCredentialId()); } catch (IMapperException $e) { - } if ($name === null) { @@ -90,5 +89,4 @@ class CredentialRepository implements PublicKeyCredentialSourceRepository { public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, string $name = null): void { $this->saveAndReturnCredentialSource($publicKeyCredentialSource, $name); } - } diff --git a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php index 0b27c78efbd..c9ebf8ce456 100644 --- a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php @@ -88,5 +88,4 @@ class PublicKeyCredentialEntity extends Entity implements JsonSerializable { 'name' => $this->getName(), ]; } - } diff --git a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php index c931ccbb3f0..a78ebee3072 100644 --- a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialMapper.php @@ -31,7 +31,6 @@ use OCP\AppFramework\Db\QBMapper; use OCP\IDBConnection; class PublicKeyCredentialMapper extends QBMapper { - public function __construct(IDBConnection $db) { parent::__construct($db, 'webauthn', PublicKeyCredentialEntity::class); } @@ -82,5 +81,4 @@ class PublicKeyCredentialMapper extends QBMapper { return $this->findEntity($qb); } - } diff --git a/lib/private/Authentication/WebAuthn/Manager.php b/lib/private/Authentication/WebAuthn/Manager.php index e33d0e48e9b..7a2e4fc6b8a 100644 --- a/lib/private/Authentication/WebAuthn/Manager.php +++ b/lib/private/Authentication/WebAuthn/Manager.php @@ -170,7 +170,7 @@ class Manager { } public function startAuthentication(string $uid, string $serverHost): PublicKeyCredentialRequestOptions { - // List of registered PublicKeyCredentialDescriptor classes associated to the user + // List of registered PublicKeyCredentialDescriptor classes associated to the user $registeredPublicKeyCredentialDescriptors = array_map(function (PublicKeyCredentialEntity $entity) { $credential = $entity->toPublicKeyCredentialSource(); return new PublicKeyCredentialDescriptor( @@ -230,7 +230,6 @@ class Manager { $request, $uid ); - } catch (\Throwable $e) { throw $e; } diff --git a/lib/private/Avatar/Avatar.php b/lib/private/Avatar/Avatar.php index 4badc8c43f5..02fc04eae36 100644 --- a/lib/private/Avatar/Avatar.php +++ b/lib/private/Avatar/Avatar.php @@ -300,7 +300,7 @@ abstract class Avatar implements IAvatar { $hash = strtolower($hash); // Already a md5 hash? - if(preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) { + if (preg_match('/^([0-9a-f]{4}-?){8}$/', $hash, $matches) !== 1) { $hash = md5($hash); } diff --git a/lib/private/Avatar/AvatarManager.php b/lib/private/Avatar/AvatarManager.php index 2a4f51f0e1c..3bb0c4077e2 100644 --- a/lib/private/Avatar/AvatarManager.php +++ b/lib/private/Avatar/AvatarManager.php @@ -114,7 +114,7 @@ class AvatarManager implements IAvatarManager { */ public function clearCachedAvatars() { $users = $this->config->getUsersForUserValue('avatar', 'generated', 'true'); - foreach($users as $userId) { + foreach ($users as $userId) { try { $folder = $this->appData->getFolder($userId); $folder->delete(); diff --git a/lib/private/Avatar/UserAvatar.php b/lib/private/Avatar/UserAvatar.php index 485e53c249d..a5da4a278fa 100644 --- a/lib/private/Avatar/UserAvatar.php +++ b/lib/private/Avatar/UserAvatar.php @@ -208,7 +208,7 @@ class UserAvatar extends Avatar { $avatar->delete(); } $this->config->setUserValue($this->user->getUID(), 'avatar', 'generated', 'true'); - if(!$silent) { + if (!$silent) { $this->user->triggerChange('avatar', ''); } } @@ -273,7 +273,6 @@ class UserAvatar extends Avatar { if (!$data = $this->generateAvatarFromSvg($size)) { $data = $this->generateAvatar($this->getDisplayName(), $size); } - } else { $avatar = new OC_Image(); $file = $this->folder->getFile('avatar.' . $ext); @@ -289,7 +288,6 @@ class UserAvatar extends Avatar { $this->logger->error('Failed to save avatar for ' . $this->user->getUID()); throw new NotFoundException(); } - } if ($this->config->getUserValue($this->user->getUID(), 'avatar', 'generated', null) === null) { diff --git a/lib/private/Broadcast/Events/BroadcastEvent.php b/lib/private/Broadcast/Events/BroadcastEvent.php index f5aa1d8c4b8..7d4d7017af5 100644 --- a/lib/private/Broadcast/Events/BroadcastEvent.php +++ b/lib/private/Broadcast/Events/BroadcastEvent.php @@ -57,5 +57,4 @@ class BroadcastEvent extends Event implements IBroadcastEvent { public function setBroadcasted(): void { $this->event->setBroadcasted(); } - } diff --git a/lib/private/Cache/CappedMemoryCache.php b/lib/private/Cache/CappedMemoryCache.php index 3d843abf5b8..28e08759304 100644 --- a/lib/private/Cache/CappedMemoryCache.php +++ b/lib/private/Cache/CappedMemoryCache.php @@ -30,7 +30,6 @@ use OCP\ICache; * Uses a simple FIFO expiry mechanism */ class CappedMemoryCache implements ICache, \ArrayAccess { - private $capacity; private $cache = []; diff --git a/lib/private/Calendar/Manager.php b/lib/private/Calendar/Manager.php index 3c876c79e9e..3b438dfa113 100644 --- a/lib/private/Calendar/Manager.php +++ b/lib/private/Calendar/Manager.php @@ -53,9 +53,9 @@ class Manager implements \OCP\Calendar\IManager { public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null) { $this->loadCalendars(); $result = []; - foreach($this->calendars as $calendar) { + foreach ($this->calendars as $calendar) { $r = $calendar->search($pattern, $searchProperties, $options, $limit, $offset); - foreach($r as $o) { + foreach ($r as $o) { $o['calendar-key'] = $calendar->getKey(); $result[] = $o; } @@ -132,7 +132,7 @@ class Manager implements \OCP\Calendar\IManager { * loads all calendars */ private function loadCalendars() { - foreach($this->calendarLoaders as $callable) { + foreach ($this->calendarLoaders as $callable) { $callable($this); } $this->calendarLoaders = []; diff --git a/lib/private/Calendar/Resource/Manager.php b/lib/private/Calendar/Resource/Manager.php index 0a85f271498..6ae46c9530f 100644 --- a/lib/private/Calendar/Resource/Manager.php +++ b/lib/private/Calendar/Resource/Manager.php @@ -75,7 +75,7 @@ class Manager implements \OCP\Calendar\Resource\IManager { * @since 14.0.0 */ public function getBackends():array { - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { if (isset($this->initializedBackends[$backend])) { continue; } @@ -93,7 +93,7 @@ class Manager implements \OCP\Calendar\Resource\IManager { */ public function getBackend($backendId) { $backends = $this->getBackends(); - foreach($backends as $backend) { + foreach ($backends as $backend) { if ($backend->getBackendIdentifier() === $backendId) { return $backend; } diff --git a/lib/private/Calendar/Room/Manager.php b/lib/private/Calendar/Room/Manager.php index 59406ba0c8c..6c3d02c3597 100644 --- a/lib/private/Calendar/Room/Manager.php +++ b/lib/private/Calendar/Room/Manager.php @@ -75,7 +75,7 @@ class Manager implements \OCP\Calendar\Room\IManager { * @since 14.0.0 */ public function getBackends():array { - foreach($this->backends as $backend) { + foreach ($this->backends as $backend) { if (isset($this->initializedBackends[$backend])) { continue; } @@ -93,7 +93,7 @@ class Manager implements \OCP\Calendar\Room\IManager { */ public function getBackend($backendId) { $backends = $this->getBackends(); - foreach($backends as $backend) { + foreach ($backends as $backend) { if ($backend->getBackendIdentifier() === $backendId) { return $backend; } diff --git a/lib/private/CapabilitiesManager.php b/lib/private/CapabilitiesManager.php index 8034b90567f..6a4d97ad159 100644 --- a/lib/private/CapabilitiesManager.php +++ b/lib/private/CapabilitiesManager.php @@ -55,7 +55,7 @@ class CapabilitiesManager { */ public function getCapabilities(bool $public = false) : array { $capabilities = []; - foreach($this->capabilities as $capability) { + foreach ($this->capabilities as $capability) { try { $c = $capability(); } catch (QueryException $e) { @@ -68,7 +68,7 @@ class CapabilitiesManager { } if ($c instanceof ICapability) { - if(!$public || $c instanceof IPublicCapability) { + if (!$public || $c instanceof IPublicCapability) { $capabilities = array_replace_recursive($capabilities, $c->getCapabilities()); } } else { diff --git a/lib/private/Collaboration/AutoComplete/Manager.php b/lib/private/Collaboration/AutoComplete/Manager.php index d2b490f73f5..e8d5732dec7 100644 --- a/lib/private/Collaboration/AutoComplete/Manager.php +++ b/lib/private/Collaboration/AutoComplete/Manager.php @@ -42,8 +42,8 @@ class Manager implements IManager { public function runSorters(array $sorters, array &$sortArray, array $context) { $sorterInstances = $this->getSorters(); - while($sorter = array_shift($sorters)) { - if(isset($sorterInstances[$sorter])) { + while ($sorter = array_shift($sorters)) { + if (isset($sorterInstances[$sorter])) { $sorterInstances[$sorter]->sort($sortArray, $context); } else { $this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [ @@ -58,17 +58,17 @@ class Manager implements IManager { } protected function getSorters() { - if(count($this->sorterInstances) === 0) { + if (count($this->sorterInstances) === 0) { foreach ($this->sorters as $sorter) { /** @var ISorter $instance */ $instance = $this->c->resolve($sorter); - if(!$instance instanceof ISorter) { + if (!$instance instanceof ISorter) { $this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}', ['app' => 'core', 'class' => $sorter]); continue; } $sorterId = trim($instance->getId()); - if(trim($sorterId) === '') { + if (trim($sorterId) === '') { $this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}', ['app' => 'core', 'class' => $sorter]); continue; diff --git a/lib/private/Collaboration/Collaborators/GroupPlugin.php b/lib/private/Collaboration/Collaborators/GroupPlugin.php index 404d4da8ca2..64db97a5235 100644 --- a/lib/private/Collaboration/Collaborators/GroupPlugin.php +++ b/lib/private/Collaboration/Collaborators/GroupPlugin.php @@ -61,7 +61,9 @@ class GroupPlugin implements ISearchPlugin { $result = ['wide' => [], 'exact' => []]; $groups = $this->groupManager->search($search, $limit, $offset); - $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); + $groupIds = array_map(function (IGroup $group) { + return $group->getGID(); + }, $groups); if (!$this->shareeEnumeration || count($groups) < $limit) { $hasMoreResults = true; @@ -71,7 +73,9 @@ class GroupPlugin implements ISearchPlugin { if (!empty($groups) && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) { // Intersect all the groups that match with the groups this user is a member of $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser()); - $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups); + $userGroups = array_map(function (IGroup $group) { + return $group->getGID(); + }, $userGroups); $groupIds = array_intersect($groupIds, $userGroups); } diff --git a/lib/private/Collaboration/Collaborators/LookupPlugin.php b/lib/private/Collaboration/Collaborators/LookupPlugin.php index 493c35a46d4..f0d5b92f18a 100644 --- a/lib/private/Collaboration/Collaborators/LookupPlugin.php +++ b/lib/private/Collaboration/Collaborators/LookupPlugin.php @@ -73,7 +73,7 @@ class LookupPlugin implements ISearchPlugin { } $lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com'); - if(empty($lookupServerUrl)) { + if (empty($lookupServerUrl)) { return false; } $lookupServerUrl = rtrim($lookupServerUrl, '/'); diff --git a/lib/private/Collaboration/Collaborators/MailPlugin.php b/lib/private/Collaboration/Collaborators/MailPlugin.php index bafc383f746..e387e38c6dc 100644 --- a/lib/private/Collaboration/Collaborators/MailPlugin.php +++ b/lib/private/Collaboration/Collaborators/MailPlugin.php @@ -65,7 +65,6 @@ class MailPlugin implements ISearchPlugin { $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes'; - } /** @@ -99,7 +98,7 @@ class MailPlugin implements ISearchPlugin { $emailAddress = $emailAddressData['value']; $emailAddressType = $emailAddressData['type']; } - if (isset($contact['FN'])) { + if (isset($contact['FN'])) { $displayName = $contact['FN'] . ' (' . $emailAddress . ')'; } $exactEmailMatch = strtolower($emailAddress) === $lowerSearch; @@ -179,8 +178,7 @@ class MailPlugin implements ISearchPlugin { } if ($exactEmailMatch - || isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch) - { + || isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch) { if ($exactEmailMatch) { $searchResult->markExactIdMatch($emailType); } diff --git a/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php b/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php index a922befec76..777af6093db 100644 --- a/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php +++ b/lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php @@ -90,5 +90,4 @@ class RemoteGroupPlugin implements ISearchPlugin { throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e); } } - } diff --git a/lib/private/Collaboration/Collaborators/Search.php b/lib/private/Collaboration/Collaborators/Search.php index 9b9decfecbe..11c7f87db1d 100644 --- a/lib/private/Collaboration/Collaborators/Search.php +++ b/lib/private/Collaboration/Collaborators/Search.php @@ -56,7 +56,7 @@ class Search implements ISearch { $searchResult = $this->c->resolve(SearchResult::class); foreach ($shareTypes as $type) { - if(!isset($this->pluginList[$type])) { + if (!isset($this->pluginList[$type])) { continue; } foreach ($this->pluginList[$type] as $plugin) { @@ -79,7 +79,7 @@ class Search implements ISearch { // that the exact same email address and federated cloud id exists $emailType = new SearchResultType('emails'); $remoteType = new SearchResultType('remotes'); - if($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) { + if ($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) { $searchResult->unsetResult($remoteType); } elseif (!$searchResult->hasExactIdMatch($emailType) && $searchResult->hasExactIdMatch($remoteType)) { $searchResult->unsetResult($emailType); @@ -87,7 +87,7 @@ class Search implements ISearch { // if we have an exact local user match, there is no need to show the remote and email matches $userType = new SearchResultType('users'); - if($searchResult->hasExactIdMatch($userType)) { + if ($searchResult->hasExactIdMatch($userType)) { $searchResult->unsetResult($remoteType); $searchResult->unsetResult($emailType); } @@ -97,7 +97,7 @@ class Search implements ISearch { public function registerPlugin(array $pluginInfo) { $shareType = constant(Share::class . '::' . $pluginInfo['shareType']); - if($shareType === null) { + if ($shareType === null) { throw new \InvalidArgumentException('Provided ShareType is invalid'); } $this->pluginList[$shareType][] = $pluginInfo['class']; diff --git a/lib/private/Collaboration/Collaborators/SearchResult.php b/lib/private/Collaboration/Collaborators/SearchResult.php index 1ee37e65589..46d5894b6f0 100644 --- a/lib/private/Collaboration/Collaborators/SearchResult.php +++ b/lib/private/Collaboration/Collaborators/SearchResult.php @@ -28,7 +28,6 @@ use OCP\Collaboration\Collaborators\ISearchResult; use OCP\Collaboration\Collaborators\SearchResultType; class SearchResult implements ISearchResult { - protected $result = [ 'exact' => [], ]; @@ -37,13 +36,13 @@ class SearchResult implements ISearchResult { public function addResultSet(SearchResultType $type, array $matches, array $exactMatches = null) { $type = $type->getLabel(); - if(!isset($this->result[$type])) { + if (!isset($this->result[$type])) { $this->result[$type] = []; $this->result['exact'][$type] = []; } $this->result[$type] = array_merge($this->result[$type], $matches); - if(is_array($exactMatches)) { + if (is_array($exactMatches)) { $this->result['exact'][$type] = array_merge($this->result['exact'][$type], $exactMatches); } } @@ -58,12 +57,12 @@ class SearchResult implements ISearchResult { public function hasResult(SearchResultType $type, $collaboratorId) { $type = $type->getLabel(); - if(!isset($this->result[$type])) { + if (!isset($this->result[$type])) { return false; } $resultArrays = [$this->result['exact'][$type], $this->result[$type]]; - foreach($resultArrays as $resultArray) { + foreach ($resultArrays as $resultArray) { foreach ($resultArray as $result) { if ($result['value']['shareWith'] === $collaboratorId) { return true; @@ -81,7 +80,7 @@ class SearchResult implements ISearchResult { public function unsetResult(SearchResultType $type) { $type = $type->getLabel(); $this->result[$type] = []; - if(isset($this->result['exact'][$type])) { + if (isset($this->result['exact'][$type])) { $this->result['exact'][$type] = []; } } diff --git a/lib/private/Collaboration/Collaborators/UserPlugin.php b/lib/private/Collaboration/Collaborators/UserPlugin.php index 53dd0c66c7f..189ea2f8ff6 100644 --- a/lib/private/Collaboration/Collaborators/UserPlugin.php +++ b/lib/private/Collaboration/Collaborators/UserPlugin.php @@ -197,7 +197,7 @@ class UserPlugin implements ISearchPlugin { public function takeOutCurrentUser(array &$users) { $currentUser = $this->userSession->getUser(); - if(!is_null($currentUser)) { + if (!is_null($currentUser)) { if (isset($users[$currentUser->getUID()])) { unset($users[$currentUser->getUID()]); } diff --git a/lib/private/Collaboration/Resources/Collection.php b/lib/private/Collaboration/Resources/Collection.php index 827f4e6dd1f..7369b44866d 100644 --- a/lib/private/Collaboration/Resources/Collection.php +++ b/lib/private/Collaboration/Resources/Collection.php @@ -174,7 +174,6 @@ class Collection implements ICollection { } else { $this->manager->invalidateAccessCacheForCollection($this); } - } /** diff --git a/lib/private/Collaboration/Resources/Listener.php b/lib/private/Collaboration/Resources/Listener.php index 608f72ebd5d..240ec7c0649 100644 --- a/lib/private/Collaboration/Resources/Listener.php +++ b/lib/private/Collaboration/Resources/Listener.php @@ -34,7 +34,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; class Listener { - public static function register(EventDispatcherInterface $dispatcher): void { $listener = function (GenericEvent $event) { /** @var IUser $user */ diff --git a/lib/private/Collaboration/Resources/Manager.php b/lib/private/Collaboration/Resources/Manager.php index 98cc25916fe..97213c45669 100644 --- a/lib/private/Collaboration/Resources/Manager.php +++ b/lib/private/Collaboration/Resources/Manager.php @@ -42,7 +42,6 @@ use OCP\ILogger; use OCP\IUser; class Manager implements IManager { - public const TABLE_COLLECTIONS = 'collres_collections'; public const TABLE_RESOURCES = 'collres_resources'; public const TABLE_ACCESS_CACHE = 'collres_accesscache'; diff --git a/lib/private/Command/QueueBus.php b/lib/private/Command/QueueBus.php index 275435782be..2ca8f948b69 100644 --- a/lib/private/Command/QueueBus.php +++ b/lib/private/Command/QueueBus.php @@ -56,7 +56,7 @@ class QueueBus implements IBus { if ($command instanceof ICommand) { // ensure the command can be serialized $serialized = serialize($command); - if(strlen($serialized) > 4000) { + if (strlen($serialized) > 4000) { throw new \InvalidArgumentException('Trying to push a command which serialized form can not be stored in the database (>4000 character)'); } $unserialized = unserialize($serialized); diff --git a/lib/private/Comments/Comment.php b/lib/private/Comments/Comment.php index a45b1e05cfe..2fd5f20edb8 100644 --- a/lib/private/Comments/Comment.php +++ b/lib/private/Comments/Comment.php @@ -30,7 +30,6 @@ use OCP\Comments\IllegalIDChangeException; use OCP\Comments\MessageTooLongException; class Comment implements IComment { - protected $data = [ 'id' => '', 'parentId' => '0', @@ -54,7 +53,7 @@ class Comment implements IComment { * the comments database scheme */ public function __construct(array $data = null) { - if(is_array($data)) { + if (is_array($data)) { $this->fromArray($data); } } @@ -87,12 +86,12 @@ class Comment implements IComment { * @since 9.0.0 */ public function setId($id) { - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } $id = trim($id); - if($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) { + if ($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) { $this->data['id'] = $id; return $this; } @@ -118,7 +117,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setParentId($parentId) { - if(!is_string($parentId)) { + if (!is_string($parentId)) { throw new \InvalidArgumentException('String expected.'); } $this->data['parentId'] = trim($parentId); @@ -144,7 +143,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setTopmostParentId($id) { - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } $this->data['topmostParentId'] = trim($id); @@ -169,7 +168,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setChildrenCount($count) { - if(!is_int($count)) { + if (!is_int($count)) { throw new \InvalidArgumentException('Integer expected.'); } $this->data['childrenCount'] = $count; @@ -196,7 +195,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setMessage($message, $maxLength = self::MAX_MESSAGE_LENGTH) { - if(!is_string($message)) { + if (!is_string($message)) { throw new \InvalidArgumentException('String expected.'); } $message = trim($message); @@ -229,7 +228,7 @@ class Comment implements IComment { */ public function getMentions() { $ok = preg_match_all("/\B(?getMessage(), $mentions); - if(!$ok || !isset($mentions[0]) || !is_array($mentions[0])) { + if (!$ok || !isset($mentions[0]) || !is_array($mentions[0])) { return []; } $uids = array_unique($mentions[0]); @@ -263,7 +262,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setVerb($verb) { - if(!is_string($verb) || !trim($verb)) { + if (!is_string($verb) || !trim($verb)) { throw new \InvalidArgumentException('Non-empty String expected.'); } $this->data['verb'] = trim($verb); @@ -299,7 +298,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setActor($actorType, $actorId) { - if( + if ( !is_string($actorType) || !trim($actorType) || !is_string($actorId) || $actorId === '' ) { @@ -385,7 +384,7 @@ class Comment implements IComment { * @since 9.0.0 */ public function setObject($objectType, $objectId) { - if( + if ( !is_string($objectType) || !trim($objectType) || !is_string($objectId) || trim($objectId) === '' ) { @@ -434,18 +433,18 @@ class Comment implements IComment { * @return IComment */ protected function fromArray($data) { - foreach(array_keys($data) as $key) { + foreach (array_keys($data) as $key) { // translate DB keys to internal setter names $setter = 'set' . implode('', array_map('ucfirst', explode('_', $key))); $setter = str_replace('Timestamp', 'DateTime', $setter); - if(method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter($data[$key]); } } - foreach(['actor', 'object'] as $role) { - if(isset($data[$role . '_type']) && isset($data[$role . '_id'])) { + foreach (['actor', 'object'] as $role) { + if (isset($data[$role . '_type']) && isset($data[$role . '_id'])) { $setter = 'set' . ucfirst($role); $this->$setter($data[$role . '_type'], $data[$role . '_id']); } diff --git a/lib/private/Comments/Manager.php b/lib/private/Comments/Manager.php index d04f3f965b3..a0a670817f4 100644 --- a/lib/private/Comments/Manager.php +++ b/lib/private/Comments/Manager.php @@ -747,7 +747,6 @@ class Manager implements ICommentsManager { * @return bool */ protected function insert(IComment $comment): bool { - try { $result = $this->insertQuery($comment, true); } catch (InvalidFieldNameException $e) { diff --git a/lib/private/Config.php b/lib/private/Config.php index 0c5a9b0320d..1724222f4bb 100644 --- a/lib/private/Config.php +++ b/lib/private/Config.php @@ -42,7 +42,6 @@ namespace OC; * configuration file of Nextcloud. */ class Config { - const ENV_PREFIX = 'NC_'; /** @var array Associative array ($key => $value) */ @@ -200,7 +199,7 @@ class Config { foreach ($configFiles as $file) { $fileExistsAndIsReadable = file_exists($file) && is_readable($file); $filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false; - if($file === $this->configFilePath && + if ($file === $this->configFilePath && $filePointer === false) { // Opening the main config might not be possible, e.g. if the wrong // permissions are set (likely on a new installation) @@ -208,13 +207,13 @@ class Config { } // Try to acquire a file lock - if(!flock($filePointer, LOCK_SH)) { + if (!flock($filePointer, LOCK_SH)) { throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file)); } unset($CONFIG); include $file; - if(isset($CONFIG) && is_array($CONFIG)) { + if (isset($CONFIG) && is_array($CONFIG)) { $this->cache = array_merge($this->cache, $CONFIG); } @@ -246,14 +245,14 @@ class Config { chmod($this->configFilePath, 0640); // File does not exist, this can happen when doing a fresh install - if(!is_resource($filePointer)) { + if (!is_resource($filePointer)) { throw new HintException( "Can't write into config directory!", 'This can usually be fixed by giving the webserver write access to the config directory.'); } // Try to acquire a file lock - if(!flock($filePointer, LOCK_EX)) { + if (!flock($filePointer, LOCK_EX)) { throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath)); } diff --git a/lib/private/Console/Application.php b/lib/private/Console/Application.php index 00ab67f93be..94f51c2a4be 100644 --- a/lib/private/Console/Application.php +++ b/lib/private/Console/Application.php @@ -149,7 +149,7 @@ class Application { } elseif ($input->getArgument('command') !== '_completion' && $input->getArgument('command') !== 'maintenance:install') { $output->writeln("Nextcloud is not installed - only a limited number of commands are available"); } - } catch(NeedsUpdateException $e) { + } catch (NeedsUpdateException $e) { if ($input->getArgument('command') !== '_completion') { $output->writeln("Nextcloud or one of the apps require upgrade - only a limited number of commands are available"); $output->writeln("You may use your browser or the occ upgrade command to do the upgrade"); diff --git a/lib/private/Console/TimestampFormatter.php b/lib/private/Console/TimestampFormatter.php index 72e3e392e0b..7f8250a9f3d 100644 --- a/lib/private/Console/TimestampFormatter.php +++ b/lib/private/Console/TimestampFormatter.php @@ -100,7 +100,6 @@ class TimestampFormatter implements OutputFormatterInterface { * log timezone and dateformat, e.g. "2015-06-23T17:24:37+02:00" */ public function format($message) { - $timeZone = $this->config->getSystemValue('logtimezone', 'UTC'); $timeZone = $timeZone !== null ? new \DateTimeZone($timeZone) : null; diff --git a/lib/private/Contacts/ContactsMenu/ActionFactory.php b/lib/private/Contacts/ContactsMenu/ActionFactory.php index 2c216bf2592..0cdd1245b31 100644 --- a/lib/private/Contacts/ContactsMenu/ActionFactory.php +++ b/lib/private/Contacts/ContactsMenu/ActionFactory.php @@ -52,5 +52,4 @@ class ActionFactory implements IActionFactory { public function newEMailAction($icon, $name, $email) { return $this->newLinkAction($icon, $name, 'mailto:' . $email); } - } diff --git a/lib/private/Contacts/ContactsMenu/ActionProviderStore.php b/lib/private/Contacts/ContactsMenu/ActionProviderStore.php index b8ddf9258fa..5513dd06362 100644 --- a/lib/private/Contacts/ContactsMenu/ActionProviderStore.php +++ b/lib/private/Contacts/ContactsMenu/ActionProviderStore.php @@ -109,5 +109,4 @@ class ActionProviderStore { return array_merge($all, $providers); }, []); } - } diff --git a/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php b/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php index b1fd74e5bf9..eac169afb77 100644 --- a/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php +++ b/lib/private/Contacts/ContactsMenu/Actions/LinkAction.php @@ -98,5 +98,4 @@ class LinkAction implements ILinkAction { 'hyperlink' => $this->href, ]; } - } diff --git a/lib/private/Contacts/ContactsMenu/ContactsStore.php b/lib/private/Contacts/ContactsMenu/ContactsStore.php index dfa6db61607..0542d60ad3c 100644 --- a/lib/private/Contacts/ContactsMenu/ContactsStore.php +++ b/lib/private/Contacts/ContactsMenu/ContactsStore.php @@ -137,22 +137,22 @@ class ContactsStore implements IContactsStore { } // Prevent enumerating local users - if($disallowEnumeration && $entry->getProperty('isLocalSystemBook')) { + if ($disallowEnumeration && $entry->getProperty('isLocalSystemBook')) { $filterUser = true; $mailAddresses = $entry->getEMailAddresses(); - foreach($mailAddresses as $mailAddress) { - if($mailAddress === $filter) { + foreach ($mailAddresses as $mailAddress) { + if ($mailAddress === $filter) { $filterUser = false; break; } } - if($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) { + if ($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) { $filterUser = false; } - if($filterUser) { + if ($filterUser) { return false; } } @@ -182,7 +182,7 @@ class ContactsStore implements IContactsStore { * @return IEntry|null */ public function findOne(IUser $user, $shareType, $shareWith) { - switch($shareType) { + switch ($shareType) { case 0: case 6: $filter = ['UID']; @@ -224,7 +224,6 @@ class ContactsStore implements IContactsStore { } else { $match = null; } - } return $match; @@ -262,5 +261,4 @@ class ContactsStore implements IContactsStore { return $entry; } - } diff --git a/lib/private/Contacts/ContactsMenu/Entry.php b/lib/private/Contacts/ContactsMenu/Entry.php index c4b590e9397..675d925134b 100644 --- a/lib/private/Contacts/ContactsMenu/Entry.php +++ b/lib/private/Contacts/ContactsMenu/Entry.php @@ -164,5 +164,4 @@ class Entry implements IEntry { 'lastMessage' => '', ]; } - } diff --git a/lib/private/Contacts/ContactsMenu/Manager.php b/lib/private/Contacts/ContactsMenu/Manager.php index ba761c5ece8..293f1366b05 100644 --- a/lib/private/Contacts/ContactsMenu/Manager.php +++ b/lib/private/Contacts/ContactsMenu/Manager.php @@ -118,5 +118,4 @@ class Manager { } } } - } diff --git a/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php b/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php index adf09065a45..bb5e64d15aa 100644 --- a/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php +++ b/lib/private/Contacts/ContactsMenu/Providers/EMailProvider.php @@ -59,5 +59,4 @@ class EMailProvider implements IProvider { $entry->addAction($action); } } - } diff --git a/lib/private/ContactsManager.php b/lib/private/ContactsManager.php index 6ccedca77b9..c28e7f6ad4b 100644 --- a/lib/private/ContactsManager.php +++ b/lib/private/ContactsManager.php @@ -45,10 +45,10 @@ namespace OC { public function search($pattern, $searchProperties = [], $options = []) { $this->loadAddressBooks(); $result = []; - foreach($this->addressBooks as $addressBook) { + foreach ($this->addressBooks as $addressBook) { $r = $addressBook->search($pattern, $searchProperties, $options); $contacts = []; - foreach($r as $c){ + foreach ($r as $c) { $c['addressbook-key'] = $addressBook->getKey(); $contacts[] = $c; } @@ -133,7 +133,7 @@ namespace OC { public function getAddressBooks() { $this->loadAddressBooks(); $result = []; - foreach($this->addressBooks as $addressBook) { + foreach ($this->addressBooks as $addressBook) { $result[$addressBook->getKey()] = $addressBook->getDisplayName(); } @@ -175,8 +175,7 @@ namespace OC { * * @param \Closure $callable */ - public function register(\Closure $callable) - { + public function register(\Closure $callable) { $this->addressBookLoaders[] = $callable; } @@ -186,8 +185,7 @@ namespace OC { * @param string $addressBookKey * @return \OCP\IAddressBook */ - protected function getAddressBook($addressBookKey) - { + protected function getAddressBook($addressBookKey) { $this->loadAddressBooks(); if (!array_key_exists($addressBookKey, $this->addressBooks)) { return null; @@ -199,9 +197,8 @@ namespace OC { /** * Load all address books registered with 'register' */ - protected function loadAddressBooks() - { - foreach($this->addressBookLoaders as $callable) { + protected function loadAddressBooks() { + foreach ($this->addressBookLoaders as $callable) { $callable($this); } $this->addressBookLoaders = []; diff --git a/lib/private/DB/Adapter.php b/lib/private/DB/Adapter.php index f93f5aaf481..0755fa14619 100644 --- a/lib/private/DB/Adapter.php +++ b/lib/private/DB/Adapter.php @@ -106,7 +106,7 @@ class Adapter { . 'FROM `' . $table . '` WHERE '; $inserts = array_values($input); - foreach($compare as $key) { + foreach ($compare as $key) { $query .= '`' . $key . '`'; if (is_null($input[$key])) { $query .= ' IS NULL AND '; @@ -136,11 +136,11 @@ class Adapter { try { $builder = $this->conn->getQueryBuilder(); $builder->insert($table); - foreach($values as $key => $value) { + foreach ($values as $key => $value) { $builder->setValue($key, $builder->createNamedParameter($value)); } return $builder->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { return 0; } } diff --git a/lib/private/DB/AdapterPgSql.php b/lib/private/DB/AdapterPgSql.php index dd9c7dc9680..7457ab9a77d 100644 --- a/lib/private/DB/AdapterPgSql.php +++ b/lib/private/DB/AdapterPgSql.php @@ -44,7 +44,7 @@ class AdapterPgSql extends Adapter { * @suppress SqlInjectionChecker */ public function insertIgnoreConflict(string $table,array $values) : int { - if($this->isPre9_5CompatMode() === true) { + if ($this->isPre9_5CompatMode() === true) { return parent::insertIgnoreConflict($table, $values); } @@ -60,7 +60,7 @@ class AdapterPgSql extends Adapter { } protected function isPre9_5CompatMode(): bool { - if($this->compatModePre9_5 !== null) { + if ($this->compatModePre9_5 !== null) { return $this->compatModePre9_5; } diff --git a/lib/private/DB/AdapterSqlite.php b/lib/private/DB/AdapterSqlite.php index 2d8715e90f5..66c3aca1d9c 100644 --- a/lib/private/DB/AdapterSqlite.php +++ b/lib/private/DB/AdapterSqlite.php @@ -74,7 +74,7 @@ class AdapterSqlite extends Adapter { . " WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE "; $inserts = array_values($input); - foreach($compare as $key) { + foreach ($compare as $key) { $query .= '`' . $key . '`'; if (is_null($input[$key])) { $query .= ' IS NULL AND '; diff --git a/lib/private/DB/Connection.php b/lib/private/DB/Connection.php index 15c0272915a..3b24703d434 100644 --- a/lib/private/DB/Connection.php +++ b/lib/private/DB/Connection.php @@ -139,8 +139,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * @throws \Exception */ public function __construct(array $params, Driver $driver, Configuration $config = null, - EventManager $eventManager = null) - { + EventManager $eventManager = null) { if (!isset($params['adapter'])) { throw new \Exception('adapter not set'); } @@ -189,8 +188,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * * @throws \Doctrine\DBAL\DBALException */ - public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) - { + public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null) { $query = $this->replaceTablePrefix($query); $query = $this->adapter->fixupStatement($query); return parent::executeQuery($query, $params, $types, $qcp); @@ -210,8 +208,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { * * @throws \Doctrine\DBAL\DBALException */ - public function executeUpdate($query, array $params = [], array $types = []) - { + public function executeUpdate($query, array $params = [], array $types = []) { $query = $this->replaceTablePrefix($query); $query = $this->adapter->fixupStatement($query); return parent::executeUpdate($query, $params, $types); @@ -372,7 +369,7 @@ class Connection extends ReconnectWrapper implements IDBConnection { public function dropTable($table) { $table = $this->tablePrefix . trim($table); $schema = $this->getSchemaManager(); - if($schema->tablesExist([$table])) { + if ($schema->tablesExist([$table])) { $schema->dropTable($table); } } diff --git a/lib/private/DB/MDB2SchemaReader.php b/lib/private/DB/MDB2SchemaReader.php index 66a45fb5fc5..b371e1a16b2 100644 --- a/lib/private/DB/MDB2SchemaReader.php +++ b/lib/private/DB/MDB2SchemaReader.php @@ -344,5 +344,4 @@ class MDB2SchemaReader { } return (bool)$result; } - } diff --git a/lib/private/DB/MDB2SchemaWriter.php b/lib/private/DB/MDB2SchemaWriter.php index cccab28f78e..3cabff9d8f1 100644 --- a/lib/private/DB/MDB2SchemaWriter.php +++ b/lib/private/DB/MDB2SchemaWriter.php @@ -43,7 +43,7 @@ class MDB2SchemaWriter { $xml->addChild('name', $config->getSystemValue('dbname', 'owncloud')); $xml->addChild('create', 'true'); $xml->addChild('overwrite', 'false'); - if($config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false)) { + if ($config->getSystemValue('dbtype', 'sqlite') === 'mysql' && $config->getSystemValue('mysql.utf8mb4', false)) { $xml->addChild('charset', 'utf8mb4'); } else { $xml->addChild('charset', 'utf8'); @@ -71,13 +71,13 @@ class MDB2SchemaWriter { private static function saveTable($table, $xml) { $xml->addChild('name', $table->getName()); $declaration = $xml->addChild('declaration'); - foreach($table->getColumns() as $column) { + foreach ($table->getColumns() as $column) { self::saveColumn($column, $declaration->addChild('field')); } - foreach($table->getIndexes() as $index) { + foreach ($table->getIndexes() as $index) { if ($index->getName() == 'PRIMARY') { $autoincrement = false; - foreach($index->getColumns() as $column) { + foreach ($index->getColumns() as $column) { if ($table->getColumn($column)->getAutoincrement()) { $autoincrement = true; } @@ -96,7 +96,7 @@ class MDB2SchemaWriter { */ private static function saveColumn($column, $xml) { $xml->addChild('name', $column->getName()); - switch($column->getType()) { + switch ($column->getType()) { case 'SmallInt': case 'Integer': case 'BigInt': @@ -116,8 +116,7 @@ class MDB2SchemaWriter { $length = '4'; if ($column->getType() == 'SmallInt') { $length = '2'; - } - elseif ($column->getType() == 'BigInt') { + } elseif ($column->getType() == 'BigInt') { $length = '8'; } $xml->addChild('length', $length); @@ -165,15 +164,13 @@ class MDB2SchemaWriter { $xml->addChild('name', $index->getName()); if ($index->isPrimary()) { $xml->addChild('primary', 'true'); - } - elseif ($index->isUnique()) { + } elseif ($index->isUnique()) { $xml->addChild('unique', 'true'); } - foreach($index->getColumns() as $column) { + foreach ($index->getColumns() as $column) { $field = $xml->addChild('field'); $field->addChild('name', $column); $field->addChild('sorting', 'ascending'); - } } diff --git a/lib/private/DB/MigrationService.php b/lib/private/DB/MigrationService.php index 0104c1be367..18993cadd50 100644 --- a/lib/private/DB/MigrationService.php +++ b/lib/private/DB/MigrationService.php @@ -159,7 +159,6 @@ class MigrationService { // Recreate the schema after the table was dropped. $schema = new SchemaWrapper($this->connection); - } catch (SchemaException $e) { // Table not found, no need to panic, we will create it. } @@ -329,7 +328,7 @@ class MigrationService { * @return mixed|null|string */ public function getMigration($alias) { - switch($alias) { + switch ($alias) { case 'current': return $this->getCurrentVersion(); case 'next': diff --git a/lib/private/DB/Migrator.php b/lib/private/DB/Migrator.php index bda0720b3bb..2ea365ab294 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -302,14 +302,14 @@ class Migrator { if ($this->noEmit) { return; } - if(is_null($this->dispatcher)) { + if (is_null($this->dispatcher)) { return; } $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max])); } private function emitCheckStep($tableName, $step, $max) { - if(is_null($this->dispatcher)) { + if (is_null($this->dispatcher)) { return; } $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max])); diff --git a/lib/private/DB/MissingColumnInformation.php b/lib/private/DB/MissingColumnInformation.php index bcf585848fd..d1c81c2e199 100644 --- a/lib/private/DB/MissingColumnInformation.php +++ b/lib/private/DB/MissingColumnInformation.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\DB; class MissingColumnInformation { - private $listOfMissingColumns = []; public function addHintForMissingColumn(string $tableName, string $columnName): void { diff --git a/lib/private/DB/MissingIndexInformation.php b/lib/private/DB/MissingIndexInformation.php index ae8be7934d9..04853dcac2d 100644 --- a/lib/private/DB/MissingIndexInformation.php +++ b/lib/private/DB/MissingIndexInformation.php @@ -28,7 +28,6 @@ declare(strict_types=1); namespace OC\DB; class MissingIndexInformation { - private $listOfMissingIndexes = []; public function addHintForMissingSubject(string $tableName, string $indexName) { diff --git a/lib/private/DB/MySQLMigrator.php b/lib/private/DB/MySQLMigrator.php index fe56a9563e2..58c54683a3a 100644 --- a/lib/private/DB/MySQLMigrator.php +++ b/lib/private/DB/MySQLMigrator.php @@ -53,25 +53,24 @@ class MySQLMigrator extends Migrator { return $schemaDiff; } - /** - * Speed up migration test by disabling autocommit and unique indexes check - * - * @param \Doctrine\DBAL\Schema\Table $table - * @throws \OC\DB\MigrationException - */ - protected function checkTableMigrate(Table $table) { - $this->connection->exec('SET autocommit=0'); - $this->connection->exec('SET unique_checks=0'); + /** + * Speed up migration test by disabling autocommit and unique indexes check + * + * @param \Doctrine\DBAL\Schema\Table $table + * @throws \OC\DB\MigrationException + */ + protected function checkTableMigrate(Table $table) { + $this->connection->exec('SET autocommit=0'); + $this->connection->exec('SET unique_checks=0'); - try { - parent::checkTableMigrate($table); - } catch (\Exception $e) { - $this->connection->exec('SET unique_checks=1'); - $this->connection->exec('SET autocommit=1'); - throw new MigrationException($table->getName(), $e->getMessage()); - } - $this->connection->exec('SET unique_checks=1'); - $this->connection->exec('SET autocommit=1'); + try { + parent::checkTableMigrate($table); + } catch (\Exception $e) { + $this->connection->exec('SET unique_checks=1'); + $this->connection->exec('SET autocommit=1'); + throw new MigrationException($table->getName(), $e->getMessage()); } - + $this->connection->exec('SET unique_checks=1'); + $this->connection->exec('SET autocommit=1'); + } } diff --git a/lib/private/DB/OCSqlitePlatform.php b/lib/private/DB/OCSqlitePlatform.php index 5649b14d233..be33629e885 100644 --- a/lib/private/DB/OCSqlitePlatform.php +++ b/lib/private/DB/OCSqlitePlatform.php @@ -23,5 +23,4 @@ namespace OC\DB; class OCSqlitePlatform extends \Doctrine\DBAL\Platforms\SqlitePlatform { - } diff --git a/lib/private/DB/OracleConnection.php b/lib/private/DB/OracleConnection.php index 93a52d1772d..b53ee850149 100644 --- a/lib/private/DB/OracleConnection.php +++ b/lib/private/DB/OracleConnection.php @@ -34,7 +34,7 @@ class OracleConnection extends Connection { private function quoteKeys(array $data) { $return = []; $c = $this->getDatabasePlatform()->getIdentifierQuoteCharacter(); - foreach($data as $key => $value) { + foreach ($data as $key => $value) { if ($key[0] !== $c) { $return[$this->quoteIdentifier($key)] = $value; } else { @@ -87,7 +87,7 @@ class OracleConnection extends Connection { $table = $this->tablePrefix . trim($table); $table = $this->quoteIdentifier($table); $schema = $this->getSchemaManager(); - if($schema->tablesExist([$table])) { + if ($schema->tablesExist([$table])) { $schema->dropTable($table); } } diff --git a/lib/private/DB/OracleMigrator.php b/lib/private/DB/OracleMigrator.php index 86d1f71c2b7..8c8a91f9b1b 100644 --- a/lib/private/DB/OracleMigrator.php +++ b/lib/private/DB/OracleMigrator.php @@ -228,5 +228,4 @@ class OracleMigrator extends Migrator { protected function getFilterExpression() { return '/^"' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/'; } - } diff --git a/lib/private/DB/QueryBuilder/CompositeExpression.php b/lib/private/DB/QueryBuilder/CompositeExpression.php index b6546f3c806..512343662ad 100644 --- a/lib/private/DB/QueryBuilder/CompositeExpression.php +++ b/lib/private/DB/QueryBuilder/CompositeExpression.php @@ -87,8 +87,7 @@ class CompositeExpression implements ICompositeExpression, \Countable { * * @return string */ - public function __toString() - { + public function __toString() { return (string) $this->compositeExpression; } } diff --git a/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php b/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php index e7df321b102..899f9277439 100644 --- a/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php +++ b/lib/private/DB/QueryBuilder/ExpressionBuilder/MySqlExpressionBuilder.php @@ -52,5 +52,4 @@ class MySqlExpressionBuilder extends ExpressionBuilder { $y = $this->helper->quoteColumnName($y); return $this->expressionBuilder->comparison($x, ' COLLATE ' . $this->charset . '_general_ci LIKE', $y); } - } diff --git a/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php b/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php index fbf76da8690..141a93ff75a 100644 --- a/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php +++ b/lib/private/DB/QueryBuilder/ExpressionBuilder/PgSqlExpressionBuilder.php @@ -55,5 +55,4 @@ class PgSqlExpressionBuilder extends ExpressionBuilder { $y = $this->helper->quoteColumnName($y); return $this->expressionBuilder->comparison($x, 'ILIKE', $y); } - } diff --git a/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php b/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php index 774769bfdbb..6d8e947c407 100644 --- a/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php +++ b/lib/private/DB/QueryBuilder/FunctionBuilder/SqliteFunctionBuilder.php @@ -38,5 +38,4 @@ class SqliteFunctionBuilder extends FunctionBuilder { public function least($x, $y) { return new QueryFunction('MIN(' . $this->helper->quoteColumnName($x) . ', ' . $this->helper->quoteColumnName($y) . ')'); } - } diff --git a/lib/private/DB/QueryBuilder/Literal.php b/lib/private/DB/QueryBuilder/Literal.php index f2e169e7faf..8c8114209ff 100644 --- a/lib/private/DB/QueryBuilder/Literal.php +++ b/lib/private/DB/QueryBuilder/Literal.php @@ -24,7 +24,7 @@ namespace OC\DB\QueryBuilder; use OCP\DB\QueryBuilder\ILiteral; -class Literal implements ILiteral{ +class Literal implements ILiteral { /** @var mixed */ protected $literal; diff --git a/lib/private/DB/QueryBuilder/QueryBuilder.php b/lib/private/DB/QueryBuilder/QueryBuilder.php index 4845b8b1aa4..a2941950d5c 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -413,7 +413,6 @@ class QueryBuilder implements IQueryBuilder { * @return $this This QueryBuilder instance. */ public function selectAlias($select, $alias) { - $this->queryBuilder->addSelect( $this->helper->quoteColumnName($select) . ' AS ' . $this->helper->quoteColumnName($alias) ); @@ -435,7 +434,6 @@ class QueryBuilder implements IQueryBuilder { * @return $this This QueryBuilder instance. */ public function selectDistinct($select) { - $this->queryBuilder->addSelect( 'DISTINCT ' . $this->helper->quoteColumnName($select) ); diff --git a/lib/private/Dashboard/DashboardManager.php b/lib/private/Dashboard/DashboardManager.php index 6491779bce7..4501e3cc544 100644 --- a/lib/private/Dashboard/DashboardManager.php +++ b/lib/private/Dashboard/DashboardManager.php @@ -137,5 +137,4 @@ class DashboardManager implements IDashboardManager { return $this->eventsService; } - } diff --git a/lib/private/Diagnostics/EventLogger.php b/lib/private/Diagnostics/EventLogger.php index 0c058c30798..eccdd037f95 100644 --- a/lib/private/Diagnostics/EventLogger.php +++ b/lib/private/Diagnostics/EventLogger.php @@ -41,7 +41,7 @@ class EventLogger implements IEventLogger { * @inheritdoc */ public function start($id, $description) { - if ($this->activated){ + if ($this->activated) { $this->events[$id] = new Event($id, $description, microtime(true)); } } diff --git a/lib/private/DirectEditing/Manager.php b/lib/private/DirectEditing/Manager.php index d2c927360b6..c3098fb1a97 100644 --- a/lib/private/DirectEditing/Manager.php +++ b/lib/private/DirectEditing/Manager.php @@ -49,7 +49,6 @@ use function array_key_exists; use function in_array; class Manager implements IManager { - private const TOKEN_CLEANUP_TIME = 12 * 60 * 60 ; public const TABLE_TOKENS = 'direct_edit'; @@ -172,7 +171,6 @@ class Manager implements IManager { } $editor = $this->getEditor($tokenObject->getEditor()); $this->accessToken($token); - } catch (\Throwable $throwable) { $this->invalidateToken($token); return new NotFoundResponse(); @@ -277,5 +275,4 @@ class Manager implements IManager { } return $files[0]; } - } diff --git a/lib/private/DirectEditing/Token.php b/lib/private/DirectEditing/Token.php index 1c0b99b757d..eb98f3c7123 100644 --- a/lib/private/DirectEditing/Token.php +++ b/lib/private/DirectEditing/Token.php @@ -71,5 +71,4 @@ class Token implements IToken { public function getUser(): string { return $this->data['user_id']; } - } diff --git a/lib/private/Encryption/DecryptAll.php b/lib/private/Encryption/DecryptAll.php index 3f6e4131d64..19bd2f81378 100644 --- a/lib/private/Encryption/DecryptAll.php +++ b/lib/private/Encryption/DecryptAll.php @@ -83,7 +83,6 @@ class DecryptAll { * @throws \Exception */ public function decryptAll(InputInterface $input, OutputInterface $output, $user = '') { - $this->input = $input; $this->output = $output; @@ -147,12 +146,10 @@ class DecryptAll { * @param string $user which users files should be decrypted, default = all users */ protected function decryptAllUsersFiles($user = '') { - $this->output->writeln("\n"); $userList = []; if ($user === '') { - $fetchUsersProgress = new ProgressBar($this->output); $fetchUsersProgress->setFormat(" %message% \n [%bar%]"); $fetchUsersProgress->start(); @@ -197,7 +194,6 @@ class DecryptAll { $progress->finish(); $this->output->writeln("\n\n"); - } /** @@ -208,7 +204,6 @@ class DecryptAll { * @param string $userCount */ protected function decryptUsersFiles($uid, ProgressBar $progress, $userCount) { - $this->setupUserFS($uid); $directories = []; $directories[] = '/' . $uid . '/files'; @@ -217,7 +212,7 @@ class DecryptAll { $content = $this->rootView->getDirectoryContent($root); foreach ($content as $file) { // only decrypt files owned by the user - if($file->getStorage()->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { + if ($file->getStorage()->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { continue; } $path = $root . '/' . $file['name']; @@ -299,5 +294,4 @@ class DecryptAll { \OC_Util::tearDownFS(); \OC_Util::setupFS($uid); } - } diff --git a/lib/private/Encryption/EncryptionWrapper.php b/lib/private/Encryption/EncryptionWrapper.php index 6389e996c1d..edbdc692b45 100644 --- a/lib/private/Encryption/EncryptionWrapper.php +++ b/lib/private/Encryption/EncryptionWrapper.php @@ -82,7 +82,6 @@ class EncryptionWrapper { ]; if (!$storage->instanceOfStorage(Storage\IDisableEncryptionStorage::class)) { - $user = \OC::$server->getUserSession()->getUser(); $mountManager = Filesystem::getMountManager(); $uid = $user ? $user->getUID() : null; @@ -119,5 +118,4 @@ class EncryptionWrapper { return $storage; } } - } diff --git a/lib/private/Encryption/Exceptions/DecryptionFailedException.php b/lib/private/Encryption/Exceptions/DecryptionFailedException.php index 5542082bf4d..048732d62a9 100644 --- a/lib/private/Encryption/Exceptions/DecryptionFailedException.php +++ b/lib/private/Encryption/Exceptions/DecryptionFailedException.php @@ -26,5 +26,4 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class DecryptionFailedException extends GenericEncryptionException { - } diff --git a/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php b/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php index dd976b22bda..7a3be2a01bd 100644 --- a/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php +++ b/lib/private/Encryption/Exceptions/EmptyEncryptionDataException.php @@ -25,6 +25,5 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; -class EmptyEncryptionDataException extends GenericEncryptionException{ - +class EmptyEncryptionDataException extends GenericEncryptionException { } diff --git a/lib/private/Encryption/Exceptions/EncryptionFailedException.php b/lib/private/Encryption/Exceptions/EncryptionFailedException.php index 2b1672c2cb6..581d8fb7b56 100644 --- a/lib/private/Encryption/Exceptions/EncryptionFailedException.php +++ b/lib/private/Encryption/Exceptions/EncryptionFailedException.php @@ -25,6 +25,5 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; -class EncryptionFailedException extends GenericEncryptionException{ - +class EncryptionFailedException extends GenericEncryptionException { } diff --git a/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php b/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php index 3a9b8d6d33d..c44ea9d7db0 100644 --- a/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php +++ b/lib/private/Encryption/Exceptions/EncryptionHeaderToLargeException.php @@ -26,9 +26,7 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class EncryptionHeaderToLargeException extends GenericEncryptionException { - public function __construct() { parent::__construct('max header size exceeded'); } - } diff --git a/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php b/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php index c9da35d9c5d..824dce48007 100644 --- a/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php +++ b/lib/private/Encryption/Exceptions/ModuleAlreadyExistsException.php @@ -34,5 +34,4 @@ class ModuleAlreadyExistsException extends GenericEncryptionException { public function __construct($id, $name) { parent::__construct('Id "' . $id . '" already used by encryption module "' . $name . '"'); } - } diff --git a/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php b/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php index 841ead4ac16..24192e6e8d6 100644 --- a/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php +++ b/lib/private/Encryption/Exceptions/ModuleDoesNotExistsException.php @@ -26,5 +26,4 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class ModuleDoesNotExistsException extends GenericEncryptionException { - } diff --git a/lib/private/Encryption/Exceptions/UnknownCipherException.php b/lib/private/Encryption/Exceptions/UnknownCipherException.php index eb16f9c2fbc..7a8bd76d936 100644 --- a/lib/private/Encryption/Exceptions/UnknownCipherException.php +++ b/lib/private/Encryption/Exceptions/UnknownCipherException.php @@ -26,5 +26,4 @@ namespace OC\Encryption\Exceptions; use OCP\Encryption\Exceptions\GenericEncryptionException; class UnknownCipherException extends GenericEncryptionException { - } diff --git a/lib/private/Encryption/File.php b/lib/private/Encryption/File.php index 578fdeea5e6..13879c02cdc 100644 --- a/lib/private/Encryption/File.php +++ b/lib/private/Encryption/File.php @@ -124,5 +124,4 @@ class File implements \OCP\Encryption\IFile { return ['users' => $uniqueUserIds, 'public' => $public]; } - } diff --git a/lib/private/Encryption/Keys/Storage.php b/lib/private/Encryption/Keys/Storage.php index f71017bc4aa..2030f26f8f5 100644 --- a/lib/private/Encryption/Keys/Storage.php +++ b/lib/private/Encryption/Keys/Storage.php @@ -188,7 +188,6 @@ class Storage implements IStorage { * @return string */ protected function constructUserKeyPath($encryptionModuleId, $keyId, $uid) { - if ($uid === null) { $path = $this->root_dir . '/' . $this->encryption_base_dir . '/' . $encryptionModuleId . '/' . $keyId; } else { @@ -206,7 +205,6 @@ class Storage implements IStorage { * @return string */ private function getKey($path) { - $key = ''; if ($this->view->file_exists($path)) { @@ -250,7 +248,6 @@ class Storage implements IStorage { * @return string */ private function getFileKeyDir($encryptionModuleId, $path) { - list($owner, $filename) = $this->util->getUidAndFilename($path); // in case of system wide mount points the keys are stored directly in the data directory @@ -271,7 +268,6 @@ class Storage implements IStorage { * @return boolean */ public function renameKeys($source, $target) { - $sourcePath = $this->getPathToKeys($source); $targetPath = $this->getPathToKeys($target); @@ -294,7 +290,6 @@ class Storage implements IStorage { * @return boolean */ public function copyKeys($source, $target) { - $sourcePath = $this->getPathToKeys($source); $targetPath = $this->getPathToKeys($target); @@ -375,5 +370,4 @@ class Storage implements IStorage { } } } - } diff --git a/lib/private/Encryption/Manager.php b/lib/private/Encryption/Manager.php index 52fc23de947..f160a16a995 100644 --- a/lib/private/Encryption/Manager.php +++ b/lib/private/Encryption/Manager.php @@ -84,7 +84,6 @@ class Manager implements IManager { * @return bool true if enabled, false if not */ public function isEnabled() { - $installed = $this->config->getSystemValue('installed', false); if (!$installed) { return false; @@ -101,7 +100,6 @@ class Manager implements IManager { * @throws ServiceUnavailableException */ public function isReady() { - if ($this->isKeyStorageReady() === false) { throw new ServiceUnavailableException('Key Storage is not ready'); } @@ -137,7 +135,6 @@ class Manager implements IManager { * @throws Exceptions\ModuleAlreadyExistsException */ public function registerEncryptionModule($id, $displayName, callable $callback) { - if (isset($this->encryptionModules[$id])) { throw new Exceptions\ModuleAlreadyExistsException($id, $displayName); } @@ -213,7 +210,6 @@ class Manager implements IManager { $message = 'No default encryption module defined'; throw new Exceptions\ModuleDoesNotExistsException($message); } - } /** @@ -260,7 +256,6 @@ class Manager implements IManager { * @return bool */ protected function isKeyStorageReady() { - $rootDir = $this->util->getKeyStorageRoot(); // the default root is always valid @@ -275,6 +270,4 @@ class Manager implements IManager { return false; } - - } diff --git a/lib/private/Encryption/Update.php b/lib/private/Encryption/Update.php index f5128abd0b0..beb76a223b7 100644 --- a/lib/private/Encryption/Update.php +++ b/lib/private/Encryption/Update.php @@ -41,7 +41,7 @@ class Update { /** @var \OC\Encryption\Util */ protected $util; - /** @var \OC\Files\Mount\Manager */ + /** @var \OC\Files\Mount\Manager */ protected $mountManager; /** @var \OC\Encryption\Manager */ @@ -70,7 +70,6 @@ class Update { File $file, $uid ) { - $this->view = $view; $this->util = $util; $this->mountManager = $mountManager; @@ -133,13 +132,13 @@ class Update { public function postRename($params) { $source = $params['oldpath']; $target = $params['newpath']; - if( + if ( $this->encryptionManager->isEnabled() && dirname($source) !== dirname($target) ) { - list($owner, $ownerPath) = $this->getOwnerPath($target); - $absPath = '/' . $owner . '/files/' . $ownerPath; - $this->update($absPath); + list($owner, $ownerPath) = $this->getOwnerPath($target); + $absPath = '/' . $owner . '/files/' . $ownerPath; + $this->update($absPath); } } @@ -169,7 +168,6 @@ class Update { * @throws Exceptions\ModuleDoesNotExistsException */ public function update($path) { - $encryptionModule = $this->encryptionManager->getEncryptionModule(); // if the encryption module doesn't encrypt the files on a per-user basis @@ -192,5 +190,4 @@ class Update { $encryptionModule->update($file, $this->uid, $usersSharing); } } - } diff --git a/lib/private/Encryption/Util.php b/lib/private/Encryption/Util.php index 937a77bca7a..a5414a66796 100644 --- a/lib/private/Encryption/Util.php +++ b/lib/private/Encryption/Util.php @@ -38,7 +38,6 @@ use OCP\IConfig; use OCP\IUser; class Util { - const HEADER_START = 'HBEGIN'; const HEADER_END = 'HEND'; const HEADER_PADDING_CHAR = '-'; @@ -89,7 +88,6 @@ class Util { \OC\User\Manager $userManager, \OC\Group\Manager $groupManager, IConfig $config) { - $this->ocHeaderKeys = [ self::HEADER_ENCRYPTION_MODULE_KEY ]; @@ -179,7 +177,6 @@ class Util { $result[] = $c->getPath(); } } - } return $result; @@ -226,7 +223,6 @@ class Util { * @throws \BadMethodCallException */ public function getUidAndFilename($path) { - $parts = explode('/', $path); $uid = ''; if (count($parts) > 2) { @@ -241,7 +237,6 @@ class Util { $ownerPath = implode('/', array_slice($parts, 2)); return [$uid, Filesystem::normalizePath($ownerPath)]; - } /** @@ -254,18 +249,16 @@ class Util { $extension = pathinfo($path, PATHINFO_EXTENSION); if ($extension === 'part') { - $newLength = strlen($path) - 5; // 5 = strlen(".part") $fPath = substr($path, 0, $newLength); // if path also contains a transaction id, we remove it too $extension = pathinfo($fPath, PATHINFO_EXTENSION); - if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId") + if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId") $newLength = strlen($fPath) - strlen($extension) -1; $fPath = substr($fPath, 0, $newLength); } return $fPath; - } else { return $path; } @@ -372,7 +365,6 @@ class Util { // detect user specific folders if ($this->userManager->userExists($root[1]) && in_array($root[2], $this->excludedPaths)) { - return true; } } @@ -408,5 +400,4 @@ class Util { public function getKeyStorageRoot() { return $this->config->getAppValue('core', 'encryption_key_storage_root', ''); } - } diff --git a/lib/private/EventDispatcher/EventDispatcher.php b/lib/private/EventDispatcher/EventDispatcher.php index 91b3e078b25..b81b4741306 100644 --- a/lib/private/EventDispatcher/EventDispatcher.php +++ b/lib/private/EventDispatcher/EventDispatcher.php @@ -104,5 +104,4 @@ class EventDispatcher implements IEventDispatcher { public function getSymfonyDispatcher(): SymfonyDispatcher { return $this->dispatcher; } - } diff --git a/lib/private/EventDispatcher/ServiceEventListener.php b/lib/private/EventDispatcher/ServiceEventListener.php index b10e3d534d6..a648884d6f7 100644 --- a/lib/private/EventDispatcher/ServiceEventListener.php +++ b/lib/private/EventDispatcher/ServiceEventListener.php @@ -75,5 +75,4 @@ final class ServiceEventListener { $this->service->handle($event); } - } diff --git a/lib/private/EventDispatcher/SymfonyAdapter.php b/lib/private/EventDispatcher/SymfonyAdapter.php index 4d473854962..b1a39a79131 100644 --- a/lib/private/EventDispatcher/SymfonyAdapter.php +++ b/lib/private/EventDispatcher/SymfonyAdapter.php @@ -147,5 +147,4 @@ class SymfonyAdapter implements EventDispatcherInterface { public function hasListeners($eventName = null) { return $this->eventDispatcher->getSymfonyDispatcher()->hasListeners($eventName); } - } diff --git a/lib/private/Federation/CloudFederationNotification.php b/lib/private/Federation/CloudFederationNotification.php index c8ec13e1954..ad1d689dcd0 100644 --- a/lib/private/Federation/CloudFederationNotification.php +++ b/lib/private/Federation/CloudFederationNotification.php @@ -33,7 +33,6 @@ use OCP\Federation\ICloudFederationNotification; * @since 14.0.0 */ class CloudFederationNotification implements ICloudFederationNotification { - private $message = []; /** @@ -53,7 +52,6 @@ class CloudFederationNotification implements ICloudFederationNotification { 'providerId' => $providerId, 'notification' => $notification, ]; - } /** diff --git a/lib/private/Federation/CloudFederationProviderManager.php b/lib/private/Federation/CloudFederationProviderManager.php index cad72abaf79..459d82c5bfb 100644 --- a/lib/private/Federation/CloudFederationProviderManager.php +++ b/lib/private/Federation/CloudFederationProviderManager.php @@ -96,7 +96,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager 'displayName' => $displayName, 'callback' => $callback, ]; - } /** @@ -152,7 +151,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager $result = json_decode($response->getBody(), true); return (is_array($result)) ? $result : []; } - } catch (\Exception $e) { // if flat re-sharing is not supported by the remote server // we re-throw the exception and fall back to the old behaviour. @@ -164,7 +162,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager } return false; - } /** @@ -214,7 +211,6 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager * @return string */ protected function getOCMEndPoint($url) { - if (isset($this->ocmEndPoints[$url])) { return $this->ocmEndPoints[$url]; } @@ -240,6 +236,4 @@ class CloudFederationProviderManager implements ICloudFederationProviderManager $this->ocmEndPoints[$url] = ''; return ''; } - - } diff --git a/lib/private/Federation/CloudFederationShare.php b/lib/private/Federation/CloudFederationShare.php index 50a01d46b3f..16f4216d65e 100644 --- a/lib/private/Federation/CloudFederationShare.php +++ b/lib/private/Federation/CloudFederationShare.php @@ -26,7 +26,6 @@ namespace OC\Federation; use OCP\Federation\ICloudFederationShare; class CloudFederationShare implements ICloudFederationShare { - private $share = [ 'shareWith' => '', 'shareType' => '', @@ -85,7 +84,6 @@ class CloudFederationShare implements ICloudFederationShare { ]); $this->setShareType($shareType); $this->setResourceType($resourceType); - } /** diff --git a/lib/private/Files/AppData/AppData.php b/lib/private/Files/AppData/AppData.php index 32f97034050..5f917afe207 100644 --- a/lib/private/Files/AppData/AppData.php +++ b/lib/private/Files/AppData/AppData.php @@ -65,7 +65,6 @@ class AppData implements IAppData { public function __construct(IRootFolder $rootFolder, SystemConfig $systemConfig, string $appId) { - $this->rootFolder = $rootFolder; $this->config = $systemConfig; $this->appId = $appId; diff --git a/lib/private/Files/AppData/Factory.php b/lib/private/Files/AppData/Factory.php index 085c17f3589..4801b241c0b 100644 --- a/lib/private/Files/AppData/Factory.php +++ b/lib/private/Files/AppData/Factory.php @@ -42,7 +42,6 @@ class Factory { public function __construct(IRootFolder $rootFolder, SystemConfig $systemConfig) { - $this->rootFolder = $rootFolder; $this->config = $systemConfig; } diff --git a/lib/private/Files/Cache/Cache.php b/lib/private/Files/Cache/Cache.php index bce9a1d88e0..2dfefeff662 100644 --- a/lib/private/Files/Cache/Cache.php +++ b/lib/private/Files/Cache/Cache.php @@ -331,7 +331,6 @@ class Cache implements ICache { * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged */ public function update($id, array $data) { - if (isset($data['path'])) { // normalize path $data['path'] = $this->normalize($data['path']); @@ -990,7 +989,6 @@ class Cache implements ICache { * @return string */ public function normalize($path) { - return trim(\OC_Util::normalizeUnicode($path), '/'); } } diff --git a/lib/private/Files/Cache/Propagator.php b/lib/private/Files/Cache/Propagator.php index 7a1eae3498a..92fa6436548 100644 --- a/lib/private/Files/Cache/Propagator.php +++ b/lib/private/Files/Cache/Propagator.php @@ -200,6 +200,4 @@ class Propagator implements IPropagator { $this->connection->commit(); } - - } diff --git a/lib/private/Files/Cache/Scanner.php b/lib/private/Files/Cache/Scanner.php index 87f32538ec7..2a5a6536697 100644 --- a/lib/private/Files/Cache/Scanner.php +++ b/lib/private/Files/Cache/Scanner.php @@ -238,7 +238,6 @@ class Scanner extends BasicEmitter implements IScanner { $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]); \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]); } - } else { $this->removeFromCache($file); } diff --git a/lib/private/Files/Cache/Storage.php b/lib/private/Files/Cache/Storage.php index ca573be798a..62228e16290 100644 --- a/lib/private/Files/Cache/Storage.php +++ b/lib/private/Files/Cache/Storage.php @@ -126,7 +126,6 @@ class Storage { * @return string|null either the storage id string or null if the numeric id is not known */ public static function getStorageId($numericId) { - $sql = 'SELECT `id` FROM `*PREFIX*storages` WHERE `numeric_id` = ?'; $result = \OC_DB::executeAudited($sql, [$numericId]); if ($row = $result->fetchRow()) { diff --git a/lib/private/Files/Cache/Updater.php b/lib/private/Files/Cache/Updater.php index 378cadfcace..60534a153dd 100644 --- a/lib/private/Files/Cache/Updater.php +++ b/lib/private/Files/Cache/Updater.php @@ -167,7 +167,6 @@ class Updater implements IUpdater { $this->cache->correctFolderSize($parent); } } - } /** diff --git a/lib/private/Files/Cache/Watcher.php b/lib/private/Files/Cache/Watcher.php index 6270f03ca92..d6291ca71e9 100644 --- a/lib/private/Files/Cache/Watcher.php +++ b/lib/private/Files/Cache/Watcher.php @@ -34,7 +34,6 @@ use OCP\Files\Cache\IWatcher; * check the storage backends for updates and change the cache accordingly */ class Watcher implements IWatcher { - protected $watchPolicy = self::CHECK_ONCE; protected $checkedPaths = []; diff --git a/lib/private/Files/Cache/Wrapper/CacheJail.php b/lib/private/Files/Cache/Wrapper/CacheJail.php index 8c30eeda2cf..8d4f412868e 100644 --- a/lib/private/Files/Cache/Wrapper/CacheJail.php +++ b/lib/private/Files/Cache/Wrapper/CacheJail.php @@ -273,7 +273,6 @@ class CacheJail extends CacheWrapper { } else { return 0; } - } /** diff --git a/lib/private/Files/Mount/ObjectHomeMountProvider.php b/lib/private/Files/Mount/ObjectHomeMountProvider.php index e49b704fe96..9b243d7f8f2 100644 --- a/lib/private/Files/Mount/ObjectHomeMountProvider.php +++ b/lib/private/Files/Mount/ObjectHomeMountProvider.php @@ -57,7 +57,6 @@ class ObjectHomeMountProvider implements IHomeMountProvider { * @return \OCP\Files\Mount\IMountPoint */ public function getHomeMountForUser(IUser $user, IStorageFactory $loader) { - $config = $this->getMultiBucketObjectStoreConfig($user); if ($config === null) { $config = $this->getSingleBucketObjectStoreConfig($user); diff --git a/lib/private/Files/Node/Folder.php b/lib/private/Files/Node/Folder.php index b24abf34f33..d9639e9f1ab 100644 --- a/lib/private/Files/Node/Folder.php +++ b/lib/private/Files/Node/Folder.php @@ -161,7 +161,7 @@ class Folder extends Node implements \OCP\Files\Folder { $fullPath = $this->getFullPath($path); $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath); $this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]); - if(!$this->view->mkdir($fullPath)) { + if (!$this->view->mkdir($fullPath)) { throw new NotPermittedException('Could not create folder'); } $node = new Folder($this->root, $this->view, $fullPath); diff --git a/lib/private/Files/Node/HookConnector.php b/lib/private/Files/Node/HookConnector.php index 67fadf19863..1f7f194c5f7 100644 --- a/lib/private/Files/Node/HookConnector.php +++ b/lib/private/Files/Node/HookConnector.php @@ -170,7 +170,6 @@ class HookConnector { private function getNodeForPath($path) { $info = Filesystem::getView()->getFileInfo($path); if (!$info) { - $fullPath = Filesystem::getView()->getAbsolutePath($path); if (isset($this->deleteMetaCache[$fullPath])) { $info = $this->deleteMetaCache[$fullPath]; diff --git a/lib/private/Files/Node/Node.php b/lib/private/Files/Node/Node.php index f8591080840..70821e685f8 100644 --- a/lib/private/Files/Node/Node.php +++ b/lib/private/Files/Node/Node.php @@ -465,5 +465,4 @@ class Node implements \OCP\Files\Node { public function getUploadTime(): int { return $this->getFileInfo()->getUploadTime(); } - } diff --git a/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php b/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php index 98b99efcb5a..efe3f7c12d0 100644 --- a/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/HomeObjectStoreStorage.php @@ -65,6 +65,4 @@ class HomeObjectStoreStorage extends ObjectStoreStorage implements \OCP\Files\IH public function getUser($path = null) { return $this->user; } - - } diff --git a/lib/private/Files/ObjectStore/NoopScanner.php b/lib/private/Files/ObjectStore/NoopScanner.php index 7a253c82c5b..57a94aba294 100644 --- a/lib/private/Files/ObjectStore/NoopScanner.php +++ b/lib/private/Files/ObjectStore/NoopScanner.php @@ -31,7 +31,6 @@ use OC\Files\Cache\Scanner; use OC\Files\Storage\Storage; class NoopScanner extends Scanner { - public function __construct(Storage $storage) { //we don't need the storage, so do nothing here } diff --git a/lib/private/Files/ObjectStore/ObjectStoreStorage.php b/lib/private/Files/ObjectStore/ObjectStoreStorage.php index 7224f075d82..1faa44ad888 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/ObjectStoreStorage.php @@ -182,7 +182,7 @@ class ObjectStoreStorage extends \OC\Files\Storage\Common { return false; } } else { - if(!$this->unlink($child['path'])) { + if (!$this->unlink($child['path'])) { return false; } } diff --git a/lib/private/Files/ObjectStore/S3Signature.php b/lib/private/Files/ObjectStore/S3Signature.php index 6216992ad7a..f9ea2e22aad 100644 --- a/lib/private/Files/ObjectStore/S3Signature.php +++ b/lib/private/Files/ObjectStore/S3Signature.php @@ -33,8 +33,7 @@ use Psr\Http\Message\RequestInterface; /** * Legacy Amazon S3 signature implementation */ -class S3Signature implements SignatureInterface -{ +class S3Signature implements SignatureInterface { /** @var array Query string values that must be signed */ private $signableQueryString = [ 'acl', 'cors', 'delete', 'lifecycle', 'location', 'logging', @@ -52,8 +51,7 @@ class S3Signature implements SignatureInterface /** @var \Aws\S3\S3UriParser S3 URI parser */ private $parser; - public function __construct() - { + public function __construct() { $this->parser = new S3UriParser(); // Ensure that the signable query string parameters are sorted sort($this->signableQueryString); @@ -140,8 +138,7 @@ class S3Signature implements SignatureInterface return Psr7\modify_request($request, $modify); } - private function signString($string, CredentialsInterface $credentials) - { + private function signString($string, CredentialsInterface $credentials) { return base64_encode( hash_hmac('sha1', $string, $credentials->getSecretKey(), true) ); @@ -166,8 +163,7 @@ class S3Signature implements SignatureInterface return $buffer; } - private function createCanonicalizedAmzHeaders(RequestInterface $request) - { + private function createCanonicalizedAmzHeaders(RequestInterface $request) { $headers = []; foreach ($request->getHeaders() as $name => $header) { $name = strtolower($name); @@ -188,8 +184,7 @@ class S3Signature implements SignatureInterface return implode("\n", $headers) . "\n"; } - private function createCanonicalizedResource(RequestInterface $request) - { + private function createCanonicalizedResource(RequestInterface $request) { $data = $this->parser->parse($request->getUri()); $buffer = '/'; diff --git a/lib/private/Files/SimpleFS/SimpleFile.php b/lib/private/Files/SimpleFS/SimpleFile.php index dbc5f06f22b..e3a581b25d7 100644 --- a/lib/private/Files/SimpleFS/SimpleFile.php +++ b/lib/private/Files/SimpleFS/SimpleFile.php @@ -29,7 +29,7 @@ use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFile; -class SimpleFile implements ISimpleFile { +class SimpleFile implements ISimpleFile { /** @var File $file */ private $file; @@ -179,5 +179,4 @@ class SimpleFile implements ISimpleFile { public function write() { return $this->file->fopen('w'); } - } diff --git a/lib/private/Files/SimpleFS/SimpleFolder.php b/lib/private/Files/SimpleFS/SimpleFolder.php index 7196b55ea12..aa5c200f5bd 100644 --- a/lib/private/Files/SimpleFS/SimpleFolder.php +++ b/lib/private/Files/SimpleFS/SimpleFolder.php @@ -30,7 +30,7 @@ use OCP\Files\Node; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFolder; -class SimpleFolder implements ISimpleFolder { +class SimpleFolder implements ISimpleFolder { /** @var Folder */ private $folder; diff --git a/lib/private/Files/Storage/Common.php b/lib/private/Files/Storage/Common.php index 456980db538..edad9cc874c 100644 --- a/lib/private/Files/Storage/Common.php +++ b/lib/private/Files/Storage/Common.php @@ -76,7 +76,6 @@ use OCP\Lock\LockedException; * in classes which extend it, e.g. $this->stat() . */ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage { - use LocalTempFileTrait; protected $cache; @@ -301,7 +300,9 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage { $dh = $this->opendir($dir); if (is_resource($dh)) { while (($item = readdir($dh)) !== false) { - if (\OC\Files\Filesystem::isIgnoredDir($item)) continue; + if (\OC\Files\Filesystem::isIgnoredDir($item)) { + continue; + } if (strstr(strtolower($item), strtolower($query)) !== false) { $files[] = $dir . '/' . $item; } diff --git a/lib/private/Files/Storage/CommonTest.php b/lib/private/Files/Storage/CommonTest.php index 164738d9478..f3a127b635a 100644 --- a/lib/private/Files/Storage/CommonTest.php +++ b/lib/private/Files/Storage/CommonTest.php @@ -32,7 +32,7 @@ namespace OC\Files\Storage; -class CommonTest extends \OC\Files\Storage\Common{ +class CommonTest extends \OC\Files\Storage\Common { /** * underlying local storage used for missing functions * @var \OC\Files\Storage\Local diff --git a/lib/private/Files/Storage/DAV.php b/lib/private/Files/Storage/DAV.php index 3100a14a570..2974064f3a5 100644 --- a/lib/private/Files/Storage/DAV.php +++ b/lib/private/Files/Storage/DAV.php @@ -98,8 +98,11 @@ class DAV extends Common { if (isset($params['host']) && isset($params['user']) && isset($params['password'])) { $host = $params['host']; //remove leading http[s], will be generated in createBaseUri() - if (substr($host, 0, 8) == "https://") $host = substr($host, 8); - elseif (substr($host, 0, 7) == "http://") $host = substr($host, 7); + if (substr($host, 0, 8) == "https://") { + $host = substr($host, 8); + } elseif (substr($host, 0, 7) == "http://") { + $host = substr($host, 7); + } $this->host = $host; $this->user = $params['user']; $this->password = $params['password']; @@ -153,7 +156,7 @@ class DAV extends Common { $this->client = new Client($settings); $this->client->setThrowExceptions(true); - if($this->secure === true) { + if ($this->secure === true) { $certPath = $this->certManager->getAbsoluteBundlePath(); if (file_exists($certPath)) { $this->certPath = $certPath; @@ -853,7 +856,7 @@ class DAV extends Common { } elseif ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) { // ignore exception for MethodNotAllowed, false will be returned return; - } elseif ($e->getHttpStatus() === Http::STATUS_FORBIDDEN){ + } elseif ($e->getHttpStatus() === Http::STATUS_FORBIDDEN) { // The operation is forbidden. Fail somewhat gracefully throw new ForbiddenException(get_class($e) . ':' . $e->getMessage()); } diff --git a/lib/private/Files/Storage/Local.php b/lib/private/Files/Storage/Local.php index 05dd8c4d68f..89b318b4770 100644 --- a/lib/private/Files/Storage/Local.php +++ b/lib/private/Files/Storage/Local.php @@ -280,7 +280,6 @@ class Local extends \OC\Files\Storage\Common { } else { return false; } - } private function treeContainsBlacklistedFile(string $path): bool { @@ -393,8 +392,9 @@ class Local extends \OC\Files\Storage\Common { $files = []; $physicalDir = $this->getSourcePath($dir); foreach (scandir($physicalDir) as $item) { - if (\OC\Files\Filesystem::isIgnoredDir($item)) + if (\OC\Files\Filesystem::isIgnoredDir($item)) { continue; + } $physicalItem = $physicalDir . '/' . $item; if (strstr(strtolower($item), strtolower($query)) !== false) { diff --git a/lib/private/Files/Storage/Temporary.php b/lib/private/Files/Storage/Temporary.php index 5e4f834990b..5e4024286c5 100644 --- a/lib/private/Files/Storage/Temporary.php +++ b/lib/private/Files/Storage/Temporary.php @@ -29,7 +29,7 @@ namespace OC\Files\Storage; /** * local storage backend in temporary folder for testing purpose */ -class Temporary extends Local{ +class Temporary extends Local { public function __construct($arguments = null) { parent::__construct(['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]); } diff --git a/lib/private/Files/Storage/Wrapper/Availability.php b/lib/private/Files/Storage/Wrapper/Availability.php index 1540ac98a4b..b949c9103a7 100644 --- a/lib/private/Files/Storage/Wrapper/Availability.php +++ b/lib/private/Files/Storage/Wrapper/Availability.php @@ -451,7 +451,7 @@ class Availability extends Wrapper { */ protected function setUnavailable(StorageNotAvailableException $e) { $delay = self::RECHECK_TTL_SEC; - if($e instanceof StorageAuthException) { + if ($e instanceof StorageAuthException) { $delay = max( // 30min $this->config->getSystemValueInt('external_storage.auth_availability_delay', 1800), diff --git a/lib/private/Files/Storage/Wrapper/Encryption.php b/lib/private/Files/Storage/Wrapper/Encryption.php index 850b6205412..1ea2664877b 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -51,7 +51,6 @@ use OCP\Files\Storage; use OCP\ILogger; class Encryption extends Wrapper { - use LocalTempFileTrait; /** @var string */ @@ -117,7 +116,6 @@ class Encryption extends Wrapper { Manager $mountManager = null, ArrayCache $arrayCache = null ) { - $this->mountPoint = $parameters['mountPoint']; $this->mount = $parameters['mount']; $this->encryptionManager = $encryptionManager; @@ -207,7 +205,6 @@ class Encryption extends Wrapper { * @return string */ public function file_get_contents($path) { - $encryptionModule = $this->getEncryptionModule($path); if ($encryptionModule) { @@ -269,7 +266,6 @@ class Encryption extends Wrapper { * @return bool */ public function rename($path1, $path2) { - $result = $this->storage->rename($path1, $path2); if ($result && @@ -320,7 +316,6 @@ class Encryption extends Wrapper { * @return bool */ public function isReadable($path) { - $isReadable = true; $metaData = $this->getMetaData($path); @@ -345,7 +340,6 @@ class Encryption extends Wrapper { * @return bool */ public function copy($path1, $path2) { - $source = $this->getFullPath($path1); if ($this->util->isExcluded($source)) { @@ -386,7 +380,6 @@ class Encryption extends Wrapper { $encryptionModuleId = $this->util->getEncryptionModuleId($header); if ($this->util->isExcluded($fullPath) === false) { - $size = $unencryptedSize = 0; $realFile = $this->util->stripPartialFileExtension($path); $targetExists = $this->file_exists($realFile) || $this->file_exists($path); @@ -409,7 +402,6 @@ class Encryption extends Wrapper { } try { - if ( $mode === 'w' || $mode === 'w+' @@ -472,7 +464,6 @@ class Encryption extends Wrapper { $size, $unencryptedSize, $headerSize, $signed); return $handle; } - } return $this->storage->fopen($path, $mode); @@ -489,7 +480,6 @@ class Encryption extends Wrapper { * @return int unencrypted size */ protected function verifyUnencryptedSize($path, $unencryptedSize) { - $size = $this->storage->filesize($path); $result = $unencryptedSize; @@ -523,7 +513,6 @@ class Encryption extends Wrapper { * @return int calculated unencrypted size */ protected function fixUnencryptedSize($path, $size, $unencryptedSize) { - $headerSize = $this->getHeaderSize($path); $header = $this->getHeader($path); $encryptionModule = $this->getEncryptionModule($path); @@ -572,7 +561,7 @@ class Encryption extends Wrapper { $data=fread($stream, $blockSize); $count=strlen($data); $lastChunkContentEncrypted .= $data; - if(strlen($lastChunkContentEncrypted) > $blockSize) { + if (strlen($lastChunkContentEncrypted) > $blockSize) { $newUnencryptedSize += $unencryptedBlockSize; $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize); } @@ -667,7 +656,7 @@ class Encryption extends Wrapper { $cacheInformation = [ 'encrypted' => $isEncrypted, ]; - if($isEncrypted) { + if ($isEncrypted) { $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion']; // In case of a move operation from an unencrypted to an encrypted @@ -675,7 +664,7 @@ class Encryption extends Wrapper { // correct value would be "1". Thus we manually set the value to "1" // for those cases. // See also https://github.com/owncloud/core/issues/23078 - if($encryptedVersion === 0 || !$keepEncryptionVersion) { + if ($encryptedVersion === 0 || !$keepEncryptionVersion) { $encryptedVersion = 1; } @@ -762,7 +751,7 @@ class Encryption extends Wrapper { fclose($target); throw $e; } - if($result) { + if ($result) { if ($preserveMtime) { $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath)); } @@ -775,7 +764,6 @@ class Encryption extends Wrapper { } } return (bool)$result; - } /** @@ -1030,7 +1018,6 @@ class Encryption extends Wrapper { } return $encryptionModule->shouldEncrypt($fullPath); - } public function writeStream(string $path, $stream, int $size = null): int { @@ -1040,5 +1027,4 @@ class Encryption extends Wrapper { fclose($target); return $count; } - } diff --git a/lib/private/Files/Storage/Wrapper/Quota.php b/lib/private/Files/Storage/Wrapper/Quota.php index d4e4be41f71..62d3335987c 100644 --- a/lib/private/Files/Storage/Wrapper/Quota.php +++ b/lib/private/Files/Storage/Wrapper/Quota.php @@ -229,5 +229,4 @@ class Quota extends Wrapper { return parent::touch($path, $mtime); } - } diff --git a/lib/private/Files/Stream/Encryption.php b/lib/private/Files/Stream/Encryption.php index 527453c32e9..1fc14daacbd 100644 --- a/lib/private/Files/Stream/Encryption.php +++ b/lib/private/Files/Stream/Encryption.php @@ -165,7 +165,6 @@ class Encryption extends Wrapper { $headerSize, $signed, $wrapper = Encryption::class) { - $context = stream_context_create([ 'ocencryption' => [ 'source' => $source, @@ -233,7 +232,6 @@ class Encryption extends Wrapper { } } return $context; - } public function stream_open($path, $mode, $options, &$opened_path) { @@ -285,7 +283,6 @@ class Encryption extends Wrapper { } return true; - } public function stream_eof() { @@ -293,7 +290,6 @@ class Encryption extends Wrapper { } public function stream_read($count) { - $result = ''; $count = min($count, $this->unencryptedSize - $this->position); @@ -308,7 +304,7 @@ class Encryption extends Wrapper { $result .= substr($this->cache, $blockPosition, $remainingLength); $this->position += $remainingLength; $count = 0; - // otherwise remainder of current block is fetched, the block is flushed and the position updated + // otherwise remainder of current block is fetched, the block is flushed and the position updated } else { $result .= substr($this->cache, $blockPosition); $this->flush(); @@ -317,7 +313,6 @@ class Encryption extends Wrapper { } } return $result; - } /** @@ -378,7 +373,7 @@ class Encryption extends Wrapper { $this->position += $remainingLength; $length += $remainingLength; $data = ''; - // if $data doesn't fit the current block, the fill the current block and reiterate + // if $data doesn't fit the current block, the fill the current block and reiterate // after the block is filled, it is flushed and $data is updatedxxx } else { $this->cache = substr($this->cache, 0, $blockPosition) . @@ -401,7 +396,6 @@ class Encryption extends Wrapper { } public function stream_seek($offset, $whence = SEEK_SET) { - $return = false; switch ($whence) { @@ -434,7 +428,6 @@ class Encryption extends Wrapper { $return = true; } return $return; - } public function stream_close() { @@ -442,7 +435,7 @@ class Encryption extends Wrapper { $position = (int)floor($this->position/$this->unencryptedBlockSize); $remainingData = $this->encryptionModule->end($this->fullPath, $position . 'end'); if ($this->readOnly === false) { - if(!empty($remainingData)) { + if (!empty($remainingData)) { parent::stream_write($remainingData); } $this->encryptionStorage->updateUnencryptedSize($this->fullPath, $this->unencryptedSize); @@ -502,7 +495,7 @@ class Encryption extends Wrapper { $data = $this->stream_read_block($this->util->getBlockSize()); $position = (int)floor($this->position/$this->unencryptedBlockSize); $numberOfChunks = (int)($this->unencryptedSize / $this->unencryptedBlockSize); - if($numberOfChunks === $position) { + if ($numberOfChunks === $position) { $position .= 'end'; } $this->cache = $this->encryptionModule->decrypt($data, $position); @@ -545,5 +538,4 @@ class Encryption extends Wrapper { public function dir_opendir($path, $options) { return false; } - } diff --git a/lib/private/Files/Stream/Quota.php b/lib/private/Files/Stream/Quota.php index 877a05e6aa9..d0609d7e459 100644 --- a/lib/private/Files/Stream/Quota.php +++ b/lib/private/Files/Stream/Quota.php @@ -67,17 +67,16 @@ class Quota extends Wrapper { } public function stream_seek($offset, $whence = SEEK_SET) { - if ($whence === SEEK_END){ + if ($whence === SEEK_END) { // go to the end to find out last position's offset $oldOffset = $this->stream_tell(); - if (fseek($this->source, 0, $whence) !== 0){ + if (fseek($this->source, 0, $whence) !== 0) { return false; } $whence = SEEK_SET; $offset = $this->stream_tell() + $offset; $this->limit += $oldOffset - $offset; - } - elseif ($whence === SEEK_SET) { + } elseif ($whence === SEEK_SET) { $this->limit += $this->stream_tell() - $offset; } else { $this->limit -= $offset; diff --git a/lib/private/Files/Type/Detection.php b/lib/private/Files/Type/Detection.php index b36f8a70b99..e8825037666 100644 --- a/lib/private/Files/Type/Detection.php +++ b/lib/private/Files/Type/Detection.php @@ -51,7 +51,6 @@ use OCP\IURLGenerator; * @package OC\Files\Type */ class Detection implements IMimeTypeDetector { - private const CUSTOM_MIMETYPEMAPPING = 'mimetypemapping.json'; private const CUSTOM_MIMETYPEALIASES = 'mimetypealiases.json'; @@ -279,7 +278,6 @@ class Detection implements IMimeTypeDetector { return $mimeType; } } - } return 'application/octet-stream'; } diff --git a/lib/private/Files/Type/Loader.php b/lib/private/Files/Type/Loader.php index fded04b5466..d128bc724b6 100644 --- a/lib/private/Files/Type/Loader.php +++ b/lib/private/Files/Type/Loader.php @@ -173,5 +173,4 @@ class Loader implements IMimeTypeLoader { )); return $update->execute(); } - } diff --git a/lib/private/Files/Utils/Scanner.php b/lib/private/Files/Utils/Scanner.php index 49f8177834a..a729da89fb0 100644 --- a/lib/private/Files/Utils/Scanner.php +++ b/lib/private/Files/Utils/Scanner.php @@ -223,7 +223,6 @@ class Scanner extends PublicEmitter { } else {// if the root exists in neither the cache nor the storage the user isn't setup yet break; } - } // don't scan received local shares, these can be scanned when scanning the owner's storage diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index da67fc461b5..20c0fd3ed1b 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -829,7 +829,7 @@ class View { $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2); } } - } catch(\Exception $e) { + } catch (\Exception $e) { throw $e; } finally { $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true); @@ -853,7 +853,7 @@ class View { } } } - } catch(\Exception $e) { + } catch (\Exception $e) { throw $e; } finally { $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true); @@ -895,7 +895,6 @@ class View { $lockTypePath2 = ILockingProvider::LOCK_SHARED; try { - $exists = $this->file_exists($path2); if ($this->shouldEmitHooks()) { \OC_Hook::emit( @@ -946,7 +945,6 @@ class View { ); $this->emit_file_hooks_post($exists, $path2); } - } } catch (\Exception $e) { $this->unlockFile($path2, $lockTypePath2); @@ -956,7 +954,6 @@ class View { $this->unlockFile($path2, $lockTypePath2); $this->unlockFile($path1, $lockTypePath1); - } return $result; } diff --git a/lib/private/FullTextSearch/FullTextSearchManager.php b/lib/private/FullTextSearch/FullTextSearchManager.php index 4af70d97260..119c97fa95b 100644 --- a/lib/private/FullTextSearch/FullTextSearchManager.php +++ b/lib/private/FullTextSearch/FullTextSearchManager.php @@ -230,6 +230,4 @@ class FullTextSearchManager implements IFullTextSearchManager { return $this->getSearchService()->search($userId, $searchRequest); } - - } diff --git a/lib/private/FullTextSearch/Model/IndexDocument.php b/lib/private/FullTextSearch/Model/IndexDocument.php index 7c7847b7463..252aa66395a 100644 --- a/lib/private/FullTextSearch/Model/IndexDocument.php +++ b/lib/private/FullTextSearch/Model/IndexDocument.php @@ -922,7 +922,6 @@ class IndexDocument implements IIndexDocument, JsonSerializable { * @return array */ final public function getInfoAll(): array { - $info = []; foreach ($this->info as $k => $v) { if (substr($k, 0, 1) === '_') { @@ -989,5 +988,4 @@ class IndexDocument implements IIndexDocument, JsonSerializable { 'score' => $this->getScore() ]; } - } diff --git a/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php b/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php index 19be494d82f..c015c4c1579 100644 --- a/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php +++ b/lib/private/FullTextSearch/Model/SearchRequestSimpleQuery.php @@ -178,5 +178,4 @@ final class SearchRequestSimpleQuery implements ISearchRequestSimpleQuery, JsonS 'values' => $this->getValues() ]; } - } diff --git a/lib/private/GlobalScale/Config.php b/lib/private/GlobalScale/Config.php index f886ac8ff84..d4bde44a5fa 100644 --- a/lib/private/GlobalScale/Config.php +++ b/lib/private/GlobalScale/Config.php @@ -67,5 +67,4 @@ class Config implements \OCP\GlobalScale\IConfig { return $enabled === 'internal'; } - } diff --git a/lib/private/Group/Backend.php b/lib/private/Group/Backend.php index 4e2f912e7fc..0f0e2c743e8 100644 --- a/lib/private/Group/Backend.php +++ b/lib/private/Group/Backend.php @@ -53,8 +53,8 @@ abstract class Backend implements \OCP\GroupInterface { */ public function getSupportedActions() { $actions = 0; - foreach($this->possibleActions as $action => $methodName) { - if(method_exists($this, $methodName)) { + foreach ($this->possibleActions as $action => $methodName) { + if (method_exists($this, $methodName)) { $actions |= $action; } } diff --git a/lib/private/Group/Database.php b/lib/private/Group/Database.php index 99654b5d1f2..b75dc097c97 100644 --- a/lib/private/Group/Database.php +++ b/lib/private/Group/Database.php @@ -113,7 +113,7 @@ class Database extends ABackend ->setValue('gid', $builder->createNamedParameter($gid)) ->setValue('displayname', $builder->createNamedParameter($gid)) ->execute(); - } catch(UniqueConstraintViolationException $e) { + } catch (UniqueConstraintViolationException $e) { $result = 0; } @@ -194,14 +194,14 @@ class Database extends ABackend $this->fixDI(); // No duplicate entries! - if(!$this->inGroup($uid, $gid)) { + if (!$this->inGroup($uid, $gid)) { $qb = $this->dbConn->getQueryBuilder(); $qb->insert('group_user') ->setValue('uid', $qb->createNamedParameter($uid)) ->setValue('gid', $qb->createNamedParameter($gid)) ->execute(); return true; - }else{ + } else { return false; } } @@ -250,7 +250,7 @@ class Database extends ABackend ->execute(); $groups = []; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $groups[] = $row['gid']; $this->groupCache[$row['gid']] = $row['gid']; } @@ -473,5 +473,4 @@ class Database extends ABackend return true; } - } diff --git a/lib/private/Group/Group.php b/lib/private/Group/Group.php index 9eb1b616609..2e16d5f1242 100644 --- a/lib/private/Group/Group.php +++ b/lib/private/Group/Group.php @@ -265,8 +265,8 @@ class Group implements IGroup { public function count($search = '') { $users = false; foreach ($this->backends as $backend) { - if($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { - if($users === false) { + if ($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { + if ($users === false) { //we could directly add to a bool variable, but this would //be ugly $users = 0; @@ -285,8 +285,8 @@ class Group implements IGroup { public function countDisabled() { $users = false; foreach ($this->backends as $backend) { - if($backend instanceof ICountDisabledInGroup) { - if($users === false) { + if ($backend instanceof ICountDisabledInGroup) { + if ($users === false) { //we could directly add to a bool variable, but this would //be ugly $users = 0; diff --git a/lib/private/Group/MetaData.php b/lib/private/Group/MetaData.php index 335bf43c16b..880dbf6437c 100644 --- a/lib/private/Group/MetaData.php +++ b/lib/private/Group/MetaData.php @@ -83,7 +83,7 @@ class MetaData { */ public function get($groupSearch = '', $userSearch = '') { $key = $groupSearch . '::' . $userSearch; - if(isset($this->metaData[$key])) { + if (isset($this->metaData[$key])) { return $this->metaData[$key]; } @@ -94,7 +94,7 @@ class MetaData { $sortAdminGroupsIndex = 0; $sortAdminGroupsKeys = []; - foreach($this->getGroups($groupSearch) as $group) { + foreach ($this->getGroups($groupSearch) as $group) { $groupMetaData = $this->generateGroupMetaData($group, $userSearch); if (strtolower($group->getGID()) !== 'admin') { $this->addEntry( @@ -194,11 +194,11 @@ class MetaData { * @return \OCP\IGroup[] */ public function getGroups($search = '') { - if($this->isAdmin) { + if ($this->isAdmin) { return $this->groupManager->search($search); } else { $userObject = $this->userSession->getUser(); - if($userObject !== null) { + if ($userObject !== null) { $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($userObject); } else { $groups = []; diff --git a/lib/private/HintException.php b/lib/private/HintException.php index 4b51a565f7b..acb8df414a3 100644 --- a/lib/private/HintException.php +++ b/lib/private/HintException.php @@ -35,7 +35,6 @@ namespace OC; * @package OC */ class HintException extends \Exception { - private $hint; /** diff --git a/lib/private/Http/Client/Client.php b/lib/private/Http/Client/Client.php index a73ae2c2be5..19d5877f9fb 100644 --- a/lib/private/Http/Client/Client.php +++ b/lib/private/Http/Client/Client.php @@ -76,7 +76,7 @@ class Client implements IClient { // Only add RequestOptions::PROXY if Nextcloud is explicitly // configured to use a proxy. This is needed in order not to override // Guzzle default values. - if($proxy !== null) { + if ($proxy !== null) { $defaults[RequestOptions::PROXY] = $proxy; } diff --git a/lib/private/Http/CookieHelper.php b/lib/private/Http/CookieHelper.php index 7d2acc7a193..7083584bffa 100644 --- a/lib/private/Http/CookieHelper.php +++ b/lib/private/Http/CookieHelper.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\Http; class CookieHelper { - const SAMESITE_NONE = 0; const SAMESITE_LAX = 1; const SAMESITE_STRICT = 2; diff --git a/lib/private/InitialStateService.php b/lib/private/InitialStateService.php index 6c8c242b662..55ce9c41726 100644 --- a/lib/private/InitialStateService.php +++ b/lib/private/InitialStateService.php @@ -89,5 +89,4 @@ class InitialStateService implements IInitialStateService { } return $appStates; } - } diff --git a/lib/private/Installer.php b/lib/private/Installer.php index 78925a56a2e..d5c9d076eda 100644 --- a/lib/private/Installer.php +++ b/lib/private/Installer.php @@ -106,7 +106,7 @@ class Installer { */ public function installApp(string $appId, bool $forceEnable = false): string { $app = \OC_App::findAppInDirectories($appId); - if($app === false) { + if ($app === false) { throw new \Exception('App not found in any app directory'); } @@ -115,7 +115,7 @@ class Installer { $l = \OC::$server->getL10N('core'); - if(!is_array($info)) { + if (!is_array($info)) { throw new \Exception( $l->t('App "%s" cannot be installed because appinfo file cannot be read.', [$appId] @@ -146,7 +146,7 @@ class Installer { } //install the database - if(is_file($basedir.'/appinfo/database.xml')) { + if (is_file($basedir.'/appinfo/database.xml')) { if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) { OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml'); } else { @@ -173,10 +173,10 @@ class Installer { \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no'); //set remote/public handlers - foreach($info['remote'] as $name=>$path) { + foreach ($info['remote'] as $name=>$path) { \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path); } - foreach($info['public'] as $name=>$path) { + foreach ($info['public'] as $name=>$path) { \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path); } @@ -192,7 +192,7 @@ class Installer { * @return bool */ public function updateAppstoreApp($appId) { - if($this->isUpdateAvailable($appId)) { + if ($this->isUpdateAvailable($appId)) { try { $this->downloadApp($appId); } catch (\Exception $e) { @@ -219,8 +219,8 @@ class Installer { $appId = strtolower($appId); $apps = $this->appFetcher->get(); - foreach($apps as $app) { - if($app['id'] === $appId) { + foreach ($apps as $app) { + if ($app['id'] === $appId) { // Load the certificate $certificate = new X509(); $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt')); @@ -230,7 +230,7 @@ class Installer { $crl = new X509(); $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt')); $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl')); - if($crl->validateSignature() !== true) { + if ($crl->validateSignature() !== true) { throw new \Exception('Could not validate CRL signature'); } $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString(); @@ -245,7 +245,7 @@ class Installer { } // Verify if the certificate has been issued by the Nextcloud Code Authority CA - if($certificate->validateSignature() !== true) { + if ($certificate->validateSignature() !== true) { throw new \Exception( sprintf( 'App with id %s has a certificate not issued by a trusted Code Signing Authority', @@ -256,7 +256,7 @@ class Installer { // Verify if the certificate is issued for the requested app id $certInfo = openssl_x509_parse($app['certificate']); - if(!isset($certInfo['subject']['CN'])) { + if (!isset($certInfo['subject']['CN'])) { throw new \Exception( sprintf( 'App with id %s has a cert with no CN', @@ -264,7 +264,7 @@ class Installer { ) ); } - if($certInfo['subject']['CN'] !== $appId) { + if ($certInfo['subject']['CN'] !== $appId) { throw new \Exception( sprintf( 'App with id %s has a cert issued to %s', @@ -285,12 +285,12 @@ class Installer { $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512); openssl_free_key($certificate); - if($verified === true) { + if ($verified === true) { // Seems to match, let's proceed $extractDir = $this->tempManager->getTemporaryFolder(); $archive = new TAR($tempFile); - if($archive) { + if ($archive) { if (!$archive->extract($extractDir)) { throw new \Exception( sprintf( @@ -303,7 +303,7 @@ class Installer { $folders = array_diff($allFiles, ['.', '..']); $folders = array_values($folders); - if(count($folders) > 1) { + if (count($folders) > 1) { throw new \Exception( sprintf( 'Extracted app %s has more than 1 folder', @@ -316,7 +316,7 @@ class Installer { $loadEntities = libxml_disable_entity_loader(false); $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml'); libxml_disable_entity_loader($loadEntities); - if((string)$xml->id !== $appId) { + if ((string)$xml->id !== $appId) { throw new \Exception( sprintf( 'App for id %s has a wrong app ID in info.xml: %s', @@ -329,7 +329,7 @@ class Installer { // Check if the version is lower than before $currentVersion = OC_App::getAppVersion($appId); $newVersion = (string)$xml->version; - if(version_compare($currentVersion, $newVersion) === 1) { + if (version_compare($currentVersion, $newVersion) === 1) { throw new \Exception( sprintf( 'App for id %s has version %s and tried to update to lower version %s', @@ -344,7 +344,7 @@ class Installer { // Remove old app with the ID if existent OC_Helper::rmdirr($baseDir); // Move to app folder - if(@mkdir($baseDir)) { + if (@mkdir($baseDir)) { $extractDir .= '/' . $folders[0]; OC_Helper::copyr($extractDir, $baseDir); } @@ -408,8 +408,8 @@ class Installer { $this->apps = $this->appFetcher->get(); } - foreach($this->apps as $app) { - if($app['id'] === $appId) { + foreach ($this->apps as $app) { + if ($app['id'] === $appId) { $currentVersion = OC_App::getAppVersion($appId); if (!isset($app['releases'][0]['version'])) { @@ -436,7 +436,7 @@ class Installer { */ private function isInstalledFromGit($appId) { $app = \OC_App::findAppInDirectories($appId); - if($app === false) { + if ($app === false) { return false; } $basedir = $app['path'].'/'.$appId; @@ -451,7 +451,7 @@ class Installer { * The function will check if the app is already downloaded in the apps repository */ public function isDownloaded($name) { - foreach(\OC::$APPSROOTS as $dir) { + foreach (\OC::$APPSROOTS as $dir) { $dirToTest = $dir['path']; $dirToTest .= '/'; $dirToTest .= $name; @@ -479,19 +479,18 @@ class Installer { * this has to be done by the function oc_app_uninstall(). */ public function removeApp($appId) { - if($this->isDownloaded($appId)) { + if ($this->isDownloaded($appId)) { if (\OC::$server->getAppManager()->isShipped($appId)) { return false; } $appDir = OC_App::getInstallPath() . '/' . $appId; OC_Helper::rmdirr($appDir); return true; - }else{ + } else { \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR); return false; } - } /** @@ -502,8 +501,8 @@ class Installer { */ public function installAppBundle(Bundle $bundle) { $appIds = $bundle->getAppIdentifiers(); - foreach($appIds as $appId) { - if(!$this->isDownloaded($appId)) { + foreach ($appIds as $appId) { + if (!$this->isDownloaded($appId)) { $this->downloadApp($appId); } $this->installApp($appId); @@ -527,12 +526,12 @@ class Installer { $appManager = \OC::$server->getAppManager(); $config = \OC::$server->getConfig(); $errors = []; - foreach(\OC::$APPSROOTS as $app_dir) { - if($dir = opendir($app_dir['path'])) { - while(false !== ($filename = readdir($dir))) { - if($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) { - if(file_exists($app_dir['path']."/$filename/appinfo/info.xml")) { - if($config->getAppValue($filename, "installed_version", null) === null) { + foreach (\OC::$APPSROOTS as $app_dir) { + if ($dir = opendir($app_dir['path'])) { + while (false !== ($filename = readdir($dir))) { + if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) { + if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) { + if ($config->getAppValue($filename, "installed_version", null) === null) { $info=OC_App::getAppInfo($filename); $enabled = isset($info['default_enable']); if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps())) @@ -573,7 +572,7 @@ class Installer { $appPath = OC_App::getAppPath($app); \OC_App::registerAutoloading($app, $appPath); - if(is_file("$appPath/appinfo/database.xml")) { + if (is_file("$appPath/appinfo/database.xml")) { try { OC_DB::createDbFromStructure("$appPath/appinfo/database.xml"); } catch (TableExistsException $e) { @@ -607,10 +606,10 @@ class Installer { } //set remote/public handlers - foreach($info['remote'] as $name=>$path) { + foreach ($info['remote'] as $name=>$path) { $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path); } - foreach($info['public'] as $name=>$path) { + foreach ($info['public'] as $name=>$path) { $config->setAppValue('core', 'public_'.$name, $app.'/'.$path); } @@ -623,7 +622,7 @@ class Installer { * @param string $script */ private static function includeAppScript($script) { - if (file_exists($script)){ + if (file_exists($script)) { include $script; } } diff --git a/lib/private/IntegrityCheck/Checker.php b/lib/private/IntegrityCheck/Checker.php index 725d72d9c79..1084a9e1dd5 100644 --- a/lib/private/IntegrityCheck/Checker.php +++ b/lib/private/IntegrityCheck/Checker.php @@ -144,7 +144,7 @@ class Checker { $folderToIterate, \RecursiveDirectoryIterator::SKIP_DOTS ); - if($root === '') { + if ($root === '') { $root = \OC::$SERVERROOT; } $root = rtrim($root, '/'); @@ -171,9 +171,9 @@ class Checker { $hashes = []; $baseDirectoryLength = \strlen($path); - foreach($iterator as $filename => $data) { + foreach ($iterator as $filename => $data) { /** @var \DirectoryIterator $data */ - if($data->isDir()) { + if ($data->isDir()) { continue; } @@ -181,11 +181,11 @@ class Checker { $relativeFileName = ltrim($relativeFileName, '/'); // Exclude signature.json files in the appinfo and root folder - if($relativeFileName === 'appinfo/signature.json') { + if ($relativeFileName === 'appinfo/signature.json') { continue; } // Exclude signature.json files in the appinfo and core folder - if($relativeFileName === 'core/signature.json') { + if ($relativeFileName === 'core/signature.json') { continue; } @@ -196,10 +196,10 @@ class Checker { // Thus we ignore everything below the first occurrence of // "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####" and have the // hash generated based on this. - if($filename === $this->environmentHelper->getServerRoot() . '/.htaccess') { + if ($filename === $this->environmentHelper->getServerRoot() . '/.htaccess') { $fileContent = file_get_contents($filename); $explodedArray = explode('#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####', $fileContent); - if(\count($explodedArray) === 2) { + if (\count($explodedArray) === 2) { $hashes[$relativeFileName] = hash('sha512', $explodedArray[0]); continue; } @@ -207,7 +207,7 @@ class Checker { if ($filename === $this->environmentHelper->getServerRoot() . '/core/js/mimetypelist.js') { $oldMimetypeList = new GenerateMimetypeFileBuilder(); $newFile = $oldMimetypeList->generateFile($this->mimeTypeDetector->getAllAliases()); - if($newFile === file_get_contents($filename)) { + if ($newFile === file_get_contents($filename)) { $hashes[$relativeFileName] = hash('sha512', $oldMimetypeList->generateFile($this->mimeTypeDetector->getOnlyDefaultAliases())); continue; } @@ -263,11 +263,11 @@ class Checker { $iterator = $this->getFolderIterator($path); $hashes = $this->generateHashes($iterator, $path); $signature = $this->createSignatureData($hashes, $certificate, $privateKey); - $this->fileAccessHelper->file_put_contents( + $this->fileAccessHelper->file_put_contents( $appInfoDir . '/signature.json', json_encode($signature, JSON_PRETTY_PRINT) ); - } catch (\Exception $e){ + } catch (\Exception $e) { if (!$this->fileAccessHelper->is_writable($appInfoDir)) { throw new \Exception($appInfoDir . ' is not writable'); } @@ -288,7 +288,6 @@ class Checker { $path) { $coreDir = $path . '/core'; try { - $this->fileAccessHelper->assertDirectoryExists($coreDir); $iterator = $this->getFolderIterator($path, $path); $hashes = $this->generateHashes($iterator, $path); @@ -297,7 +296,7 @@ class Checker { $coreDir . '/signature.json', json_encode($signatureData, JSON_PRETTY_PRINT) ); - } catch (\Exception $e){ + } catch (\Exception $e) { if (!$this->fileAccessHelper->is_writable($coreDir)) { throw new \Exception($coreDir . ' is not writable'); } @@ -316,7 +315,7 @@ class Checker { * @throws \Exception */ private function verify(string $signaturePath, string $basePath, string $certificateCN): array { - if(!$this->isCodeCheckEnforced()) { + if (!$this->isCodeCheckEnforced()) { return []; } @@ -326,7 +325,7 @@ class Checker { if (\is_string($content)) { $signatureData = json_decode($content, true); } - if(!\is_array($signatureData)) { + if (!\is_array($signatureData)) { throw new InvalidSignatureException('Signature data not found.'); } @@ -340,11 +339,11 @@ class Checker { $rootCertificatePublicKey = $this->fileAccessHelper->file_get_contents($this->environmentHelper->getServerRoot().'/resources/codesigning/root.crt'); $x509->loadCA($rootCertificatePublicKey); $x509->loadX509($certificate); - if(!$x509->validateSignature()) { + if (!$x509->validateSignature()) { throw new InvalidSignatureException('Certificate is not valid.'); } // Verify if certificate has proper CN. "core" CN is always trusted. - if($x509->getDN(X509::DN_OPENSSL)['CN'] !== $certificateCN && $x509->getDN(X509::DN_OPENSSL)['CN'] !== 'core') { + if ($x509->getDN(X509::DN_OPENSSL)['CN'] !== $certificateCN && $x509->getDN(X509::DN_OPENSSL)['CN'] !== 'core') { throw new InvalidSignatureException( sprintf('Certificate is not valid for required scope. (Requested: %s, current: CN=%s)', $certificateCN, $x509->getDN(true)['CN']) ); @@ -357,7 +356,7 @@ class Checker { $rsa->setMGFHash('sha512'); // See https://tools.ietf.org/html/rfc3447#page-38 $rsa->setSaltLength(0); - if(!$rsa->verify(json_encode($expectedHashes), $signature)) { + if (!$rsa->verify(json_encode($expectedHashes), $signature)) { throw new InvalidSignatureException('Signature could not get verified.'); } @@ -366,9 +365,9 @@ class Checker { // // Due to this reason we exclude the whole updater/ folder from the code // integrity check. - if($basePath === $this->environmentHelper->getServerRoot()) { - foreach($expectedHashes as $fileName => $hash) { - if(strpos($fileName, 'updater/') === 0) { + if ($basePath === $this->environmentHelper->getServerRoot()) { + foreach ($expectedHashes as $fileName => $hash) { + if (strpos($fileName, 'updater/') === 0) { unset($expectedHashes[$fileName]); } } @@ -380,23 +379,23 @@ class Checker { $differencesB = array_diff($currentInstanceHashes, $expectedHashes); $differences = array_unique(array_merge($differencesA, $differencesB)); $differenceArray = []; - foreach($differences as $filename => $hash) { + foreach ($differences as $filename => $hash) { // Check if file should not exist in the new signature table - if(!array_key_exists($filename, $expectedHashes)) { + if (!array_key_exists($filename, $expectedHashes)) { $differenceArray['EXTRA_FILE'][$filename]['expected'] = ''; $differenceArray['EXTRA_FILE'][$filename]['current'] = $hash; continue; } // Check if file is missing - if(!array_key_exists($filename, $currentInstanceHashes)) { + if (!array_key_exists($filename, $currentInstanceHashes)) { $differenceArray['FILE_MISSING'][$filename]['expected'] = $expectedHashes[$filename]; $differenceArray['FILE_MISSING'][$filename]['current'] = ''; continue; } // Check if hash does mismatch - if($expectedHashes[$filename] !== $currentInstanceHashes[$filename]) { + if ($expectedHashes[$filename] !== $currentInstanceHashes[$filename]) { $differenceArray['INVALID_HASH'][$filename]['expected'] = $expectedHashes[$filename]; $differenceArray['INVALID_HASH'][$filename]['current'] = $currentInstanceHashes[$filename]; continue; @@ -416,7 +415,7 @@ class Checker { */ public function hasPassedCheck(): bool { $results = $this->getResults(); - if(empty($results)) { + if (empty($results)) { return true; } @@ -428,7 +427,7 @@ class Checker { */ public function getResults(): array { $cachedResults = $this->cache->get(self::CACHE_KEY); - if(!\is_null($cachedResults)) { + if (!\is_null($cachedResults)) { return json_decode($cachedResults, true); } @@ -447,7 +446,7 @@ class Checker { private function storeResults(string $scope, array $result) { $resultArray = $this->getResults(); unset($resultArray[$scope]); - if(!empty($result)) { + if (!empty($result)) { $resultArray[$scope] = $result; } if ($this->config !== null) { @@ -499,7 +498,7 @@ class Checker { */ public function verifyAppSignature(string $appId, string $path = ''): array { try { - if($path === '') { + if ($path === '') { $path = $this->appLocator->getAppPath($appId); } $result = $this->verify( @@ -578,7 +577,7 @@ class Checker { $this->cleanResults(); $this->verifyCoreSignature(); $appIds = $this->appLocator->getAllApps(); - foreach($appIds as $appId) { + foreach ($appIds as $appId) { // If an application is shipped a valid signature is required $isShipped = $this->appManager->isShipped($appId); $appNeedsToBeChecked = false; @@ -589,7 +588,7 @@ class Checker { $appNeedsToBeChecked = true; } - if($appNeedsToBeChecked) { + if ($appNeedsToBeChecked) { $this->verifyAppSignature($appId); } } diff --git a/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php b/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php index 8a7f5129dce..0e55afa9a40 100644 --- a/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php +++ b/lib/private/IntegrityCheck/Exceptions/InvalidSignatureException.php @@ -28,4 +28,5 @@ namespace OC\IntegrityCheck\Exceptions; * * @package OC\IntegrityCheck\Exceptions */ -class InvalidSignatureException extends \Exception {} +class InvalidSignatureException extends \Exception { +} diff --git a/lib/private/IntegrityCheck/Helpers/AppLocator.php b/lib/private/IntegrityCheck/Helpers/AppLocator.php index 75a64bfe0b8..6faff0a8982 100644 --- a/lib/private/IntegrityCheck/Helpers/AppLocator.php +++ b/lib/private/IntegrityCheck/Helpers/AppLocator.php @@ -43,8 +43,7 @@ class AppLocator { */ public function getAppPath(string $appId): string { $path = \OC_App::getAppPath($appId); - if($path === false) { - + if ($path === false) { throw new \Exception('App not found'); } return $path; diff --git a/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php b/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php index 322b6ada9e1..de2a560223c 100644 --- a/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php +++ b/lib/private/IntegrityCheck/Helpers/FileAccessHelper.php @@ -64,7 +64,7 @@ class FileAccessHelper { */ public function file_put_contents(string $filename, string $data): int { $bytesWritten = @file_put_contents($filename, $data); - if ($bytesWritten === false || $bytesWritten !== \strlen($data)){ + if ($bytesWritten === false || $bytesWritten !== \strlen($data)) { throw new \Exception('Failed to write into ' . $filename); } return $bytesWritten; diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php index 3a713954a79..7127742b531 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php @@ -34,7 +34,7 @@ class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { parent::__construct($iterator); $appFolders = \OC::$APPSROOTS; - foreach($appFolders as $key => $appFolder) { + foreach ($appFolders as $key => $appFolder) { $appFolders[$key] = rtrim($appFolder['path'], '/'); } @@ -52,7 +52,7 @@ class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { rtrim($root . '/_oc_upgrade', '/'), ]; $customDataDir = \OC::$server->getConfig()->getSystemValue('datadirectory', ''); - if($customDataDir !== '') { + if ($customDataDir !== '') { $excludedFolders[] = rtrim($customDataDir, '/'); } diff --git a/lib/private/L10N/Factory.php b/lib/private/L10N/Factory.php index a5b208cfb3c..a1afb1f4f0a 100644 --- a/lib/private/L10N/Factory.php +++ b/lib/private/L10N/Factory.php @@ -115,7 +115,6 @@ class Factory implements IFactory { */ public function get($app, $lang = null, $locale = null) { return new LazyL10N(function () use ($app, $lang, $locale) { - $app = \OC_App::cleanAppId($app); if ($lang !== null) { $lang = str_replace(['\0', '/', '\\', '..'], '', (string)$lang); @@ -353,7 +352,7 @@ class Factory implements IFactory { public function getLanguageIterator(IUser $user = null): ILanguageIterator { $user = $user ?? $this->userSession->getUser(); - if($user === null) { + if ($user === null) { throw new \RuntimeException('Failed to get an IUser instance'); } return new LanguageIterator($user, $this->config); @@ -543,7 +542,7 @@ class Factory implements IFactory { $res = ''; $p = 0; $length = strlen($body); - for($i = 0; $i < $length; $i++) { + for ($i = 0; $i < $length; $i++) { $ch = $body[$i]; switch ($ch) { case '?': @@ -594,7 +593,7 @@ class Factory implements IFactory { $commonLanguages = []; $languages = []; - foreach($languageCodes as $lang) { + foreach ($languageCodes as $lang) { $l = $this->get('lib', $lang); // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version $potentialName = (string) $l->t('__language_name__'); diff --git a/lib/private/L10N/L10NString.php b/lib/private/L10N/L10NString.php index 47635cf67fc..683cd902ab6 100644 --- a/lib/private/L10N/L10NString.php +++ b/lib/private/L10N/L10NString.php @@ -63,13 +63,12 @@ class L10NString implements \JsonSerializable { $translations = $this->l10n->getTranslations(); $text = $this->text; - if(array_key_exists($this->text, $translations)) { - if(is_array($translations[$this->text])) { + if (array_key_exists($this->text, $translations)) { + if (is_array($translations[$this->text])) { $fn = $this->l10n->getPluralFormFunction(); $id = $fn($this->count); $text = $translations[$this->text][$id]; - } - else{ + } else { $text = $translations[$this->text]; } } diff --git a/lib/private/L10N/LanguageIterator.php b/lib/private/L10N/LanguageIterator.php index 8c9624d7d53..0670ac56503 100644 --- a/lib/private/L10N/LanguageIterator.php +++ b/lib/private/L10N/LanguageIterator.php @@ -55,18 +55,18 @@ class LanguageIterator implements ILanguageIterator { * @since 14.0.0 */ public function current(): string { - switch($this->i) { + switch ($this->i) { /** @noinspection PhpMissingBreakStatementInspection */ case 0: $forcedLang = $this->config->getSystemValue('force_language', false); - if(is_string($forcedLang)) { + if (is_string($forcedLang)) { return $forcedLang; } $this->next(); /** @noinspection PhpMissingBreakStatementInspection */ case 1: $forcedLang = $this->config->getSystemValue('force_language', false); - if(is_string($forcedLang) + if (is_string($forcedLang) && ($truncated = $this->getTruncatedLanguage($forcedLang)) !== $forcedLang ) { return $truncated; @@ -75,14 +75,14 @@ class LanguageIterator implements ILanguageIterator { /** @noinspection PhpMissingBreakStatementInspection */ case 2: $userLang = $this->config->getUserValue($this->user->getUID(), 'core', 'lang', null); - if(is_string($userLang)) { + if (is_string($userLang)) { return $userLang; } $this->next(); /** @noinspection PhpMissingBreakStatementInspection */ case 3: $userLang = $this->config->getUserValue($this->user->getUID(), 'core', 'lang', null); - if(is_string($userLang) + if (is_string($userLang) && ($truncated = $this->getTruncatedLanguage($userLang)) !== $userLang ) { return $truncated; @@ -93,7 +93,7 @@ class LanguageIterator implements ILanguageIterator { /** @noinspection PhpMissingBreakStatementInspection */ case 5: $defaultLang = $this->config->getSystemValue('default_language', 'en'); - if(($truncated = $this->getTruncatedLanguage($defaultLang)) !== $defaultLang) { + if (($truncated = $this->getTruncatedLanguage($defaultLang)) !== $defaultLang) { return $truncated; } $this->next(); @@ -131,7 +131,7 @@ class LanguageIterator implements ILanguageIterator { protected function getTruncatedLanguage(string $lang):string { $pos = strpos($lang, '_'); - if($pos !== false) { + if ($pos !== false) { $lang = substr($lang, 0, $pos); } return $lang; diff --git a/lib/private/L10N/LanguageNotFoundException.php b/lib/private/L10N/LanguageNotFoundException.php index b7c407f6ee9..20b22a8b5ec 100644 --- a/lib/private/L10N/LanguageNotFoundException.php +++ b/lib/private/L10N/LanguageNotFoundException.php @@ -24,5 +24,4 @@ namespace OC\L10N; class LanguageNotFoundException extends \Exception { - } diff --git a/lib/private/L10N/LazyL10N.php b/lib/private/L10N/LazyL10N.php index 2b47de55dd9..9ffcb4df98f 100644 --- a/lib/private/L10N/LazyL10N.php +++ b/lib/private/L10N/LazyL10N.php @@ -68,5 +68,4 @@ class LazyL10N implements IL10N { public function getLocaleCode(): string { return $this->getL()->getLocaleCode(); } - } diff --git a/lib/private/LargeFileHelper.php b/lib/private/LargeFileHelper.php index 603fe7e461f..c24657a5c9c 100755 --- a/lib/private/LargeFileHelper.php +++ b/lib/private/LargeFileHelper.php @@ -201,8 +201,6 @@ class LargeFileHelper { } } return $result; - - } protected function exec($cmd) { diff --git a/lib/private/Lockdown/Filesystem/NullCache.php b/lib/private/Lockdown/Filesystem/NullCache.php index 83b0d744913..396bf68d5df 100644 --- a/lib/private/Lockdown/Filesystem/NullCache.php +++ b/lib/private/Lockdown/Filesystem/NullCache.php @@ -122,5 +122,4 @@ class NullCache implements ICache { public function normalize($path) { return $path; } - } diff --git a/lib/private/Log.php b/lib/private/Log.php index d288e724179..2048d60a53b 100644 --- a/lib/private/Log.php +++ b/lib/private/Log.php @@ -373,7 +373,7 @@ class Log implements ILogger, IDataLogger { } public function getLogPath():string { - if($this->logger instanceof IFileBased) { + if ($this->logger instanceof IFileBased) { return $this->logger->getLogFilePath(); } throw new \RuntimeException('Log implementation has no path'); diff --git a/lib/private/Log/ErrorHandler.php b/lib/private/Log/ErrorHandler.php index 2d2cf7abd67..d37af8212a0 100644 --- a/lib/private/Log/ErrorHandler.php +++ b/lib/private/Log/ErrorHandler.php @@ -63,7 +63,7 @@ class ErrorHandler { //Fatal errors handler public static function onShutdown() { $error = error_get_last(); - if($error && self::$logger) { + if ($error && self::$logger) { //ob_end_clean(); $msg = $error['message'] . ' at ' . $error['file'] . '#' . $error['line']; self::$logger->critical(self::removePassword($msg), ['app' => 'PHP']); @@ -89,14 +89,11 @@ class ErrorHandler { } $msg = $message . ' at ' . $file . '#' . $line; self::$logger->error(self::removePassword($msg), ['app' => 'PHP']); - } //Recoverable handler which catch all errors, warnings and notices public static function onAll($number, $message, $file, $line) { $msg = $message . ' at ' . $file . '#' . $line; self::$logger->debug(self::removePassword($msg), ['app' => 'PHP']); - } - } diff --git a/lib/private/Log/File.php b/lib/private/Log/File.php index 57b4e9353ef..6be200f6d3e 100644 --- a/lib/private/Log/File.php +++ b/lib/private/Log/File.php @@ -59,7 +59,7 @@ class File extends LogDetails implements IWriter, IFileBased { parent::__construct($config); $this->logFile = $path; if (!file_exists($this->logFile)) { - if( + if ( ( !is_writable(dirname($this->logFile)) || !touch($this->logFile) diff --git a/lib/private/Log/LogDetails.php b/lib/private/Log/LogDetails.php index 5ed486195cf..dcaa5919d73 100644 --- a/lib/private/Log/LogDetails.php +++ b/lib/private/Log/LogDetails.php @@ -58,7 +58,7 @@ abstract class LogDetails { $time = $time->format($format); $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--'; $method = is_string($request->getMethod()) ? $request->getMethod() : '--'; - if($this->config->getValue('installed', false)) { + if ($this->config->getValue('installed', false)) { $user = \OC_User::getUser() ? \OC_User::getUser() : '--'; } else { $user = '--'; @@ -82,7 +82,7 @@ abstract class LogDetails { 'version' ); - if(is_array($message) && !array_key_exists('Exception', $message)) { + if (is_array($message) && !array_key_exists('Exception', $message)) { // Exception messages should stay as they are, // anything else modern is split to 'message' (string) and // data (array) fields @@ -99,10 +99,10 @@ abstract class LogDetails { // PHP's json_encode only accept proper UTF-8 strings, loop over all // elements to ensure that they are properly UTF-8 compliant or convert // them manually. - foreach($entry as $key => $value) { - if(is_string($value)) { + foreach ($entry as $key => $value) { + if (is_string($value)) { $testEncode = json_encode($value, JSON_UNESCAPED_SLASHES); - if($testEncode === false) { + if ($testEncode === false) { $entry[$key] = utf8_encode($value); } } diff --git a/lib/private/Log/LogFactory.php b/lib/private/Log/LogFactory.php index 901ff382d8b..9a55b155f39 100644 --- a/lib/private/Log/LogFactory.php +++ b/lib/private/Log/LogFactory.php @@ -71,7 +71,7 @@ class LogFactory implements ILogFactory { protected function buildLogFile(string $logFile = ''):File { $defaultLogFile = $this->systemConfig->getValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log'; - if($logFile === '') { + if ($logFile === '') { $logFile = $this->systemConfig->getValue('logfile', $defaultLogFile); } $fallback = $defaultLogFile !== $logFile ? $defaultLogFile : ''; diff --git a/lib/private/Log/PsrLoggerAdapter.php b/lib/private/Log/PsrLoggerAdapter.php index 4bfd9a2a246..bdaeda9f129 100644 --- a/lib/private/Log/PsrLoggerAdapter.php +++ b/lib/private/Log/PsrLoggerAdapter.php @@ -162,5 +162,4 @@ final class PsrLoggerAdapter implements LoggerInterface { } $this->logger->log($level, $message, $context); } - } diff --git a/lib/private/Log/Rotate.php b/lib/private/Log/Rotate.php index a5fc7d5a0cd..8cafc6e639c 100644 --- a/lib/private/Log/Rotate.php +++ b/lib/private/Log/Rotate.php @@ -41,7 +41,7 @@ class Rotate extends \OC\BackgroundJob\Job { $this->filePath = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log'); $this->maxSize = \OC::$server->getConfig()->getSystemValue('log_rotate_size', 100 * 1024 * 1024); - if($this->shouldRotateBySize()) { + if ($this->shouldRotateBySize()) { $rotatedFile = $this->rotate(); $msg = 'Log file "'.$this->filePath.'" was over '.$this->maxSize.' bytes, moved to "'.$rotatedFile.'"'; \OC::$server->getLogger()->warning($msg, ['app' => Rotate::class]); diff --git a/lib/private/Log/Systemdlog.php b/lib/private/Log/Systemdlog.php index e74cab40fd6..692af7d8ecf 100644 --- a/lib/private/Log/Systemdlog.php +++ b/lib/private/Log/Systemdlog.php @@ -58,11 +58,10 @@ class Systemdlog extends LogDetails implements IWriter { public function __construct(SystemConfig $config) { parent::__construct($config); - if(!function_exists('sd_journal_send')) { + if (!function_exists('sd_journal_send')) { throw new HintException( 'PHP extension php-systemd is not available.', 'Please install and enable PHP extension systemd if you wish to log to the Systemd journal.'); - } $this->syslogId = $config->getValue('syslog_tag', 'Nextcloud'); } diff --git a/lib/private/Mail/Attachment.php b/lib/private/Mail/Attachment.php index 3f80b065d5a..1f88c875565 100644 --- a/lib/private/Mail/Attachment.php +++ b/lib/private/Mail/Attachment.php @@ -80,5 +80,4 @@ class Attachment implements IAttachment { public function getSwiftAttachment(): \Swift_Mime_Attachment { return $this->swiftAttachment; } - } diff --git a/lib/private/Mail/EMailTemplate.php b/lib/private/Mail/EMailTemplate.php index c3da61c707b..9e2f099259c 100644 --- a/lib/private/Mail/EMailTemplate.php +++ b/lib/private/Mail/EMailTemplate.php @@ -191,7 +191,7 @@ EOF;
        t('External storage')); ?> t('Authentication')); ?> t('Configuration')); ?>     
        EOF; - // note: listBegin (like bodyBegin) is not processed through sprintf, so "%" is not escaped as "%%". (bug #12151) + // note: listBegin (like bodyBegin) is not processed through sprintf, so "%" is not escaped as "%%". (bug #12151) protected $listBegin = << @@ -550,7 +550,6 @@ EOF; $this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, $textColor, $textColor, $textLeft, $urlRight, $textRight]); $this->plainBody .= $plainTextLeft . ': ' . $urlLeft . PHP_EOL; $this->plainBody .= $plainTextRight . ': ' . $urlRight . PHP_EOL . PHP_EOL; - } /** @@ -585,7 +584,6 @@ EOF; } $this->plainBody .= $url . PHP_EOL; - } /** @@ -608,7 +606,7 @@ EOF; * @param string $text If the text is empty the default "Name - Slogan
        This is an automatically sent email" will be used */ public function addFooter(string $text = '') { - if($text === '') { + if ($text === '') { $text = $this->themingDefaults->getName() . ' - ' . $this->themingDefaults->getSlogan() . '
        ' . $this->l10n->t('This is an automatically sent email, please do not reply.'); } diff --git a/lib/private/Mail/Mailer.php b/lib/private/Mail/Mailer.php index c07556b6a62..57778e263d7 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -186,7 +186,7 @@ class Mailer implements IMailer { $mailer = $this->getInstance(); // Enable logger if debug mode is enabled - if($debugMode) { + if ($debugMode) { $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger(); $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger)); } @@ -199,7 +199,7 @@ class Mailer implements IMailer { // Debugging logging $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject()); $this->logger->debug($logMessage, ['app' => 'core']); - if($debugMode && isset($mailLogger)) { + if ($debugMode && isset($mailLogger)) { $this->logger->debug($mailLogger->dump(), ['app' => 'core']); } diff --git a/lib/private/Mail/Message.php b/lib/private/Mail/Message.php index e5a31b5cbe1..c8c48518d52 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -77,8 +77,8 @@ class Message implements IMessage { $convertedAddresses = []; - foreach($addresses as $email => $readableName) { - if(!is_numeric($email)) { + foreach ($addresses as $email => $readableName) { + if (!is_numeric($email)) { list($name, $domain) = explode('@', $email, 2); $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); $convertedAddresses[$name.'@'.$domain] = $readableName; diff --git a/lib/private/Memcache/APCu.php b/lib/private/Memcache/APCu.php index e1aec896db2..3523ea2a86b 100644 --- a/lib/private/Memcache/APCu.php +++ b/lib/private/Memcache/APCu.php @@ -59,7 +59,7 @@ class APCu extends Cache implements IMemcache { public function clear($prefix = '') { $ns = $this->getPrefix() . $prefix; $ns = preg_quote($ns, '/'); - if(class_exists('\APCIterator')) { + if (class_exists('\APCIterator')) { $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY); } else { $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY); diff --git a/lib/private/Memcache/Factory.php b/lib/private/Memcache/Factory.php index 675c1088dee..0e6552ba436 100644 --- a/lib/private/Memcache/Factory.php +++ b/lib/private/Memcache/Factory.php @@ -71,8 +71,7 @@ class Factory implements ICacheFactory { * @param string|null $lockingCacheClass */ public function __construct(string $globalPrefix, ILogger $logger, - $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null) - { + $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null) { $this->logger = $logger; $this->globalPrefix = $globalPrefix; diff --git a/lib/private/MemoryInfo.php b/lib/private/MemoryInfo.php index 37bf98fef59..520225fc6d1 100644 --- a/lib/private/MemoryInfo.php +++ b/lib/private/MemoryInfo.php @@ -30,7 +30,6 @@ namespace OC; * Helper class that covers memory info. */ class MemoryInfo { - const RECOMMENDED_MEMORY_LIMIT = 512 * 1024 * 1024; /** @@ -70,7 +69,7 @@ class MemoryInfo { $memoryLimit = (int)substr($memoryLimit, 0, -1); // intended fall trough - switch($last) { + switch ($last) { case 'g': $memoryLimit *= 1024; case 'm': diff --git a/lib/private/NaturalSort.php b/lib/private/NaturalSort.php index aefa5d5a92a..31829a84e6a 100644 --- a/lib/private/NaturalSort.php +++ b/lib/private/NaturalSort.php @@ -91,8 +91,7 @@ class NaturalSort { // German umlauts, so using en_US instead if (class_exists('Collator')) { $this->collator = new \Collator('en_US'); - } - else { + } else { $this->collator = new \OC\NaturalSort_DefaultCollator(); } } diff --git a/lib/private/NavigationManager.php b/lib/private/NavigationManager.php index b71e194398f..b40f403c056 100644 --- a/lib/private/NavigationManager.php +++ b/lib/private/NavigationManager.php @@ -93,13 +93,13 @@ class NavigationManager implements INavigationManager { } $entry['active'] = false; - if(!isset($entry['icon'])) { + if (!isset($entry['icon'])) { $entry['icon'] = ''; } - if(!isset($entry['classes'])) { + if (!isset($entry['classes'])) { $entry['classes'] = ''; } - if(!isset($entry['type'])) { + if (!isset($entry['type'])) { $entry['type'] = 'link'; } $this->entries[$entry['id']] = $entry; @@ -231,7 +231,7 @@ class NavigationManager implements INavigationManager { ]); $logoutUrl = \OC_User::getLogoutUrl($this->urlGenerator); - if($logoutUrl !== '') { + if ($logoutUrl !== '') { // Logout $this->add([ 'type' => 'settings', diff --git a/lib/private/OCS/DiscoveryService.php b/lib/private/OCS/DiscoveryService.php index caad064a48b..d30cf1d980c 100644 --- a/lib/private/OCS/DiscoveryService.php +++ b/lib/private/OCS/DiscoveryService.php @@ -85,7 +85,7 @@ class DiscoveryService implements IDiscoveryService { 'timeout' => 10, 'connect_timeout' => 10, ]); - if($response->getStatusCode() === Http::STATUS_OK) { + if ($response->getStatusCode() === Http::STATUS_OK) { $decodedServices = json_decode($response->getBody(), true); if (\is_array($decodedServices)) { $discoveredServices = $this->getEndpoints($decodedServices, $service); @@ -108,12 +108,11 @@ class DiscoveryService implements IDiscoveryService { * @return array */ protected function getEndpoints(array $decodedServices, string $service): array { - $discoveredServices = []; - if(isset($decodedServices['services'][$service]['endpoints'])) { + if (isset($decodedServices['services'][$service]['endpoints'])) { foreach ($decodedServices['services'][$service]['endpoints'] as $endpoint => $url) { - if($this->isSafeUrl($url)) { + if ($this->isSafeUrl($url)) { $discoveredServices[$endpoint] = $url; } } @@ -132,5 +131,4 @@ class DiscoveryService implements IDiscoveryService { protected function isSafeUrl(string $url): bool { return (bool)preg_match('/^[\/\.\-A-Za-z0-9]+$/', $url); } - } diff --git a/lib/private/OCS/Exception.php b/lib/private/OCS/Exception.php index 704b9160f32..63a7bdb54ea 100644 --- a/lib/private/OCS/Exception.php +++ b/lib/private/OCS/Exception.php @@ -36,5 +36,4 @@ class Exception extends \Exception { public function getResult() { return $this->result; } - } diff --git a/lib/private/OCS/Provider.php b/lib/private/OCS/Provider.php index f4322d23028..33386c0e946 100644 --- a/lib/private/OCS/Provider.php +++ b/lib/private/OCS/Provider.php @@ -55,7 +55,7 @@ class Provider extends \OCP\AppFramework\Controller { ], ]; - if($this->appManager->isEnabledForUser('files_sharing')) { + if ($this->appManager->isEnabledForUser('files_sharing')) { $services['SHARING'] = [ 'version' => 1, 'endpoints' => [ @@ -88,7 +88,7 @@ class Provider extends \OCP\AppFramework\Controller { } } - if($this->appManager->isEnabledForUser('activity')) { + if ($this->appManager->isEnabledForUser('activity')) { $services['ACTIVITY'] = [ 'version' => 1, 'endpoints' => [ @@ -97,7 +97,7 @@ class Provider extends \OCP\AppFramework\Controller { ]; } - if($this->appManager->isEnabledForUser('provisioning_api')) { + if ($this->appManager->isEnabledForUser('provisioning_api')) { $services['PROVISIONING'] = [ 'version' => 1, 'endpoints' => [ diff --git a/lib/private/OCS/Result.php b/lib/private/OCS/Result.php index b16d83e0410..0199783b47d 100644 --- a/lib/private/OCS/Result.php +++ b/lib/private/OCS/Result.php @@ -104,14 +104,13 @@ class Result { $meta['status'] = $this->succeeded() ? 'ok' : 'failure'; $meta['statuscode'] = $this->statusCode; $meta['message'] = $this->message; - if(isset($this->items)) { + if (isset($this->items)) { $meta['totalitems'] = $this->items; } - if(isset($this->perPage)) { + if (isset($this->perPage)) { $meta['itemsperpage'] = $this->perPage; } return $meta; - } /** @@ -141,7 +140,7 @@ class Result { // to be able to reliably check for security // headers - if(is_null($value)) { + if (is_null($value)) { unset($this->headers[$name]); } else { $this->headers[$name] = $value; @@ -157,5 +156,4 @@ class Result { public function getHeaders() { return $this->headers; } - } diff --git a/lib/private/Preview/Bitmap.php b/lib/private/Preview/Bitmap.php index fccb176c737..7322e07ab34 100644 --- a/lib/private/Preview/Bitmap.php +++ b/lib/private/Preview/Bitmap.php @@ -43,7 +43,6 @@ abstract class Bitmap extends ProviderV2 { * {@inheritDoc} */ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage { - $tmpPath = $this->getLocalFile($file); // Creates \Imagick object from bitmap or vector file @@ -117,5 +116,4 @@ abstract class Bitmap extends ProviderV2 { return $bp; } - } diff --git a/lib/private/Preview/Bundled.php b/lib/private/Preview/Bundled.php index afd286d895b..4e89682dc6c 100644 --- a/lib/private/Preview/Bundled.php +++ b/lib/private/Preview/Bundled.php @@ -31,7 +31,6 @@ use OCP\IImage; * Extracts a preview from files that embed them in an ZIP archive */ abstract class Bundled extends ProviderV2 { - protected function extractThumbnail(File $file, $path): ?IImage { $sourceTmp = \OC::$server->getTempManager()->getTemporaryFile(); $targetTmp = \OC::$server->getTempManager()->getTemporaryFile(); @@ -52,5 +51,4 @@ abstract class Bundled extends ProviderV2 { return null; } } - } diff --git a/lib/private/Preview/HEIC.php b/lib/private/Preview/HEIC.php index 166e1cc3074..c2b9b541ad3 100644 --- a/lib/private/Preview/HEIC.php +++ b/lib/private/Preview/HEIC.php @@ -141,5 +141,4 @@ class HEIC extends ProviderV2 { return $bp; } - } diff --git a/lib/private/Preview/Image.php b/lib/private/Preview/Image.php index 3180ee853ec..eea471a2356 100644 --- a/lib/private/Preview/Image.php +++ b/lib/private/Preview/Image.php @@ -61,5 +61,4 @@ abstract class Image extends ProviderV2 { } return null; } - } diff --git a/lib/private/Preview/MP3.php b/lib/private/Preview/MP3.php index db06733a892..0986cf8c5c3 100644 --- a/lib/private/Preview/MP3.php +++ b/lib/private/Preview/MP3.php @@ -51,11 +51,11 @@ class MP3 extends ProviderV2 { $tags = $getID3->analyze($tmpPath); $this->cleanTmpFiles(); $picture = isset($tags['id3v2']['APIC'][0]['data']) ? $tags['id3v2']['APIC'][0]['data'] : null; - if(is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) { + if (is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) { $picture = $tags['id3v2']['PIC'][0]['data']; } - if(!is_null($picture)) { + if (!is_null($picture)) { $image = new \OC_Image(); $image->loadFromData($picture); diff --git a/lib/private/Preview/MarkDown.php b/lib/private/Preview/MarkDown.php index 0cf096148e5..91e276eb170 100644 --- a/lib/private/Preview/MarkDown.php +++ b/lib/private/Preview/MarkDown.php @@ -31,5 +31,4 @@ class MarkDown extends TXT { public function getMimeType(): string { return '/text\/(x-)?markdown/'; } - } diff --git a/lib/private/Preview/Office.php b/lib/private/Preview/Office.php index bdf8c528135..6719aeace8f 100644 --- a/lib/private/Preview/Office.php +++ b/lib/private/Preview/Office.php @@ -86,7 +86,6 @@ abstract class Office extends ProviderV2 { return $image; } return null; - } private function initCmd() { diff --git a/lib/private/Preview/ProviderV1Adapter.php b/lib/private/Preview/ProviderV1Adapter.php index 645905517cb..f09b0f47583 100644 --- a/lib/private/Preview/ProviderV1Adapter.php +++ b/lib/private/Preview/ProviderV1Adapter.php @@ -61,5 +61,4 @@ class ProviderV1Adapter implements IProviderV2 { return [$view, $path]; } - } diff --git a/lib/private/Preview/TXT.php b/lib/private/Preview/TXT.php index 3090446ac4d..d116726c683 100644 --- a/lib/private/Preview/TXT.php +++ b/lib/private/Preview/TXT.php @@ -61,7 +61,7 @@ class TXT extends ProviderV2 { $content = stream_get_contents($content,3000); //don't create previews of empty text files - if(trim($content) === '') { + if (trim($content) === '') { return null; } @@ -81,7 +81,7 @@ class TXT extends ProviderV2 { $canUseTTF = function_exists('imagettftext'); - foreach($lines as $index => $line) { + foreach ($lines as $index => $line) { $index = $index + 1; $x = (int) 1; @@ -94,7 +94,7 @@ class TXT extends ProviderV2 { imagestring($image, 1, $x, $y, $line, $textColor); } - if(($index * $lineSize) >= $maxY) { + if (($index * $lineSize) >= $maxY) { break; } } diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index adfc04199e3..b71865de545 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -229,7 +229,7 @@ class PreviewManager implements IPreview { } $mount = $file->getMountPoint(); - if ($mount and !$mount->getOption('previews', true)){ + if ($mount and !$mount->getOption('previews', true)) { return false; } diff --git a/lib/private/RedisFactory.php b/lib/private/RedisFactory.php index 9aa822c40c8..cd3ab39bdd7 100644 --- a/lib/private/RedisFactory.php +++ b/lib/private/RedisFactory.php @@ -68,7 +68,6 @@ class RedisFactory { $this->instance->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, $config['failover_mode']); } } else { - $this->instance = new \Redis(); $config = $this->config->getValue('redis', []); if (isset($config['host'])) { diff --git a/lib/private/Remote/Api/NotFoundException.php b/lib/private/Remote/Api/NotFoundException.php index 51ecfabd402..fadf4a4d324 100644 --- a/lib/private/Remote/Api/NotFoundException.php +++ b/lib/private/Remote/Api/NotFoundException.php @@ -24,5 +24,4 @@ namespace OC\Remote\Api; class NotFoundException extends \Exception { - } diff --git a/lib/private/Repair/ClearGeneratedAvatarCache.php b/lib/private/Repair/ClearGeneratedAvatarCache.php index 656dbcafaca..44a390d66a1 100644 --- a/lib/private/Repair/ClearGeneratedAvatarCache.php +++ b/lib/private/Repair/ClearGeneratedAvatarCache.php @@ -66,7 +66,6 @@ class ClearGeneratedAvatarCache implements IRepairStep { } catch (\Exception $e) { $output->warning('Unable to clear the avatar cache'); } - } } } diff --git a/lib/private/Repair/MoveUpdaterStepFile.php b/lib/private/Repair/MoveUpdaterStepFile.php index 481cff47e15..6be54bbb576 100644 --- a/lib/private/Repair/MoveUpdaterStepFile.php +++ b/lib/private/Repair/MoveUpdaterStepFile.php @@ -43,24 +43,23 @@ class MoveUpdaterStepFile implements IRepairStep { } public function run(IOutput $output) { - $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); $instanceId = $this->config->getSystemValue('instanceid', null); - if(!is_string($instanceId) || empty($instanceId)) { + if (!is_string($instanceId) || empty($instanceId)) { return; } $updaterFolderPath = $dataDir . '/updater-' . $instanceId; $stepFile = $updaterFolderPath . '/.step'; - if(file_exists($stepFile)) { + if (file_exists($stepFile)) { $output->info('.step file exists'); $previousStepFile = $updaterFolderPath . '/.step-previous-update'; // cleanup - if(file_exists($previousStepFile)) { - if(\OC_Helper::rmdirr($previousStepFile)) { + if (file_exists($previousStepFile)) { + if (\OC_Helper::rmdirr($previousStepFile)) { $output->info('.step-previous-update removed'); } else { $output->info('.step-previous-update can\'t be removed - abort move of .step file'); @@ -69,7 +68,7 @@ class MoveUpdaterStepFile implements IRepairStep { } // move step file - if(rename($stepFile, $previousStepFile)) { + if (rename($stepFile, $previousStepFile)) { $output->info('.step file moved to .step-previous-update'); } else { $output->warning('.step file can\'t be moved'); diff --git a/lib/private/Repair/NC13/AddLogRotateJob.php b/lib/private/Repair/NC13/AddLogRotateJob.php index ceef8d0c7ee..7bd290894a4 100644 --- a/lib/private/Repair/NC13/AddLogRotateJob.php +++ b/lib/private/Repair/NC13/AddLogRotateJob.php @@ -44,5 +44,4 @@ class AddLogRotateJob implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(Rotate::class); } - } diff --git a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php index f76e106dfac..f2958de5b96 100644 --- a/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php +++ b/lib/private/Repair/NC14/AddPreviewBackgroundCleanupJob.php @@ -47,5 +47,4 @@ class AddPreviewBackgroundCleanupJob implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(BackgroundCleanupJob::class); } - } diff --git a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php index 5b8712fff85..34afd5dea60 100644 --- a/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php +++ b/lib/private/Repair/NC16/AddClenupLoginFlowV2BackgroundJob.php @@ -47,5 +47,4 @@ class AddClenupLoginFlowV2BackgroundJob implements IRepairStep { public function run(IOutput $output) { $this->jobList->add(CleanupLoginFlowV2::class); } - } diff --git a/lib/private/Repair/Owncloud/SaveAccountsTableData.php b/lib/private/Repair/Owncloud/SaveAccountsTableData.php index 12515f2e882..6dd49e6c9fd 100644 --- a/lib/private/Repair/Owncloud/SaveAccountsTableData.php +++ b/lib/private/Repair/Owncloud/SaveAccountsTableData.php @@ -35,7 +35,6 @@ use OCP\PreConditionNotMetException; * before the data structure is changed and the information is gone */ class SaveAccountsTableData implements IRepairStep { - const BATCH_SIZE = 75; /** @var IDBConnection */ @@ -186,6 +185,5 @@ class SaveAccountsTableData implements IRepairStep { ->setParameter('userid', $userdata['user_id']); $update->execute(); } - } } diff --git a/lib/private/Repair/RemoveLinkShares.php b/lib/private/Repair/RemoveLinkShares.php index 580c9567f34..319fb80277c 100644 --- a/lib/private/Repair/RemoveLinkShares.php +++ b/lib/private/Repair/RemoveLinkShares.php @@ -210,7 +210,7 @@ class RemoveLinkShares implements IRepairStep { $output->startProgress($total); $shareCursor = $this->getShares(); - while($data = $shareCursor->fetch()) { + while ($data = $shareCursor->fetch()) { $this->processShare($data); $output->advance(); } diff --git a/lib/private/Repair/RepairInvalidShares.php b/lib/private/Repair/RepairInvalidShares.php index cb71bef9ffa..becf8ba7594 100644 --- a/lib/private/Repair/RepairInvalidShares.php +++ b/lib/private/Repair/RepairInvalidShares.php @@ -32,7 +32,6 @@ use OCP\Migration\IRepairStep; * Repairs shares with invalid data */ class RepairInvalidShares implements IRepairStep { - const CHUNK_SIZE = 200; /** @var \OCP\IConfig */ diff --git a/lib/private/Repair/RepairMimeTypes.php b/lib/private/Repair/RepairMimeTypes.php index 67dd1ca971d..b6b6ceed104 100644 --- a/lib/private/Repair/RepairMimeTypes.php +++ b/lib/private/Repair/RepairMimeTypes.php @@ -195,7 +195,6 @@ class RepairMimeTypes implements IRepairStep { * Fix mime types */ public function run(IOutput $out) { - $ocVersionFromBeforeUpdate = $this->config->getSystemValue('version', '0.0.0'); // NOTE TO DEVELOPERS: when adding new mime types, please make sure to diff --git a/lib/private/Route/Router.php b/lib/private/Route/Router.php index b125fd60164..ccb1578f8d3 100644 --- a/lib/private/Route/Router.php +++ b/lib/private/Route/Router.php @@ -73,7 +73,7 @@ class Router implements IRouter { public function __construct(ILogger $logger) { $this->logger = $logger; $baseUrl = \OC::$WEBROOT; - if(!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) { + if (!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) { $baseUrl = \OC::$server->getURLGenerator()->linkTo('', 'index.php'); } if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) { @@ -99,7 +99,7 @@ class Router implements IRouter { $this->routingFiles = []; foreach (\OC_APP::getEnabledApps() as $app) { $appPath = \OC_App::getAppPath($app); - if($appPath !== false) { + if ($appPath !== false) { $file = $appPath . '/appinfo/routes.php'; if (file_exists($file)) { $this->routingFiles[$app] = $file; @@ -116,7 +116,7 @@ class Router implements IRouter { * @param null|string $app */ public function loadRoutes($app = null) { - if(is_string($app)) { + if (is_string($app)) { $app = \OC_App::cleanAppId($app); } diff --git a/lib/private/Search.php b/lib/private/Search.php index f58822d68f6..ae22a6d9f19 100644 --- a/lib/private/Search.php +++ b/lib/private/Search.php @@ -36,7 +36,6 @@ use OCP\Search\Provider; * Provide an interface to all search providers */ class Search implements ISearch { - private $providers = []; private $registeredProviders = []; @@ -51,7 +50,7 @@ class Search implements ISearch { public function searchPaged($query, array $inApps = [], $page = 1, $size = 30) { $this->initProviders(); $results = []; - foreach($this->providers as $provider) { + foreach ($this->providers as $provider) { /** @var $provider Provider */ if (! $provider->providesResultsFor($inApps)) { continue; @@ -109,14 +108,13 @@ class Search implements ISearch { * Create instances of all the registered search providers */ private function initProviders() { - if(! empty($this->providers)) { + if (! empty($this->providers)) { return; } - foreach($this->registeredProviders as $provider) { + foreach ($this->registeredProviders as $provider) { $class = $provider['class']; $options = $provider['options']; $this->providers[] = new $class($options); } } - } diff --git a/lib/private/Search/Provider/File.php b/lib/private/Search/Provider/File.php index 734878be982..02521460d8c 100644 --- a/lib/private/Search/Provider/File.php +++ b/lib/private/Search/Provider/File.php @@ -54,19 +54,19 @@ class File extends \OCP\Search\Provider { continue; } // create audio result - if($fileData['mimepart'] === 'audio'){ + if ($fileData['mimepart'] === 'audio') { $result = new \OC\Search\Result\Audio($fileData); } // create image result - elseif($fileData['mimepart'] === 'image'){ + elseif ($fileData['mimepart'] === 'image') { $result = new \OC\Search\Result\Image($fileData); } // create folder result - elseif($fileData['mimetype'] === 'httpd/unix-directory'){ + elseif ($fileData['mimetype'] === 'httpd/unix-directory') { $result = new \OC\Search\Result\Folder($fileData); } // or create file result - else{ + else { $result = new \OC\Search\Result\File($fileData); } // add to results @@ -75,5 +75,4 @@ class File extends \OCP\Search\Provider { // return return $results; } - } diff --git a/lib/private/Search/Result/File.php b/lib/private/Search/Result/File.php index cd605c49821..b0f6b3df622 100644 --- a/lib/private/Search/Result/File.php +++ b/lib/private/Search/Result/File.php @@ -75,7 +75,6 @@ class File extends \OCP\Search\Result { * @param FileInfo $data file data given by provider */ public function __construct(FileInfo $data) { - $path = $this->getRelativePath($data->getPath()); $info = pathinfo($path); @@ -113,5 +112,4 @@ class File extends \OCP\Search\Result { } return self::$userFolderCache->getRelativePath($path); } - } diff --git a/lib/private/Search/Result/Folder.php b/lib/private/Search/Result/Folder.php index 0a746221ee0..aa166cff8fc 100644 --- a/lib/private/Search/Result/Folder.php +++ b/lib/private/Search/Result/Folder.php @@ -34,5 +34,4 @@ class Folder extends File { * @var string */ public $type = 'folder'; - } diff --git a/lib/private/Security/Bruteforce/Throttler.php b/lib/private/Security/Bruteforce/Throttler.php index d8e06032ef1..c04e0e1b383 100644 --- a/lib/private/Security/Bruteforce/Throttler.php +++ b/lib/private/Security/Bruteforce/Throttler.php @@ -100,7 +100,7 @@ class Throttler { $ip, array $metadata = []) { // No need to log if the bruteforce protection is disabled - if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { + if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { return; } @@ -126,7 +126,7 @@ class Throttler { $qb = $this->db->getQueryBuilder(); $qb->insert('bruteforce_attempts'); - foreach($values as $column => $value) { + foreach ($values as $column => $value) { $qb->setValue($column, $qb->createNamedParameter($value)); } $qb->execute(); @@ -139,7 +139,7 @@ class Throttler { * @return bool */ private function isIPWhitelisted($ip) { - if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { + if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { return true; } @@ -175,7 +175,7 @@ class Throttler { $addr = inet_pton($addr); $valid = true; - for($i = 0; $i < $mask; $i++) { + for ($i = 0; $i < $mask; $i++) { $part = ord($addr[(int)($i/8)]); $orig = ord($ip[(int)($i/8)]); @@ -196,7 +196,6 @@ class Throttler { } return false; - } /** @@ -234,7 +233,7 @@ class Throttler { $maxDelay = 25; $firstDelay = 0.1; - if ($attempts > (8 * PHP_INT_SIZE - 1)) { + if ($attempts > (8 * PHP_INT_SIZE - 1)) { // Don't ever overflow. Just assume the maxDelay time:s $firstDelay = $maxDelay; } else { diff --git a/lib/private/Security/CSP/ContentSecurityPolicy.php b/lib/private/Security/CSP/ContentSecurityPolicy.php index 4db1314e782..4d41bd56206 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicy.php +++ b/lib/private/Security/CSP/ContentSecurityPolicy.php @@ -245,5 +245,4 @@ class ContentSecurityPolicy extends \OCP\AppFramework\Http\ContentSecurityPolicy public function setReportTo(array $reportTo) { $this->reportTo = $reportTo; } - } diff --git a/lib/private/Security/CSP/ContentSecurityPolicyManager.php b/lib/private/Security/CSP/ContentSecurityPolicyManager.php index 9f1a480ccce..4245fdcb2de 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicyManager.php +++ b/lib/private/Security/CSP/ContentSecurityPolicyManager.php @@ -59,7 +59,7 @@ class ContentSecurityPolicyManager implements IContentSecurityPolicyManager { $this->dispatcher->dispatch(AddContentSecurityPolicyEvent::class, $event); $defaultPolicy = new \OC\Security\CSP\ContentSecurityPolicy(); - foreach($this->policies as $policy) { + foreach ($this->policies as $policy) { $defaultPolicy = $this->mergePolicies($defaultPolicy, $policy); } return $defaultPolicy; @@ -74,9 +74,9 @@ class ContentSecurityPolicyManager implements IContentSecurityPolicyManager { */ public function mergePolicies(ContentSecurityPolicy $defaultPolicy, EmptyContentSecurityPolicy $originalPolicy): ContentSecurityPolicy { - foreach((object)(array)$originalPolicy as $name => $value) { + foreach ((object)(array)$originalPolicy as $name => $value) { $setter = 'set'.ucfirst($name); - if(\is_array($value)) { + if (\is_array($value)) { $getter = 'get'.ucfirst($name); $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : []; $defaultPolicy->$setter(array_values(array_unique(array_merge($currentValues, $value)))); diff --git a/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php b/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php index 9dec2907b2f..06f8faece13 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php +++ b/lib/private/Security/CSP/ContentSecurityPolicyNonceManager.php @@ -61,7 +61,7 @@ class ContentSecurityPolicyNonceManager { * @return string */ public function getNonce(): string { - if($this->nonce === '') { + if ($this->nonce === '') { if (empty($this->request->server['CSP_NONCE'])) { $this->nonce = base64_encode($this->csrfTokenManager->getToken()->getEncryptedValue()); } else { @@ -86,7 +86,7 @@ class ContentSecurityPolicyNonceManager { '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/(?:1[2-9]|[2-9][0-9])\.[0-9]+(?:\.[0-9]+)? Safari\/[0-9.A-Z]+$/', ]; - if($this->request->isUserAgent($browserWhitelist)) { + if ($this->request->isUserAgent($browserWhitelist)) { return true; } diff --git a/lib/private/Security/CSRF/CsrfToken.php b/lib/private/Security/CSRF/CsrfToken.php index 9b6b249e20f..a0ecdbd1008 100644 --- a/lib/private/Security/CSRF/CsrfToken.php +++ b/lib/private/Security/CSRF/CsrfToken.php @@ -55,7 +55,7 @@ class CsrfToken { * @return string */ public function getEncryptedValue(): string { - if($this->encryptedValue === '') { + if ($this->encryptedValue === '') { $sharedSecret = random_bytes(\strlen($this->value)); $this->encryptedValue = base64_encode($this->value ^ $sharedSecret) . ':' . base64_encode($sharedSecret); } diff --git a/lib/private/Security/CSRF/CsrfTokenManager.php b/lib/private/Security/CSRF/CsrfTokenManager.php index 8314639e8ef..2f64aeb24f4 100644 --- a/lib/private/Security/CSRF/CsrfTokenManager.php +++ b/lib/private/Security/CSRF/CsrfTokenManager.php @@ -57,11 +57,11 @@ class CsrfTokenManager { * @return CsrfToken */ public function getToken(): CsrfToken { - if(!\is_null($this->csrfToken)) { + if (!\is_null($this->csrfToken)) { return $this->csrfToken; } - if($this->sessionStorage->hasToken()) { + if ($this->sessionStorage->hasToken()) { $value = $this->sessionStorage->getToken(); } else { $value = $this->tokenGenerator->generateToken(); @@ -99,7 +99,7 @@ class CsrfTokenManager { * @return bool */ public function isTokenValid(CsrfToken $token): bool { - if(!$this->sessionStorage->hasToken()) { + if (!$this->sessionStorage->hasToken()) { return false; } diff --git a/lib/private/Security/CSRF/TokenStorage/SessionStorage.php b/lib/private/Security/CSRF/TokenStorage/SessionStorage.php index d73c8d94206..34adc566bf7 100644 --- a/lib/private/Security/CSRF/TokenStorage/SessionStorage.php +++ b/lib/private/Security/CSRF/TokenStorage/SessionStorage.php @@ -60,7 +60,7 @@ class SessionStorage { */ public function getToken(): string { $token = $this->session->get('requesttoken'); - if(empty($token)) { + if (empty($token)) { throw new \Exception('Session does not contain a requesttoken'); } diff --git a/lib/private/Security/Certificate.php b/lib/private/Security/Certificate.php index 5e6c425dbf7..cc4baeaa658 100644 --- a/lib/private/Security/Certificate.php +++ b/lib/private/Security/Certificate.php @@ -54,12 +54,12 @@ class Certificate implements ICertificate { // If string starts with "file://" ignore the certificate $query = 'file://'; - if(strtolower(substr($data, 0, strlen($query))) === $query) { + if (strtolower(substr($data, 0, strlen($query))) === $query) { throw new \Exception('Certificate could not get parsed.'); } $info = openssl_x509_parse($data); - if(!is_array($info)) { + if (!is_array($info)) { throw new \Exception('Certificate could not get parsed.'); } diff --git a/lib/private/Security/CertificateManager.php b/lib/private/Security/CertificateManager.php index 86df38625e0..e69132ff4df 100644 --- a/lib/private/Security/CertificateManager.php +++ b/lib/private/Security/CertificateManager.php @@ -87,7 +87,6 @@ class CertificateManager implements ICertificateManager { * @return \OCP\ICertificate[] */ public function listCertificates() { - if (!$this->config->getSystemValue('installed', false)) { return []; } @@ -187,7 +186,6 @@ class CertificateManager implements ICertificateManager { } catch (\Exception $e) { throw $e; } - } /** @@ -287,5 +285,4 @@ class CertificateManager implements ICertificateManager { protected function getFilemtimeOfCaBundle() { return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt'); } - } diff --git a/lib/private/Security/CredentialsManager.php b/lib/private/Security/CredentialsManager.php index 0120f69e431..ab06a807613 100644 --- a/lib/private/Security/CredentialsManager.php +++ b/lib/private/Security/CredentialsManager.php @@ -33,7 +33,6 @@ use OCP\Security\ICrypto; * @package OC\Security */ class CredentialsManager implements ICredentialsManager { - const DB_TABLE = 'credentials'; /** @var ICrypto */ @@ -122,5 +121,4 @@ class CredentialsManager implements ICredentialsManager { ; return $qb->execute(); } - } diff --git a/lib/private/Security/Crypto.php b/lib/private/Security/Crypto.php index ca17b6e2b8a..19258d2018e 100644 --- a/lib/private/Security/Crypto.php +++ b/lib/private/Security/Crypto.php @@ -70,7 +70,7 @@ class Crypto implements ICrypto { * @return string Calculated HMAC */ public function calculateHMAC(string $message, string $password = ''): string { - if($password === '') { + if ($password === '') { $password = $this->config->getSystemValue('secret'); } @@ -89,7 +89,7 @@ class Crypto implements ICrypto { * @return string Authenticated ciphertext */ public function encrypt(string $plaintext, string $password = ''): string { - if($password === '') { + if ($password === '') { $password = $this->config->getSystemValue('secret'); } $this->cipher->setPassword($password); @@ -139,5 +139,4 @@ class Crypto implements ICrypto { return $result; } - } diff --git a/lib/private/Security/FeaturePolicy/FeaturePolicy.php b/lib/private/Security/FeaturePolicy/FeaturePolicy.php index b59d873b533..93556708789 100644 --- a/lib/private/Security/FeaturePolicy/FeaturePolicy.php +++ b/lib/private/Security/FeaturePolicy/FeaturePolicy.php @@ -27,7 +27,6 @@ declare(strict_types=1); namespace OC\Security\FeaturePolicy; class FeaturePolicy extends \OCP\AppFramework\Http\FeaturePolicy { - public function getAutoplayDomains(): array { return $this->autoplayDomains; } diff --git a/lib/private/Security/Hasher.php b/lib/private/Security/Hasher.php index 9850dbe1467..8c081414353 100644 --- a/lib/private/Security/Hasher.php +++ b/lib/private/Security/Hasher.php @@ -79,7 +79,7 @@ class Hasher implements IHasher { } $hashingCost = $this->config->getSystemValue('hashingCost', null); - if(!\is_null($hashingCost)) { + if (!\is_null($hashingCost)) { $this->options['cost'] = $hashingCost; } } @@ -113,8 +113,8 @@ class Hasher implements IHasher { */ protected function splitHash(string $prefixedHash) { $explodedString = explode('|', $prefixedHash, 2); - if(\count($explodedString) === 2) { - if((int)$explodedString[0] > 0) { + if (\count($explodedString) === 2) { + if ((int)$explodedString[0] > 0) { return ['version' => (int)$explodedString[0], 'hash' => $explodedString[1]]; } } @@ -130,13 +130,13 @@ class Hasher implements IHasher { * @return bool Whether $hash is a valid hash of $message */ protected function legacyHashVerify($message, $hash, &$newHash = null): bool { - if(empty($this->legacySalt)) { + if (empty($this->legacySalt)) { $this->legacySalt = $this->config->getSystemValue('passwordsalt', ''); } // Verify whether it matches a legacy PHPass or SHA1 string $hashLength = \strlen($hash); - if(($hashLength === 60 && password_verify($message.$this->legacySalt, $hash)) || + if (($hashLength === 60 && password_verify($message.$this->legacySalt, $hash)) || ($hashLength === 40 && hash_equals($hash, sha1($message)))) { $newHash = $this->hash($message); return true; @@ -155,7 +155,7 @@ class Hasher implements IHasher { * @return bool Whether $hash is a valid hash of $message */ protected function verifyHash(string $message, string $hash, &$newHash = null): bool { - if(password_verify($message, $hash)) { + if (password_verify($message, $hash)) { if ($this->needsRehash($hash)) { $newHash = $this->hash($message); } @@ -174,7 +174,7 @@ class Hasher implements IHasher { public function verify(string $message, string $hash, &$newHash = null): bool { $splittedHash = $this->splitHash($hash); - if(isset($splittedHash['version'])) { + if (isset($splittedHash['version'])) { switch ($splittedHash['version']) { case 3: case 2: @@ -211,5 +211,4 @@ class Hasher implements IHasher { return $default; } - } diff --git a/lib/private/Security/IdentityProof/Manager.php b/lib/private/Security/IdentityProof/Manager.php index 2c101769f18..abbda2f11eb 100644 --- a/lib/private/Security/IdentityProof/Manager.php +++ b/lib/private/Security/IdentityProof/Manager.php @@ -104,7 +104,8 @@ class Manager { // Write the private and public key to the disk try { $this->appData->newFolder($id); - } catch (\Exception $e) {} + } catch (\Exception $e) { + } $folder = $this->appData->getFolder($id); $folder->newFile('private') ->putContent($this->crypto->encrypt($privateKey)); @@ -167,6 +168,4 @@ class Manager { } $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors)); } - - } diff --git a/lib/private/Security/IdentityProof/Signer.php b/lib/private/Security/IdentityProof/Signer.php index c5410397a27..9f6b27d358f 100644 --- a/lib/private/Security/IdentityProof/Signer.php +++ b/lib/private/Security/IdentityProof/Signer.php @@ -83,7 +83,7 @@ class Signer { * @return bool */ public function verify(array $data): bool { - if(isset($data['message']) + if (isset($data['message']) && isset($data['signature']) && isset($data['message']['signer']) ) { @@ -91,7 +91,7 @@ class Signer { $userId = substr($data['message']['signer'], 0, $location); $user = $this->userManager->get($userId); - if($user !== null) { + if ($user !== null) { $key = $this->keyManager->getKey($user); return (bool)openssl_verify( json_encode($data['message']), diff --git a/lib/private/Security/RateLimiting/Backend/MemoryCache.php b/lib/private/Security/RateLimiting/Backend/MemoryCache.php index 2d4ff9812f5..ce8bacfb588 100644 --- a/lib/private/Security/RateLimiting/Backend/MemoryCache.php +++ b/lib/private/Security/RateLimiting/Backend/MemoryCache.php @@ -75,7 +75,7 @@ class MemoryCache implements IBackend { } $cachedAttempts = json_decode($cachedAttempts, true); - if(\is_array($cachedAttempts)) { + if (\is_array($cachedAttempts)) { return $cachedAttempts; } @@ -95,7 +95,7 @@ class MemoryCache implements IBackend { $currentTime = $this->timeFactory->getTime(); /** @var array $existingAttempts */ foreach ($existingAttempts as $attempt) { - if(($attempt + $seconds) > $currentTime) { + if (($attempt + $seconds) > $currentTime) { $count++; } } @@ -115,7 +115,7 @@ class MemoryCache implements IBackend { // Unset all attempts older than $period foreach ($existingAttempts as $key => $attempt) { - if(($attempt + $period) < $currentTime) { + if (($attempt + $period) < $currentTime) { unset($existingAttempts[$key]); } } diff --git a/lib/private/Security/SecureRandom.php b/lib/private/Security/SecureRandom.php index 0e3411f8ab6..4826399ff5b 100644 --- a/lib/private/Security/SecureRandom.php +++ b/lib/private/Security/SecureRandom.php @@ -51,7 +51,7 @@ class SecureRandom implements ISecureRandom { $maxCharIndex = \strlen($characters) - 1; $randomString = ''; - while($length > 0) { + while ($length > 0) { $randomNumber = \random_int(0, $maxCharIndex); $randomString .= $characters[$randomNumber]; $length--; diff --git a/lib/private/Security/TrustedDomainHelper.php b/lib/private/Security/TrustedDomainHelper.php index c1789da6ad7..320646e1b7f 100644 --- a/lib/private/Security/TrustedDomainHelper.php +++ b/lib/private/Security/TrustedDomainHelper.php @@ -98,7 +98,9 @@ class TrustedDomainHelper { if (gettype($trusted) !== 'string') { break; } - $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function ($v) { return preg_quote($v, '/'); }, explode('*', $trusted))) . '$/i'; + $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function ($v) { + return preg_quote($v, '/'); + }, explode('*', $trusted))) . '$/i'; if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) { return true; } diff --git a/lib/private/Server.php b/lib/private/Server.php index 026dcdf9a85..629673418f7 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -651,7 +651,6 @@ class Server extends ServerContainer implements IServerContainer { $this->registerDeprecatedAlias('UserCache', ICache::class); $this->registerService(Factory::class, function (Server $c) { - $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(), ArrayCache::class, ArrayCache::class, @@ -673,7 +672,6 @@ class Server extends ServerContainer implements IServerContainer { ); } return $arrayCacheFactory; - }); $this->registerDeprecatedAlias('MemCacheFactory', Factory::class); $this->registerAlias(ICacheFactory::class, Factory::class); @@ -1088,7 +1086,7 @@ class Server extends ServerContainer implements IServerContainer { $manager->registerDisplayNameResolver('user', function ($id) use ($c) { $manager = $c->getUserManager(); $user = $manager->get($id); - if(is_null($user)) { + if (is_null($user)) { $l = $c->getL10N('core'); $displayName = $l->t('Unknown user'); } else { diff --git a/lib/private/ServerNotAvailableException.php b/lib/private/ServerNotAvailableException.php index 1dd93aefb20..d0618883107 100644 --- a/lib/private/ServerNotAvailableException.php +++ b/lib/private/ServerNotAvailableException.php @@ -23,5 +23,4 @@ namespace OC; class ServerNotAvailableException extends \Exception { - } diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index da9bf950ba2..892c2436040 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -72,7 +72,7 @@ class CryptoSessionData implements \ArrayAccess, ISession { public function __destruct() { try { $this->close(); - } catch (SessionNotAvailableException $e){ + } catch (SessionNotAvailableException $e) { // This exception can occur if session is already closed // So it is safe to ignore it and let the garbage collector to proceed } @@ -108,7 +108,7 @@ class CryptoSessionData implements \ArrayAccess, ISession { * @return string|null Either the value or null */ public function get(string $key) { - if(isset($this->sessionValues[$key])) { + if (isset($this->sessionValues[$key])) { return $this->sessionValues[$key]; } @@ -175,7 +175,7 @@ class CryptoSessionData implements \ArrayAccess, ISession { * Close the session and release the lock, also writes all changed data in batch */ public function close() { - if($this->isModified) { + if ($this->isModified) { $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase); $this->session->set(self::encryptedSessionName, $encryptedValue); $this->isModified = false; diff --git a/lib/private/Session/CryptoWrapper.php b/lib/private/Session/CryptoWrapper.php index b9dbc90edd6..bb82652a01d 100644 --- a/lib/private/Session/CryptoWrapper.php +++ b/lib/private/Session/CryptoWrapper.php @@ -83,7 +83,7 @@ class CryptoWrapper { // FIXME: Required for CI if (!defined('PHPUNIT_RUN')) { $webRoot = \OC::$WEBROOT; - if($webRoot === '') { + if ($webRoot === '') { $webRoot = '/'; } diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php index 7990c4a7dae..ffe16537874 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -203,12 +203,12 @@ class Internal extends Session { */ private function invoke(string $functionName, array $parameters = [], bool $silence = false) { try { - if($silence) { + if ($silence) { return @call_user_func_array($functionName, $parameters); } else { return call_user_func_array($functionName, $parameters); } - } catch(\Error $e) { + } catch (\Error $e) { $this->trapError($e->getCode(), $e->getMessage()); } } diff --git a/lib/private/Session/Memory.php b/lib/private/Session/Memory.php index a7b1cd07ead..abbf026899b 100644 --- a/lib/private/Session/Memory.php +++ b/lib/private/Session/Memory.php @@ -94,7 +94,8 @@ class Memory extends Session { * * @param bool $deleteOldSession */ - public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {} + public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) { + } /** * Wrapper around session_id diff --git a/lib/private/Setup/AbstractDatabase.php b/lib/private/Setup/AbstractDatabase.php index d509a6b8722..649afbe27cb 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -69,14 +69,14 @@ abstract class AbstractDatabase { public function validate($config) { $errors = []; - if(empty($config['dbuser']) && empty($config['dbname'])) { + if (empty($config['dbuser']) && empty($config['dbname'])) { $errors[] = $this->trans->t("%s enter the database username and name.", [$this->dbprettyname]); - } elseif(empty($config['dbuser'])) { + } elseif (empty($config['dbuser'])) { $errors[] = $this->trans->t("%s enter the database username.", [$this->dbprettyname]); - } elseif(empty($config['dbname'])) { + } elseif (empty($config['dbname'])) { $errors[] = $this->trans->t("%s enter the database name.", [$this->dbprettyname]); } - if(substr_count($config['dbname'], '.') >= 1) { + if (substr_count($config['dbname'], '.') >= 1) { $errors[] = $this->trans->t("%s you may not use dots in the database name", [$this->dbprettyname]); } return $errors; diff --git a/lib/private/Setup/MySQL.php b/lib/private/Setup/MySQL.php index 7371c7aeab2..9d48bbca488 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -74,7 +74,7 @@ class MySQL extends AbstractDatabase { * @param \OC\DB\Connection $connection */ private function createDatabase($connection) { - try{ + try { $name = $this->dbName; $user = $this->dbUser; //we can't use OC_DB functions here because we need to connect as the administrative user. @@ -108,7 +108,7 @@ class MySQL extends AbstractDatabase { * @throws \OC\DatabaseSetupException */ private function createDBUser($connection) { - try{ + try { $name = $this->dbUser; $password = $this->dbPassword; // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one, @@ -125,8 +125,7 @@ class MySQL extends AbstractDatabase { $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'"; $connection->executeUpdate($query); } - } - catch (\Exception $ex){ + } catch (\Exception $ex) { $this->logger->logException($ex, [ 'message' => 'Database user creation failed.', 'level' => ILogger::ERROR, diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php index a3b8da44c4c..ec5136040e8 100644 --- a/lib/private/Share/Helper.php +++ b/lib/private/Share/Helper.php @@ -159,7 +159,6 @@ class Helper extends \OC\Share\Constants { * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' */ public static function getDefaultExpireSetting() { - $config = \OC::$server->getConfig(); $defaultExpireSettings = ['defaultExpireDateSet' => false]; @@ -185,7 +184,6 @@ class Helper extends \OC\Share\Constants { //$dateString = $date->format('Y-m-d') . ' 00:00:00'; return $date; - } /** @@ -196,7 +194,6 @@ class Helper extends \OC\Share\Constants { * @return mixed integer timestamp or False */ public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) { - $expires = false; $defaultExpires = null; diff --git a/lib/private/Share/SearchResultSorter.php b/lib/private/Share/SearchResultSorter.php index 54232b828ca..2151eb2acb6 100644 --- a/lib/private/Share/SearchResultSorter.php +++ b/lib/private/Share/SearchResultSorter.php @@ -54,8 +54,8 @@ class SearchResultSorter { * Callback function for usort. http://php.net/usort */ public function sort($a, $b) { - if(!isset($a[$this->key]) || !isset($b[$this->key])) { - if(!is_null($this->log)) { + if (!isset($a[$this->key]) || !isset($b[$this->key])) { + if (!is_null($this->log)) { $this->log->error('Sharing dialogue: cannot sort due to ' . 'missing array key', ['app' => 'core']); } @@ -66,7 +66,7 @@ class SearchResultSorter { $i = mb_strpos($nameA, $this->search, 0, $this->encoding); $j = mb_strpos($nameB, $this->search, 0, $this->encoding); - if($i === $j || $i > 0 && $j > 0) { + if ($i === $j || $i > 0 && $j > 0) { return strcmp(mb_strtolower($nameA, $this->encoding), mb_strtolower($nameB, $this->encoding)); } elseif ($i === 0) { diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index 319bd5bec38..8ea97cd69a7 100644 --- a/lib/private/Share/Share.php +++ b/lib/private/Share/Share.php @@ -195,7 +195,7 @@ class Share extends Constants { } //if didn't found a result than let's look for a group share. - if(empty($shares) && $user !== null) { + if (empty($shares) && $user !== null) { $userObject = \OC::$server->getUserManager()->get($user); $groups = []; if ($userObject) { @@ -229,7 +229,6 @@ class Share extends Constants { } return $shares; - } /** @@ -353,7 +352,7 @@ class Share extends Constants { // delete the item with the expected share_type and owner if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) { $toDelete = $item; - // if there is more then one result we don't have to delete the children + // if there is more then one result we don't have to delete the children // but update their parent. For group shares the new parent should always be // the original group share and not the db entry with the unique name } elseif ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) { @@ -376,7 +375,6 @@ class Share extends Constants { * @return boolean True if item was expired, false otherwise. */ protected static function expireItem(array $item) { - $result = false; // only use default expiration date for link shares @@ -414,7 +412,6 @@ class Share extends Constants { * @return null */ protected static function unshareItem(array $item, $newParent = null) { - $shareType = (int)$item['share_type']; $shareWith = null; if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) { @@ -431,7 +428,7 @@ class Share extends Constants { 'itemParent' => $item['parent'], 'uidOwner' => $item['uid_owner'], ]; - if($item['item_type'] === 'file' || $item['item_type'] === 'folder') { + if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') { $hookParams['fileSource'] = $item['file_source']; $hookParams['fileTarget'] = $item['file_target']; } @@ -605,7 +602,7 @@ class Share extends Constants { // Get filesystem root to add it to the file target and remove from the // file source, match file_source with the file cache if ($itemType == 'file' || $itemType == 'folder') { - if(!is_null($uidOwner)) { + if (!is_null($uidOwner)) { $root = \OC\Files\Filesystem::getRoot(); } else { $root = ''; @@ -800,7 +797,6 @@ class Share extends Constants { $id = $row['id']; } $items[$id]['permissions'] |= (int)$row['permissions']; - } continue; } elseif (!empty($row['parent'])) { @@ -843,7 +839,7 @@ class Share extends Constants { } } - if($checkExpireDate) { + if ($checkExpireDate) { if (self::expireItem($row)) { continue; } @@ -858,7 +854,7 @@ class Share extends Constants { $row['share_type'] === self::SHARE_TYPE_USER) { $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']); $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName(); - } elseif(isset($row['share_with']) && $row['share_with'] != '' && + } elseif (isset($row['share_with']) && $row['share_with'] != '' && $row['share_type'] === self::SHARE_TYPE_REMOTE) { $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']); foreach ($addressBookEntries as $entry) { @@ -877,7 +873,6 @@ class Share extends Constants { if ($row['permissions'] > 0) { $items[$row['id']] = $row; } - } // group items if we are looking for items shared with the current user @@ -1007,7 +1002,6 @@ class Share extends Constants { * @return array of grouped items */ protected static function groupItems($items, $itemType) { - $fileSharing = $itemType === 'file' || $itemType === 'folder'; $result = []; @@ -1034,7 +1028,6 @@ class Share extends Constants { if (!$grouped) { $result[] = $item; } - } return $result; @@ -1056,14 +1049,13 @@ class Share extends Constants { */ private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions) { - $queriesToExecute = []; $suggestedItemTarget = null; $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = ''; $groupItemTarget = $itemTarget = $fileSource = $parent = 0; $result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null); - if(!empty($result)) { + if (!empty($result)) { $parent = $result['parent']; $itemSource = $result['itemSource']; $fileSource = $result['fileSource']; @@ -1073,8 +1065,8 @@ class Share extends Constants { } $isGroupShare = false; - $users = [$shareWith]; - $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, + $users = [$shareWith]; + $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedItemTarget); $run = true; @@ -1110,18 +1102,15 @@ class Share extends Constants { if ($sourceExists && $sourceExists['item_source'] === $itemSource) { $fileTarget = $sourceExists['file_target']; $itemTarget = $sourceExists['item_target']; - - } elseif(!$sourceExists) { - + } elseif (!$sourceExists) { $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user, $uidOwner, $suggestedItemTarget, $parent); if (isset($fileSource)) { - $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, + $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user, $uidOwner, $suggestedFileTarget, $parent); } else { $fileTarget = null; } - } else { // group share which doesn't exists until now, check if we need a unique target for this user @@ -1158,7 +1147,6 @@ class Share extends Constants { 'parent' => $parent, 'expiration' => null, ]; - } $id = false; @@ -1232,7 +1220,7 @@ class Share extends Constants { $result['expirationDate'] = $expirationDate; // $checkReshare['expiration'] could be null and then is always less than any value - if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) { + if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) { $result['expirationDate'] = $checkReshare['expiration']; } @@ -1269,8 +1257,8 @@ class Share extends Constants { } if ($backend instanceof \OCP\Share_Backend_File_Dependent) { $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner); - $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']); - $result['fileSource'] = $meta['fileid']; + $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']); + $result['fileSource'] = $meta['fileid']; if ($result['fileSource'] == -1) { $message = 'Sharing %s failed, because the file could not be found in the file cache'; throw new \Exception(sprintf($message, $itemSource)); @@ -1290,7 +1278,6 @@ class Share extends Constants { * @return mixed false in case of a failure or the id of the new share */ private static function insertShare(array $shareData) { - $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (' .' `item_type`, `item_source`, `item_target`, `share_type`,' .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,' @@ -1316,7 +1303,6 @@ class Share extends Constants { } return $id; - } /** diff --git a/lib/private/Share20/DefaultShareProvider.php b/lib/private/Share20/DefaultShareProvider.php index ad002a1fc96..41a727593b3 100644 --- a/lib/private/Share20/DefaultShareProvider.php +++ b/lib/private/Share20/DefaultShareProvider.php @@ -249,7 +249,6 @@ class DefaultShareProvider implements IShareProvider { * @throws \OCP\Files\NotFoundException */ public function update(\OCP\Share\IShare $share) { - $originalShare = $this->getShareById($share->getId()); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { @@ -306,7 +305,6 @@ class DefaultShareProvider implements IShareProvider { ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0))) ->set('permissions', $qb->createNamedParameter($share->getPermissions())) ->execute(); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $qb = $this->dbConn->getQueryBuilder(); $qb->update('share') @@ -380,7 +378,6 @@ class DefaultShareProvider implements IShareProvider { } else { $id = $data['id']; } - } elseif ($share->getShareType() === IShare::TYPE_USER) { if ($share->getSharedWith() !== $recipient) { throw new ProviderException('Recipient does not match'); @@ -431,7 +428,7 @@ class DefaultShareProvider implements IShareProvider { ->orderBy('id'); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $children[] = $this->createShare($data); } $cursor->closeCursor(); @@ -471,7 +468,6 @@ class DefaultShareProvider implements IShareProvider { */ public function deleteFromSelf(IShare $share, $recipient) { if ($share->getShareType() === IShare::TYPE_GROUP) { - $group = $this->groupManager->get($share->getSharedWith()); $user = $this->userManager->get($recipient); @@ -518,9 +514,7 @@ class DefaultShareProvider implements IShareProvider { ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))) ->execute(); } - } elseif ($share->getShareType() === IShare::TYPE_USER) { - if ($share->getSharedWith() !== $recipient) { throw new ProviderException('Recipient does not match'); } @@ -600,7 +594,6 @@ class DefaultShareProvider implements IShareProvider { ->set('file_target', $qb->createNamedParameter($share->getTarget())) ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) ->execute(); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { // Check if there is a usergroup share @@ -737,7 +730,7 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShare($data); } $cursor->closeCursor(); @@ -816,7 +809,7 @@ class DefaultShareProvider implements IShareProvider { ->execute(); $shares = []; - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { $shares[] = $this->createShare($data); } $cursor->closeCursor(); @@ -887,13 +880,12 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { if ($this->isAccessibleResult($data)) { $shares[] = $this->createShare($data); } } $cursor->closeCursor(); - } elseif ($shareType === \OCP\Share::SHARE_TYPE_GROUP) { $user = $this->userManager->get($userId); $allGroups = $this->groupManager->getUserGroups($user); @@ -902,7 +894,7 @@ class DefaultShareProvider implements IShareProvider { $shares2 = []; $start = 0; - while(true) { + while (true) { $groups = array_slice($allGroups, $start, 100); $start += 100; @@ -933,8 +925,12 @@ class DefaultShareProvider implements IShareProvider { } - $groups = array_filter($groups, function ($group) { return $group instanceof IGroup; }); - $groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); + $groups = array_filter($groups, function ($group) { + return $group instanceof IGroup; + }); + $groups = array_map(function (IGroup $group) { + return $group->getGID(); + }, $groups); $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))) ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter( @@ -947,7 +943,7 @@ class DefaultShareProvider implements IShareProvider { )); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { if ($offset > 0) { $offset--; continue; @@ -1077,7 +1073,7 @@ class DefaultShareProvider implements IShareProvider { $result = []; $start = 0; - while(true) { + while (true) { /** @var Share[] $shareSlice */ $shareSlice = array_slice($shares, $start, 100); $start += 100; @@ -1109,7 +1105,7 @@ class DefaultShareProvider implements IShareProvider { $stmt = $query->execute(); - while($data = $stmt->fetch()) { + while ($data = $stmt->fetch()) { $shareMap[$data['parent']]->setPermissions((int)$data['permissions']); $shareMap[$data['parent']]->setStatus((int)$data['accepted']); $shareMap[$data['parent']]->setTarget($data['file_target']); @@ -1212,7 +1208,7 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); $ids = []; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $ids[] = (int)$row['id']; } $cursor->closeCursor(); @@ -1255,7 +1251,7 @@ class DefaultShareProvider implements IShareProvider { $cursor = $qb->execute(); $ids = []; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $ids[] = (int)$row['id']; } $cursor->closeCursor(); @@ -1310,7 +1306,7 @@ class DefaultShareProvider implements IShareProvider { $users = []; $link = false; - while($row = $cursor->fetch()) { + while ($row = $cursor->fetch()) { $type = (int)$row['share_type']; if ($type === \OCP\Share::SHARE_TYPE_USER) { $uid = $row['share_with']; @@ -1411,7 +1407,6 @@ class DefaultShareProvider implements IShareProvider { * @throws \OCP\Files\NotFoundException */ private function sendNote(array $recipients, IShare $share) { - $toList = []; foreach ($recipients as $recipient) { @@ -1423,7 +1418,6 @@ class DefaultShareProvider implements IShareProvider { } if (!empty($toList)) { - $filename = $share->getNode()->getName(); $initiator = $share->getSharedBy(); $note = $share->getNote(); @@ -1475,7 +1469,6 @@ class DefaultShareProvider implements IShareProvider { $message->useTemplate($emailTemplate); $this->mailer->send($message); } - } public function getAllShares(): iterable { @@ -1492,7 +1485,7 @@ class DefaultShareProvider implements IShareProvider { ); $cursor = $qb->execute(); - while($data = $cursor->fetch()) { + while ($data = $cursor->fetch()) { try { $share = $this->createShare($data); } catch (InvalidShare $e) { diff --git a/lib/private/Share20/Exception/BackendError.php b/lib/private/Share20/Exception/BackendError.php index b36cc1a9111..5ba17b7a458 100644 --- a/lib/private/Share20/Exception/BackendError.php +++ b/lib/private/Share20/Exception/BackendError.php @@ -23,5 +23,4 @@ namespace OC\Share20\Exception; class BackendError extends \Exception { - } diff --git a/lib/private/Share20/Exception/InvalidShare.php b/lib/private/Share20/Exception/InvalidShare.php index 908049ae75a..1216bfa9aea 100644 --- a/lib/private/Share20/Exception/InvalidShare.php +++ b/lib/private/Share20/Exception/InvalidShare.php @@ -23,5 +23,4 @@ namespace OC\Share20\Exception; class InvalidShare extends \Exception { - } diff --git a/lib/private/Share20/Exception/ProviderException.php b/lib/private/Share20/Exception/ProviderException.php index 7d3f79f7120..f60f5a8f385 100644 --- a/lib/private/Share20/Exception/ProviderException.php +++ b/lib/private/Share20/Exception/ProviderException.php @@ -23,5 +23,4 @@ namespace OC\Share20\Exception; class ProviderException extends \Exception { - } diff --git a/lib/private/Share20/LegacyHooks.php b/lib/private/Share20/LegacyHooks.php index f292499584e..1e2391f0bd0 100644 --- a/lib/private/Share20/LegacyHooks.php +++ b/lib/private/Share20/LegacyHooks.php @@ -173,6 +173,5 @@ class LegacyHooks { ]; \OC_Hook::emit(Share::class, 'post_shared', $postHookData); - } } diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index 7ec678b07fb..b9a97e4225f 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -234,7 +234,7 @@ class Manager implements IManager { if ($share->getSharedWith() === null) { throw new \InvalidArgumentException('SharedWith should not be empty'); } - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) { + } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) { if ($share->getSharedWith() === null) { throw new \InvalidArgumentException('SharedWith should not be empty'); } @@ -442,7 +442,6 @@ class Manager implements IManager { * @throws \Exception */ protected function validateExpirationDate(\OCP\Share\IShare $share) { - $expirationDate = $share->getExpirationDate(); if ($expirationDate !== null) { @@ -532,7 +531,7 @@ class Manager implements IManager { */ $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER); $existingShares = $provider->getSharesByPath($share->getNode()); - foreach($existingShares as $existingShare) { + foreach ($existingShares as $existingShare) { // Ignore if it is the same share try { if ($existingShare->getFullId() === $share->getFullId()) { @@ -589,7 +588,7 @@ class Manager implements IManager { */ $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); $existingShares = $provider->getSharesByPath($share->getNode()); - foreach($existingShares as $existingShare) { + foreach ($existingShares as $existingShare) { try { if ($existingShare->getFullId() === $share->getFullId()) { continue; @@ -658,7 +657,7 @@ class Manager implements IManager { // Make sure that we do not share a path that contains a shared mountpoint if ($path instanceof \OCP\Files\Folder) { $mounts = $this->mountManager->findIn($path->getPath()); - foreach($mounts as $mount) { + foreach ($mounts as $mount) { if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { throw new \InvalidArgumentException('Path contains files shared with you'); } @@ -706,7 +705,7 @@ class Manager implements IManager { $storage = $share->getNode()->getStorage(); if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { $parent = $share->getNode()->getParent(); - while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { + while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { $parent = $parent->getParent(); } $share->setShareOwner($parent->getOwner()->getUID()); @@ -720,13 +719,11 @@ class Manager implements IManager { //Verify the expiration date $share = $this->validateExpirationDateInternal($share); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { $this->groupCreateChecks($share); //Verify the expiration date $share = $this->validateExpirationDateInternal($share); - } elseif ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { $this->linkCreateChecks($share); $this->setLinkParent($share); @@ -797,7 +794,7 @@ class Manager implements IManager { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { $mailSend = $share->getMailSend(); - if($mailSend === true) { + if ($mailSend === true) { $user = $this->userManager->get($share->getSharedWith()); if ($user !== null) { $emailAddress = $user->getEMailAddress(); @@ -888,7 +885,7 @@ class Manager implements IManager { // The "Reply-To" is set to the sharer if an mail address is configured // also the default footer contains a "Do not reply" which needs to be adjusted. $initiatorEmail = $initiatorUser->getEMailAddress(); - if($initiatorEmail !== null) { + if ($initiatorEmail !== null) { $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')); } else { @@ -898,7 +895,7 @@ class Manager implements IManager { $message->useTemplate($emailTemplate); try { $failedRecipients = $this->mailer->send($message); - if(!empty($failedRecipients)) { + if (!empty($failedRecipients)) { $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients)); return; } @@ -1117,7 +1114,6 @@ class Manager implements IManager { * @throws \InvalidArgumentException */ public function deleteShare(\OCP\Share\IShare $share) { - try { $share->getFullId(); } catch (\UnexpectedValueException $e) { @@ -1238,10 +1234,9 @@ class Manager implements IManager { $shares2 = []; - while(true) { + while (true) { $added = 0; foreach ($shares as $share) { - try { $this->checkExpireDate($share); } catch (ShareNotFound $e) { @@ -1381,7 +1376,7 @@ class Manager implements IManager { } $share = null; try { - if($this->shareApiAllowLinks()) { + if ($this->shareApiAllowLinks()) { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK); $share = $provider->getShareByToken($token); } @@ -1450,7 +1445,6 @@ class Manager implements IManager { $this->deleteShare($share); throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); } - } /** diff --git a/lib/private/Share20/ProviderFactory.php b/lib/private/Share20/ProviderFactory.php index cf23779a8b9..6186d1c37cf 100644 --- a/lib/private/Share20/ProviderFactory.php +++ b/lib/private/Share20/ProviderFactory.php @@ -197,7 +197,6 @@ class ProviderFactory implements IProviderFactory { * @suppress PhanUndeclaredClassMethod */ protected function getShareByCircleProvider() { - if ($this->circlesAreNotAvailable) { return null; } @@ -210,7 +209,6 @@ class ProviderFactory implements IProviderFactory { } if ($this->shareByCircleProvider === null) { - $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider( $this->serverContainer->getDatabaseConnection(), $this->serverContainer->getSecureRandom(), diff --git a/lib/private/Share20/Share.php b/lib/private/Share20/Share.php index b05b72e7ada..fb4fc4c4078 100644 --- a/lib/private/Share20/Share.php +++ b/lib/private/Share20/Share.php @@ -112,7 +112,7 @@ class Share implements \OCP\Share\IShare { $id = (string)$id; } - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } @@ -145,7 +145,7 @@ class Share implements \OCP\Share\IShare { * @inheritdoc */ public function setProviderId($id) { - if(!is_string($id)) { + if (!is_string($id)) { throw new \InvalidArgumentException('String expected.'); } @@ -172,14 +172,13 @@ class Share implements \OCP\Share\IShare { */ public function getNode() { if ($this->node === null) { - if ($this->shareOwner === null || $this->fileId === null) { throw new NotFoundException(); } // for federated shares the owner can be a remote user, in this // case we use the initiator - if($this->userManager->userExists($this->shareOwner)) { + if ($this->userManager->userExists($this->shareOwner)) { $userFolder = $this->rootFolder->getUserFolder($this->shareOwner); } else { $userFolder = $this->rootFolder->getUserFolder($this->sharedBy); diff --git a/lib/private/Streamer.php b/lib/private/Streamer.php index 7ae03532a83..f4d5cc221ac 100644 --- a/lib/private/Streamer.php +++ b/lib/private/Streamer.php @@ -117,8 +117,8 @@ class Streamer { $dirNode = $userFolder->get($dir); $files = $dirNode->getDirectoryListing(); - foreach($files as $file) { - if($file instanceof File) { + foreach ($files as $file) { + if ($file instanceof File) { try { $fh = $file->fopen('r'); } catch (NotPermittedException $e) { @@ -132,7 +132,7 @@ class Streamer { ); fclose($fh); } elseif ($file instanceof Folder) { - if($file->isReadable()) { + if ($file->isReadable()) { $this->addDirRecursive($dir . '/' . $file->getName(), $internalDir); } } diff --git a/lib/private/SubAdmin.php b/lib/private/SubAdmin.php index 8a8cbdb9813..d292e998ab9 100644 --- a/lib/private/SubAdmin.php +++ b/lib/private/SubAdmin.php @@ -118,9 +118,9 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { ->execute(); $groups = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $group = $this->groupManager->get($row['gid']); - if(!is_null($group)) { + if (!is_null($group)) { $groups[$group->getGID()] = $group; } } @@ -154,9 +154,9 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { ->execute(); $users = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $user = $this->userManager->get($row['uid']); - if(!is_null($user)) { + if (!is_null($user)) { $users[] = $user; } } @@ -177,10 +177,10 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { ->execute(); $subadmins = []; - while($row = $result->fetch()) { + while ($row = $result->fetch()) { $user = $this->userManager->get($row['uid']); $group = $this->groupManager->get($row['gid']); - if(!is_null($user) && !is_null($group)) { + if (!is_null($user) && !is_null($group)) { $subadmins[] = [ 'user' => $user, 'group' => $group @@ -249,15 +249,15 @@ class SubAdmin extends PublicEmitter implements ISubAdmin { * @return bool */ public function isUserAccessible(IUser $subadmin, IUser $user): bool { - if(!$this->isSubAdmin($subadmin)) { + if (!$this->isSubAdmin($subadmin)) { return false; } - if($this->groupManager->isAdmin($user->getUID())) { + if ($this->groupManager->isAdmin($user->getUID())) { return false; } $accessibleGroups = $this->getSubAdminsGroups($subadmin); - foreach($accessibleGroups as $accessibleGroup) { - if($accessibleGroup->inGroup($user)) { + foreach ($accessibleGroups as $accessibleGroup) { + if ($accessibleGroup->inGroup($user)) { return true; } } diff --git a/lib/private/Support/CrashReport/Registry.php b/lib/private/Support/CrashReport/Registry.php index f81ac36a8a6..44a6d290678 100644 --- a/lib/private/Support/CrashReport/Registry.php +++ b/lib/private/Support/CrashReport/Registry.php @@ -90,5 +90,4 @@ class Registry implements IRegistry { } } } - } diff --git a/lib/private/SystemTag/SystemTagManager.php b/lib/private/SystemTag/SystemTagManager.php index 75f12e59fce..2d7b1bc3ae4 100644 --- a/lib/private/SystemTag/SystemTagManager.php +++ b/lib/private/SystemTag/SystemTagManager.php @@ -44,7 +44,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; * Manager class for system tags */ class SystemTagManager implements ISystemTagManager { - const TAG_TABLE = 'systemtag'; const TAG_GROUP_TABLE = 'systemtag_group'; diff --git a/lib/private/SystemTag/SystemTagObjectMapper.php b/lib/private/SystemTag/SystemTagObjectMapper.php index e9df865ee96..eb33d2d30bb 100644 --- a/lib/private/SystemTag/SystemTagObjectMapper.php +++ b/lib/private/SystemTag/SystemTagObjectMapper.php @@ -38,7 +38,6 @@ use OCP\SystemTag\TagNotFoundException; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class SystemTagObjectMapper implements ISystemTagObjectMapper { - const RELATION_TABLE = 'systemtag_object_mapping'; /** @var ISystemTagManager */ diff --git a/lib/private/TagManager.php b/lib/private/TagManager.php index 52d000f8c94..ecc80b271fa 100644 --- a/lib/private/TagManager.php +++ b/lib/private/TagManager.php @@ -64,7 +64,6 @@ class TagManager implements \OCP\ITagManager { public function __construct(TagMapper $mapper, \OCP\IUserSession $userSession) { $this->mapper = $mapper; $this->userSession = $userSession; - } /** @@ -89,5 +88,4 @@ class TagManager implements \OCP\ITagManager { } return new Tags($this->mapper, $userId, $type, $defaultTags, $includeShared); } - } diff --git a/lib/private/Tagging/Tag.php b/lib/private/Tagging/Tag.php index f818a115b25..73b3f57ca15 100644 --- a/lib/private/Tagging/Tag.php +++ b/lib/private/Tagging/Tag.php @@ -37,7 +37,6 @@ use OCP\AppFramework\Db\Entity; * @method void setName(string $name) */ class Tag extends Entity { - protected $owner; protected $type; protected $name; diff --git a/lib/private/Tagging/TagMapper.php b/lib/private/Tagging/TagMapper.php index 2ffb663aeff..d9c8a7fb470 100644 --- a/lib/private/Tagging/TagMapper.php +++ b/lib/private/Tagging/TagMapper.php @@ -52,7 +52,7 @@ class TagMapper extends Mapper { * @return array An array of Tag objects. */ public function loadTags($owners, $type) { - if(!is_array($owners)) { + if (!is_array($owners)) { $owners = [$owners]; } diff --git a/lib/private/Tags.php b/lib/private/Tags.php index 4d05beb259c..a176967bd2b 100644 --- a/lib/private/Tags.php +++ b/lib/private/Tags.php @@ -136,7 +136,7 @@ class Tags implements ITags { } $this->tags = $this->mapper->loadTags($this->owners, $this->type); - if(count($defaultTags) > 0 && count($this->tags) === 0) { + if (count($defaultTags) > 0 && count($this->tags) === 0) { $this->addMultiple($defaultTags, true); } } @@ -177,7 +177,7 @@ class Tags implements ITags { * @return array */ public function getTags() { - if(!count($this->tags)) { + if (!count($this->tags)) { return []; } @@ -186,13 +186,12 @@ class Tags implements ITags { }); $tagMap = []; - foreach($this->tags as $tag) { - if($tag->getName() !== ITags::TAG_FAVORITE) { + foreach ($this->tags as $tag) { + if ($tag->getName() !== ITags::TAG_FAVORITE) { $tagMap[] = $this->tagMap($tag); } } return $tagMap; - } /** @@ -243,7 +242,7 @@ class Tags implements ITags { return false; } } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -267,18 +266,18 @@ class Tags implements ITags { public function getIdsForTag($tag) { $result = null; $tagId = false; - if(is_numeric($tag)) { + if (is_numeric($tag)) { $tagId = $tag; - } elseif(is_string($tag)) { + } elseif (is_string($tag)) { $tag = trim($tag); - if($tag === '') { + if ($tag === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG); return false; } $tagId = $this->getTagId($tag); } - if($tagId === false) { + if ($tagId === false) { $l10n = \OC::$server->getL10N('core'); throw new \Exception( $l10n->t('Could not find category "%s"', [$tag]) @@ -296,7 +295,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); return false; } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -305,8 +304,8 @@ class Tags implements ITags { return false; } - if(!is_null($result)) { - while($row = $result->fetchRow()) { + if (!is_null($result)) { + while ($row = $result->fetchRow()) { $id = (int)$row['objid']; if ($this->includeShared) { @@ -361,11 +360,11 @@ class Tags implements ITags { public function add($name) { $name = trim($name); - if($name === '') { + if ($name === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG); return false; } - if($this->userHasTag($name, $this->user)) { + if ($this->userHasTag($name, $this->user)) { \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG); return false; } @@ -373,7 +372,7 @@ class Tags implements ITags { $tag = new Tag($this->user, $this->type, $name); $tag = $this->mapper->insert($tag); $this->tags[] = $tag; - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -396,7 +395,7 @@ class Tags implements ITags { $from = trim($from); $to = trim($to); - if($to === '' || $from === '') { + if ($to === '' || $from === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG); return false; } @@ -406,13 +405,13 @@ class Tags implements ITags { } else { $key = $this->getTagByName($from); } - if($key === false) { + if ($key === false) { \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG); return false; } $tag = $this->tags[$key]; - if($this->userHasTag($to, $tag->getOwner())) { + if ($this->userHasTag($to, $tag->getOwner())) { \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG); return false; } @@ -420,7 +419,7 @@ class Tags implements ITags { try { $tag->setName($to); $this->tags[$key] = $this->mapper->update($tag); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -441,24 +440,24 @@ class Tags implements ITags { * @return bool Returns false on error. */ public function addMultiple($names, $sync=false, $id = null) { - if(!is_array($names)) { + if (!is_array($names)) { $names = [$names]; } $names = array_map('trim', $names); array_filter($names); $newones = []; - foreach($names as $name) { - if(!$this->hasTag($name) && $name !== '') { + foreach ($names as $name) { + if (!$this->hasTag($name) && $name !== '') { $newones[] = new Tag($this->user, $this->type, $name); } - if(!is_null($id)) { + if (!is_null($id)) { // Insert $objectid, $categoryid pairs if not exist. self::$relations[] = ['objid' => $id, 'tag' => $name]; } } $this->tags = array_merge($this->tags, $newones); - if($sync === true) { + if ($sync === true) { $this->save(); } @@ -469,13 +468,13 @@ class Tags implements ITags { * Save the list of tags and their object relations */ protected function save() { - if(is_array($this->tags)) { - foreach($this->tags as $tag) { + if (is_array($this->tags)) { + foreach ($this->tags as $tag) { try { if (!$this->mapper->tagExists($tag)) { $this->mapper->insert($tag); } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -494,10 +493,10 @@ class Tags implements ITags { // For some reason this is needed or array_search(i) will return 0..? ksort($tags); $dbConnection = \OC::$server->getDatabaseConnection(); - foreach(self::$relations as $relation) { + foreach (self::$relations as $relation) { $tagId = $this->getTagId($relation['tag']); \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG); - if($tagId) { + if ($tagId) { try { $dbConnection->insertIfNotExist(self::RELATION_TABLE, [ @@ -505,7 +504,7 @@ class Tags implements ITags { 'categoryid' => $tagId, 'type' => $this->type, ]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -538,7 +537,7 @@ class Tags implements ITags { if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -546,14 +545,14 @@ class Tags implements ITags { ]); } - if(!is_null($result)) { + if (!is_null($result)) { try { $stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `categoryid` = ?'); - while($row = $result->fetchRow()) { + while ($row = $result->fetchRow()) { try { $stmt->execute([$row['id']]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -561,7 +560,7 @@ class Tags implements ITags { ]); } } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -576,7 +575,7 @@ class Tags implements ITags { if ($result === null) { \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -592,7 +591,7 @@ class Tags implements ITags { * @return boolean Returns false on error. */ public function purgeObjects(array $ids) { - if(count($ids) === 0) { + if (count($ids) === 0) { // job done ;) return true; } @@ -608,7 +607,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR); return false; } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -625,13 +624,13 @@ class Tags implements ITags { * @return array|false An array of object ids. */ public function getFavorites() { - if(!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { + if (!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { return []; } try { return $this->getIdsForTag(ITags::TAG_FAVORITE); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -648,7 +647,7 @@ class Tags implements ITags { * @return boolean */ public function addToFavorites($objid) { - if(!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { + if (!$this->userHasTag(ITags::TAG_FAVORITE, $this->user)) { $this->add(ITags::TAG_FAVORITE); } return $this->tagAs($objid, ITags::TAG_FAVORITE); @@ -672,13 +671,13 @@ class Tags implements ITags { * @return boolean Returns false on error. */ public function tagAs($objid, $tag) { - if(is_string($tag) && !is_numeric($tag)) { + if (is_string($tag) && !is_numeric($tag)) { $tag = trim($tag); - if($tag === '') { + if ($tag === '') { \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG); return false; } - if(!$this->hasTag($tag)) { + if (!$this->hasTag($tag)) { $this->add($tag); } $tagId = $this->getTagId($tag); @@ -692,7 +691,7 @@ class Tags implements ITags { 'categoryid' => $tagId, 'type' => $this->type, ]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -711,9 +710,9 @@ class Tags implements ITags { * @return boolean */ public function unTag($objid, $tag) { - if(is_string($tag) && !is_numeric($tag)) { + if (is_string($tag) && !is_numeric($tag)) { $tag = trim($tag); - if($tag === '') { + if ($tag === '') { \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG); return false; } @@ -727,7 +726,7 @@ class Tags implements ITags { . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?'; $stmt = \OC_DB::prepare($sql); $stmt->execute([$objid, $tagId, $this->type]); - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -745,7 +744,7 @@ class Tags implements ITags { * @return bool Returns false on error */ public function delete($names) { - if(!is_array($names)) { + if (!is_array($names)) { $names = [$names]; } @@ -754,7 +753,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__ . ', before: ' . print_r($this->tags, true), ILogger::DEBUG); - foreach($names as $name) { + foreach ($names as $name) { $id = null; if (is_numeric($name)) { @@ -771,7 +770,7 @@ class Tags implements ITags { \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name . ': not found.', ILogger::ERROR); } - if(!is_null($id) && $id !== false) { + if (!is_null($id) && $id !== false) { try { $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `categoryid` = ?'; @@ -783,7 +782,7 @@ class Tags implements ITags { ILogger::ERROR); return false; } - } catch(\Exception $e) { + } catch (\Exception $e) { \OC::$server->getLogger()->logException($e, [ 'message' => __METHOD__, 'level' => ILogger::ERROR, @@ -798,7 +797,7 @@ class Tags implements ITags { // case-insensitive array_search protected function array_searchi($needle, $haystack, $mem='getName') { - if(!is_array($haystack)) { + if (!is_array($haystack)) { return false; } return array_search(strtolower($needle), array_map( diff --git a/lib/private/TempManager.php b/lib/private/TempManager.php index cb5f51582ac..13735d69d47 100644 --- a/lib/private/TempManager.php +++ b/lib/private/TempManager.php @@ -66,7 +66,7 @@ class TempManager implements ITempManager { * @return string */ private function buildFileNameWithSuffix($absolutePath, $postFix = '') { - if($postFix !== '') { + if ($postFix !== '') { $postFix = '.' . ltrim($postFix, '.'); $postFix = str_replace(['\\', '/'], '', $postFix); $absolutePath .= '-'; @@ -92,7 +92,7 @@ class TempManager implements ITempManager { // If a postfix got specified sanitize it and create a postfixed // temporary file - if($postFix !== '') { + if ($postFix !== '') { $fileNameWithPostfix = $this->buildFileNameWithSuffix($file, $postFix); touch($fileNameWithPostfix); chmod($fileNameWithPostfix, 0600); @@ -276,5 +276,4 @@ class TempManager implements ITempManager { public function overrideTempBaseDir($directory) { $this->tmpBaseDir = $directory; } - } diff --git a/lib/private/Template/Base.php b/lib/private/Template/Base.php index d07cf2249f7..04d03b6e6f5 100644 --- a/lib/private/Template/Base.php +++ b/lib/private/Template/Base.php @@ -65,7 +65,7 @@ class Base { */ protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) { // Check if the app is in the app folder or in the root - if(file_exists($app_dir.'/templates/')) { + if (file_exists($app_dir.'/templates/')) { return [ $serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/', $app_dir.'/templates/', @@ -115,10 +115,9 @@ class Base { * $_[$key][$position] in the template. */ public function append($key, $value) { - if(array_key_exists($key, $this->vars)) { + if (array_key_exists($key, $this->vars)) { $this->vars[$key][] = $value; - } - else{ + } else { $this->vars[$key] = [ $value ]; } } @@ -131,10 +130,9 @@ class Base { */ public function printPage() { $data = $this->fetchPage(); - if($data === false) { + if ($data === false) { return false; - } - else{ + } else { print $data; return true; } @@ -167,7 +165,7 @@ class Base { $l = $this->l10n; $theme = $this->theme; - if(!is_null($additionalParams)) { + if (!is_null($additionalParams)) { $_ = array_merge($additionalParams, $this->vars); foreach ($_ as $var => $value) { ${$var} = $value; @@ -188,5 +186,4 @@ class Base { // Return data return $data; } - } diff --git a/lib/private/Template/CSSResourceLocator.php b/lib/private/Template/CSSResourceLocator.php index c931a62420a..750d33fd726 100644 --- a/lib/private/Template/CSSResourceLocator.php +++ b/lib/private/Template/CSSResourceLocator.php @@ -83,7 +83,7 @@ class CSSResourceLocator extends ResourceLocator { // turned into cwd. $app_path = realpath($app_path); - if(!$this->cacheAndAppendScssIfExist($app_path, $style.'.scss', $app)) { + if (!$this->cacheAndAppendScssIfExist($app_path, $style.'.scss', $app)) { $this->append($app_path, $style.'.css', $app_url); } } @@ -107,9 +107,8 @@ class CSSResourceLocator extends ResourceLocator { */ protected function cacheAndAppendScssIfExist($root, $file, $app = 'core') { if (is_file($root.'/'.$file)) { - if($this->scssCacher !== null) { - if($this->scssCacher->process($root, $file, $app)) { - + if ($this->scssCacher !== null) { + if ($this->scssCacher->process($root, $file, $app)) { $this->append($root, $this->scssCacher->getCachedSCSS($app, $file), \OC::$WEBROOT, true, true); return true; } else { diff --git a/lib/private/Template/IconsCacher.php b/lib/private/Template/IconsCacher.php index 3315f29d98f..00654b5f8fc 100644 --- a/lib/private/Template/IconsCacher.php +++ b/lib/private/Template/IconsCacher.php @@ -107,7 +107,6 @@ class IconsCacher { * @throws \OCP\Files\NotPermittedException */ public function setIconsCss(string $css): string { - $cachedFile = $this->getCachedList(); if (!$cachedFile) { $currentData = ''; @@ -169,14 +168,13 @@ class IconsCacher { $location = \OC::$SERVERROOT . '/core/img/' . $cleanUrl . '.svg'; } } elseif (\strpos($url, $base) === 0) { - if(\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) { + if (\preg_match('/([A-z0-9\_\-]+)\/([a-zA-Z0-9-_\~\/\.\=\:\;\+\,]+)\?color=([0-9a-fA-F]{3,6})/', $cleanUrl, $matches)) { list(,$app,$cleanUrl, $color) = $matches; $location = \OC_App::getAppPath($app) . '/img/' . $cleanUrl . '.svg'; if ($app === 'settings') { $location = \OC::$SERVERROOT . '/settings/img/' . $cleanUrl . '.svg'; } } - } return [ $location, @@ -265,5 +263,4 @@ class IconsCacher { $linkToCSS = $this->urlGenerator->linkToRoute('core.Css.getCss', ['appName' => 'icons', 'fileName' => $this->fileName, 'v' => $mtime]); \OC_Util::addHeader('link', ['rel' => 'stylesheet', 'href' => $linkToCSS], null, true); } - } diff --git a/lib/private/Template/JSCombiner.php b/lib/private/Template/JSCombiner.php index 96d5a1e7779..48f6dadfd6a 100644 --- a/lib/private/Template/JSCombiner.php +++ b/lib/private/Template/JSCombiner.php @@ -95,12 +95,12 @@ class JSCombiner { try { $folder = $this->appData->getFolder($app); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { // creating css appdata folder $folder = $this->appData->newFolder($app); } - if($this->isCached($fileName, $folder)) { + if ($this->isCached($fileName, $folder)) { return true; } return $this->cache($path, $fileName, $folder); @@ -145,7 +145,7 @@ class JSCombiner { } return true; - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { return false; } } @@ -176,7 +176,7 @@ class JSCombiner { $fileName = str_replace('.json', '.js', $fileName); try { $cachedfile = $folder->getFile($fileName); - } catch(NotFoundException $e) { + } catch (NotFoundException $e) { $cachedfile = $folder->newFile($fileName); } @@ -228,7 +228,7 @@ class JSCombiner { public function getContent($root, $file) { /** @var array $data */ $data = json_decode(file_get_contents($root . '/' . $file)); - if(!is_array($data)) { + if (!is_array($data)) { return []; } diff --git a/lib/private/Template/JSConfigHelper.php b/lib/private/Template/JSConfigHelper.php index 24573d71fe0..70d6f73628d 100644 --- a/lib/private/Template/JSConfigHelper.php +++ b/lib/private/Template/JSConfigHelper.php @@ -113,7 +113,6 @@ class JSConfigHelper { } public function getConfig() { - $userBackendAllowsPasswordConfirmation = true; if ($this->currentUser !== null) { $uid = $this->currentUser->getUID(); @@ -137,7 +136,7 @@ class JSConfigHelper { $apps = $this->appManager->getEnabledAppsForUser($this->currentUser); } - foreach($apps as $app) { + foreach ($apps as $app) { $apps_paths[$app] = \OC_App::getAppWebPath($app); } @@ -161,7 +160,7 @@ class JSConfigHelper { $countOfDataLocation = 0; $dataLocation = str_replace(\OC::$SERVERROOT .'/', '', $this->config->getSystemValue('datadirectory', ''), $countOfDataLocation); - if($countOfDataLocation !== 1 || !$this->groupManager->isAdmin($uid)) { + if ($countOfDataLocation !== 1 || !$this->groupManager->isAdmin($uid)) { $dataLocation = false; } diff --git a/lib/private/Template/ResourceLocator.php b/lib/private/Template/ResourceLocator.php index c99df063588..1d9f60cf5dd 100755 --- a/lib/private/Template/ResourceLocator.php +++ b/lib/private/Template/ResourceLocator.php @@ -164,7 +164,6 @@ abstract class ResourceLocator { * @throws ResourceNotFoundException Only thrown when $throw is true and the resource is missing */ protected function append($root, $file, $webRoot = null, $throw = true) { - if (!is_string($root)) { if ($throw) { throw new ResourceNotFoundException($file, $webRoot); diff --git a/lib/private/Template/TemplateFileLocator.php b/lib/private/Template/TemplateFileLocator.php index afeddd6b544..3c7631ba2b5 100644 --- a/lib/private/Template/TemplateFileLocator.php +++ b/lib/private/Template/TemplateFileLocator.php @@ -46,7 +46,7 @@ class TemplateFileLocator { throw new \InvalidArgumentException('Empty template name'); } - foreach($this->dirs as $dir) { + foreach ($this->dirs as $dir) { $file = $dir.$template.'.php'; if (is_file($file)) { $this->path = $dir; diff --git a/lib/private/TemplateLayout.php b/lib/private/TemplateLayout.php index cdab4c25693..89904827b2a 100644 --- a/lib/private/TemplateLayout.php +++ b/lib/private/TemplateLayout.php @@ -52,7 +52,6 @@ use OCP\Defaults; use OCP\Support\Subscription\IRegistry; class TemplateLayout extends \OC_Template { - private static $versionHash = ''; /** @@ -69,16 +68,16 @@ class TemplateLayout extends \OC_Template { // yes - should be injected .... $this->config = \OC::$server->getConfig(); - if(\OCP\Util::isIE()) { + if (\OCP\Util::isIE()) { \OC_Util::addStyle('ie'); } // Decide which page we show - if($renderAs === 'user') { + if ($renderAs === 'user') { parent::__construct('core', 'layout.user'); - if(in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) { + if (in_array(\OC_App::getCurrentApp(), ['settings','admin', 'help']) !== false) { $this->assign('bodyid', 'body-settings'); - }else{ + } else { $this->assign('bodyid', 'body-user'); } @@ -89,14 +88,14 @@ class TemplateLayout extends \OC_Template { $this->assign('navigation', $navigation); $settingsNavigation = \OC::$server->getNavigationManager()->getAll('settings'); $this->assign('settingsnavigation', $settingsNavigation); - foreach($navigation as $entry) { + foreach ($navigation as $entry) { if ($entry['active']) { $this->assign('application', $entry['name']); break; } } - foreach($settingsNavigation as $entry) { + foreach ($settingsNavigation as $entry) { if ($entry['active']) { $this->assign('application', $entry['name']); break; @@ -123,7 +122,6 @@ class TemplateLayout extends \OC_Template { } catch (\OCP\AutoloadNotAllowedException $e) { $this->assign('themingInvertMenu', false); } - } elseif ($renderAs === 'error') { parent::__construct('core', 'layout.guest', '', false); $this->assign('bodyid', 'body-login'); @@ -151,7 +149,6 @@ class TemplateLayout extends \OC_Template { $this->assign('showSimpleSignUpLink', $showSimpleSignup); } else { parent::__construct('core', 'layout.base'); - } // Send the language and the locale to our layouts $lang = \OC::$server->getL10NFactory()->findLanguage(); @@ -161,7 +158,7 @@ class TemplateLayout extends \OC_Template { $this->assign('language', $lang); $this->assign('locale', $locale); - if(\OC::$server->getSystemConfig()->getValue('installed', false)) { + if (\OC::$server->getSystemConfig()->getValue('installed', false)) { if (empty(self::$versionHash)) { $v = \OC_App::getAppVersions(); $v['core'] = implode('.', \OCP\Util::getVersion()); @@ -193,7 +190,7 @@ class TemplateLayout extends \OC_Template { $this->append('jsfiles', \OC::$server->getURLGenerator()->linkToRoute('core.OCJS.getConfig', ['v' => self::$versionHash])); } } - foreach($jsFiles as $info) { + foreach ($jsFiles as $info) { $web = $info[1]; $file = $info[2]; $this->append('jsfiles', $web.'/'.$file . $this->getVersionHashSuffix()); @@ -207,7 +204,7 @@ class TemplateLayout extends \OC_Template { // Do not initialise scss appdata until we have a fully installed instance // Do not load scss for update, errors, installation or login page - if(\OC::$server->getSystemConfig()->getValue('installed', false) + if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade() && $pathInfo !== '' && !preg_match('/^\/login/', $pathInfo) @@ -224,7 +221,7 @@ class TemplateLayout extends \OC_Template { $this->assign('cssfiles', []); $this->assign('printcssfiles', []); $this->assign('versionHash', self::$versionHash); - foreach($cssFiles as $info) { + foreach ($cssFiles as $info) { $web = $info[1]; $file = $info[2]; @@ -238,7 +235,6 @@ class TemplateLayout extends \OC_Template { } else { $this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3)); } - } } @@ -270,7 +266,7 @@ class TemplateLayout extends \OC_Template { // Try the webroot path for a match if ($path !== false && $path !== '') { $appName = $this->getAppNamefromPath($path); - if(array_key_exists($appName, $v)) { + if (array_key_exists($appName, $v)) { $appVersion = $v[$appName]; return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix; } @@ -278,7 +274,7 @@ class TemplateLayout extends \OC_Template { // fallback to the file path instead if ($file !== false && $file !== '') { $appName = $this->getAppNamefromPath($file); - if(array_key_exists($appName, $v)) { + if (array_key_exists($appName, $v)) { $appVersion = $v[$appName]; return '?v=' . substr(md5($appVersion), 0, 8) . $themingSuffix; } @@ -295,7 +291,7 @@ class TemplateLayout extends \OC_Template { // Read the selected theme from the config file $theme = \OC_Util::getTheme(); - if($compileScss) { + if ($compileScss) { $SCSSCacher = \OC::$server->query(SCSSCacher::class); } else { $SCSSCacher = null; @@ -326,7 +322,6 @@ class TemplateLayout extends \OC_Template { return end($pathParts); } return false; - } /** @@ -356,7 +351,7 @@ class TemplateLayout extends \OC_Template { */ public static function convertToRelativePath($filePath) { $relativePath = explode(\OC::$SERVERROOT, $filePath); - if(count($relativePath) !== 2) { + if (count($relativePath) !== 2) { throw new \Exception('$filePath is not under the \OC::$SERVERROOT'); } diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index c0896ec3516..b432b0b69ca 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -122,12 +122,11 @@ class URLGenerator implements IURLGenerator { public function linkTo(string $app, string $file, array $args = []): string { $frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true'); - if($app !== '') { + if ($app !== '') { $app_path = \OC_App::getAppPath($app); // Check if the app is in the app folder if ($app_path && file_exists($app_path . '/' . $file)) { if (substr($file, -3) === 'php') { - $urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app; if ($frontControllerActive) { $urlLinkTo = \OC::$WEBROOT . '/apps/' . $app; @@ -170,7 +169,7 @@ class URLGenerator implements IURLGenerator { public function imagePath(string $app, string $image): string { $cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-'); $cacheKey = $app.'-'.$image; - if($key = $cache->get($cacheKey)) { + if ($key = $cache->get($cacheKey)) { return $key; } @@ -186,7 +185,7 @@ class URLGenerator implements IURLGenerator { $path = ''; $themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming'); $themingImagePath = false; - if($themingEnabled) { + if ($themingEnabled) { $themingDefaults = \OC::$server->getThemingDefaults(); if ($themingDefaults instanceof ThemingDefaults) { $themingImagePath = $themingDefaults->replaceImagePath($app, $image); @@ -208,7 +207,7 @@ class URLGenerator implements IURLGenerator { } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg") && file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) { $path = \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png"; - } elseif($themingEnabled && $themingImagePath) { + } elseif ($themingEnabled && $themingImagePath) { $path = $themingImagePath; } elseif ($appPath && file_exists($appPath . "/img/$image")) { $path = \OC_App::getAppWebPath($app) . "/img/$image"; @@ -227,7 +226,7 @@ class URLGenerator implements IURLGenerator { $path = \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png"; } - if($path !== '') { + if ($path !== '') { $cache->set($cacheKey, $path); return $path; } @@ -248,7 +247,7 @@ class URLGenerator implements IURLGenerator { return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/'); } // The ownCloud web root can already be prepended. - if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) { + if (\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) { $url = substr($url, \strlen(\OC::$WEBROOT)); } diff --git a/lib/private/Updater.php b/lib/private/Updater.php index e94f36554d7..edbf43ea972 100644 --- a/lib/private/Updater.php +++ b/lib/private/Updater.php @@ -109,7 +109,7 @@ class Updater extends BasicEmitter { $wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance'); - if(!$wasMaintenanceModeEnabled) { + if (!$wasMaintenanceModeEnabled) { $this->config->setSystemValue('maintenance', true); $this->emit('\OC\Updater', 'maintenanceEnabled'); } @@ -141,7 +141,7 @@ class Updater extends BasicEmitter { $this->emit('\OC\Updater', 'updateEnd', [$success]); - if(!$wasMaintenanceModeEnabled && $success) { + if (!$wasMaintenanceModeEnabled && $success) { $this->config->setSystemValue('maintenance', false); $this->emit('\OC\Updater', 'maintenanceDisabled'); } else { @@ -279,7 +279,7 @@ class Updater extends BasicEmitter { $this->config->setAppValue('core', 'lastupdatedat', 0); // Check for code integrity if not disabled - if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { + if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { $this->emit('\OC\Updater', 'startCheckCodeIntegrity'); $this->checker->runInstanceVerification(); $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity'); @@ -356,7 +356,7 @@ class Updater extends BasicEmitter { foreach ($apps as $appId) { $priorityType = false; foreach ($priorityTypes as $type) { - if(!isset($stacks[$type])) { + if (!isset($stacks[$type])) { $stacks[$type] = []; } if (\OC_App::isType($appId, [$type])) { @@ -376,7 +376,7 @@ class Updater extends BasicEmitter { \OC_App::updateApp($appId); $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]); } - if($type !== $pseudoOtherType) { + if ($type !== $pseudoOtherType) { // load authentication, filesystem and logging apps after // upgrading them. Other apps my need to rely on modifying // user and/or filesystem aspects. @@ -404,7 +404,7 @@ class Updater extends BasicEmitter { foreach ($apps as $app) { // check if the app is compatible with this version of ownCloud $info = OC_App::getAppInfo($app); - if($info === null || !OC_App::isAppCompatible($version, $info)) { + if ($info === null || !OC_App::isAppCompatible($version, $info)) { if ($appManager->isShipped($app)) { throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update'); } @@ -445,7 +445,7 @@ class Updater extends BasicEmitter { * @throws \Exception */ private function upgradeAppStoreApps(array $disabledApps, $reenable = false) { - foreach($disabledApps as $app) { + foreach ($disabledApps as $app) { try { $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]); if ($this->installer->isUpdateAvailable($app)) { @@ -621,7 +621,5 @@ class Updater extends BasicEmitter { $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) { $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']); }); - } - } diff --git a/lib/private/Updater/ChangesCheck.php b/lib/private/Updater/ChangesCheck.php index 2dd18467cd9..8700b9609d2 100644 --- a/lib/private/Updater/ChangesCheck.php +++ b/lib/private/Updater/ChangesCheck.php @@ -70,7 +70,7 @@ class ChangesCheck { try { $version = $this->normalizeVersion($version); $changesInfo = $this->mapper->getChanges($version); - if($changesInfo->getLastCheck() + 1800 > time()) { + if ($changesInfo->getLastCheck() + 1800 > time()) { return json_decode($changesInfo->getData(), true); } } catch (DoesNotExistException $e) { @@ -79,7 +79,7 @@ class ChangesCheck { $response = $this->queryChangesServer($uri, $changesInfo); - switch($this->evaluateResponse($response)) { + switch ($this->evaluateResponse($response)) { case self::RESPONSE_NO_CONTENT: return []; case self::RESPONSE_USE_CACHE: @@ -96,11 +96,11 @@ class ChangesCheck { } protected function evaluateResponse(IResponse $response): int { - if($response->getStatusCode() === 304) { + if ($response->getStatusCode() === 304) { return self::RESPONSE_USE_CACHE; - } elseif($response->getStatusCode() === 404) { + } elseif ($response->getStatusCode() === 404) { return self::RESPONSE_NO_CONTENT; - } elseif($response->getStatusCode() === 200) { + } elseif ($response->getStatusCode() === 200) { return self::RESPONSE_HAS_CONTENT; } $this->logger->debug('Unexpected return code {code} from changelog server', [ @@ -111,7 +111,7 @@ class ChangesCheck { } protected function cacheResult(ChangesResult $entry, string $version) { - if($entry->getVersion() === $version) { + if ($entry->getVersion() === $version) { $this->mapper->update($entry); } else { $entry->setVersion($version); @@ -124,7 +124,7 @@ class ChangesCheck { */ protected function queryChangesServer(string $uri, ChangesResult $entry): IResponse { $headers = []; - if($entry->getEtag() !== '') { + if ($entry->getEtag() !== '') { $headers['If-None-Match'] = [$entry->getEtag()]; } @@ -144,7 +144,7 @@ class ChangesCheck { if ($xml !== false) { $data['changelogURL'] = (string)$xml->changelog['href']; $data['whatsNew'] = []; - foreach($xml->whatsNew as $infoSet) { + foreach ($xml->whatsNew as $infoSet) { $data['whatsNew'][(string)$infoSet['lang']] = [ 'regular' => (array)$infoSet->regular->item, 'admin' => (array)$infoSet->admin->item, @@ -164,7 +164,7 @@ class ChangesCheck { public function normalizeVersion(string $version): string { $versionNumbers = array_slice(explode('.', $version), 0, 3); $versionNumbers[0] = $versionNumbers[0] ?: '0'; // deal with empty input - while(count($versionNumbers) < 3) { + while (count($versionNumbers) < 3) { // changelog server expects x.y.z, pad 0 if it is too short $versionNumbers[] = 0; } diff --git a/lib/private/User/Backend.php b/lib/private/User/Backend.php index e90cfdc2e3d..354e1c3fd71 100644 --- a/lib/private/User/Backend.php +++ b/lib/private/User/Backend.php @@ -68,8 +68,8 @@ abstract class Backend implements UserInterface { */ public function getSupportedActions() { $actions = 0; - foreach($this->possibleActions as $action => $methodName) { - if(method_exists($this, $methodName)) { + foreach ($this->possibleActions as $action => $methodName) { + if (method_exists($this, $methodName)) { $actions |= $action; } } diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index c89d3ce3690..d5098483d61 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -324,7 +324,6 @@ class Database extends ABackend } return (string)$row['uid']; } - } return false; diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index 1ab335eeea6..303050a7716 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -368,7 +368,7 @@ class Manager extends PublicEmitter implements IUserManager { $this->emit('\OC\User', 'preCreateUser', [$uid, $password]); $this->eventDispatcher->dispatchTyped(new CreateUserEvent($uid, $password)); $state = $backend->createUser($uid, $password); - if($state === false) { + if ($state === false) { throw new \InvalidArgumentException($l->t('Could not create user')); } $user = $this->getUserObject($uid, $backend); @@ -395,13 +395,13 @@ class Manager extends PublicEmitter implements IUserManager { foreach ($this->backends as $backend) { if ($backend->implementsActions(Backend::COUNT_USERS)) { $backendUsers = $backend->countUsers(); - if($backendUsers !== false) { - if($backend instanceof IUserBackend) { + if ($backendUsers !== false) { + if ($backend instanceof IUserBackend) { $name = $backend->getBackendName(); } else { $name = get_class($backend); } - if(isset($userCountStatistics[$name])) { + if (isset($userCountStatistics[$name])) { $userCountStatistics[$name] += $backendUsers; } else { $userCountStatistics[$name] = $backendUsers; @@ -421,7 +421,7 @@ class Manager extends PublicEmitter implements IUserManager { */ public function countUsersOfGroups(array $groups) { $users = []; - foreach($groups as $group) { + foreach ($groups as $group) { $usersIds = array_map(function ($user) { return $user->getUID(); }, $group->getUsers()); diff --git a/lib/private/User/NoUserException.php b/lib/private/User/NoUserException.php index 697776115be..6ae22eb1e58 100644 --- a/lib/private/User/NoUserException.php +++ b/lib/private/User/NoUserException.php @@ -23,4 +23,5 @@ namespace OC\User; -class NoUserException extends \Exception {} +class NoUserException extends \Exception { +} diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index d908a3d78b2..817dcbf4c33 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -321,9 +321,7 @@ class Session implements IUserSession, Emitter { * @return null|string */ public function getImpersonatingUserID(): ?string { - return $this->session->get('oldUserId'); - } public function setImpersonatingUserID(bool $useCurrentUser = true): void { @@ -338,7 +336,6 @@ class Session implements IUserSession, Emitter { throw new \OC\User\NoUserException(); } $this->session->set('oldUserId', $currentUser->getUID()); - } /** * set the token id @@ -384,7 +381,7 @@ class Session implements IUserSession, Emitter { throw new LoginException($message); } - if($regenerateSessionId) { + if ($regenerateSessionId) { $this->session->regenerateId(); } @@ -411,7 +408,7 @@ class Session implements IUserSession, Emitter { $loginDetails['password'], $isToken, ]); - if($this->isLoggedIn()) { + if ($this->isLoggedIn()) { $this->prepareUserLogin($firstTimeLogin, $regenerateSessionId); return true; } @@ -464,7 +461,6 @@ class Session implements IUserSession, Emitter { // Failed, maybe the user used their email address $users = $this->manager->getByEmail($user); if (!(\count($users) === 1 && $this->login($users[0]->getUID(), $password))) { - $this->logger->warning('Login failed: \'' . $user . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']); $throttler->registerAttempt('login', $request->getRemoteAddress(), ['user' => $user]); @@ -480,7 +476,7 @@ class Session implements IUserSession, Emitter { if ($isTokenPassword) { $this->session->set('app_password', $password); - } elseif($this->supportsCookies($request)) { + } elseif ($this->supportsCookies($request)) { // Password login, but cookies supported -> create (browser) session token $this->createSessionToken($request, $this->getUser()->getUID(), $user, $password); } @@ -592,7 +588,7 @@ class Session implements IUserSession, Emitter { ); // Set the last-password-confirm session to make the sudo mode work - $this->session->set('last-password-confirm', $this->timeFactory->getTime()); + $this->session->set('last-password-confirm', $this->timeFactory->getTime()); return true; } @@ -825,7 +821,7 @@ class Session implements IUserSession, Emitter { if (!$this->loginWithToken($token)) { return false; } - if(!$this->validateToken($token)) { + if (!$this->validateToken($token)) { return false; } @@ -910,7 +906,6 @@ class Session implements IUserSession, Emitter { try { $this->tokenProvider->invalidateToken($this->session->getId()); } catch (SessionNotAvailableException $ex) { - } } $this->setUser(null); @@ -1011,6 +1006,4 @@ class Session implements IUserSession, Emitter { public function updateTokens(string $uid, string $password) { $this->tokenProvider->updatePasswords($uid, $password); } - - } diff --git a/lib/private/User/User.php b/lib/private/User/User.php index 6bd86bbc516..dd451c8eb3f 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -87,7 +87,7 @@ class User implements IUser { $this->backend = $backend; $this->dispatcher = $dispatcher; $this->emitter = $emitter; - if(is_null($config)) { + if (is_null($config)) { $config = \OC::$server->getConfig(); } $this->config = $config; @@ -163,8 +163,8 @@ class User implements IUser { */ public function setEMailAddress($mailAddress) { $oldMailAddress = $this->getEMailAddress(); - if($oldMailAddress !== $mailAddress) { - if($mailAddress === '') { + if ($oldMailAddress !== $mailAddress) { + if ($mailAddress === '') { $this->config->deleteUserValue($this->uid, 'settings', 'email'); } else { $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress); @@ -308,7 +308,7 @@ class User implements IUser { * @return string */ public function getBackendClassName() { - if($this->backend instanceof IUserBackend) { + if ($this->backend instanceof IUserBackend) { return $this->backend->getBackendName(); } return get_class($this->backend); @@ -393,7 +393,7 @@ class User implements IUser { */ public function getQuota() { $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default'); - if($quota === 'default') { + if ($quota === 'default') { $quota = $this->config->getAppValue('files', 'default_quota', 'none'); } return $quota; @@ -408,11 +408,11 @@ class User implements IUser { */ public function setQuota($quota) { $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', ''); - if($quota !== 'none' and $quota !== 'default') { + if ($quota !== 'none' and $quota !== 'default') { $quota = OC_Helper::computerFileSize($quota); $quota = OC_Helper::humanFileSize($quota); } - if($quota !== $oldQuota) { + if ($quota !== $oldQuota) { $this->config->setUserValue($this->uid, 'files', 'quota', $quota); $this->triggerChange('quota', $quota, $oldQuota); } diff --git a/lib/private/legacy/OC_API.php b/lib/private/legacy/OC_API.php index b9960c70777..37a496a38fe 100644 --- a/lib/private/legacy/OC_API.php +++ b/lib/private/legacy/OC_API.php @@ -48,9 +48,9 @@ class OC_API { $request = \OC::$server->getRequest(); // Send 401 headers if unauthorised - if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { + if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) { // If request comes from JS return dummy auth request - if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { + if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { header('WWW-Authenticate: DummyBasic realm="Authorisation Required"'); } else { header('WWW-Authenticate: Basic realm="Authorisation Required"'); @@ -58,7 +58,7 @@ class OC_API { http_response_code(401); } - foreach($result->getHeaders() as $name => $value) { + foreach ($result->getHeaders() as $name => $value) { header($name . ': ' . $value); } @@ -81,14 +81,14 @@ class OC_API { * @param XMLWriter $writer */ private static function toXML($array, $writer) { - foreach($array as $k => $v) { + foreach ($array as $k => $v) { if ($k[0] === '@') { $writer->writeAttribute(substr($k, 1), $v); continue; } elseif (is_numeric($k)) { $k = 'element'; } - if(is_array($v)) { + if (is_array($v)) { $writer->startElement($k); self::toXML($v, $writer); $writer->endElement(); diff --git a/lib/private/legacy/OC_App.php b/lib/private/legacy/OC_App.php index 3cc194cc03d..5c06f66a20a 100644 --- a/lib/private/legacy/OC_App.php +++ b/lib/private/legacy/OC_App.php @@ -114,9 +114,9 @@ class OC_App { $apps = self::getEnabledApps(); // Add each apps' folder as allowed class path - foreach($apps as $app) { + foreach ($apps as $app) { $path = self::getAppPath($app); - if($path !== false) { + if ($path !== false) { self::registerAutoloading($app, $path); } } @@ -142,7 +142,7 @@ class OC_App { public static function loadApp(string $app) { self::$loadedApps[] = $app; $appPath = self::getAppPath($app); - if($appPath === false) { + if ($appPath === false) { return; } @@ -154,7 +154,7 @@ class OC_App { try { self::requireAppFile($app); } catch (Throwable $ex) { - if($ex instanceof ServerNotAvailableException) { + if ($ex instanceof ServerNotAvailableException) { throw $ex; } \OC::$server->getLogger()->logException($ex); @@ -210,7 +210,7 @@ class OC_App { $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ? [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin']; foreach ($plugins as $plugin) { - if($plugin['@attributes']['type'] === 'collaborator-search') { + if ($plugin['@attributes']['type'] === 'collaborator-search') { $pluginInfo = [ 'shareType' => $plugin['@attributes']['share-type'], 'class' => $plugin['@value'], @@ -308,7 +308,7 @@ class OC_App { public static function setAppTypes(string $app) { $appManager = \OC::$server->getAppManager(); $appData = $appManager->getAppInfo($app); - if(!is_array($appData)) { + if (!is_array($appData)) { return; } @@ -395,7 +395,7 @@ class OC_App { $installer = \OC::$server->query(Installer::class); $isDownloaded = $installer->isDownloaded($appId); - if(!$isDownloaded) { + if (!$isDownloaded) { $installer->downloadApp($appId); } @@ -446,7 +446,7 @@ class OC_App { */ public static function findAppInDirectories(string $appId) { $sanitizedAppId = self::cleanAppId($appId); - if($sanitizedAppId !== $appId) { + if ($sanitizedAppId !== $appId) { return false; } static $app_dir = []; @@ -671,7 +671,6 @@ class OC_App { * @todo: change the name of this method to getInstalledApps, which is more accurate */ public static function getAllApps(): array { - $apps = []; foreach (OC::$APPSROOTS as $apps_dir) { @@ -683,9 +682,7 @@ class OC_App { if (is_resource($dh)) { while (($file = readdir($dh)) !== false) { - if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) { - $apps[] = $file; } } @@ -717,7 +714,6 @@ class OC_App { foreach ($installedApps as $app) { if (array_search($app, $blacklist) === false) { - $info = OC_App::getAppInfo($app, false, $langCode); if (!is_array($info)) { \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR); @@ -756,7 +752,7 @@ class OC_App { } $appPath = self::getAppPath($app); - if($appPath !== false) { + if ($appPath !== false) { $appIcon = $appPath . '/img/' . $app . '.svg'; if (file_exists($appIcon)) { $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg'); @@ -864,7 +860,6 @@ class OC_App { if (!empty($requireMin) && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<') ) { - return false; } @@ -883,7 +878,7 @@ class OC_App { public static function getAppVersions() { static $versions; - if(!$versions) { + if (!$versions) { $appConfig = \OC::$server->getAppConfig(); $versions = $appConfig->getValues(false, 'installed_version'); } @@ -898,7 +893,7 @@ class OC_App { */ public static function updateApp(string $appId): bool { $appPath = self::getAppPath($appId); - if($appPath === false) { + if ($appPath === false) { return false; } @@ -931,7 +926,7 @@ class OC_App { //set remote/public handlers if (array_key_exists('ocsid', $appData)) { \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']); - } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) { + } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) { \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid'); } foreach ($appData['remote'] as $name => $path) { @@ -1081,7 +1076,6 @@ class OC_App { * @return array improved app data */ public static function parseAppInfo(array $data, $lang = null): array { - if ($lang && isset($data['name']) && is_array($data['name'])) { $data['name'] = self::findBestL10NOption($data['name'], $lang); } @@ -1092,7 +1086,7 @@ class OC_App { $data['description'] = trim(self::findBestL10NOption($data['description'], $lang)); } elseif (isset($data['description']) && is_string($data['description'])) { $data['description'] = trim($data['description']); - } else { + } else { $data['description'] = ''; } diff --git a/lib/private/legacy/OC_DB.php b/lib/private/legacy/OC_DB.php index cf45faae314..63f1447ad91 100644 --- a/lib/private/legacy/OC_DB.php +++ b/lib/private/legacy/OC_DB.php @@ -212,7 +212,7 @@ class OC_DB { * @throws \OC\DatabaseException */ public static function raiseExceptionOnError($result, $message = null) { - if($result === false) { + if ($result === false) { if ($message === null) { $message = self::getErrorMessage(); } else { diff --git a/lib/private/legacy/OC_Defaults.php b/lib/private/legacy/OC_Defaults.php index d5a4b5eecee..f90cae61bd7 100644 --- a/lib/private/legacy/OC_Defaults.php +++ b/lib/private/legacy/OC_Defaults.php @@ -36,7 +36,6 @@ * */ class OC_Defaults { - private $theme; private $defaultEntity; @@ -282,7 +281,6 @@ class OC_Defaults { * @return string */ public function getColorPrimary() { - if ($this->themeExist('getColorPrimary')) { return $this->theme->getColorPrimary(); } @@ -296,7 +294,7 @@ class OC_Defaults { * @return array scss variables to overwrite */ public function getScssVariables() { - if($this->themeExist('getScssVariables')) { + if ($this->themeExist('getScssVariables')) { return $this->theme->getScssVariables(); } return []; @@ -317,7 +315,7 @@ class OC_Defaults { return $this->theme->getLogo($useSvg); } - if($useSvg) { + if ($useSvg) { $logo = \OC::$server->getURLGenerator()->imagePath('core', 'logo/logo.svg'); } else { $logo = \OC::$server->getURLGenerator()->imagePath('core', 'logo/logo.png'); diff --git a/lib/private/legacy/OC_EventSource.php b/lib/private/legacy/OC_EventSource.php index 7191028295a..b8c4389f985 100644 --- a/lib/private/legacy/OC_EventSource.php +++ b/lib/private/legacy/OC_EventSource.php @@ -77,7 +77,7 @@ class OC_EventSource implements \OCP\IEventSource { } else { header("Content-Type: text/event-stream"); } - if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + if (!\OC::$server->getRequest()->passesStrictCookieCheck()) { header('Location: '.\OC::$WEBROOT); exit(); } diff --git a/lib/private/legacy/OC_FileChunking.php b/lib/private/legacy/OC_FileChunking.php index 048bd085bb5..37cf42a31cb 100644 --- a/lib/private/legacy/OC_FileChunking.php +++ b/lib/private/legacy/OC_FileChunking.php @@ -87,7 +87,7 @@ class OC_FileChunking { $cache = $this->getCache(); $chunkcount = (int)$this->info['chunkcount']; - for($i=($chunkcount-1); $i >= 0; $i--) { + for ($i=($chunkcount-1); $i >= 0; $i--) { if (!$cache->hasKey($prefix.$i)) { return false; } @@ -143,7 +143,7 @@ class OC_FileChunking { public function cleanup() { $cache = $this->getCache(); $prefix = $this->getPrefix(); - for($i=0; $i < $this->info['chunkcount']; $i++) { + for ($i=0; $i < $this->info['chunkcount']; $i++) { $cache->remove($prefix.$i); } } diff --git a/lib/private/legacy/OC_Files.php b/lib/private/legacy/OC_Files.php index 710e0882010..e046a577026 100644 --- a/lib/private/legacy/OC_Files.php +++ b/lib/private/legacy/OC_Files.php @@ -87,15 +87,13 @@ class OC_Files { http_response_code(206); header('Accept-Ranges: bytes', true); if (count($rangeArray) > 1) { - $type = 'multipart/byteranges; boundary='.self::getBoundary(); + $type = 'multipart/byteranges; boundary='.self::getBoundary(); // no Content-Length header here + } else { + header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true); + OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1); } - else { - header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true); - OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1); - } - } - else { + } else { OC_Response::setContentLengthHeader($fileSize); } } @@ -110,12 +108,10 @@ class OC_Files { * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header */ public static function get($dir, $files, $params = null) { - $view = \OC\Files\Filesystem::getView(); $getType = self::FILE; $filename = $dir; try { - if (is_array($files) && count($files) === 1) { $files = $files[0]; } @@ -180,7 +176,7 @@ class OC_Files { if (\OC\Files\Filesystem::is_file($file)) { $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot()); $file = $userFolder->get($file); - if($file instanceof \OC\Files\Node\File) { + if ($file instanceof \OC\Files\Node\File) { try { $fh = $file->fopen('r'); } catch (\OCP\Files\NotPermittedException $e) { @@ -263,13 +259,11 @@ class OC_Files { if ($minOffset >= $fileSize) { break; } - } - elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) { + } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) { // case: x- $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ]; break; - } - elseif (is_numeric($ranges[1])) { + } elseif (is_numeric($ranges[1])) { // case: -x if ($ranges[1] > $fileSize) { $ranges[1] = $fileSize; @@ -294,7 +288,7 @@ class OC_Files { try { $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot()); $file = $userFolder->get($filename); - if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) { + if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) { http_response_code(403); die('403 Forbidden'); } @@ -330,22 +324,21 @@ class OC_Files { if (!empty($rangeArray)) { try { if (count($rangeArray) == 1) { - $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']); - } - else { - // check if file is seekable (if not throw UnseekableException) - // we have to check it before body contents - $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']); + $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']); + } else { + // check if file is seekable (if not throw UnseekableException) + // we have to check it before body contents + $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']); - $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); + $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename)); - foreach ($rangeArray as $range) { - echo "\r\n--".self::getBoundary()."\r\n". + foreach ($rangeArray as $range) { + echo "\r\n--".self::getBoundary()."\r\n". "Content-type: ".$type."\r\n". "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n"; - $view->readfilePart($filename, $range['from'], $range['to']); - } - echo "\r\n--".self::getBoundary()."--\r\n"; + $view->readfilePart($filename, $range['from'], $range['to']); + } + echo "\r\n--".self::getBoundary()."--\r\n"; } } catch (\OCP\Files\UnseekableException $ex) { // file is unseekable @@ -355,8 +348,7 @@ class OC_Files { self::sendHeaders($filename, $name, []); $view->readfile($filename); } - } - else { + } else { $view->readfile($filename); } } @@ -430,5 +422,4 @@ class OC_Files { $view->unlockFile($file, ILockingProvider::LOCK_SHARED); } } - } diff --git a/lib/private/legacy/OC_Helper.php b/lib/private/legacy/OC_Helper.php index 1c4ce50f4ef..3439d1f8936 100644 --- a/lib/private/legacy/OC_Helper.php +++ b/lib/private/legacy/OC_Helper.php @@ -231,8 +231,9 @@ class OC_Helper { } foreach ($dirs as $dir) { foreach ($exts as $ext) { - if ($check_fn("$dir/$name" . $ext)) + if ($check_fn("$dir/$name" . $ext)) { return true; + } } } return false; @@ -385,7 +386,7 @@ class OC_Helper { * @return int number of bytes representing */ public static function maxUploadFilesize($dir, $freeSpace = null) { - if (is_null($freeSpace) || $freeSpace < 0){ + if (is_null($freeSpace) || $freeSpace < 0) { $freeSpace = self::freeSpace($dir); } return min($freeSpace, self::uploadLimit()); @@ -540,7 +541,7 @@ class OC_Helper { $ownerId = $storage->getOwner($path); $ownerDisplayName = ''; $owner = \OC::$server->getUserManager()->get($ownerId); - if($owner) { + if ($owner) { $ownerDisplayName = $owner->getDisplayName(); } diff --git a/lib/private/legacy/OC_Hook.php b/lib/private/legacy/OC_Hook.php index b98424711dd..fe08266fe5b 100644 --- a/lib/private/legacy/OC_Hook.php +++ b/lib/private/legacy/OC_Hook.php @@ -54,12 +54,12 @@ class OC_Hook { static public function connect($signalClass, $signalName, $slotClass, $slotName) { // If we're trying to connect to an emitting class that isn't // yet registered, register it - if(!array_key_exists($signalClass, self::$registered)) { + if (!array_key_exists($signalClass, self::$registered)) { self::$registered[$signalClass] = []; } // If we're trying to connect to an emitting method that isn't // yet registered, register it with the emitting class - if(!array_key_exists($signalName, self::$registered[$signalClass])) { + if (!array_key_exists($signalName, self::$registered[$signalClass])) { self::$registered[$signalClass][$signalName] = []; } @@ -95,27 +95,27 @@ class OC_Hook { // Return false if no hook handlers are listening to this // emitting class - if(!array_key_exists($signalClass, self::$registered)) { + if (!array_key_exists($signalClass, self::$registered)) { return false; } // Return false if no hook handlers are listening to this // emitting method - if(!array_key_exists($signalName, self::$registered[$signalClass])) { + if (!array_key_exists($signalName, self::$registered[$signalClass])) { return false; } // Call all slots - foreach(self::$registered[$signalClass][$signalName] as $i) { + foreach (self::$registered[$signalClass][$signalName] as $i) { try { call_user_func([ $i["class"], $i["name"] ], $params); - } catch (Exception $e){ + } catch (Exception $e) { self::$thrownExceptions[] = $e; \OC::$server->getLogger()->logException($e); - if($e instanceof \OC\HintException) { + if ($e instanceof \OC\HintException) { throw $e; } - if($e instanceof \OC\ServerNotAvailableException) { + if ($e instanceof \OC\ServerNotAvailableException) { throw $e; } } @@ -133,10 +133,10 @@ class OC_Hook { if ($signalClass) { if ($signalName) { self::$registered[$signalClass][$signalName]=[]; - }else{ + } else { self::$registered[$signalClass]=[]; } - }else{ + } else { self::$registered=[]; } } diff --git a/lib/private/legacy/OC_Image.php b/lib/private/legacy/OC_Image.php index 829a9b81652..a3ac82c216d 100644 --- a/lib/private/legacy/OC_Image.php +++ b/lib/private/legacy/OC_Image.php @@ -489,7 +489,7 @@ class OC_Image implements \OCP\IImage { $rotate = 90; break; } - if($flip && function_exists('imageflip')) { + if ($flip && function_exists('imageflip')) { imageflip($this->resource, IMG_FLIP_HORIZONTAL); } if ($rotate) { diff --git a/lib/private/legacy/OC_JSON.php b/lib/private/legacy/OC_JSON.php index 5b4b97e6fd0..d3a33e3a0f3 100644 --- a/lib/private/legacy/OC_JSON.php +++ b/lib/private/legacy/OC_JSON.php @@ -33,7 +33,7 @@ * Class OC_JSON * @deprecated Use a AppFramework JSONResponse instead */ -class OC_JSON{ +class OC_JSON { /** * Check if the app is enabled, send json error msg if not @@ -42,7 +42,7 @@ class OC_JSON{ * @suppress PhanDeprecatedFunction */ public static function checkAppEnabled($app) { - if(!\OC::$server->getAppManager()->isEnabledForUser($app)) { + if (!\OC::$server->getAppManager()->isEnabledForUser($app)) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' ]]); exit(); @@ -56,7 +56,7 @@ class OC_JSON{ */ public static function checkLoggedIn() { $twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager(); - if(!\OC::$server->getUserSession()->isLoggedIn() + if (!\OC::$server->getUserSession()->isLoggedIn() || $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { $l = \OC::$server->getL10N('lib'); http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED); @@ -71,12 +71,12 @@ class OC_JSON{ * @suppress PhanDeprecatedFunction */ public static function callCheck() { - if(!\OC::$server->getRequest()->passesStrictCookieCheck()) { + if (!\OC::$server->getRequest()->passesStrictCookieCheck()) { header('Location: '.\OC::$WEBROOT); exit(); } - if(!\OC::$server->getRequest()->passesCSRFCheck()) { + if (!\OC::$server->getRequest()->passesCSRFCheck()) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' ]]); exit(); @@ -89,7 +89,7 @@ class OC_JSON{ * @suppress PhanDeprecatedFunction */ public static function checkAdminUser() { - if(!OC_User::isAdminUser(OC_User::getUser())) { + if (!OC_User::isAdminUser(OC_User::getUser())) { $l = \OC::$server->getL10N('lib'); self::error([ 'data' => [ 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' ]]); exit(); diff --git a/lib/private/legacy/OC_Response.php b/lib/private/legacy/OC_Response.php index 45fea27d61d..bbeb6258109 100644 --- a/lib/private/legacy/OC_Response.php +++ b/lib/private/legacy/OC_Response.php @@ -94,7 +94,7 @@ class OC_Response { // Send fallback headers for installations that don't have the possibility to send // custom headers on the webserver side - if(getenv('modHeadersAvailable') !== 'true') { + if (getenv('modHeadersAvailable') !== 'true') { header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/ header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx @@ -104,5 +104,4 @@ class OC_Response { header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters } } - } diff --git a/lib/private/legacy/OC_Template.php b/lib/private/legacy/OC_Template.php index 08f23b55a0f..736011b4359 100644 --- a/lib/private/legacy/OC_Template.php +++ b/lib/private/legacy/OC_Template.php @@ -99,7 +99,7 @@ class OC_Template extends \OC\Template\Base { * @param string $renderAs */ public static function initTemplateEngine($renderAs) { - if (self::$initTemplateEngineFirstRun){ + if (self::$initTemplateEngineFirstRun) { //apps that started before the template initialization can load their own scripts/styles //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true @@ -130,7 +130,6 @@ class OC_Template extends \OC\Template\Base { self::$initTemplateEngineFirstRun = false; } - } @@ -146,7 +145,7 @@ class OC_Template extends \OC\Template\Base { */ protected function findTemplate($theme, $app, $name) { // Check if it is a app template or not. - if($app !== '') { + if ($app !== '') { $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app)); } else { $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT); @@ -182,10 +181,10 @@ class OC_Template extends \OC\Template\Base { public function fetchPage($additionalParams = null) { $data = parent::fetchPage($additionalParams); - if($this->renderAs) { + if ($this->renderAs) { $page = new TemplateLayout($this->renderAs, $this->app); - if(is_array($additionalParams)) { + if (is_array($additionalParams)) { foreach ($additionalParams as $key => $value) { $page->assign($key, $value); } @@ -193,12 +192,12 @@ class OC_Template extends \OC\Template\Base { // Add custom headers $headers = ''; - foreach(OC_Util::$headers as $header) { + foreach (OC_Util::$headers as $header) { $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']); if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) { $headers .= ' defer'; } - foreach($header['attributes'] as $name=>$value) { + foreach ($header['attributes'] as $name=>$value) { $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"'; } if ($header['text'] !== null) { @@ -240,7 +239,7 @@ class OC_Template extends \OC\Template\Base { */ public static function printUserPage($application, $name, $parameters = []) { $content = new OC_Template($application, $name, "user"); - foreach($parameters as $key => $value) { + foreach ($parameters as $key => $value) { $content->assign($key, $value); } print $content->printPage(); @@ -255,7 +254,7 @@ class OC_Template extends \OC\Template\Base { */ public static function printAdminPage($application, $name, $parameters = []) { $content = new OC_Template($application, $name, "admin"); - foreach($parameters as $key => $value) { + foreach ($parameters as $key => $value) { $content->assign($key, $value); } return $content->printPage(); @@ -270,7 +269,7 @@ class OC_Template extends \OC\Template\Base { */ public static function printGuestPage($application, $name, $parameters = []) { $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest'); - foreach($parameters as $key => $value) { + foreach ($parameters as $key => $value) { $content->assign($key, $value); } return $content->printPage(); diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index a9de5cdef9f..c61d99eee74 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -57,7 +57,6 @@ use OCP\ILogger; * logout() */ class OC_User { - private static $_usedBackends = []; private static $_setupedBackends = []; @@ -161,7 +160,6 @@ class OC_User { * @return bool */ public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) { - $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit("OC_User", "pre_login", ["run" => &$run, "uid" => $uid, 'backend' => $backend]); diff --git a/lib/private/legacy/OC_Util.php b/lib/private/legacy/OC_Util.php index 9322ef07a79..71f6edba0bf 100644 --- a/lib/private/legacy/OC_Util.php +++ b/lib/private/legacy/OC_Util.php @@ -302,7 +302,6 @@ class OC_Util { //if we aren't logged in, there is no use to set up the filesystem if ($user != "") { - $userDir = '/' . $user . '/files'; //jail the user into his "home" directory @@ -382,7 +381,7 @@ class OC_Util { return \OCP\Files\FileInfo::SPACE_UNLIMITED; } $userQuota = $user->getQuota(); - if($userQuota === 'none') { + if ($userQuota === 'none') { return \OCP\Files\FileInfo::SPACE_UNLIMITED; } return OC_Helper::computerFileSize($userQuota); @@ -398,7 +397,6 @@ class OC_Util { * @suppress PhanDeprecatedFunction */ public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { - $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton'); $userLang = \OC::$server->getL10NFactory()->findLanguage(); $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory); @@ -450,7 +448,7 @@ class OC_Util { // Verify if folder exists $dir = opendir($source); - if($dir === false) { + if ($dir === false) { $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']); return; } @@ -464,7 +462,7 @@ class OC_Util { } else { $child = $target->newFile($file); $sourceStream = fopen($source . '/' . $file, 'r'); - if($sourceStream === false) { + if ($sourceStream === false) { $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']); closedir($dir); return; @@ -663,7 +661,6 @@ class OC_Util { * @return void */ private static function addExternalResource($application, $prepend, $path, $type = "script") { - if ($type === "style") { if (!in_array($path, self::$styles)) { if ($prepend === true) { @@ -700,7 +697,6 @@ class OC_Util { ]; if ($prepend === true) { array_unshift(self::$headers, $header); - } else { self::$headers[] = $header; } @@ -750,7 +746,7 @@ class OC_Util { } // Check if config folder is writable. - if(!OC_Helper::isReadOnlyConfigEnabled()) { + if (!OC_Helper::isReadOnlyConfigEnabled()) { if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) { $errors[] = [ 'error' => $l->t('Cannot write into "config" directory'), @@ -890,15 +886,15 @@ class OC_Util { } } - foreach($missingDependencies as $missingDependency) { + foreach ($missingDependencies as $missingDependency) { $errors[] = [ 'error' => $l->t('PHP module %s not installed.', [$missingDependency]), 'hint' => $moduleHint ]; $webServerRestart = true; } - foreach($invalidIniSettings as $setting) { - if(is_bool($setting[1])) { + foreach ($invalidIniSettings as $setting) { + if (is_bool($setting[1])) { $setting[1] = $setting[1] ? 'on' : 'off'; } $errors[] = [ @@ -916,7 +912,7 @@ class OC_Util { * TODO: Should probably be implemented in the above generic dependency * check somehow in the long-term. */ - if($iniWrapper->getBool('mbstring.func_overload') !== null && + if ($iniWrapper->getBool('mbstring.func_overload') !== null && $iniWrapper->getBool('mbstring.func_overload') === true) { $errors[] = [ 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]), @@ -924,7 +920,7 @@ class OC_Util { ]; } - if(function_exists('xml_parser_create') && + if (function_exists('xml_parser_create') && LIBXML_LOADED_VERSION < 20700) { $version = LIBXML_LOADED_VERSION; $major = floor($version/10000); @@ -999,7 +995,7 @@ class OC_Util { * @return array arrays with error messages and hints */ public static function checkDataDirectoryPermissions($dataDirectory) { - if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) { + if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) { return []; } $l = \OC::$server->getL10N('lib'); @@ -1116,7 +1112,7 @@ class OC_Util { } } - if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') { + if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') { $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/'); } else { $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/'); @@ -1226,7 +1222,6 @@ class OC_Util { * @throws \OC\HintException If the test file can't get written. */ public function isHtaccessWorking(\OCP\IConfig $config) { - if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) { return true; } @@ -1349,7 +1344,7 @@ class OC_Util { * @return bool|string */ public static function normalizeUnicode($value) { - if(Normalizer::isNormalized($value)) { + if (Normalizer::isNormalized($value)) { return $value; } @@ -1466,5 +1461,4 @@ class OC_Util { return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1; } - } diff --git a/lib/private/legacy/template/functions.php b/lib/private/legacy/template/functions.php index 83751db1e31..e2a1c476433 100644 --- a/lib/private/legacy/template/functions.php +++ b/lib/private/legacy/template/functions.php @@ -62,10 +62,10 @@ function emit_css_tag($href, $opts = '') { * @param array $obj all the script information from template */ function emit_css_loading_tags($obj) { - foreach($obj['cssfiles'] as $css) { + foreach ($obj['cssfiles'] as $css) { emit_css_tag($css); } - foreach($obj['printcssfiles'] as $css) { + foreach ($obj['printcssfiles'] as $css) { emit_css_tag($css, 'media="print"'); } } @@ -79,7 +79,7 @@ function emit_script_tag($src, $script_content='') { $defer_str=' defer'; $s='