Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
apps/twofactor_backupcodes/lib/BackgroundJob/CheckBackupCodes.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -36,35 +36,35 @@
 block discarded – undo
36 36
 
37 37
 class CheckBackupCodes extends QueuedJob {
38 38
 
39
-	/** @var IUserManager */
40
-	private $userManager;
39
+    /** @var IUserManager */
40
+    private $userManager;
41 41
 
42
-	/** @var IJobList */
43
-	private $jobList;
42
+    /** @var IJobList */
43
+    private $jobList;
44 44
 
45
-	/** @var Manager */
46
-	private $registry;
45
+    /** @var Manager */
46
+    private $registry;
47 47
 
48
-	/** @var Manager */
49
-	private $twofactorManager;
48
+    /** @var Manager */
49
+    private $twofactorManager;
50 50
 
51
-	public function __construct(ITimeFactory $timeFactory, IUserManager $userManager, IJobList $jobList, Manager $twofactorManager, IRegistry $registry) {
52
-		parent::__construct($timeFactory);
53
-		$this->userManager = $userManager;
54
-		$this->jobList = $jobList;
55
-		$this->twofactorManager = $twofactorManager;
56
-		$this->registry = $registry;
57
-	}
51
+    public function __construct(ITimeFactory $timeFactory, IUserManager $userManager, IJobList $jobList, Manager $twofactorManager, IRegistry $registry) {
52
+        parent::__construct($timeFactory);
53
+        $this->userManager = $userManager;
54
+        $this->jobList = $jobList;
55
+        $this->twofactorManager = $twofactorManager;
56
+        $this->registry = $registry;
57
+    }
58 58
 
59
-	protected function run($argument) {
60
-		$this->userManager->callForSeenUsers(function (IUser $user) {
61
-			$providers = $this->registry->getProviderStates($user);
62
-			$isTwoFactorAuthenticated = $this->twofactorManager->isTwoFactorAuthenticated($user);
59
+    protected function run($argument) {
60
+        $this->userManager->callForSeenUsers(function (IUser $user) {
61
+            $providers = $this->registry->getProviderStates($user);
62
+            $isTwoFactorAuthenticated = $this->twofactorManager->isTwoFactorAuthenticated($user);
63 63
 
64
-			if ($isTwoFactorAuthenticated && isset($providers['backup_codes']) && $providers['backup_codes'] === false) {
65
-				$this->jobList->add(RememberBackupCodesJob::class, ['uid' => $user->getUID()]);
66
-			}
67
-		});
68
-	}
64
+            if ($isTwoFactorAuthenticated && isset($providers['backup_codes']) && $providers['backup_codes'] === false) {
65
+                $this->jobList->add(RememberBackupCodesJob::class, ['uid' => $user->getUID()]);
66
+            }
67
+        });
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
apps/twofactor_backupcodes/lib/BackgroundJob/RememberBackupCodesJob.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -35,66 +35,66 @@
 block discarded – undo
35 35
 
36 36
 class RememberBackupCodesJob extends TimedJob {
37 37
 
38
-	/** @var IRegistry */
39
-	private $registry;
40
-
41
-	/** @var IUserManager */
42
-	private $userManager;
43
-
44
-	/** @var IManager */
45
-	private $notificationManager;
46
-
47
-	/** @var IJobList */
48
-	private $jobList;
49
-
50
-	public function __construct(IRegistry $registry,
51
-								IUserManager $userManager,
52
-								ITimeFactory $timeFactory,
53
-								IManager $notificationManager,
54
-								IJobList $jobList) {
55
-		parent::__construct($timeFactory);
56
-		$this->registry = $registry;
57
-		$this->userManager = $userManager;
58
-		$this->time = $timeFactory;
59
-		$this->notificationManager = $notificationManager;
60
-		$this->jobList = $jobList;
61
-
62
-		$this->setInterval(60*60*24*14);
63
-	}
64
-
65
-	protected function run($argument) {
66
-		$uid = $argument['uid'];
67
-		$user = $this->userManager->get($uid);
68
-
69
-		if ($user === null) {
70
-			// We can't run with an invalid user
71
-			return;
72
-		}
73
-
74
-		$providers = $this->registry->getProviderStates($user);
75
-		$state2fa = array_reduce($providers, function (bool $carry, bool $state) {
76
-			return $carry || $state;
77
-		}, false);
78
-
79
-		/*
38
+    /** @var IRegistry */
39
+    private $registry;
40
+
41
+    /** @var IUserManager */
42
+    private $userManager;
43
+
44
+    /** @var IManager */
45
+    private $notificationManager;
46
+
47
+    /** @var IJobList */
48
+    private $jobList;
49
+
50
+    public function __construct(IRegistry $registry,
51
+                                IUserManager $userManager,
52
+                                ITimeFactory $timeFactory,
53
+                                IManager $notificationManager,
54
+                                IJobList $jobList) {
55
+        parent::__construct($timeFactory);
56
+        $this->registry = $registry;
57
+        $this->userManager = $userManager;
58
+        $this->time = $timeFactory;
59
+        $this->notificationManager = $notificationManager;
60
+        $this->jobList = $jobList;
61
+
62
+        $this->setInterval(60*60*24*14);
63
+    }
64
+
65
+    protected function run($argument) {
66
+        $uid = $argument['uid'];
67
+        $user = $this->userManager->get($uid);
68
+
69
+        if ($user === null) {
70
+            // We can't run with an invalid user
71
+            return;
72
+        }
73
+
74
+        $providers = $this->registry->getProviderStates($user);
75
+        $state2fa = array_reduce($providers, function (bool $carry, bool $state) {
76
+            return $carry || $state;
77
+        }, false);
78
+
79
+        /*
80 80
 		 * If no provider is active or if the backup codes are already generate
81 81
 		 * we can remove the job
82 82
 		 */
83
-		if ($state2fa === false || (isset($providers['backup_codes']) && $providers['backup_codes'] === true)) {
84
-			// Backup codes already generated lets remove this job
85
-			$this->jobList->remove(self::class, $argument);
86
-			return;
87
-		}
88
-
89
-		$date = new \DateTime();
90
-		$date->setTimestamp($this->time->getTime());
91
-
92
-		$notification = $this->notificationManager->createNotification();
93
-		$notification->setApp('twofactor_backupcodes')
94
-			->setUser($user->getUID())
95
-			->setDateTime($date)
96
-			->setObject('create', 'codes')
97
-			->setSubject('create_backupcodes');
98
-		$this->notificationManager->notify($notification);
99
-	}
83
+        if ($state2fa === false || (isset($providers['backup_codes']) && $providers['backup_codes'] === true)) {
84
+            // Backup codes already generated lets remove this job
85
+            $this->jobList->remove(self::class, $argument);
86
+            return;
87
+        }
88
+
89
+        $date = new \DateTime();
90
+        $date->setTimestamp($this->time->getTime());
91
+
92
+        $notification = $this->notificationManager->createNotification();
93
+        $notification->setApp('twofactor_backupcodes')
94
+            ->setUser($user->getUID())
95
+            ->setDateTime($date)
96
+            ->setObject('create', 'codes')
97
+            ->setSubject('create_backupcodes');
98
+        $this->notificationManager->notify($notification);
99
+    }
100 100
 }
Please login to merge, or discard this patch.
apps/twofactor_backupcodes/lib/Provider/BackupCodesProvider.php 1 patch
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -41,129 +41,129 @@
 block discarded – undo
41 41
 
42 42
 class BackupCodesProvider implements IProvider, IProvidesPersonalSettings {
43 43
 
44
-	/** @var string */
45
-	private $appName;
46
-
47
-	/** @var BackupCodeStorage */
48
-	private $storage;
49
-
50
-	/** @var IL10N */
51
-	private $l10n;
52
-
53
-	/** @var AppManager */
54
-	private $appManager;
55
-	/** @var IInitialStateService */
56
-	private $initialStateService;
57
-
58
-	/**
59
-	 * @param string $appName
60
-	 * @param BackupCodeStorage $storage
61
-	 * @param IL10N $l10n
62
-	 * @param AppManager $appManager
63
-	 */
64
-	public function __construct(string $appName,
65
-								BackupCodeStorage $storage,
66
-								IL10N $l10n,
67
-								AppManager $appManager,
68
-								IInitialStateService $initialStateService) {
69
-		$this->appName = $appName;
70
-		$this->l10n = $l10n;
71
-		$this->storage = $storage;
72
-		$this->appManager = $appManager;
73
-		$this->initialStateService = $initialStateService;
74
-	}
75
-
76
-	/**
77
-	 * Get unique identifier of this 2FA provider
78
-	 *
79
-	 * @return string
80
-	 */
81
-	public function getId(): string {
82
-		return 'backup_codes';
83
-	}
84
-
85
-	/**
86
-	 * Get the display name for selecting the 2FA provider
87
-	 *
88
-	 * @return string
89
-	 */
90
-	public function getDisplayName(): string {
91
-		return $this->l10n->t('Backup code');
92
-	}
93
-
94
-	/**
95
-	 * Get the description for selecting the 2FA provider
96
-	 *
97
-	 * @return string
98
-	 */
99
-	public function getDescription(): string {
100
-		return $this->l10n->t('Use backup code');
101
-	}
102
-
103
-	/**
104
-	 * Get the template for rending the 2FA provider view
105
-	 *
106
-	 * @param IUser $user
107
-	 * @return Template
108
-	 */
109
-	public function getTemplate(IUser $user): Template {
110
-		return new Template('twofactor_backupcodes', 'challenge');
111
-	}
112
-
113
-	/**
114
-	 * Verify the given challenge
115
-	 *
116
-	 * @param IUser $user
117
-	 * @param string $challenge
118
-	 * @return bool
119
-	 */
120
-	public function verifyChallenge(IUser $user, string $challenge): bool {
121
-		return $this->storage->validateCode($user, $challenge);
122
-	}
123
-
124
-	/**
125
-	 * Decides whether 2FA is enabled for the given user
126
-	 *
127
-	 * @param IUser $user
128
-	 * @return boolean
129
-	 */
130
-	public function isTwoFactorAuthEnabledForUser(IUser $user): bool {
131
-		return $this->storage->hasBackupCodes($user);
132
-	}
133
-
134
-	/**
135
-	 * Determine whether backup codes should be active or not
136
-	 *
137
-	 * Backup codes only make sense if at least one 2FA provider is active,
138
-	 * hence this method checks all enabled apps on whether they provide 2FA
139
-	 * functionality or not. If there's at least one app, backup codes are
140
-	 * enabled on the personal settings page.
141
-	 *
142
-	 * @param IUser $user
143
-	 * @return boolean
144
-	 */
145
-	public function isActive(IUser $user): bool {
146
-		$appIds = array_filter($this->appManager->getEnabledAppsForUser($user), function ($appId) {
147
-			return $appId !== $this->appName;
148
-		});
149
-		foreach ($appIds as $appId) {
150
-			$info = $this->appManager->getAppInfo($appId);
151
-			if (isset($info['two-factor-providers']) && count($info['two-factor-providers']) > 0) {
152
-				return true;
153
-			}
154
-		}
155
-		return false;
156
-	}
157
-
158
-	/**
159
-	 * @param IUser $user
160
-	 *
161
-	 * @return IPersonalProviderSettings
162
-	 */
163
-	public function getPersonalSettings(IUser $user): IPersonalProviderSettings {
164
-		$state = $this->storage->getBackupCodesState($user);
165
-		$this->initialStateService->provideInitialState($this->appName, 'state', $state);
166
-		return new Personal();
167
-	}
44
+    /** @var string */
45
+    private $appName;
46
+
47
+    /** @var BackupCodeStorage */
48
+    private $storage;
49
+
50
+    /** @var IL10N */
51
+    private $l10n;
52
+
53
+    /** @var AppManager */
54
+    private $appManager;
55
+    /** @var IInitialStateService */
56
+    private $initialStateService;
57
+
58
+    /**
59
+     * @param string $appName
60
+     * @param BackupCodeStorage $storage
61
+     * @param IL10N $l10n
62
+     * @param AppManager $appManager
63
+     */
64
+    public function __construct(string $appName,
65
+                                BackupCodeStorage $storage,
66
+                                IL10N $l10n,
67
+                                AppManager $appManager,
68
+                                IInitialStateService $initialStateService) {
69
+        $this->appName = $appName;
70
+        $this->l10n = $l10n;
71
+        $this->storage = $storage;
72
+        $this->appManager = $appManager;
73
+        $this->initialStateService = $initialStateService;
74
+    }
75
+
76
+    /**
77
+     * Get unique identifier of this 2FA provider
78
+     *
79
+     * @return string
80
+     */
81
+    public function getId(): string {
82
+        return 'backup_codes';
83
+    }
84
+
85
+    /**
86
+     * Get the display name for selecting the 2FA provider
87
+     *
88
+     * @return string
89
+     */
90
+    public function getDisplayName(): string {
91
+        return $this->l10n->t('Backup code');
92
+    }
93
+
94
+    /**
95
+     * Get the description for selecting the 2FA provider
96
+     *
97
+     * @return string
98
+     */
99
+    public function getDescription(): string {
100
+        return $this->l10n->t('Use backup code');
101
+    }
102
+
103
+    /**
104
+     * Get the template for rending the 2FA provider view
105
+     *
106
+     * @param IUser $user
107
+     * @return Template
108
+     */
109
+    public function getTemplate(IUser $user): Template {
110
+        return new Template('twofactor_backupcodes', 'challenge');
111
+    }
112
+
113
+    /**
114
+     * Verify the given challenge
115
+     *
116
+     * @param IUser $user
117
+     * @param string $challenge
118
+     * @return bool
119
+     */
120
+    public function verifyChallenge(IUser $user, string $challenge): bool {
121
+        return $this->storage->validateCode($user, $challenge);
122
+    }
123
+
124
+    /**
125
+     * Decides whether 2FA is enabled for the given user
126
+     *
127
+     * @param IUser $user
128
+     * @return boolean
129
+     */
130
+    public function isTwoFactorAuthEnabledForUser(IUser $user): bool {
131
+        return $this->storage->hasBackupCodes($user);
132
+    }
133
+
134
+    /**
135
+     * Determine whether backup codes should be active or not
136
+     *
137
+     * Backup codes only make sense if at least one 2FA provider is active,
138
+     * hence this method checks all enabled apps on whether they provide 2FA
139
+     * functionality or not. If there's at least one app, backup codes are
140
+     * enabled on the personal settings page.
141
+     *
142
+     * @param IUser $user
143
+     * @return boolean
144
+     */
145
+    public function isActive(IUser $user): bool {
146
+        $appIds = array_filter($this->appManager->getEnabledAppsForUser($user), function ($appId) {
147
+            return $appId !== $this->appName;
148
+        });
149
+        foreach ($appIds as $appId) {
150
+            $info = $this->appManager->getAppInfo($appId);
151
+            if (isset($info['two-factor-providers']) && count($info['two-factor-providers']) > 0) {
152
+                return true;
153
+            }
154
+        }
155
+        return false;
156
+    }
157
+
158
+    /**
159
+     * @param IUser $user
160
+     *
161
+     * @return IPersonalProviderSettings
162
+     */
163
+    public function getPersonalSettings(IUser $user): IPersonalProviderSettings {
164
+        $state = $this->storage->getBackupCodesState($user);
165
+        $this->initialStateService->provideInitialState($this->appName, 'state', $state);
166
+        return new Personal();
167
+    }
168 168
 
169 169
 }
Please login to merge, or discard this patch.
apps/federation/lib/SyncJob.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -30,32 +30,32 @@
 block discarded – undo
30 30
 
31 31
 class SyncJob extends TimedJob {
32 32
 
33
-	/** @var SyncFederationAddressBooks */
34
-	protected $syncService;
33
+    /** @var SyncFederationAddressBooks */
34
+    protected $syncService;
35 35
 
36
-	/** @var ILogger */
37
-	protected $logger;
36
+    /** @var ILogger */
37
+    protected $logger;
38 38
 
39
-	/**
40
-	 * @param SyncFederationAddressBooks $syncService
41
-	 * @param ILogger $logger
42
-	 */
43
-	public function __construct(SyncFederationAddressBooks $syncService, ILogger $logger) {
44
-		// Run once a day
45
-		$this->setInterval(24 * 60 * 60);
46
-		$this->syncService = $syncService;
47
-		$this->logger = $logger;
48
-	}
39
+    /**
40
+     * @param SyncFederationAddressBooks $syncService
41
+     * @param ILogger $logger
42
+     */
43
+    public function __construct(SyncFederationAddressBooks $syncService, ILogger $logger) {
44
+        // Run once a day
45
+        $this->setInterval(24 * 60 * 60);
46
+        $this->syncService = $syncService;
47
+        $this->logger = $logger;
48
+    }
49 49
 
50
-	protected function run($argument) {
51
-		$this->syncService->syncThemAll(function ($url, $ex) {
52
-			if ($ex instanceof \Exception) {
53
-				$this->logger->logException($ex, [
54
-					'message' => "Error while syncing $url.",
55
-					'level' => ILogger::INFO,
56
-					'app' => 'fed-sync',
57
-				]);
58
-			}
59
-		});
60
-	}
50
+    protected function run($argument) {
51
+        $this->syncService->syncThemAll(function ($url, $ex) {
52
+            if ($ex instanceof \Exception) {
53
+                $this->logger->logException($ex, [
54
+                    'message' => "Error while syncing $url.",
55
+                    'level' => ILogger::INFO,
56
+                    'app' => 'fed-sync',
57
+                ]);
58
+            }
59
+        });
60
+    }
61 61
 }
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -38,48 +38,48 @@
 block discarded – undo
38 38
 
39 39
 class Application extends App {
40 40
 
41
-	/**
42
-	 * @param array $urlParams
43
-	 */
44
-	public function __construct($urlParams = []) {
45
-		parent::__construct('federation', $urlParams);
46
-		$this->registerMiddleware();
47
-	}
41
+    /**
42
+     * @param array $urlParams
43
+     */
44
+    public function __construct($urlParams = []) {
45
+        parent::__construct('federation', $urlParams);
46
+        $this->registerMiddleware();
47
+    }
48 48
 
49
-	private function registerMiddleware() {
50
-		$container = $this->getContainer();
51
-		$container->registerAlias('AddServerMiddleware', AddServerMiddleware::class);
52
-		$container->registerMiddleWare('AddServerMiddleware');
53
-	}
49
+    private function registerMiddleware() {
50
+        $container = $this->getContainer();
51
+        $container->registerAlias('AddServerMiddleware', AddServerMiddleware::class);
52
+        $container->registerMiddleWare('AddServerMiddleware');
53
+    }
54 54
 
55
-	/**
56
-	 * listen to federated_share_added hooks to auto-add new servers to the
57
-	 * list of trusted servers.
58
-	 */
59
-	public function registerHooks() {
55
+    /**
56
+     * listen to federated_share_added hooks to auto-add new servers to the
57
+     * list of trusted servers.
58
+     */
59
+    public function registerHooks() {
60 60
 
61
-		$container = $this->getContainer();
62
-		$hooksManager = $container->query(Hooks::class);
61
+        $container = $this->getContainer();
62
+        $hooksManager = $container->query(Hooks::class);
63 63
 
64
-		Util::connectHook(
65
-				Share::class,
66
-				'federated_share_added',
67
-				$hooksManager,
68
-				'addServerHook'
69
-		);
64
+        Util::connectHook(
65
+                Share::class,
66
+                'federated_share_added',
67
+                $hooksManager,
68
+                'addServerHook'
69
+        );
70 70
 
71
-		$dispatcher = $container->getServer()->getEventDispatcher();
72
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function ($event) use ($container) {
73
-			if ($event instanceof SabrePluginEvent) {
74
-				$server = $event->getServer();
75
-				if ($server instanceof Server) {
76
-					$authPlugin = $server->getPlugin('auth');
77
-					if ($authPlugin instanceof Plugin) {
78
-						$authPlugin->addBackend($container->query(FedAuth::class));
79
-					}
80
-				}
81
-			}
82
-		});
83
-	}
71
+        $dispatcher = $container->getServer()->getEventDispatcher();
72
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function ($event) use ($container) {
73
+            if ($event instanceof SabrePluginEvent) {
74
+                $server = $event->getServer();
75
+                if ($server instanceof Server) {
76
+                    $authPlugin = $server->getPlugin('auth');
77
+                    if ($authPlugin instanceof Plugin) {
78
+                        $authPlugin->addBackend($container->query(FedAuth::class));
79
+                    }
80
+                }
81
+            }
82
+        });
83
+    }
84 84
 
85 85
 }
Please login to merge, or discard this patch.
apps/federation/lib/Command/SyncFederationAddressBooks.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -33,45 +33,45 @@
 block discarded – undo
33 33
 
34 34
 class SyncFederationAddressBooks extends Command {
35 35
 
36
-	/** @var \OCA\Federation\SyncFederationAddressBooks */
37
-	private $syncService;
36
+    /** @var \OCA\Federation\SyncFederationAddressBooks */
37
+    private $syncService;
38 38
 
39
-	/**
40
-	 * @param \OCA\Federation\SyncFederationAddressBooks $syncService
41
-	 */
42
-	public function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
43
-		parent::__construct();
39
+    /**
40
+     * @param \OCA\Federation\SyncFederationAddressBooks $syncService
41
+     */
42
+    public function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
43
+        parent::__construct();
44 44
 
45
-		$this->syncService = $syncService;
46
-	}
45
+        $this->syncService = $syncService;
46
+    }
47 47
 
48
-	protected function configure() {
49
-		$this
50
-			->setName('federation:sync-addressbooks')
51
-			->setDescription('Synchronizes addressbooks of all federated clouds');
52
-	}
48
+    protected function configure() {
49
+        $this
50
+            ->setName('federation:sync-addressbooks')
51
+            ->setDescription('Synchronizes addressbooks of all federated clouds');
52
+    }
53 53
 
54
-	/**
55
-	 * @param InputInterface $input
56
-	 * @param OutputInterface $output
57
-	 * @return int
58
-	 */
59
-	protected function execute(InputInterface $input, OutputInterface $output) {
54
+    /**
55
+     * @param InputInterface $input
56
+     * @param OutputInterface $output
57
+     * @return int
58
+     */
59
+    protected function execute(InputInterface $input, OutputInterface $output) {
60 60
 
61
-		$progress = new ProgressBar($output);
62
-		$progress->start();
63
-		$this->syncService->syncThemAll(function ($url, $ex) use ($progress, $output) {
64
-			if ($ex instanceof \Exception) {
65
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
61
+        $progress = new ProgressBar($output);
62
+        $progress->start();
63
+        $this->syncService->syncThemAll(function ($url, $ex) use ($progress, $output) {
64
+            if ($ex instanceof \Exception) {
65
+                $output->writeln("Error while syncing $url : " . $ex->getMessage());
66 66
 
67
-			} else {
68
-				$progress->advance();
69
-			}
70
-		});
67
+            } else {
68
+                $progress->advance();
69
+            }
70
+        });
71 71
 
72
-		$progress->finish();
73
-		$output->writeln('');
72
+        $progress->finish();
73
+        $output->writeln('');
74 74
 
75
-		return 0;
76
-	}
75
+        return 0;
76
+    }
77 77
 }
Please login to merge, or discard this patch.
apps/files_external/templates/settings.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -1,51 +1,51 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	use \OCA\Files_External\Lib\Backend\Backend;
3
-	use \OCA\Files_External\Lib\Auth\AuthMechanism;
4
-	use \OCA\Files_External\Lib\DefinitionParameter;
5
-	use \OCA\Files_External\Service\BackendService;
2
+    use \OCA\Files_External\Lib\Backend\Backend;
3
+    use \OCA\Files_External\Lib\Auth\AuthMechanism;
4
+    use \OCA\Files_External\Lib\DefinitionParameter;
5
+    use \OCA\Files_External\Service\BackendService;
6 6
 
7
-	$canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || $_['allowUserMounting'];
7
+    $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || $_['allowUserMounting'];
8 8
 
9
-	$l->t("Enable encryption");
10
-	$l->t("Enable previews");
11
-	$l->t("Enable sharing");
12
-	$l->t("Check for changes");
13
-	$l->t("Never");
14
-	$l->t("Once every direct access");
15
-	$l->t('Read only');
9
+    $l->t("Enable encryption");
10
+    $l->t("Enable previews");
11
+    $l->t("Enable sharing");
12
+    $l->t("Check for changes");
13
+    $l->t("Never");
14
+    $l->t("Once every direct access");
15
+    $l->t('Read only');
16 16
 
17
-	script('files_external', [
18
-		'settings',
19
-		'templates'
20
-	]);
21
-	style('files_external', 'settings');
17
+    script('files_external', [
18
+        'settings',
19
+        'templates'
20
+    ]);
21
+    style('files_external', 'settings');
22 22
 
23
-	// load custom JS
24
-	foreach ($_['backends'] as $backend) {
25
-		/** @var Backend $backend */
26
-		$scripts = $backend->getCustomJs();
27
-		foreach ($scripts as $script) {
28
-			script('files_external', $script);
29
-		}
30
-	}
31
-	foreach ($_['authMechanisms'] as $authMechanism) {
32
-		/** @var AuthMechanism $authMechanism */
33
-		$scripts = $authMechanism->getCustomJs();
34
-		foreach ($scripts as $script) {
35
-			script('files_external', $script);
36
-		}
37
-	}
23
+    // load custom JS
24
+    foreach ($_['backends'] as $backend) {
25
+        /** @var Backend $backend */
26
+        $scripts = $backend->getCustomJs();
27
+        foreach ($scripts as $script) {
28
+            script('files_external', $script);
29
+        }
30
+    }
31
+    foreach ($_['authMechanisms'] as $authMechanism) {
32
+        /** @var AuthMechanism $authMechanism */
33
+        $scripts = $authMechanism->getCustomJs();
34
+        foreach ($scripts as $script) {
35
+            script('files_external', $script);
36
+        }
37
+    }
38 38
 
39
-	function writeParameterInput($parameter, $options, $classes = []) {
40
-		$value = '';
41
-		if (isset($options[$parameter->getName()])) {
42
-			$value = $options[$parameter->getName()];
43
-		}
44
-		$placeholder = $parameter->getText();
45
-		$is_optional = $parameter->isFlagSet(DefinitionParameter::FLAG_OPTIONAL);
39
+    function writeParameterInput($parameter, $options, $classes = []) {
40
+        $value = '';
41
+        if (isset($options[$parameter->getName()])) {
42
+            $value = $options[$parameter->getName()];
43
+        }
44
+        $placeholder = $parameter->getText();
45
+        $is_optional = $parameter->isFlagSet(DefinitionParameter::FLAG_OPTIONAL);
46 46
 
47
-		switch ($parameter->getType()) {
48
-		case DefinitionParameter::VALUE_PASSWORD: ?>
47
+        switch ($parameter->getType()) {
48
+        case DefinitionParameter::VALUE_PASSWORD: ?>
49 49
 			<?php if ($is_optional) { $classes[] = 'optional'; } ?>
50 50
 			<input type="password"
51 51
 				<?php if (!empty($classes)): ?> class="<?php p(implode(' ', $classes)); ?>"<?php endif; ?>
@@ -54,8 +54,8 @@  discard block
 block discarded – undo
54 54
 				placeholder="<?php p($placeholder); ?>"
55 55
 			/>
56 56
 			<?php
57
-			break;
58
-		case DefinitionParameter::VALUE_BOOLEAN: ?>
57
+            break;
58
+        case DefinitionParameter::VALUE_BOOLEAN: ?>
59 59
 			<?php $checkboxId = uniqid("checkbox_"); ?>
60 60
 			<div>
61 61
 			<label>
@@ -69,16 +69,16 @@  discard block
 block discarded – undo
69 69
 			</label>
70 70
 			</div>
71 71
 			<?php
72
-			break;
73
-		case DefinitionParameter::VALUE_HIDDEN: ?>
72
+            break;
73
+        case DefinitionParameter::VALUE_HIDDEN: ?>
74 74
 			<input type="hidden"
75 75
 				<?php if (!empty($classes)): ?> class="<?php p(implode(' ', $classes)); ?>"<?php endif; ?>
76 76
 				data-parameter="<?php p($parameter->getName()); ?>"
77 77
 				value="<?php p($value); ?>"
78 78
 			/>
79 79
 			<?php
80
-			break;
81
-		default: ?>
80
+            break;
81
+        default: ?>
82 82
 			<?php if ($is_optional) { $classes[] = 'optional'; } ?>
83 83
 			<input type="text"
84 84
 				<?php if (!empty($classes)): ?> class="<?php p(implode(' ', $classes)); ?>"<?php endif; ?>
@@ -87,8 +87,8 @@  discard block
 block discarded – undo
87 87
 				placeholder="<?php p($placeholder); ?>"
88 88
 			/>
89 89
 			<?php
90
-		}
91
-	}
90
+        }
91
+    }
92 92
 ?>
93 93
 
94 94
 <div id="emptycontent" class="hidden">
@@ -134,13 +134,13 @@  discard block
 block discarded – undo
134 134
 							<?php p($l->t('Add storage')); ?>
135 135
 						</option>
136 136
 						<?php
137
-							$sortedBackends = array_filter($_['backends'], function ($backend) use ($_) {
138
-								return $backend->isVisibleFor($_['visibilityType']);
139
-							});
140
-							uasort($sortedBackends, function ($a, $b) {
141
-								return strcasecmp($a->getText(), $b->getText());
142
-							});
143
-						?>
137
+                            $sortedBackends = array_filter($_['backends'], function ($backend) use ($_) {
138
+                                return $backend->isVisibleFor($_['visibilityType']);
139
+                            });
140
+                            uasort($sortedBackends, function ($a, $b) {
141
+                                return strcasecmp($a->getText(), $b->getText());
142
+                            });
143
+                        ?>
144 144
 						<?php foreach ($sortedBackends as $backend): ?>
145 145
 							<?php if ($backend->getDeprecateTo()) continue; // ignore deprecated backends ?>
146 146
 							<option value="<?php p($backend->getIdentifier()); ?>"><?php p($backend->getText()); ?></option>
@@ -172,10 +172,10 @@  discard block
 block discarded – undo
172 172
 
173 173
 		<p id="userMountingBackends"<?php if (!$_['allowUserMounting']): ?> class="hidden"<?php endif; ?>>
174 174
 			<?php
175
-				$userBackends = array_filter($_['backends'], function ($backend) {
176
-					return $backend->isAllowedVisibleFor(BackendService::VISIBILITY_PERSONAL);
177
-				});
178
-			?>
175
+                $userBackends = array_filter($_['backends'], function ($backend) {
176
+                    return $backend->isAllowedVisibleFor(BackendService::VISIBILITY_PERSONAL);
177
+                });
178
+            ?>
179 179
 			<?php $i = 0; foreach ($userBackends as $backend): ?>
180 180
 				<?php if ($deprecateTo = $backend->getDeprecateTo()): ?>
181 181
 					<input type="hidden" id="allowUserMountingBackends<?php p($i); ?>" name="allowUserMountingBackends[]" value="<?php p($backend->getIdentifier()); ?>" data-deprecate-to="<?php p($deprecateTo->getIdentifier()); ?>" />
Please login to merge, or discard this patch.
apps/files_external/lib/Service/BackendService.php 1 patch
Indentation   +326 added lines, -326 removed lines patch added patch discarded remove patch
@@ -40,330 +40,330 @@
 block discarded – undo
40 40
  */
41 41
 class BackendService {
42 42
 
43
-	/** Visibility constants for VisibilityTrait */
44
-	const VISIBILITY_NONE = 0;
45
-	const VISIBILITY_PERSONAL = 1;
46
-	const VISIBILITY_ADMIN = 2;
47
-	//const VISIBILITY_ALIENS = 4;
48
-
49
-	const VISIBILITY_DEFAULT = 3; // PERSONAL | ADMIN
50
-
51
-	/** Priority constants for PriorityTrait */
52
-	const PRIORITY_DEFAULT = 100;
53
-
54
-	/** @var IConfig */
55
-	protected $config;
56
-
57
-	/** @var bool */
58
-	private $userMountingAllowed = true;
59
-
60
-	/** @var string[] */
61
-	private $userMountingBackends = [];
62
-
63
-	/** @var Backend[] */
64
-	private $backends = [];
65
-
66
-	/** @var IBackendProvider[] */
67
-	private $backendProviders = [];
68
-
69
-	/** @var AuthMechanism[] */
70
-	private $authMechanisms = [];
71
-
72
-	/** @var IAuthMechanismProvider[] */
73
-	private $authMechanismProviders = [];
74
-
75
-	/** @var callable[] */
76
-	private $configHandlerLoaders = [];
77
-
78
-	private $configHandlers = [];
79
-
80
-	/**
81
-	 * @param IConfig $config
82
-	 */
83
-	public function __construct(
84
-		IConfig $config
85
-	) {
86
-		$this->config = $config;
87
-
88
-		// Load config values
89
-		if ($this->config->getAppValue('files_external', 'allow_user_mounting', 'yes') !== 'yes') {
90
-			$this->userMountingAllowed = false;
91
-		}
92
-		$this->userMountingBackends = explode(',',
93
-			$this->config->getAppValue('files_external', 'user_mounting_backends', '')
94
-		);
95
-
96
-		// if no backend is in the list an empty string is in the array and user mounting is disabled
97
-		if ($this->userMountingBackends === ['']) {
98
-			$this->userMountingAllowed = false;
99
-		}
100
-	}
101
-
102
-	/**
103
-	 * Register a backend provider
104
-	 *
105
-	 * @since 9.1.0
106
-	 * @param IBackendProvider $provider
107
-	 */
108
-	public function registerBackendProvider(IBackendProvider $provider) {
109
-		$this->backendProviders[] = $provider;
110
-	}
111
-
112
-	private function callForRegistrations() {
113
-		static $eventSent = false;
114
-		if(!$eventSent) {
115
-			\OC::$server->getEventDispatcher()->dispatch(
116
-				'OCA\\Files_External::loadAdditionalBackends',
117
-				new GenericEvent()
118
-			);
119
-			$eventSent = true;
120
-		}
121
-	}
122
-
123
-	private function loadBackendProviders() {
124
-		$this->callForRegistrations();
125
-		foreach ($this->backendProviders as $provider) {
126
-			$this->registerBackends($provider->getBackends());
127
-		}
128
-		$this->backendProviders = [];
129
-	}
130
-
131
-	/**
132
-	 * Register an auth mechanism provider
133
-	 *
134
-	 * @since 9.1.0
135
-	 * @param IAuthMechanismProvider $provider
136
-	 */
137
-	public function registerAuthMechanismProvider(IAuthMechanismProvider $provider) {
138
-		$this->authMechanismProviders[] = $provider;
139
-	}
140
-
141
-	private function loadAuthMechanismProviders() {
142
-		$this->callForRegistrations();
143
-		foreach ($this->authMechanismProviders as $provider) {
144
-			$this->registerAuthMechanisms($provider->getAuthMechanisms());
145
-		}
146
-		$this->authMechanismProviders = [];
147
-	}
148
-
149
-	/**
150
-	 * Register a backend
151
-	 *
152
-	 * @deprecated 9.1.0 use registerBackendProvider()
153
-	 * @param Backend $backend
154
-	 */
155
-	public function registerBackend(Backend $backend) {
156
-		if (!$this->isAllowedUserBackend($backend)) {
157
-			$backend->removeVisibility(BackendService::VISIBILITY_PERSONAL);
158
-		}
159
-		foreach ($backend->getIdentifierAliases() as $alias) {
160
-			$this->backends[$alias] = $backend;
161
-		}
162
-	}
163
-
164
-	/**
165
-	 * @deprecated 9.1.0 use registerBackendProvider()
166
-	 * @param Backend[] $backends
167
-	 */
168
-	public function registerBackends(array $backends) {
169
-		foreach ($backends as $backend) {
170
-			$this->registerBackend($backend);
171
-		}
172
-	}
173
-	/**
174
-	 * Register an authentication mechanism
175
-	 *
176
-	 * @deprecated 9.1.0 use registerAuthMechanismProvider()
177
-	 * @param AuthMechanism $authMech
178
-	 */
179
-	public function registerAuthMechanism(AuthMechanism $authMech) {
180
-		if (!$this->isAllowedAuthMechanism($authMech)) {
181
-			$authMech->removeVisibility(BackendService::VISIBILITY_PERSONAL);
182
-		}
183
-		foreach ($authMech->getIdentifierAliases() as $alias) {
184
-			$this->authMechanisms[$alias] = $authMech;
185
-		}
186
-	}
187
-
188
-	/**
189
-	 * @deprecated 9.1.0 use registerAuthMechanismProvider()
190
-	 * @param AuthMechanism[] $mechanisms
191
-	 */
192
-	public function registerAuthMechanisms(array $mechanisms) {
193
-		foreach ($mechanisms as $mechanism) {
194
-			$this->registerAuthMechanism($mechanism);
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * Get all backends
200
-	 *
201
-	 * @return Backend[]
202
-	 */
203
-	public function getBackends() {
204
-		$this->loadBackendProviders();
205
-		// only return real identifiers, no aliases
206
-		$backends = [];
207
-		foreach ($this->backends as $backend) {
208
-			$backends[$backend->getIdentifier()] = $backend;
209
-		}
210
-		return $backends;
211
-	}
212
-
213
-	/**
214
-	 * Get all available backends
215
-	 *
216
-	 * @return Backend[]
217
-	 */
218
-	public function getAvailableBackends() {
219
-		return array_filter($this->getBackends(), function ($backend) {
220
-			return !$backend->checkDependencies();
221
-		});
222
-	}
223
-
224
-	/**
225
-	 * @param string $identifier
226
-	 * @return Backend|null
227
-	 */
228
-	public function getBackend($identifier) {
229
-		$this->loadBackendProviders();
230
-		if (isset($this->backends[$identifier])) {
231
-			return $this->backends[$identifier];
232
-		}
233
-		return null;
234
-	}
235
-
236
-	/**
237
-	 * Get all authentication mechanisms
238
-	 *
239
-	 * @return AuthMechanism[]
240
-	 */
241
-	public function getAuthMechanisms() {
242
-		$this->loadAuthMechanismProviders();
243
-		// only return real identifiers, no aliases
244
-		$mechanisms = [];
245
-		foreach ($this->authMechanisms as $mechanism) {
246
-			$mechanisms[$mechanism->getIdentifier()] = $mechanism;
247
-		}
248
-		return $mechanisms;
249
-	}
250
-
251
-	/**
252
-	 * Get all authentication mechanisms for schemes
253
-	 *
254
-	 * @param string[] $schemes
255
-	 * @return AuthMechanism[]
256
-	 */
257
-	public function getAuthMechanismsByScheme(array $schemes) {
258
-		return array_filter($this->getAuthMechanisms(), function ($authMech) use ($schemes) {
259
-			return in_array($authMech->getScheme(), $schemes, true);
260
-		});
261
-	}
262
-
263
-	/**
264
-	 * @param string $identifier
265
-	 * @return AuthMechanism|null
266
-	 */
267
-	public function getAuthMechanism($identifier) {
268
-		$this->loadAuthMechanismProviders();
269
-		if (isset($this->authMechanisms[$identifier])) {
270
-			return $this->authMechanisms[$identifier];
271
-		}
272
-		return null;
273
-	}
274
-
275
-	/**
276
-	 * @return bool
277
-	 */
278
-	public function isUserMountingAllowed() {
279
-		return $this->userMountingAllowed;
280
-	}
281
-
282
-	/**
283
-	 * Check a backend if a user is allowed to mount it
284
-	 *
285
-	 * @param Backend $backend
286
-	 * @return bool
287
-	 */
288
-	protected function isAllowedUserBackend(Backend $backend) {
289
-		if ($this->userMountingAllowed &&
290
-			array_intersect($backend->getIdentifierAliases(), $this->userMountingBackends)
291
-		) {
292
-			return true;
293
-		}
294
-		return false;
295
-	}
296
-
297
-	/**
298
-	 * Check an authentication mechanism if a user is allowed to use it
299
-	 *
300
-	 * @param AuthMechanism $authMechanism
301
-	 * @return bool
302
-	 */
303
-	protected function isAllowedAuthMechanism(AuthMechanism $authMechanism) {
304
-		return true; // not implemented
305
-	}
306
-
307
-	/**
308
-	 * registers a configuration handler
309
-	 *
310
-	 * The function of the provided $placeholder is mostly to act a sorting
311
-	 * criteria, so longer placeholders are replaced first. This avoids
312
-	 * "$user" overwriting parts of "$userMail" and "$userLang", for example.
313
-	 * The provided value should not contain the $ prefix, only a-z0-9 are
314
-	 * allowed. Upper case letters are lower cased, the replacement is case-
315
-	 * insensitive.
316
-	 *
317
-	 * The configHandlerLoader should just instantiate the handler on demand.
318
-	 * For now all handlers are instantiated when a mount is loaded, independent
319
-	 * of whether the placeholder is present or not. This may change in future.
320
-	 *
321
-	 * @since 16.0.0
322
-	 */
323
-	public function registerConfigHandler(string $placeholder, callable $configHandlerLoader) {
324
-		$placeholder = trim(strtolower($placeholder));
325
-		if(!(bool)\preg_match('/^[a-z0-9]*$/', $placeholder)) {
326
-			throw new \RuntimeException(sprintf(
327
-				'Invalid placeholder %s, only [a-z0-9] are allowed', $placeholder
328
-			));
329
-		}
330
-		if($placeholder === '') {
331
-			throw new \RuntimeException('Invalid empty placeholder');
332
-		}
333
-		if(isset($this->configHandlerLoaders[$placeholder]) || isset($this->configHandlers[$placeholder])) {
334
-			throw new \RuntimeException(sprintf('A handler is already registered for %s', $placeholder));
335
-		}
336
-		$this->configHandlerLoaders[$placeholder] = $configHandlerLoader;
337
-	}
338
-
339
-	protected function loadConfigHandlers():void {
340
-		$this->callForRegistrations();
341
-		$newLoaded = false;
342
-		foreach ($this->configHandlerLoaders as $placeholder => $loader) {
343
-			$handler = $loader();
344
-			if(!$handler instanceof IConfigHandler) {
345
-				throw new \RuntimeException(sprintf(
346
-					'Handler for %s is not an instance of IConfigHandler', $placeholder
347
-				));
348
-			}
349
-			$this->configHandlers[$placeholder] = $handler;
350
-			$newLoaded = true;
351
-		}
352
-		$this->configHandlerLoaders = [];
353
-		if($newLoaded) {
354
-			// ensure those with longest placeholders come first,
355
-			// to avoid substring matches
356
-			uksort($this->configHandlers, function ($phA, $phB) {
357
-				return strlen($phB) <=> strlen($phA);
358
-			});
359
-		}
360
-	}
361
-
362
-	/**
363
-	 * @since 16.0.0
364
-	 */
365
-	public function getConfigHandlers() {
366
-		$this->loadConfigHandlers();
367
-		return $this->configHandlers;
368
-	}
43
+    /** Visibility constants for VisibilityTrait */
44
+    const VISIBILITY_NONE = 0;
45
+    const VISIBILITY_PERSONAL = 1;
46
+    const VISIBILITY_ADMIN = 2;
47
+    //const VISIBILITY_ALIENS = 4;
48
+
49
+    const VISIBILITY_DEFAULT = 3; // PERSONAL | ADMIN
50
+
51
+    /** Priority constants for PriorityTrait */
52
+    const PRIORITY_DEFAULT = 100;
53
+
54
+    /** @var IConfig */
55
+    protected $config;
56
+
57
+    /** @var bool */
58
+    private $userMountingAllowed = true;
59
+
60
+    /** @var string[] */
61
+    private $userMountingBackends = [];
62
+
63
+    /** @var Backend[] */
64
+    private $backends = [];
65
+
66
+    /** @var IBackendProvider[] */
67
+    private $backendProviders = [];
68
+
69
+    /** @var AuthMechanism[] */
70
+    private $authMechanisms = [];
71
+
72
+    /** @var IAuthMechanismProvider[] */
73
+    private $authMechanismProviders = [];
74
+
75
+    /** @var callable[] */
76
+    private $configHandlerLoaders = [];
77
+
78
+    private $configHandlers = [];
79
+
80
+    /**
81
+     * @param IConfig $config
82
+     */
83
+    public function __construct(
84
+        IConfig $config
85
+    ) {
86
+        $this->config = $config;
87
+
88
+        // Load config values
89
+        if ($this->config->getAppValue('files_external', 'allow_user_mounting', 'yes') !== 'yes') {
90
+            $this->userMountingAllowed = false;
91
+        }
92
+        $this->userMountingBackends = explode(',',
93
+            $this->config->getAppValue('files_external', 'user_mounting_backends', '')
94
+        );
95
+
96
+        // if no backend is in the list an empty string is in the array and user mounting is disabled
97
+        if ($this->userMountingBackends === ['']) {
98
+            $this->userMountingAllowed = false;
99
+        }
100
+    }
101
+
102
+    /**
103
+     * Register a backend provider
104
+     *
105
+     * @since 9.1.0
106
+     * @param IBackendProvider $provider
107
+     */
108
+    public function registerBackendProvider(IBackendProvider $provider) {
109
+        $this->backendProviders[] = $provider;
110
+    }
111
+
112
+    private function callForRegistrations() {
113
+        static $eventSent = false;
114
+        if(!$eventSent) {
115
+            \OC::$server->getEventDispatcher()->dispatch(
116
+                'OCA\\Files_External::loadAdditionalBackends',
117
+                new GenericEvent()
118
+            );
119
+            $eventSent = true;
120
+        }
121
+    }
122
+
123
+    private function loadBackendProviders() {
124
+        $this->callForRegistrations();
125
+        foreach ($this->backendProviders as $provider) {
126
+            $this->registerBackends($provider->getBackends());
127
+        }
128
+        $this->backendProviders = [];
129
+    }
130
+
131
+    /**
132
+     * Register an auth mechanism provider
133
+     *
134
+     * @since 9.1.0
135
+     * @param IAuthMechanismProvider $provider
136
+     */
137
+    public function registerAuthMechanismProvider(IAuthMechanismProvider $provider) {
138
+        $this->authMechanismProviders[] = $provider;
139
+    }
140
+
141
+    private function loadAuthMechanismProviders() {
142
+        $this->callForRegistrations();
143
+        foreach ($this->authMechanismProviders as $provider) {
144
+            $this->registerAuthMechanisms($provider->getAuthMechanisms());
145
+        }
146
+        $this->authMechanismProviders = [];
147
+    }
148
+
149
+    /**
150
+     * Register a backend
151
+     *
152
+     * @deprecated 9.1.0 use registerBackendProvider()
153
+     * @param Backend $backend
154
+     */
155
+    public function registerBackend(Backend $backend) {
156
+        if (!$this->isAllowedUserBackend($backend)) {
157
+            $backend->removeVisibility(BackendService::VISIBILITY_PERSONAL);
158
+        }
159
+        foreach ($backend->getIdentifierAliases() as $alias) {
160
+            $this->backends[$alias] = $backend;
161
+        }
162
+    }
163
+
164
+    /**
165
+     * @deprecated 9.1.0 use registerBackendProvider()
166
+     * @param Backend[] $backends
167
+     */
168
+    public function registerBackends(array $backends) {
169
+        foreach ($backends as $backend) {
170
+            $this->registerBackend($backend);
171
+        }
172
+    }
173
+    /**
174
+     * Register an authentication mechanism
175
+     *
176
+     * @deprecated 9.1.0 use registerAuthMechanismProvider()
177
+     * @param AuthMechanism $authMech
178
+     */
179
+    public function registerAuthMechanism(AuthMechanism $authMech) {
180
+        if (!$this->isAllowedAuthMechanism($authMech)) {
181
+            $authMech->removeVisibility(BackendService::VISIBILITY_PERSONAL);
182
+        }
183
+        foreach ($authMech->getIdentifierAliases() as $alias) {
184
+            $this->authMechanisms[$alias] = $authMech;
185
+        }
186
+    }
187
+
188
+    /**
189
+     * @deprecated 9.1.0 use registerAuthMechanismProvider()
190
+     * @param AuthMechanism[] $mechanisms
191
+     */
192
+    public function registerAuthMechanisms(array $mechanisms) {
193
+        foreach ($mechanisms as $mechanism) {
194
+            $this->registerAuthMechanism($mechanism);
195
+        }
196
+    }
197
+
198
+    /**
199
+     * Get all backends
200
+     *
201
+     * @return Backend[]
202
+     */
203
+    public function getBackends() {
204
+        $this->loadBackendProviders();
205
+        // only return real identifiers, no aliases
206
+        $backends = [];
207
+        foreach ($this->backends as $backend) {
208
+            $backends[$backend->getIdentifier()] = $backend;
209
+        }
210
+        return $backends;
211
+    }
212
+
213
+    /**
214
+     * Get all available backends
215
+     *
216
+     * @return Backend[]
217
+     */
218
+    public function getAvailableBackends() {
219
+        return array_filter($this->getBackends(), function ($backend) {
220
+            return !$backend->checkDependencies();
221
+        });
222
+    }
223
+
224
+    /**
225
+     * @param string $identifier
226
+     * @return Backend|null
227
+     */
228
+    public function getBackend($identifier) {
229
+        $this->loadBackendProviders();
230
+        if (isset($this->backends[$identifier])) {
231
+            return $this->backends[$identifier];
232
+        }
233
+        return null;
234
+    }
235
+
236
+    /**
237
+     * Get all authentication mechanisms
238
+     *
239
+     * @return AuthMechanism[]
240
+     */
241
+    public function getAuthMechanisms() {
242
+        $this->loadAuthMechanismProviders();
243
+        // only return real identifiers, no aliases
244
+        $mechanisms = [];
245
+        foreach ($this->authMechanisms as $mechanism) {
246
+            $mechanisms[$mechanism->getIdentifier()] = $mechanism;
247
+        }
248
+        return $mechanisms;
249
+    }
250
+
251
+    /**
252
+     * Get all authentication mechanisms for schemes
253
+     *
254
+     * @param string[] $schemes
255
+     * @return AuthMechanism[]
256
+     */
257
+    public function getAuthMechanismsByScheme(array $schemes) {
258
+        return array_filter($this->getAuthMechanisms(), function ($authMech) use ($schemes) {
259
+            return in_array($authMech->getScheme(), $schemes, true);
260
+        });
261
+    }
262
+
263
+    /**
264
+     * @param string $identifier
265
+     * @return AuthMechanism|null
266
+     */
267
+    public function getAuthMechanism($identifier) {
268
+        $this->loadAuthMechanismProviders();
269
+        if (isset($this->authMechanisms[$identifier])) {
270
+            return $this->authMechanisms[$identifier];
271
+        }
272
+        return null;
273
+    }
274
+
275
+    /**
276
+     * @return bool
277
+     */
278
+    public function isUserMountingAllowed() {
279
+        return $this->userMountingAllowed;
280
+    }
281
+
282
+    /**
283
+     * Check a backend if a user is allowed to mount it
284
+     *
285
+     * @param Backend $backend
286
+     * @return bool
287
+     */
288
+    protected function isAllowedUserBackend(Backend $backend) {
289
+        if ($this->userMountingAllowed &&
290
+            array_intersect($backend->getIdentifierAliases(), $this->userMountingBackends)
291
+        ) {
292
+            return true;
293
+        }
294
+        return false;
295
+    }
296
+
297
+    /**
298
+     * Check an authentication mechanism if a user is allowed to use it
299
+     *
300
+     * @param AuthMechanism $authMechanism
301
+     * @return bool
302
+     */
303
+    protected function isAllowedAuthMechanism(AuthMechanism $authMechanism) {
304
+        return true; // not implemented
305
+    }
306
+
307
+    /**
308
+     * registers a configuration handler
309
+     *
310
+     * The function of the provided $placeholder is mostly to act a sorting
311
+     * criteria, so longer placeholders are replaced first. This avoids
312
+     * "$user" overwriting parts of "$userMail" and "$userLang", for example.
313
+     * The provided value should not contain the $ prefix, only a-z0-9 are
314
+     * allowed. Upper case letters are lower cased, the replacement is case-
315
+     * insensitive.
316
+     *
317
+     * The configHandlerLoader should just instantiate the handler on demand.
318
+     * For now all handlers are instantiated when a mount is loaded, independent
319
+     * of whether the placeholder is present or not. This may change in future.
320
+     *
321
+     * @since 16.0.0
322
+     */
323
+    public function registerConfigHandler(string $placeholder, callable $configHandlerLoader) {
324
+        $placeholder = trim(strtolower($placeholder));
325
+        if(!(bool)\preg_match('/^[a-z0-9]*$/', $placeholder)) {
326
+            throw new \RuntimeException(sprintf(
327
+                'Invalid placeholder %s, only [a-z0-9] are allowed', $placeholder
328
+            ));
329
+        }
330
+        if($placeholder === '') {
331
+            throw new \RuntimeException('Invalid empty placeholder');
332
+        }
333
+        if(isset($this->configHandlerLoaders[$placeholder]) || isset($this->configHandlers[$placeholder])) {
334
+            throw new \RuntimeException(sprintf('A handler is already registered for %s', $placeholder));
335
+        }
336
+        $this->configHandlerLoaders[$placeholder] = $configHandlerLoader;
337
+    }
338
+
339
+    protected function loadConfigHandlers():void {
340
+        $this->callForRegistrations();
341
+        $newLoaded = false;
342
+        foreach ($this->configHandlerLoaders as $placeholder => $loader) {
343
+            $handler = $loader();
344
+            if(!$handler instanceof IConfigHandler) {
345
+                throw new \RuntimeException(sprintf(
346
+                    'Handler for %s is not an instance of IConfigHandler', $placeholder
347
+                ));
348
+            }
349
+            $this->configHandlers[$placeholder] = $handler;
350
+            $newLoaded = true;
351
+        }
352
+        $this->configHandlerLoaders = [];
353
+        if($newLoaded) {
354
+            // ensure those with longest placeholders come first,
355
+            // to avoid substring matches
356
+            uksort($this->configHandlers, function ($phA, $phB) {
357
+                return strlen($phB) <=> strlen($phA);
358
+            });
359
+        }
360
+    }
361
+
362
+    /**
363
+     * @since 16.0.0
364
+     */
365
+    public function getConfigHandlers() {
366
+        $this->loadConfigHandlers();
367
+        return $this->configHandlers;
368
+    }
369 369
 }
Please login to merge, or discard this patch.
apps/files_external/lib/AppInfo/Application.php 1 patch
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -71,115 +71,115 @@
 block discarded – undo
71 71
  */
72 72
 class Application extends App implements IBackendProvider, IAuthMechanismProvider {
73 73
 
74
-	/**
75
-	 * Application constructor.
76
-	 *
77
-	 * @throws \OCP\AppFramework\QueryException
78
-	 */
79
-	public function __construct(array $urlParams = []) {
80
-		parent::__construct('files_external', $urlParams);
81
-
82
-		$container = $this->getContainer();
83
-
84
-		/** @var BackendService $backendService */
85
-		$backendService = $container->query(BackendService::class);
86
-		$backendService->registerBackendProvider($this);
87
-		$backendService->registerAuthMechanismProvider($this);
88
-		$backendService->registerConfigHandler('user', function () use ($container) {
89
-			return $container->query(UserPlaceholderHandler::class);
90
-		});
91
-
92
-		// force-load auth mechanisms since some will register hooks
93
-		// TODO: obsolete these and use the TokenProvider to get the user's password from the session
94
-		$this->getAuthMechanisms();
95
-	}
96
-
97
-	public function registerListeners() {
98
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
99
-		$dispatcher->addListener(
100
-			IUser::class . '::postDelete',
101
-			function (GenericEvent $event) {
102
-				/** @var IUser $user */
103
-				$user = $event->getSubject();
104
-				/** @var DBConfigService $config */
105
-				$config = $this->getContainer()->query(DBConfigService::class);
106
-				$config->modifyMountsOnUserDelete($user->getUID());
107
-			}
108
-		);
109
-		$dispatcher->addListener(
110
-			IGroup::class . '::postDelete',
111
-			function (GenericEvent $event) {
112
-				/** @var IGroup $group */
113
-				$group = $event->getSubject();
114
-				/** @var DBConfigService $config */
115
-				$config = $this->getContainer()->query(DBConfigService::class);
116
-				$config->modifyMountsOnGroupDelete($group->getGID());
117
-			}
118
-		);
119
-	}
120
-
121
-	/**
122
-	 * @{inheritdoc}
123
-	 */
124
-	public function getBackends() {
125
-		$container = $this->getContainer();
126
-
127
-		$backends = [
128
-			$container->query(Local::class),
129
-			$container->query(FTP::class),
130
-			$container->query(DAV::class),
131
-			$container->query(OwnCloud::class),
132
-			$container->query(SFTP::class),
133
-			$container->query(AmazonS3::class),
134
-			$container->query(Swift::class),
135
-			$container->query(SFTP_Key::class),
136
-			$container->query(SMB::class),
137
-			$container->query(SMB_OC::class),
138
-		];
139
-
140
-		return $backends;
141
-	}
142
-
143
-	/**
144
-	 * @{inheritdoc}
145
-	 */
146
-	public function getAuthMechanisms() {
147
-		$container = $this->getContainer();
148
-
149
-		return [
150
-			// AuthMechanism::SCHEME_NULL mechanism
151
-			$container->query(NullMechanism::class),
152
-
153
-			// AuthMechanism::SCHEME_BUILTIN mechanism
154
-			$container->query(Builtin::class),
155
-
156
-			// AuthMechanism::SCHEME_PASSWORD mechanisms
157
-			$container->query(Password::class),
158
-			$container->query(SessionCredentials::class),
159
-			$container->query(LoginCredentials::class),
160
-			$container->query(UserProvided::class),
161
-			$container->query(GlobalAuth::class),
162
-			$container->query(UserGlobalAuth::class),
163
-
164
-			// AuthMechanism::SCHEME_OAUTH1 mechanisms
165
-			$container->query(OAuth1::class),
166
-
167
-			// AuthMechanism::SCHEME_OAUTH2 mechanisms
168
-			$container->query(OAuth2::class),
169
-
170
-			// AuthMechanism::SCHEME_PUBLICKEY mechanisms
171
-			$container->query(RSA::class),
172
-			$container->query(RSAPrivateKey::class),
173
-
174
-			// AuthMechanism::SCHEME_OPENSTACK mechanisms
175
-			$container->query(OpenStackV2::class),
176
-			$container->query(OpenStackV3::class),
177
-			$container->query(Rackspace::class),
178
-
179
-			// Specialized mechanisms
180
-			$container->query(AccessKey::class),
181
-			$container->query(KerberosAuth::class),
182
-		];
183
-	}
74
+    /**
75
+     * Application constructor.
76
+     *
77
+     * @throws \OCP\AppFramework\QueryException
78
+     */
79
+    public function __construct(array $urlParams = []) {
80
+        parent::__construct('files_external', $urlParams);
81
+
82
+        $container = $this->getContainer();
83
+
84
+        /** @var BackendService $backendService */
85
+        $backendService = $container->query(BackendService::class);
86
+        $backendService->registerBackendProvider($this);
87
+        $backendService->registerAuthMechanismProvider($this);
88
+        $backendService->registerConfigHandler('user', function () use ($container) {
89
+            return $container->query(UserPlaceholderHandler::class);
90
+        });
91
+
92
+        // force-load auth mechanisms since some will register hooks
93
+        // TODO: obsolete these and use the TokenProvider to get the user's password from the session
94
+        $this->getAuthMechanisms();
95
+    }
96
+
97
+    public function registerListeners() {
98
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
99
+        $dispatcher->addListener(
100
+            IUser::class . '::postDelete',
101
+            function (GenericEvent $event) {
102
+                /** @var IUser $user */
103
+                $user = $event->getSubject();
104
+                /** @var DBConfigService $config */
105
+                $config = $this->getContainer()->query(DBConfigService::class);
106
+                $config->modifyMountsOnUserDelete($user->getUID());
107
+            }
108
+        );
109
+        $dispatcher->addListener(
110
+            IGroup::class . '::postDelete',
111
+            function (GenericEvent $event) {
112
+                /** @var IGroup $group */
113
+                $group = $event->getSubject();
114
+                /** @var DBConfigService $config */
115
+                $config = $this->getContainer()->query(DBConfigService::class);
116
+                $config->modifyMountsOnGroupDelete($group->getGID());
117
+            }
118
+        );
119
+    }
120
+
121
+    /**
122
+     * @{inheritdoc}
123
+     */
124
+    public function getBackends() {
125
+        $container = $this->getContainer();
126
+
127
+        $backends = [
128
+            $container->query(Local::class),
129
+            $container->query(FTP::class),
130
+            $container->query(DAV::class),
131
+            $container->query(OwnCloud::class),
132
+            $container->query(SFTP::class),
133
+            $container->query(AmazonS3::class),
134
+            $container->query(Swift::class),
135
+            $container->query(SFTP_Key::class),
136
+            $container->query(SMB::class),
137
+            $container->query(SMB_OC::class),
138
+        ];
139
+
140
+        return $backends;
141
+    }
142
+
143
+    /**
144
+     * @{inheritdoc}
145
+     */
146
+    public function getAuthMechanisms() {
147
+        $container = $this->getContainer();
148
+
149
+        return [
150
+            // AuthMechanism::SCHEME_NULL mechanism
151
+            $container->query(NullMechanism::class),
152
+
153
+            // AuthMechanism::SCHEME_BUILTIN mechanism
154
+            $container->query(Builtin::class),
155
+
156
+            // AuthMechanism::SCHEME_PASSWORD mechanisms
157
+            $container->query(Password::class),
158
+            $container->query(SessionCredentials::class),
159
+            $container->query(LoginCredentials::class),
160
+            $container->query(UserProvided::class),
161
+            $container->query(GlobalAuth::class),
162
+            $container->query(UserGlobalAuth::class),
163
+
164
+            // AuthMechanism::SCHEME_OAUTH1 mechanisms
165
+            $container->query(OAuth1::class),
166
+
167
+            // AuthMechanism::SCHEME_OAUTH2 mechanisms
168
+            $container->query(OAuth2::class),
169
+
170
+            // AuthMechanism::SCHEME_PUBLICKEY mechanisms
171
+            $container->query(RSA::class),
172
+            $container->query(RSAPrivateKey::class),
173
+
174
+            // AuthMechanism::SCHEME_OPENSTACK mechanisms
175
+            $container->query(OpenStackV2::class),
176
+            $container->query(OpenStackV3::class),
177
+            $container->query(Rackspace::class),
178
+
179
+            // Specialized mechanisms
180
+            $container->query(AccessKey::class),
181
+            $container->query(KerberosAuth::class),
182
+        ];
183
+    }
184 184
 
185 185
 }
Please login to merge, or discard this patch.