Passed
Push — master ( 21b7e5...813bdc )
by Christoph
12:53 queued 10s
created
apps/user_ldap/lib/Command/DeleteConfig.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -33,39 +33,39 @@
 block discarded – undo
33 33
 use Symfony\Component\Console\Output\OutputInterface;
34 34
 
35 35
 class DeleteConfig extends Command {
36
-	/** @var \OCA\User_LDAP\Helper */
37
-	protected $helper;
36
+    /** @var \OCA\User_LDAP\Helper */
37
+    protected $helper;
38 38
 
39
-	/**
40
-	 * @param Helper $helper
41
-	 */
42
-	public function __construct(Helper $helper) {
43
-		$this->helper = $helper;
44
-		parent::__construct();
45
-	}
39
+    /**
40
+     * @param Helper $helper
41
+     */
42
+    public function __construct(Helper $helper) {
43
+        $this->helper = $helper;
44
+        parent::__construct();
45
+    }
46 46
 
47
-	protected function configure() {
48
-		$this
49
-			->setName('ldap:delete-config')
50
-			->setDescription('deletes an existing LDAP configuration')
51
-			->addArgument(
52
-					'configID',
53
-					InputArgument::REQUIRED,
54
-					'the configuration ID'
55
-					 )
56
-		;
57
-	}
47
+    protected function configure() {
48
+        $this
49
+            ->setName('ldap:delete-config')
50
+            ->setDescription('deletes an existing LDAP configuration')
51
+            ->addArgument(
52
+                    'configID',
53
+                    InputArgument::REQUIRED,
54
+                    'the configuration ID'
55
+                        )
56
+        ;
57
+    }
58 58
 
59 59
 
60
-	protected function execute(InputInterface $input, OutputInterface $output) {
61
-		$configPrefix = $input->getArgument('configID');
60
+    protected function execute(InputInterface $input, OutputInterface $output) {
61
+        $configPrefix = $input->getArgument('configID');
62 62
 
63
-		$success = $this->helper->deleteServerConfiguration($configPrefix);
63
+        $success = $this->helper->deleteServerConfiguration($configPrefix);
64 64
 
65
-		if($success) {
66
-			$output->writeln("Deleted configuration with configID '{$configPrefix}'");
67
-		} else {
68
-			$output->writeln("Cannot delete configuration with configID '{$configPrefix}'");
69
-		}
70
-	}
65
+        if($success) {
66
+            $output->writeln("Deleted configuration with configID '{$configPrefix}'");
67
+        } else {
68
+            $output->writeln("Cannot delete configuration with configID '{$configPrefix}'");
69
+        }
70
+    }
71 71
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/SetConfig.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -37,56 +37,56 @@
 block discarded – undo
37 37
 
38 38
 class SetConfig extends Command {
39 39
 
40
-	protected function configure() {
41
-		$this
42
-			->setName('ldap:set-config')
43
-			->setDescription('modifies an LDAP configuration')
44
-			->addArgument(
45
-					'configID',
46
-					InputArgument::REQUIRED,
47
-					'the configuration ID'
48
-					 )
49
-			->addArgument(
50
-					'configKey',
51
-					InputArgument::REQUIRED,
52
-					'the configuration key'
53
-					 )
54
-			->addArgument(
55
-					'configValue',
56
-					InputArgument::REQUIRED,
57
-					'the new configuration value'
58
-					 )
59
-		;
60
-	}
40
+    protected function configure() {
41
+        $this
42
+            ->setName('ldap:set-config')
43
+            ->setDescription('modifies an LDAP configuration')
44
+            ->addArgument(
45
+                    'configID',
46
+                    InputArgument::REQUIRED,
47
+                    'the configuration ID'
48
+                        )
49
+            ->addArgument(
50
+                    'configKey',
51
+                    InputArgument::REQUIRED,
52
+                    'the configuration key'
53
+                        )
54
+            ->addArgument(
55
+                    'configValue',
56
+                    InputArgument::REQUIRED,
57
+                    'the new configuration value'
58
+                        )
59
+        ;
60
+    }
61 61
 
62
-	protected function execute(InputInterface $input, OutputInterface $output) {
63
-		$helper = new Helper(\OC::$server->getConfig());
64
-		$availableConfigs = $helper->getServerConfigurationPrefixes();
65
-		$configID = $input->getArgument('configID');
66
-		if(!in_array($configID, $availableConfigs)) {
67
-			$output->writeln("Invalid configID");
68
-			return;
69
-		}
62
+    protected function execute(InputInterface $input, OutputInterface $output) {
63
+        $helper = new Helper(\OC::$server->getConfig());
64
+        $availableConfigs = $helper->getServerConfigurationPrefixes();
65
+        $configID = $input->getArgument('configID');
66
+        if(!in_array($configID, $availableConfigs)) {
67
+            $output->writeln("Invalid configID");
68
+            return;
69
+        }
70 70
 
71
-		$this->setValue(
72
-			$configID,
73
-			$input->getArgument('configKey'),
74
-			$input->getArgument('configValue')
75
-		);
76
-	}
71
+        $this->setValue(
72
+            $configID,
73
+            $input->getArgument('configKey'),
74
+            $input->getArgument('configValue')
75
+        );
76
+    }
77 77
 
78
-	/**
79
-	 * save the configuration value as provided
80
-	 * @param string $configID
81
-	 * @param string $configKey
82
-	 * @param string $configValue
83
-	 */
84
-	protected function setValue($configID, $key, $value) {
85
-		$configHolder = new Configuration($configID);
86
-		$configHolder->$key = $value;
87
-		$configHolder->saveConfiguration();
78
+    /**
79
+     * save the configuration value as provided
80
+     * @param string $configID
81
+     * @param string $configKey
82
+     * @param string $configValue
83
+     */
84
+    protected function setValue($configID, $key, $value) {
85
+        $configHolder = new Configuration($configID);
86
+        $configHolder->$key = $value;
87
+        $configHolder->saveConfiguration();
88 88
 
89
-		$connectionFactory = new ConnectionFactory(new LDAP());
90
-		$connectionFactory->get($configID)->clearCache();
91
-	}
89
+        $connectionFactory = new ConnectionFactory(new LDAP());
90
+        $connectionFactory->get($configID)->clearCache();
91
+    }
92 92
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/CheckUser.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -36,132 +36,132 @@
 block discarded – undo
36 36
 use Symfony\Component\Console\Output\OutputInterface;
37 37
 
38 38
 class CheckUser extends Command {
39
-	/** @var User_Proxy */
40
-	protected $backend;
41
-
42
-	/** @var Helper */
43
-	protected $helper;
44
-
45
-	/** @var DeletedUsersIndex */
46
-	protected $dui;
47
-
48
-	/** @var UserMapping */
49
-	protected $mapping;
50
-
51
-	/**
52
-	 * @param User_Proxy $uBackend
53
-	 * @param Helper $helper
54
-	 * @param DeletedUsersIndex $dui
55
-	 * @param UserMapping $mapping
56
-	 */
57
-	public function __construct(User_Proxy $uBackend, Helper $helper, DeletedUsersIndex $dui, UserMapping $mapping) {
58
-		$this->backend = $uBackend;
59
-		$this->helper = $helper;
60
-		$this->dui = $dui;
61
-		$this->mapping = $mapping;
62
-		parent::__construct();
63
-	}
64
-
65
-	protected function configure() {
66
-		$this
67
-			->setName('ldap:check-user')
68
-			->setDescription('checks whether a user exists on LDAP.')
69
-			->addArgument(
70
-					'ocName',
71
-					InputArgument::REQUIRED,
72
-					'the user name as used in Nextcloud'
73
-					 )
74
-			->addOption(
75
-					'force',
76
-					null,
77
-					InputOption::VALUE_NONE,
78
-					'ignores disabled LDAP configuration'
79
-					 )
80
-			->addOption(
81
-				'update',
82
-				null,
83
-				InputOption::VALUE_NONE,
84
-				'syncs values from LDAP'
85
-			)
86
-		;
87
-	}
88
-
89
-	protected function execute(InputInterface $input, OutputInterface $output) {
90
-		try {
91
-			$uid = $input->getArgument('ocName');
92
-			$this->isAllowed($input->getOption('force'));
93
-			$this->confirmUserIsMapped($uid);
94
-			$exists = $this->backend->userExistsOnLDAP($uid);
95
-			if($exists === true) {
96
-				$output->writeln('The user is still available on LDAP.');
97
-				if($input->getOption('update')) {
98
-					$this->updateUser($uid, $output);
99
-				}
100
-				return;
101
-			}
102
-
103
-			$this->dui->markUser($uid);
104
-			$output->writeln('The user does not exists on LDAP anymore.');
105
-			$output->writeln('Clean up the user\'s remnants by: ./occ user:delete "'
106
-				. $uid . '"');
107
-		} catch (\Exception $e) {
108
-			$output->writeln('<error>' . $e->getMessage(). '</error>');
109
-		}
110
-	}
111
-
112
-	/**
113
-	 * checks whether a user is actually mapped
114
-	 * @param string $ocName the username as used in Nextcloud
115
-	 * @throws \Exception
116
-	 * @return true
117
-	 */
118
-	protected function confirmUserIsMapped($ocName) {
119
-		$dn = $this->mapping->getDNByName($ocName);
120
-		if ($dn === false) {
121
-			throw new \Exception('The given user is not a recognized LDAP user.');
122
-		}
123
-
124
-		return true;
125
-	}
126
-
127
-	/**
128
-	 * checks whether the setup allows reliable checking of LDAP user existence
129
-	 * @throws \Exception
130
-	 * @return true
131
-	 */
132
-	protected function isAllowed($force) {
133
-		if($this->helper->haveDisabledConfigurations() && !$force) {
134
-			throw new \Exception('Cannot check user existence, because '
135
-				. 'disabled LDAP configurations are present.');
136
-		}
137
-
138
-		// we don't check ldapUserCleanupInterval from config.php because this
139
-		// action is triggered manually, while the setting only controls the
140
-		// background job.
141
-
142
-		return true;
143
-	}
144
-
145
-	private function updateUser(string $uid, OutputInterface $output): void {
146
-		try {
147
-			$access = $this->backend->getLDAPAccess($uid);
148
-			$attrs = $access->userManager->getAttributes();
149
-			$user = $access->userManager->get($uid);
150
-			$avatarAttributes = $access->getConnection()->resolveRule('avatar');
151
-			$result = $access->search('objectclass=*', [$user->getDN()], $attrs, 1, 0);
152
-			foreach ($result[0] as $attribute => $valueSet) {
153
-				$output->writeln('  ' . $attribute . ': ');
154
-				foreach ($valueSet as $value) {
155
-					if (in_array($attribute, $avatarAttributes)) {
156
-						$value = '{ImageData}';
157
-					}
158
-					$output->writeln('    ' . $value);
159
-				}
160
-			}
161
-			$access->batchApplyUserAttributes($result);
162
-		} catch (\Exception $e) {
163
-			$output->writeln('<error>Error while trying to lookup and update attributes from LDAP</error>');
164
-		}
165
-	}
39
+    /** @var User_Proxy */
40
+    protected $backend;
41
+
42
+    /** @var Helper */
43
+    protected $helper;
44
+
45
+    /** @var DeletedUsersIndex */
46
+    protected $dui;
47
+
48
+    /** @var UserMapping */
49
+    protected $mapping;
50
+
51
+    /**
52
+     * @param User_Proxy $uBackend
53
+     * @param Helper $helper
54
+     * @param DeletedUsersIndex $dui
55
+     * @param UserMapping $mapping
56
+     */
57
+    public function __construct(User_Proxy $uBackend, Helper $helper, DeletedUsersIndex $dui, UserMapping $mapping) {
58
+        $this->backend = $uBackend;
59
+        $this->helper = $helper;
60
+        $this->dui = $dui;
61
+        $this->mapping = $mapping;
62
+        parent::__construct();
63
+    }
64
+
65
+    protected function configure() {
66
+        $this
67
+            ->setName('ldap:check-user')
68
+            ->setDescription('checks whether a user exists on LDAP.')
69
+            ->addArgument(
70
+                    'ocName',
71
+                    InputArgument::REQUIRED,
72
+                    'the user name as used in Nextcloud'
73
+                        )
74
+            ->addOption(
75
+                    'force',
76
+                    null,
77
+                    InputOption::VALUE_NONE,
78
+                    'ignores disabled LDAP configuration'
79
+                        )
80
+            ->addOption(
81
+                'update',
82
+                null,
83
+                InputOption::VALUE_NONE,
84
+                'syncs values from LDAP'
85
+            )
86
+        ;
87
+    }
88
+
89
+    protected function execute(InputInterface $input, OutputInterface $output) {
90
+        try {
91
+            $uid = $input->getArgument('ocName');
92
+            $this->isAllowed($input->getOption('force'));
93
+            $this->confirmUserIsMapped($uid);
94
+            $exists = $this->backend->userExistsOnLDAP($uid);
95
+            if($exists === true) {
96
+                $output->writeln('The user is still available on LDAP.');
97
+                if($input->getOption('update')) {
98
+                    $this->updateUser($uid, $output);
99
+                }
100
+                return;
101
+            }
102
+
103
+            $this->dui->markUser($uid);
104
+            $output->writeln('The user does not exists on LDAP anymore.');
105
+            $output->writeln('Clean up the user\'s remnants by: ./occ user:delete "'
106
+                . $uid . '"');
107
+        } catch (\Exception $e) {
108
+            $output->writeln('<error>' . $e->getMessage(). '</error>');
109
+        }
110
+    }
111
+
112
+    /**
113
+     * checks whether a user is actually mapped
114
+     * @param string $ocName the username as used in Nextcloud
115
+     * @throws \Exception
116
+     * @return true
117
+     */
118
+    protected function confirmUserIsMapped($ocName) {
119
+        $dn = $this->mapping->getDNByName($ocName);
120
+        if ($dn === false) {
121
+            throw new \Exception('The given user is not a recognized LDAP user.');
122
+        }
123
+
124
+        return true;
125
+    }
126
+
127
+    /**
128
+     * checks whether the setup allows reliable checking of LDAP user existence
129
+     * @throws \Exception
130
+     * @return true
131
+     */
132
+    protected function isAllowed($force) {
133
+        if($this->helper->haveDisabledConfigurations() && !$force) {
134
+            throw new \Exception('Cannot check user existence, because '
135
+                . 'disabled LDAP configurations are present.');
136
+        }
137
+
138
+        // we don't check ldapUserCleanupInterval from config.php because this
139
+        // action is triggered manually, while the setting only controls the
140
+        // background job.
141
+
142
+        return true;
143
+    }
144
+
145
+    private function updateUser(string $uid, OutputInterface $output): void {
146
+        try {
147
+            $access = $this->backend->getLDAPAccess($uid);
148
+            $attrs = $access->userManager->getAttributes();
149
+            $user = $access->userManager->get($uid);
150
+            $avatarAttributes = $access->getConnection()->resolveRule('avatar');
151
+            $result = $access->search('objectclass=*', [$user->getDN()], $attrs, 1, 0);
152
+            foreach ($result[0] as $attribute => $valueSet) {
153
+                $output->writeln('  ' . $attribute . ': ');
154
+                foreach ($valueSet as $value) {
155
+                    if (in_array($attribute, $avatarAttributes)) {
156
+                        $value = '{ImageData}';
157
+                    }
158
+                    $output->writeln('    ' . $value);
159
+                }
160
+            }
161
+            $access->batchApplyUserAttributes($result);
162
+        } catch (\Exception $e) {
163
+            $output->writeln('<error>Error while trying to lookup and update attributes from LDAP</error>');
164
+        }
165
+    }
166 166
 
167 167
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/ShowConfig.php 1 patch
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -37,77 +37,77 @@
 block discarded – undo
37 37
 use Symfony\Component\Console\Output\OutputInterface;
38 38
 
39 39
 class ShowConfig extends Command {
40
-	/** @var \OCA\User_LDAP\Helper */
41
-	protected $helper;
40
+    /** @var \OCA\User_LDAP\Helper */
41
+    protected $helper;
42 42
 
43
-	/**
44
-	 * @param Helper $helper
45
-	 */
46
-	public function __construct(Helper $helper) {
47
-		$this->helper = $helper;
48
-		parent::__construct();
49
-	}
43
+    /**
44
+     * @param Helper $helper
45
+     */
46
+    public function __construct(Helper $helper) {
47
+        $this->helper = $helper;
48
+        parent::__construct();
49
+    }
50 50
 
51
-	protected function configure() {
52
-		$this
53
-			->setName('ldap:show-config')
54
-			->setDescription('shows the LDAP configuration')
55
-			->addArgument(
56
-					'configID',
57
-					InputArgument::OPTIONAL,
58
-					'will show the configuration of the specified id'
59
-					 )
60
-			->addOption(
61
-					'show-password',
62
-					null,
63
-					InputOption::VALUE_NONE,
64
-					'show ldap bind password'
65
-					 )
66
-		;
67
-	}
51
+    protected function configure() {
52
+        $this
53
+            ->setName('ldap:show-config')
54
+            ->setDescription('shows the LDAP configuration')
55
+            ->addArgument(
56
+                    'configID',
57
+                    InputArgument::OPTIONAL,
58
+                    'will show the configuration of the specified id'
59
+                        )
60
+            ->addOption(
61
+                    'show-password',
62
+                    null,
63
+                    InputOption::VALUE_NONE,
64
+                    'show ldap bind password'
65
+                        )
66
+        ;
67
+    }
68 68
 
69
-	protected function execute(InputInterface $input, OutputInterface $output) {
70
-		$availableConfigs = $this->helper->getServerConfigurationPrefixes();
71
-		$configID = $input->getArgument('configID');
72
-		if(!is_null($configID)) {
73
-			$configIDs[] = $configID;
74
-			if(!in_array($configIDs[0], $availableConfigs)) {
75
-				$output->writeln("Invalid configID");
76
-				return;
77
-			}
78
-		} else {
79
-			$configIDs = $availableConfigs;
80
-		}
69
+    protected function execute(InputInterface $input, OutputInterface $output) {
70
+        $availableConfigs = $this->helper->getServerConfigurationPrefixes();
71
+        $configID = $input->getArgument('configID');
72
+        if(!is_null($configID)) {
73
+            $configIDs[] = $configID;
74
+            if(!in_array($configIDs[0], $availableConfigs)) {
75
+                $output->writeln("Invalid configID");
76
+                return;
77
+            }
78
+        } else {
79
+            $configIDs = $availableConfigs;
80
+        }
81 81
 
82
-		$this->renderConfigs($configIDs, $output, $input->getOption('show-password'));
83
-	}
82
+        $this->renderConfigs($configIDs, $output, $input->getOption('show-password'));
83
+    }
84 84
 
85
-	/**
86
-	 * prints the LDAP configuration(s)
87
-	 * @param string[] configID(s)
88
-	 * @param OutputInterface $output
89
-	 * @param bool $withPassword      Set to TRUE to show plaintext passwords in output
90
-	 */
91
-	protected function renderConfigs($configIDs, $output, $withPassword) {
92
-		foreach($configIDs as $id) {
93
-			$configHolder = new Configuration($id);
94
-			$configuration = $configHolder->getConfiguration();
95
-			ksort($configuration);
85
+    /**
86
+     * prints the LDAP configuration(s)
87
+     * @param string[] configID(s)
88
+     * @param OutputInterface $output
89
+     * @param bool $withPassword      Set to TRUE to show plaintext passwords in output
90
+     */
91
+    protected function renderConfigs($configIDs, $output, $withPassword) {
92
+        foreach($configIDs as $id) {
93
+            $configHolder = new Configuration($id);
94
+            $configuration = $configHolder->getConfiguration();
95
+            ksort($configuration);
96 96
 
97
-			$table = new Table($output);
98
-			$table->setHeaders(['Configuration', $id]);
99
-			$rows = [];
100
-			foreach($configuration as $key => $value) {
101
-				if($key === 'ldapAgentPassword' && !$withPassword) {
102
-					$value = '***';
103
-				}
104
-				if(is_array($value)) {
105
-					$value = implode(';', $value);
106
-				}
107
-				$rows[] = [$key, $value];
108
-			}
109
-			$table->setRows($rows);
110
-			$table->render($output);
111
-		}
112
-	}
97
+            $table = new Table($output);
98
+            $table->setHeaders(['Configuration', $id]);
99
+            $rows = [];
100
+            foreach($configuration as $key => $value) {
101
+                if($key === 'ldapAgentPassword' && !$withPassword) {
102
+                    $value = '***';
103
+                }
104
+                if(is_array($value)) {
105
+                    $value = implode(';', $value);
106
+                }
107
+                $rows[] = [$key, $value];
108
+            }
109
+            $table->setRows($rows);
110
+            $table->render($output);
111
+        }
112
+    }
113 113
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/TestConfig.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -36,59 +36,59 @@
 block discarded – undo
36 36
 
37 37
 class TestConfig extends Command {
38 38
 
39
-	protected function configure() {
40
-		$this
41
-			->setName('ldap:test-config')
42
-			->setDescription('tests an LDAP configuration')
43
-			->addArgument(
44
-					'configID',
45
-					InputArgument::REQUIRED,
46
-					'the configuration ID'
47
-					 )
48
-		;
49
-	}
39
+    protected function configure() {
40
+        $this
41
+            ->setName('ldap:test-config')
42
+            ->setDescription('tests an LDAP configuration')
43
+            ->addArgument(
44
+                    'configID',
45
+                    InputArgument::REQUIRED,
46
+                    'the configuration ID'
47
+                        )
48
+        ;
49
+    }
50 50
 
51
-	protected function execute(InputInterface $input, OutputInterface $output) {
52
-		$helper = new Helper(\OC::$server->getConfig());
53
-		$availableConfigs = $helper->getServerConfigurationPrefixes();
54
-		$configID = $input->getArgument('configID');
55
-		if(!in_array($configID, $availableConfigs)) {
56
-			$output->writeln("Invalid configID");
57
-			return;
58
-		}
51
+    protected function execute(InputInterface $input, OutputInterface $output) {
52
+        $helper = new Helper(\OC::$server->getConfig());
53
+        $availableConfigs = $helper->getServerConfigurationPrefixes();
54
+        $configID = $input->getArgument('configID');
55
+        if(!in_array($configID, $availableConfigs)) {
56
+            $output->writeln("Invalid configID");
57
+            return;
58
+        }
59 59
 
60
-		$result = $this->testConfig($configID);
61
-		if($result === 0) {
62
-			$output->writeln('The configuration is valid and the connection could be established!');
63
-		} else if($result === 1) {
64
-			$output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
65
-		} else if($result === 2) {
66
-			$output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.');
67
-		} else {
68
-			$output->writeln('Your LDAP server was kidnapped by aliens.');
69
-		}
70
-	}
60
+        $result = $this->testConfig($configID);
61
+        if($result === 0) {
62
+            $output->writeln('The configuration is valid and the connection could be established!');
63
+        } else if($result === 1) {
64
+            $output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
65
+        } else if($result === 2) {
66
+            $output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.');
67
+        } else {
68
+            $output->writeln('Your LDAP server was kidnapped by aliens.');
69
+        }
70
+    }
71 71
 
72
-	/**
73
-	 * tests the specified connection
74
-	 * @param string $configID
75
-	 * @return int
76
-	 */
77
-	protected function testConfig($configID) {
78
-		$lw = new \OCA\User_LDAP\LDAP();
79
-		$connection = new Connection($lw, $configID);
72
+    /**
73
+     * tests the specified connection
74
+     * @param string $configID
75
+     * @return int
76
+     */
77
+    protected function testConfig($configID) {
78
+        $lw = new \OCA\User_LDAP\LDAP();
79
+        $connection = new Connection($lw, $configID);
80 80
 
81
-		//ensure validation is run before we attempt the bind
82
-		$connection->getConfiguration();
81
+        //ensure validation is run before we attempt the bind
82
+        $connection->getConfiguration();
83 83
 
84
-		if(!$connection->setConfiguration([
85
-			'ldap_configuration_active' => 1,
86
-		])) {
87
-			return 1;
88
-		}
89
-		if($connection->bind()) {
90
-			return 0;
91
-		}
92
-		return 2;
93
-	}
84
+        if(!$connection->setConfiguration([
85
+            'ldap_configuration_active' => 1,
86
+        ])) {
87
+            return 1;
88
+        }
89
+        if($connection->bind()) {
90
+            return 0;
91
+        }
92
+        return 2;
93
+    }
94 94
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/Search.php 1 patch
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -40,105 +40,105 @@
 block discarded – undo
40 40
 use Symfony\Component\Console\Output\OutputInterface;
41 41
 
42 42
 class Search extends Command {
43
-	/** @var \OCP\IConfig */
44
-	protected $ocConfig;
43
+    /** @var \OCP\IConfig */
44
+    protected $ocConfig;
45 45
 
46
-	/**
47
-	 * @param \OCP\IConfig $ocConfig
48
-	 */
49
-	public function __construct(IConfig $ocConfig) {
50
-		$this->ocConfig = $ocConfig;
51
-		parent::__construct();
52
-	}
46
+    /**
47
+     * @param \OCP\IConfig $ocConfig
48
+     */
49
+    public function __construct(IConfig $ocConfig) {
50
+        $this->ocConfig = $ocConfig;
51
+        parent::__construct();
52
+    }
53 53
 
54
-	protected function configure() {
55
-		$this
56
-			->setName('ldap:search')
57
-			->setDescription('executes a user or group search')
58
-			->addArgument(
59
-					'search',
60
-					InputArgument::REQUIRED,
61
-					'the search string (can be empty)'
62
-					 )
63
-			->addOption(
64
-					'group',
65
-					null,
66
-					InputOption::VALUE_NONE,
67
-					'searches groups instead of users'
68
-					 )
69
-			->addOption(
70
-					'offset',
71
-					null,
72
-					InputOption::VALUE_REQUIRED,
73
-					'The offset of the result set. Needs to be a multiple of limit. defaults to 0.',
74
-					0
75
-					 )
76
-			->addOption(
77
-					'limit',
78
-					null,
79
-					InputOption::VALUE_REQUIRED,
80
-					'limit the results. 0 means no limit, defaults to 15',
81
-					15
82
-					 )
83
-		;
84
-	}
54
+    protected function configure() {
55
+        $this
56
+            ->setName('ldap:search')
57
+            ->setDescription('executes a user or group search')
58
+            ->addArgument(
59
+                    'search',
60
+                    InputArgument::REQUIRED,
61
+                    'the search string (can be empty)'
62
+                        )
63
+            ->addOption(
64
+                    'group',
65
+                    null,
66
+                    InputOption::VALUE_NONE,
67
+                    'searches groups instead of users'
68
+                        )
69
+            ->addOption(
70
+                    'offset',
71
+                    null,
72
+                    InputOption::VALUE_REQUIRED,
73
+                    'The offset of the result set. Needs to be a multiple of limit. defaults to 0.',
74
+                    0
75
+                        )
76
+            ->addOption(
77
+                    'limit',
78
+                    null,
79
+                    InputOption::VALUE_REQUIRED,
80
+                    'limit the results. 0 means no limit, defaults to 15',
81
+                    15
82
+                        )
83
+        ;
84
+    }
85 85
 
86
-	/**
87
-	 * Tests whether the offset and limit options are valid
88
-	 * @param int $offset
89
-	 * @param int $limit
90
-	 * @throws \InvalidArgumentException
91
-	 */
92
-	protected function validateOffsetAndLimit($offset, $limit) {
93
-		if($limit < 0) {
94
-			throw new \InvalidArgumentException('limit must be  0 or greater');
95
-		}
96
-		if($offset  < 0) {
97
-			throw new \InvalidArgumentException('offset must be 0 or greater');
98
-		}
99
-		if($limit === 0 && $offset !== 0) {
100
-			throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0');
101
-		}
102
-		if($offset > 0 && ($offset % $limit !== 0)) {
103
-			throw new \InvalidArgumentException('offset must be a multiple of limit');
104
-		}
105
-	}
86
+    /**
87
+     * Tests whether the offset and limit options are valid
88
+     * @param int $offset
89
+     * @param int $limit
90
+     * @throws \InvalidArgumentException
91
+     */
92
+    protected function validateOffsetAndLimit($offset, $limit) {
93
+        if($limit < 0) {
94
+            throw new \InvalidArgumentException('limit must be  0 or greater');
95
+        }
96
+        if($offset  < 0) {
97
+            throw new \InvalidArgumentException('offset must be 0 or greater');
98
+        }
99
+        if($limit === 0 && $offset !== 0) {
100
+            throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0');
101
+        }
102
+        if($offset > 0 && ($offset % $limit !== 0)) {
103
+            throw new \InvalidArgumentException('offset must be a multiple of limit');
104
+        }
105
+    }
106 106
 
107
-	protected function execute(InputInterface $input, OutputInterface $output) {
108
-		$helper = new Helper($this->ocConfig);
109
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
110
-		$ldapWrapper = new LDAP();
107
+    protected function execute(InputInterface $input, OutputInterface $output) {
108
+        $helper = new Helper($this->ocConfig);
109
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
110
+        $ldapWrapper = new LDAP();
111 111
 
112
-		$offset = (int)$input->getOption('offset');
113
-		$limit = (int)$input->getOption('limit');
114
-		$this->validateOffsetAndLimit($offset, $limit);
112
+        $offset = (int)$input->getOption('offset');
113
+        $limit = (int)$input->getOption('limit');
114
+        $this->validateOffsetAndLimit($offset, $limit);
115 115
 
116
-		if($input->getOption('group')) {
117
-			$proxy = new Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
118
-			$getMethod = 'getGroups';
119
-			$printID = false;
120
-			// convert the limit of groups to null. This will show all the groups available instead of
121
-			// nothing, and will match the same behaviour the search for users has.
122
-			if ($limit === 0) {
123
-				$limit = null;
124
-			}
125
-		} else {
126
-			$proxy = new User_Proxy(
127
-				$configPrefixes,
128
-				$ldapWrapper,
129
-				$this->ocConfig,
130
-				\OC::$server->getNotificationManager(),
131
-				\OC::$server->getUserSession(),
132
-				\OC::$server->query('LDAPUserPluginManager')
133
-			);
134
-			$getMethod = 'getDisplayNames';
135
-			$printID = true;
136
-		}
116
+        if($input->getOption('group')) {
117
+            $proxy = new Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
118
+            $getMethod = 'getGroups';
119
+            $printID = false;
120
+            // convert the limit of groups to null. This will show all the groups available instead of
121
+            // nothing, and will match the same behaviour the search for users has.
122
+            if ($limit === 0) {
123
+                $limit = null;
124
+            }
125
+        } else {
126
+            $proxy = new User_Proxy(
127
+                $configPrefixes,
128
+                $ldapWrapper,
129
+                $this->ocConfig,
130
+                \OC::$server->getNotificationManager(),
131
+                \OC::$server->getUserSession(),
132
+                \OC::$server->query('LDAPUserPluginManager')
133
+            );
134
+            $getMethod = 'getDisplayNames';
135
+            $printID = true;
136
+        }
137 137
 
138
-		$result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset);
139
-		foreach($result as $id => $name) {
140
-			$line = $name . ($printID ? ' ('.$id.')' : '');
141
-			$output->writeln($line);
142
-		}
143
-	}
138
+        $result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset);
139
+        foreach($result as $id => $name) {
140
+            $line = $name . ($printID ? ' ('.$id.')' : '');
141
+            $output->writeln($line);
142
+        }
143
+    }
144 144
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/User.php 2 patches
Indentation   +741 added lines, -741 removed lines patch added patch discarded remove patch
@@ -51,745 +51,745 @@
 block discarded – undo
51 51
  * represents an LDAP user, gets and holds user-specific information from LDAP
52 52
  */
53 53
 class User {
54
-	/**
55
-	 * @var Access
56
-	 */
57
-	protected $access;
58
-	/**
59
-	 * @var Connection
60
-	 */
61
-	protected $connection;
62
-	/**
63
-	 * @var IConfig
64
-	 */
65
-	protected $config;
66
-	/**
67
-	 * @var FilesystemHelper
68
-	 */
69
-	protected $fs;
70
-	/**
71
-	 * @var Image
72
-	 */
73
-	protected $image;
74
-	/**
75
-	 * @var LogWrapper
76
-	 */
77
-	protected $log;
78
-	/**
79
-	 * @var IAvatarManager
80
-	 */
81
-	protected $avatarManager;
82
-	/**
83
-	 * @var IUserManager
84
-	 */
85
-	protected $userManager;
86
-	/**
87
-	 * @var INotificationManager
88
-	 */
89
-	protected $notificationManager;
90
-	/**
91
-	 * @var string
92
-	 */
93
-	protected $dn;
94
-	/**
95
-	 * @var string
96
-	 */
97
-	protected $uid;
98
-	/**
99
-	 * @var string[]
100
-	 */
101
-	protected $refreshedFeatures = [];
102
-	/**
103
-	 * @var string
104
-	 */
105
-	protected $avatarImage;
106
-
107
-	/**
108
-	 * DB config keys for user preferences
109
-	 */
110
-	const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
111
-	const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
112
-
113
-	/**
114
-	 * @brief constructor, make sure the subclasses call this one!
115
-	 * @param string $username the internal username
116
-	 * @param string $dn the LDAP DN
117
-	 * @param Access $access
118
-	 * @param IConfig $config
119
-	 * @param FilesystemHelper $fs
120
-	 * @param Image $image any empty instance
121
-	 * @param LogWrapper $log
122
-	 * @param IAvatarManager $avatarManager
123
-	 * @param IUserManager $userManager
124
-	 * @param INotificationManager $notificationManager
125
-	 */
126
-	public function __construct($username, $dn, Access $access,
127
-		IConfig $config, FilesystemHelper $fs, Image $image,
128
-		LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
129
-		INotificationManager $notificationManager) {
130
-
131
-		if ($username === null) {
132
-			$log->log("uid for '$dn' must not be null!", ILogger::ERROR);
133
-			throw new \InvalidArgumentException('uid must not be null!');
134
-		} else if ($username === '') {
135
-			$log->log("uid for '$dn' must not be an empty string", ILogger::ERROR);
136
-			throw new \InvalidArgumentException('uid must not be an empty string!');
137
-		}
138
-
139
-		$this->access              = $access;
140
-		$this->connection          = $access->getConnection();
141
-		$this->config              = $config;
142
-		$this->fs                  = $fs;
143
-		$this->dn                  = $dn;
144
-		$this->uid                 = $username;
145
-		$this->image               = $image;
146
-		$this->log                 = $log;
147
-		$this->avatarManager       = $avatarManager;
148
-		$this->userManager         = $userManager;
149
-		$this->notificationManager = $notificationManager;
150
-
151
-		\OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
152
-	}
153
-
154
-	/**
155
-	 * @brief updates properties like email, quota or avatar provided by LDAP
156
-	 * @return null
157
-	 */
158
-	public function update() {
159
-		if(is_null($this->dn)) {
160
-			return null;
161
-		}
162
-
163
-		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
164
-				self::USER_PREFKEY_FIRSTLOGIN, 0);
165
-
166
-		if($this->needsRefresh()) {
167
-			$this->updateEmail();
168
-			$this->updateQuota();
169
-			if($hasLoggedIn !== 0) {
170
-				//we do not need to try it, when the user has not been logged in
171
-				//before, because the file system will not be ready.
172
-				$this->updateAvatar();
173
-				//in order to get an avatar as soon as possible, mark the user
174
-				//as refreshed only when updating the avatar did happen
175
-				$this->markRefreshTime();
176
-			}
177
-		}
178
-	}
179
-
180
-	/**
181
-	 * marks a user as deleted
182
-	 *
183
-	 * @throws \OCP\PreConditionNotMetException
184
-	 */
185
-	public function markUser() {
186
-		$curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
187
-		if($curValue === '1') {
188
-			// the user is already marked, do not write to DB again
189
-			return;
190
-		}
191
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
192
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
193
-	}
194
-
195
-	/**
196
-	 * processes results from LDAP for attributes as returned by getAttributesToRead()
197
-	 * @param array $ldapEntry the user entry as retrieved from LDAP
198
-	 */
199
-	public function processAttributes($ldapEntry) {
200
-		$this->markRefreshTime();
201
-		//Quota
202
-		$attr = strtolower($this->connection->ldapQuotaAttribute);
203
-		if(isset($ldapEntry[$attr])) {
204
-			$this->updateQuota($ldapEntry[$attr][0]);
205
-		} else {
206
-			if ($this->connection->ldapQuotaDefault !== '') {
207
-				$this->updateQuota();
208
-			}
209
-		}
210
-		unset($attr);
211
-
212
-		//displayName
213
-		$displayName = $displayName2 = '';
214
-		$attr = strtolower($this->connection->ldapUserDisplayName);
215
-		if(isset($ldapEntry[$attr])) {
216
-			$displayName = (string)$ldapEntry[$attr][0];
217
-		}
218
-		$attr = strtolower($this->connection->ldapUserDisplayName2);
219
-		if(isset($ldapEntry[$attr])) {
220
-			$displayName2 = (string)$ldapEntry[$attr][0];
221
-		}
222
-		if ($displayName !== '') {
223
-			$this->composeAndStoreDisplayName($displayName, $displayName2);
224
-			$this->access->cacheUserDisplayName(
225
-				$this->getUsername(),
226
-				$displayName,
227
-				$displayName2
228
-			);
229
-		}
230
-		unset($attr);
231
-
232
-		//Email
233
-		//email must be stored after displayname, because it would cause a user
234
-		//change event that will trigger fetching the display name again
235
-		$attr = strtolower($this->connection->ldapEmailAttribute);
236
-		if(isset($ldapEntry[$attr])) {
237
-			$this->updateEmail($ldapEntry[$attr][0]);
238
-		}
239
-		unset($attr);
240
-
241
-		// LDAP Username, needed for s2s sharing
242
-		if(isset($ldapEntry['uid'])) {
243
-			$this->storeLDAPUserName($ldapEntry['uid'][0]);
244
-		} else if(isset($ldapEntry['samaccountname'])) {
245
-			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
246
-		}
247
-
248
-		//homePath
249
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
250
-			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
251
-			if(isset($ldapEntry[$attr])) {
252
-				$this->access->cacheUserHome(
253
-					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
254
-			}
255
-		}
256
-
257
-		//memberOf groups
258
-		$cacheKey = 'getMemberOf'.$this->getUsername();
259
-		$groups = false;
260
-		if(isset($ldapEntry['memberof'])) {
261
-			$groups = $ldapEntry['memberof'];
262
-		}
263
-		$this->connection->writeToCache($cacheKey, $groups);
264
-
265
-		//external storage var
266
-		$attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
267
-		if(isset($ldapEntry[$attr])) {
268
-			$this->updateExtStorageHome($ldapEntry[$attr][0]);
269
-		}
270
-		unset($attr);
271
-
272
-		//Avatar
273
-		/** @var Connection $connection */
274
-		$connection = $this->access->getConnection();
275
-		$attributes = $connection->resolveRule('avatar');
276
-		foreach ($attributes as $attribute)  {
277
-			if(isset($ldapEntry[$attribute])) {
278
-				$this->avatarImage = $ldapEntry[$attribute][0];
279
-				// the call to the method that saves the avatar in the file
280
-				// system must be postponed after the login. It is to ensure
281
-				// external mounts are mounted properly (e.g. with login
282
-				// credentials from the session).
283
-				\OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
284
-				break;
285
-			}
286
-		}
287
-	}
288
-
289
-	/**
290
-	 * @brief returns the LDAP DN of the user
291
-	 * @return string
292
-	 */
293
-	public function getDN() {
294
-		return $this->dn;
295
-	}
296
-
297
-	/**
298
-	 * @brief returns the Nextcloud internal username of the user
299
-	 * @return string
300
-	 */
301
-	public function getUsername() {
302
-		return $this->uid;
303
-	}
304
-
305
-	/**
306
-	 * returns the home directory of the user if specified by LDAP settings
307
-	 * @param string $valueFromLDAP
308
-	 * @return bool|string
309
-	 * @throws \Exception
310
-	 */
311
-	public function getHomePath($valueFromLDAP = null) {
312
-		$path = (string)$valueFromLDAP;
313
-		$attr = null;
314
-
315
-		if (is_null($valueFromLDAP)
316
-		   && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
317
-		   && $this->access->connection->homeFolderNamingRule !== 'attr:')
318
-		{
319
-			$attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
320
-			$homedir = $this->access->readAttribute(
321
-				$this->access->username2dn($this->getUsername()), $attr);
322
-			if ($homedir && isset($homedir[0])) {
323
-				$path = $homedir[0];
324
-			}
325
-		}
326
-
327
-		if ($path !== '') {
328
-			//if attribute's value is an absolute path take this, otherwise append it to data dir
329
-			//check for / at the beginning or pattern c:\ resp. c:/
330
-			if(   '/' !== $path[0]
331
-			   && !(3 < strlen($path) && ctype_alpha($path[0])
332
-				   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
333
-			) {
334
-				$path = $this->config->getSystemValue('datadirectory',
335
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
336
-			}
337
-			//we need it to store it in the DB as well in case a user gets
338
-			//deleted so we can clean up afterwards
339
-			$this->config->setUserValue(
340
-				$this->getUsername(), 'user_ldap', 'homePath', $path
341
-			);
342
-			return $path;
343
-		}
344
-
345
-		if(    !is_null($attr)
346
-			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
347
-		) {
348
-			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
349
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
350
-		}
351
-
352
-		//false will apply default behaviour as defined and done by OC_User
353
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
354
-		return false;
355
-	}
356
-
357
-	public function getMemberOfGroups() {
358
-		$cacheKey = 'getMemberOf'.$this->getUsername();
359
-		$memberOfGroups = $this->connection->getFromCache($cacheKey);
360
-		if(!is_null($memberOfGroups)) {
361
-			return $memberOfGroups;
362
-		}
363
-		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
364
-		$this->connection->writeToCache($cacheKey, $groupDNs);
365
-		return $groupDNs;
366
-	}
367
-
368
-	/**
369
-	 * @brief reads the image from LDAP that shall be used as Avatar
370
-	 * @return string data (provided by LDAP) | false
371
-	 */
372
-	public function getAvatarImage() {
373
-		if(!is_null($this->avatarImage)) {
374
-			return $this->avatarImage;
375
-		}
376
-
377
-		$this->avatarImage = false;
378
-		/** @var Connection $connection */
379
-		$connection = $this->access->getConnection();
380
-		$attributes = $connection->resolveRule('avatar');
381
-		foreach($attributes as $attribute) {
382
-			$result = $this->access->readAttribute($this->dn, $attribute);
383
-			if($result !== false && is_array($result) && isset($result[0])) {
384
-				$this->avatarImage = $result[0];
385
-				break;
386
-			}
387
-		}
388
-
389
-		return $this->avatarImage;
390
-	}
391
-
392
-	/**
393
-	 * @brief marks the user as having logged in at least once
394
-	 * @return null
395
-	 */
396
-	public function markLogin() {
397
-		$this->config->setUserValue(
398
-			$this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
399
-	}
400
-
401
-	/**
402
-	 * @brief marks the time when user features like email have been updated
403
-	 * @return null
404
-	 */
405
-	public function markRefreshTime() {
406
-		$this->config->setUserValue(
407
-			$this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
408
-	}
409
-
410
-	/**
411
-	 * @brief checks whether user features needs to be updated again by
412
-	 * comparing the difference of time of the last refresh to now with the
413
-	 * desired interval
414
-	 * @return bool
415
-	 */
416
-	private function needsRefresh() {
417
-		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
418
-			self::USER_PREFKEY_LASTREFRESH, 0);
419
-
420
-		if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
421
-			return false;
422
-		}
423
-		return  true;
424
-	}
425
-
426
-	/**
427
-	 * Stores a key-value pair in relation to this user
428
-	 *
429
-	 * @param string $key
430
-	 * @param string $value
431
-	 */
432
-	private function store($key, $value) {
433
-		$this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
434
-	}
435
-
436
-	/**
437
-	 * Composes the display name and stores it in the database. The final
438
-	 * display name is returned.
439
-	 *
440
-	 * @param string $displayName
441
-	 * @param string $displayName2
442
-	 * @return string the effective display name
443
-	 */
444
-	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
445
-		$displayName2 = (string)$displayName2;
446
-		if($displayName2 !== '') {
447
-			$displayName .= ' (' . $displayName2 . ')';
448
-		}
449
-		$oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
450
-		if ($oldName !== $displayName)  {
451
-			$this->store('displayName', $displayName);
452
-			$user = $this->userManager->get($this->getUsername());
453
-			if (!empty($oldName) && $user instanceof \OC\User\User) {
454
-				// if it was empty, it would be a new record, not a change emitting the trigger could
455
-				// potentially cause a UniqueConstraintViolationException, depending on some factors.
456
-				$user->triggerChange('displayName', $displayName, $oldName);
457
-			}
458
-		}
459
-		return $displayName;
460
-	}
461
-
462
-	/**
463
-	 * Stores the LDAP Username in the Database
464
-	 * @param string $userName
465
-	 */
466
-	public function storeLDAPUserName($userName) {
467
-		$this->store('uid', $userName);
468
-	}
469
-
470
-	/**
471
-	 * @brief checks whether an update method specified by feature was run
472
-	 * already. If not, it will marked like this, because it is expected that
473
-	 * the method will be run, when false is returned.
474
-	 * @param string $feature email | quota | avatar (can be extended)
475
-	 * @return bool
476
-	 */
477
-	private function wasRefreshed($feature) {
478
-		if(isset($this->refreshedFeatures[$feature])) {
479
-			return true;
480
-		}
481
-		$this->refreshedFeatures[$feature] = 1;
482
-		return false;
483
-	}
484
-
485
-	/**
486
-	 * fetches the email from LDAP and stores it as Nextcloud user value
487
-	 * @param string $valueFromLDAP if known, to save an LDAP read request
488
-	 * @return null
489
-	 */
490
-	public function updateEmail($valueFromLDAP = null) {
491
-		if($this->wasRefreshed('email')) {
492
-			return;
493
-		}
494
-		$email = (string)$valueFromLDAP;
495
-		if(is_null($valueFromLDAP)) {
496
-			$emailAttribute = $this->connection->ldapEmailAttribute;
497
-			if ($emailAttribute !== '') {
498
-				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
499
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
500
-					$email = (string)$aEmail[0];
501
-				}
502
-			}
503
-		}
504
-		if ($email !== '') {
505
-			$user = $this->userManager->get($this->uid);
506
-			if (!is_null($user)) {
507
-				$currentEmail = (string)$user->getEMailAddress();
508
-				if ($currentEmail !== $email) {
509
-					$user->setEMailAddress($email);
510
-				}
511
-			}
512
-		}
513
-	}
514
-
515
-	/**
516
-	 * Overall process goes as follow:
517
-	 * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
518
-	 * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
519
-	 * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
520
-	 * 4. check if the target user exists and set the quota for the user.
521
-	 *
522
-	 * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
523
-	 * parameter can be passed with the value of the attribute. This value will be considered as the
524
-	 * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
525
-	 * fetch all the user's attributes in one call and use the fetched values in this function.
526
-	 * The expected value for that parameter is a string describing the quota for the user. Valid
527
-	 * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
528
-	 * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
529
-	 *
530
-	 * fetches the quota from LDAP and stores it as Nextcloud user value
531
-	 * @param string $valueFromLDAP the quota attribute's value can be passed,
532
-	 * to save the readAttribute request
533
-	 * @return null
534
-	 */
535
-	public function updateQuota($valueFromLDAP = null) {
536
-		if($this->wasRefreshed('quota')) {
537
-			return;
538
-		}
539
-
540
-		$quotaAttribute = $this->connection->ldapQuotaAttribute;
541
-		$defaultQuota = $this->connection->ldapQuotaDefault;
542
-		if($quotaAttribute === '' && $defaultQuota === '') {
543
-			return;
544
-		}
545
-
546
-		$quota = false;
547
-		if(is_null($valueFromLDAP) && $quotaAttribute !== '') {
548
-			$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
549
-			if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
550
-				$quota = $aQuota[0];
551
-			} else if(is_array($aQuota) && isset($aQuota[0])) {
552
-				$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG);
553
-			}
554
-		} else if ($this->verifyQuotaValue($valueFromLDAP)) {
555
-			$quota = $valueFromLDAP;
556
-		} else {
557
-			$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG);
558
-		}
559
-
560
-		if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
561
-			// quota not found using the LDAP attribute (or not parseable). Try the default quota
562
-			$quota = $defaultQuota;
563
-		} else if($quota === false) {
564
-			$this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG);
565
-			return;
566
-		}
567
-
568
-		$targetUser = $this->userManager->get($this->uid);
569
-		if ($targetUser instanceof IUser) {
570
-			$targetUser->setQuota($quota);
571
-		} else {
572
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO);
573
-		}
574
-	}
575
-
576
-	private function verifyQuotaValue($quotaValue) {
577
-		return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
578
-	}
579
-
580
-	/**
581
-	 * called by a post_login hook to save the avatar picture
582
-	 *
583
-	 * @param array $params
584
-	 */
585
-	public function updateAvatarPostLogin($params) {
586
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
587
-			$this->updateAvatar();
588
-		}
589
-	}
590
-
591
-	/**
592
-	 * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
593
-	 * @return bool
594
-	 */
595
-	public function updateAvatar($force = false) {
596
-		if(!$force && $this->wasRefreshed('avatar')) {
597
-			return false;
598
-		}
599
-		$avatarImage = $this->getAvatarImage();
600
-		if($avatarImage === false) {
601
-			//not set, nothing left to do;
602
-			return false;
603
-		}
604
-
605
-		if(!$this->image->loadFromBase64(base64_encode($avatarImage))) {
606
-			return false;
607
-		}
608
-
609
-		// use the checksum before modifications
610
-		$checksum = md5($this->image->data());
611
-
612
-		if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
613
-			return true;
614
-		}
615
-
616
-		$isSet = $this->setOwnCloudAvatar();
617
-
618
-		if($isSet) {
619
-			// save checksum only after successful setting
620
-			$this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
621
-		}
622
-
623
-		return $isSet;
624
-	}
625
-
626
-	/**
627
-	 * @brief sets an image as Nextcloud avatar
628
-	 * @return bool
629
-	 */
630
-	private function setOwnCloudAvatar() {
631
-		if(!$this->image->valid()) {
632
-			$this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR);
633
-			return false;
634
-		}
635
-
636
-
637
-		//make sure it is a square and not bigger than 128x128
638
-		$size = min([$this->image->width(), $this->image->height(), 128]);
639
-		if(!$this->image->centerCrop($size)) {
640
-			$this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR);
641
-			return false;
642
-		}
643
-
644
-		if(!$this->fs->isLoaded()) {
645
-			$this->fs->setup($this->uid);
646
-		}
647
-
648
-		try {
649
-			$avatar = $this->avatarManager->getAvatar($this->uid);
650
-			$avatar->set($this->image);
651
-			return true;
652
-		} catch (\Exception $e) {
653
-			\OC::$server->getLogger()->logException($e, [
654
-				'message' => 'Could not set avatar for ' . $this->dn,
655
-				'level' => ILogger::INFO,
656
-				'app' => 'user_ldap',
657
-			]);
658
-		}
659
-		return false;
660
-	}
661
-
662
-	/**
663
-	 * @throws AttributeNotSet
664
-	 * @throws \OC\ServerNotAvailableException
665
-	 * @throws \OCP\PreConditionNotMetException
666
-	 */
667
-	public function getExtStorageHome():string {
668
-		$value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
669
-		if ($value !== '') {
670
-			return $value;
671
-		}
672
-
673
-		$value = $this->updateExtStorageHome();
674
-		if ($value !== '') {
675
-			return $value;
676
-		}
677
-
678
-		throw new AttributeNotSet(sprintf(
679
-			'external home storage attribute yield no value for %s', $this->getUsername()
680
-		));
681
-	}
682
-
683
-	/**
684
-	 * @throws \OCP\PreConditionNotMetException
685
-	 * @throws \OC\ServerNotAvailableException
686
-	 */
687
-	public function updateExtStorageHome(string $valueFromLDAP = null):string {
688
-		if ($valueFromLDAP === null) {
689
-			$extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
690
-		} else {
691
-			$extHomeValues = [$valueFromLDAP];
692
-		}
693
-		if ($extHomeValues && isset($extHomeValues[0])) {
694
-			$extHome = $extHomeValues[0];
695
-			$this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
696
-			return $extHome;
697
-		} else {
698
-			$this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
699
-			return '';
700
-		}
701
-	}
702
-
703
-	/**
704
-	 * called by a post_login hook to handle password expiry
705
-	 *
706
-	 * @param array $params
707
-	 */
708
-	public function handlePasswordExpiry($params) {
709
-		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
710
-		if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
711
-			return;//password expiry handling disabled
712
-		}
713
-		$uid = $params['uid'];
714
-		if (isset($uid) && $uid === $this->getUsername()) {
715
-			//retrieve relevant user attributes
716
-			$result = $this->access->search('objectclass=*', [$this->dn], ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
717
-
718
-			if (array_key_exists('pwdpolicysubentry', $result[0])) {
719
-				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
720
-				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
721
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
722
-				}
723
-			}
724
-
725
-			$pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
726
-			$pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
727
-			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
728
-
729
-			//retrieve relevant password policy attributes
730
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
731
-			$result = $this->connection->getFromCache($cacheKey);
732
-			if(is_null($result)) {
733
-				$result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
734
-				$this->connection->writeToCache($cacheKey, $result);
735
-			}
736
-
737
-			$pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
738
-			$pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
739
-			$pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
740
-
741
-			//handle grace login
742
-			if (!empty($pwdGraceUseTime)) { //was this a grace login?
743
-				if (!empty($pwdGraceAuthNLimit)
744
-					&& count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
745
-					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
746
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
747
-					'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
748
-				} else { //no more grace login available
749
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
750
-					'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
751
-				}
752
-				exit();
753
-			}
754
-			//handle pwdReset attribute
755
-			if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
756
-				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
757
-				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
758
-				'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
759
-				exit();
760
-			}
761
-			//handle password expiry warning
762
-			if (!empty($pwdChangedTime)) {
763
-				if (!empty($pwdMaxAge)
764
-					&& !empty($pwdExpireWarning)) {
765
-					$pwdMaxAgeInt = (int)$pwdMaxAge[0];
766
-					$pwdExpireWarningInt = (int)$pwdExpireWarning[0];
767
-					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
768
-						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
769
-						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
770
-						$currentDateTime = new \DateTime();
771
-						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
772
-						if ($secondsToExpiry <= $pwdExpireWarningInt) {
773
-							//remove last password expiry warning if any
774
-							$notification = $this->notificationManager->createNotification();
775
-							$notification->setApp('user_ldap')
776
-								->setUser($uid)
777
-								->setObject('pwd_exp_warn', $uid)
778
-							;
779
-							$this->notificationManager->markProcessed($notification);
780
-							//create new password expiry warning
781
-							$notification = $this->notificationManager->createNotification();
782
-							$notification->setApp('user_ldap')
783
-								->setUser($uid)
784
-								->setDateTime($currentDateTime)
785
-								->setObject('pwd_exp_warn', $uid)
786
-								->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
787
-							;
788
-							$this->notificationManager->notify($notification);
789
-						}
790
-					}
791
-				}
792
-			}
793
-		}
794
-	}
54
+    /**
55
+     * @var Access
56
+     */
57
+    protected $access;
58
+    /**
59
+     * @var Connection
60
+     */
61
+    protected $connection;
62
+    /**
63
+     * @var IConfig
64
+     */
65
+    protected $config;
66
+    /**
67
+     * @var FilesystemHelper
68
+     */
69
+    protected $fs;
70
+    /**
71
+     * @var Image
72
+     */
73
+    protected $image;
74
+    /**
75
+     * @var LogWrapper
76
+     */
77
+    protected $log;
78
+    /**
79
+     * @var IAvatarManager
80
+     */
81
+    protected $avatarManager;
82
+    /**
83
+     * @var IUserManager
84
+     */
85
+    protected $userManager;
86
+    /**
87
+     * @var INotificationManager
88
+     */
89
+    protected $notificationManager;
90
+    /**
91
+     * @var string
92
+     */
93
+    protected $dn;
94
+    /**
95
+     * @var string
96
+     */
97
+    protected $uid;
98
+    /**
99
+     * @var string[]
100
+     */
101
+    protected $refreshedFeatures = [];
102
+    /**
103
+     * @var string
104
+     */
105
+    protected $avatarImage;
106
+
107
+    /**
108
+     * DB config keys for user preferences
109
+     */
110
+    const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
111
+    const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
112
+
113
+    /**
114
+     * @brief constructor, make sure the subclasses call this one!
115
+     * @param string $username the internal username
116
+     * @param string $dn the LDAP DN
117
+     * @param Access $access
118
+     * @param IConfig $config
119
+     * @param FilesystemHelper $fs
120
+     * @param Image $image any empty instance
121
+     * @param LogWrapper $log
122
+     * @param IAvatarManager $avatarManager
123
+     * @param IUserManager $userManager
124
+     * @param INotificationManager $notificationManager
125
+     */
126
+    public function __construct($username, $dn, Access $access,
127
+        IConfig $config, FilesystemHelper $fs, Image $image,
128
+        LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
129
+        INotificationManager $notificationManager) {
130
+
131
+        if ($username === null) {
132
+            $log->log("uid for '$dn' must not be null!", ILogger::ERROR);
133
+            throw new \InvalidArgumentException('uid must not be null!');
134
+        } else if ($username === '') {
135
+            $log->log("uid for '$dn' must not be an empty string", ILogger::ERROR);
136
+            throw new \InvalidArgumentException('uid must not be an empty string!');
137
+        }
138
+
139
+        $this->access              = $access;
140
+        $this->connection          = $access->getConnection();
141
+        $this->config              = $config;
142
+        $this->fs                  = $fs;
143
+        $this->dn                  = $dn;
144
+        $this->uid                 = $username;
145
+        $this->image               = $image;
146
+        $this->log                 = $log;
147
+        $this->avatarManager       = $avatarManager;
148
+        $this->userManager         = $userManager;
149
+        $this->notificationManager = $notificationManager;
150
+
151
+        \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
152
+    }
153
+
154
+    /**
155
+     * @brief updates properties like email, quota or avatar provided by LDAP
156
+     * @return null
157
+     */
158
+    public function update() {
159
+        if(is_null($this->dn)) {
160
+            return null;
161
+        }
162
+
163
+        $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
164
+                self::USER_PREFKEY_FIRSTLOGIN, 0);
165
+
166
+        if($this->needsRefresh()) {
167
+            $this->updateEmail();
168
+            $this->updateQuota();
169
+            if($hasLoggedIn !== 0) {
170
+                //we do not need to try it, when the user has not been logged in
171
+                //before, because the file system will not be ready.
172
+                $this->updateAvatar();
173
+                //in order to get an avatar as soon as possible, mark the user
174
+                //as refreshed only when updating the avatar did happen
175
+                $this->markRefreshTime();
176
+            }
177
+        }
178
+    }
179
+
180
+    /**
181
+     * marks a user as deleted
182
+     *
183
+     * @throws \OCP\PreConditionNotMetException
184
+     */
185
+    public function markUser() {
186
+        $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
187
+        if($curValue === '1') {
188
+            // the user is already marked, do not write to DB again
189
+            return;
190
+        }
191
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
192
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
193
+    }
194
+
195
+    /**
196
+     * processes results from LDAP for attributes as returned by getAttributesToRead()
197
+     * @param array $ldapEntry the user entry as retrieved from LDAP
198
+     */
199
+    public function processAttributes($ldapEntry) {
200
+        $this->markRefreshTime();
201
+        //Quota
202
+        $attr = strtolower($this->connection->ldapQuotaAttribute);
203
+        if(isset($ldapEntry[$attr])) {
204
+            $this->updateQuota($ldapEntry[$attr][0]);
205
+        } else {
206
+            if ($this->connection->ldapQuotaDefault !== '') {
207
+                $this->updateQuota();
208
+            }
209
+        }
210
+        unset($attr);
211
+
212
+        //displayName
213
+        $displayName = $displayName2 = '';
214
+        $attr = strtolower($this->connection->ldapUserDisplayName);
215
+        if(isset($ldapEntry[$attr])) {
216
+            $displayName = (string)$ldapEntry[$attr][0];
217
+        }
218
+        $attr = strtolower($this->connection->ldapUserDisplayName2);
219
+        if(isset($ldapEntry[$attr])) {
220
+            $displayName2 = (string)$ldapEntry[$attr][0];
221
+        }
222
+        if ($displayName !== '') {
223
+            $this->composeAndStoreDisplayName($displayName, $displayName2);
224
+            $this->access->cacheUserDisplayName(
225
+                $this->getUsername(),
226
+                $displayName,
227
+                $displayName2
228
+            );
229
+        }
230
+        unset($attr);
231
+
232
+        //Email
233
+        //email must be stored after displayname, because it would cause a user
234
+        //change event that will trigger fetching the display name again
235
+        $attr = strtolower($this->connection->ldapEmailAttribute);
236
+        if(isset($ldapEntry[$attr])) {
237
+            $this->updateEmail($ldapEntry[$attr][0]);
238
+        }
239
+        unset($attr);
240
+
241
+        // LDAP Username, needed for s2s sharing
242
+        if(isset($ldapEntry['uid'])) {
243
+            $this->storeLDAPUserName($ldapEntry['uid'][0]);
244
+        } else if(isset($ldapEntry['samaccountname'])) {
245
+            $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
246
+        }
247
+
248
+        //homePath
249
+        if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
250
+            $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
251
+            if(isset($ldapEntry[$attr])) {
252
+                $this->access->cacheUserHome(
253
+                    $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
254
+            }
255
+        }
256
+
257
+        //memberOf groups
258
+        $cacheKey = 'getMemberOf'.$this->getUsername();
259
+        $groups = false;
260
+        if(isset($ldapEntry['memberof'])) {
261
+            $groups = $ldapEntry['memberof'];
262
+        }
263
+        $this->connection->writeToCache($cacheKey, $groups);
264
+
265
+        //external storage var
266
+        $attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
267
+        if(isset($ldapEntry[$attr])) {
268
+            $this->updateExtStorageHome($ldapEntry[$attr][0]);
269
+        }
270
+        unset($attr);
271
+
272
+        //Avatar
273
+        /** @var Connection $connection */
274
+        $connection = $this->access->getConnection();
275
+        $attributes = $connection->resolveRule('avatar');
276
+        foreach ($attributes as $attribute)  {
277
+            if(isset($ldapEntry[$attribute])) {
278
+                $this->avatarImage = $ldapEntry[$attribute][0];
279
+                // the call to the method that saves the avatar in the file
280
+                // system must be postponed after the login. It is to ensure
281
+                // external mounts are mounted properly (e.g. with login
282
+                // credentials from the session).
283
+                \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
284
+                break;
285
+            }
286
+        }
287
+    }
288
+
289
+    /**
290
+     * @brief returns the LDAP DN of the user
291
+     * @return string
292
+     */
293
+    public function getDN() {
294
+        return $this->dn;
295
+    }
296
+
297
+    /**
298
+     * @brief returns the Nextcloud internal username of the user
299
+     * @return string
300
+     */
301
+    public function getUsername() {
302
+        return $this->uid;
303
+    }
304
+
305
+    /**
306
+     * returns the home directory of the user if specified by LDAP settings
307
+     * @param string $valueFromLDAP
308
+     * @return bool|string
309
+     * @throws \Exception
310
+     */
311
+    public function getHomePath($valueFromLDAP = null) {
312
+        $path = (string)$valueFromLDAP;
313
+        $attr = null;
314
+
315
+        if (is_null($valueFromLDAP)
316
+           && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
317
+           && $this->access->connection->homeFolderNamingRule !== 'attr:')
318
+        {
319
+            $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
320
+            $homedir = $this->access->readAttribute(
321
+                $this->access->username2dn($this->getUsername()), $attr);
322
+            if ($homedir && isset($homedir[0])) {
323
+                $path = $homedir[0];
324
+            }
325
+        }
326
+
327
+        if ($path !== '') {
328
+            //if attribute's value is an absolute path take this, otherwise append it to data dir
329
+            //check for / at the beginning or pattern c:\ resp. c:/
330
+            if(   '/' !== $path[0]
331
+               && !(3 < strlen($path) && ctype_alpha($path[0])
332
+                   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
333
+            ) {
334
+                $path = $this->config->getSystemValue('datadirectory',
335
+                        \OC::$SERVERROOT.'/data' ) . '/' . $path;
336
+            }
337
+            //we need it to store it in the DB as well in case a user gets
338
+            //deleted so we can clean up afterwards
339
+            $this->config->setUserValue(
340
+                $this->getUsername(), 'user_ldap', 'homePath', $path
341
+            );
342
+            return $path;
343
+        }
344
+
345
+        if(    !is_null($attr)
346
+            && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
347
+        ) {
348
+            // a naming rule attribute is defined, but it doesn't exist for that LDAP user
349
+            throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
350
+        }
351
+
352
+        //false will apply default behaviour as defined and done by OC_User
353
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
354
+        return false;
355
+    }
356
+
357
+    public function getMemberOfGroups() {
358
+        $cacheKey = 'getMemberOf'.$this->getUsername();
359
+        $memberOfGroups = $this->connection->getFromCache($cacheKey);
360
+        if(!is_null($memberOfGroups)) {
361
+            return $memberOfGroups;
362
+        }
363
+        $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
364
+        $this->connection->writeToCache($cacheKey, $groupDNs);
365
+        return $groupDNs;
366
+    }
367
+
368
+    /**
369
+     * @brief reads the image from LDAP that shall be used as Avatar
370
+     * @return string data (provided by LDAP) | false
371
+     */
372
+    public function getAvatarImage() {
373
+        if(!is_null($this->avatarImage)) {
374
+            return $this->avatarImage;
375
+        }
376
+
377
+        $this->avatarImage = false;
378
+        /** @var Connection $connection */
379
+        $connection = $this->access->getConnection();
380
+        $attributes = $connection->resolveRule('avatar');
381
+        foreach($attributes as $attribute) {
382
+            $result = $this->access->readAttribute($this->dn, $attribute);
383
+            if($result !== false && is_array($result) && isset($result[0])) {
384
+                $this->avatarImage = $result[0];
385
+                break;
386
+            }
387
+        }
388
+
389
+        return $this->avatarImage;
390
+    }
391
+
392
+    /**
393
+     * @brief marks the user as having logged in at least once
394
+     * @return null
395
+     */
396
+    public function markLogin() {
397
+        $this->config->setUserValue(
398
+            $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
399
+    }
400
+
401
+    /**
402
+     * @brief marks the time when user features like email have been updated
403
+     * @return null
404
+     */
405
+    public function markRefreshTime() {
406
+        $this->config->setUserValue(
407
+            $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
408
+    }
409
+
410
+    /**
411
+     * @brief checks whether user features needs to be updated again by
412
+     * comparing the difference of time of the last refresh to now with the
413
+     * desired interval
414
+     * @return bool
415
+     */
416
+    private function needsRefresh() {
417
+        $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
418
+            self::USER_PREFKEY_LASTREFRESH, 0);
419
+
420
+        if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
421
+            return false;
422
+        }
423
+        return  true;
424
+    }
425
+
426
+    /**
427
+     * Stores a key-value pair in relation to this user
428
+     *
429
+     * @param string $key
430
+     * @param string $value
431
+     */
432
+    private function store($key, $value) {
433
+        $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
434
+    }
435
+
436
+    /**
437
+     * Composes the display name and stores it in the database. The final
438
+     * display name is returned.
439
+     *
440
+     * @param string $displayName
441
+     * @param string $displayName2
442
+     * @return string the effective display name
443
+     */
444
+    public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
445
+        $displayName2 = (string)$displayName2;
446
+        if($displayName2 !== '') {
447
+            $displayName .= ' (' . $displayName2 . ')';
448
+        }
449
+        $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
450
+        if ($oldName !== $displayName)  {
451
+            $this->store('displayName', $displayName);
452
+            $user = $this->userManager->get($this->getUsername());
453
+            if (!empty($oldName) && $user instanceof \OC\User\User) {
454
+                // if it was empty, it would be a new record, not a change emitting the trigger could
455
+                // potentially cause a UniqueConstraintViolationException, depending on some factors.
456
+                $user->triggerChange('displayName', $displayName, $oldName);
457
+            }
458
+        }
459
+        return $displayName;
460
+    }
461
+
462
+    /**
463
+     * Stores the LDAP Username in the Database
464
+     * @param string $userName
465
+     */
466
+    public function storeLDAPUserName($userName) {
467
+        $this->store('uid', $userName);
468
+    }
469
+
470
+    /**
471
+     * @brief checks whether an update method specified by feature was run
472
+     * already. If not, it will marked like this, because it is expected that
473
+     * the method will be run, when false is returned.
474
+     * @param string $feature email | quota | avatar (can be extended)
475
+     * @return bool
476
+     */
477
+    private function wasRefreshed($feature) {
478
+        if(isset($this->refreshedFeatures[$feature])) {
479
+            return true;
480
+        }
481
+        $this->refreshedFeatures[$feature] = 1;
482
+        return false;
483
+    }
484
+
485
+    /**
486
+     * fetches the email from LDAP and stores it as Nextcloud user value
487
+     * @param string $valueFromLDAP if known, to save an LDAP read request
488
+     * @return null
489
+     */
490
+    public function updateEmail($valueFromLDAP = null) {
491
+        if($this->wasRefreshed('email')) {
492
+            return;
493
+        }
494
+        $email = (string)$valueFromLDAP;
495
+        if(is_null($valueFromLDAP)) {
496
+            $emailAttribute = $this->connection->ldapEmailAttribute;
497
+            if ($emailAttribute !== '') {
498
+                $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
499
+                if(is_array($aEmail) && (count($aEmail) > 0)) {
500
+                    $email = (string)$aEmail[0];
501
+                }
502
+            }
503
+        }
504
+        if ($email !== '') {
505
+            $user = $this->userManager->get($this->uid);
506
+            if (!is_null($user)) {
507
+                $currentEmail = (string)$user->getEMailAddress();
508
+                if ($currentEmail !== $email) {
509
+                    $user->setEMailAddress($email);
510
+                }
511
+            }
512
+        }
513
+    }
514
+
515
+    /**
516
+     * Overall process goes as follow:
517
+     * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
518
+     * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
519
+     * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
520
+     * 4. check if the target user exists and set the quota for the user.
521
+     *
522
+     * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
523
+     * parameter can be passed with the value of the attribute. This value will be considered as the
524
+     * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
525
+     * fetch all the user's attributes in one call and use the fetched values in this function.
526
+     * The expected value for that parameter is a string describing the quota for the user. Valid
527
+     * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
528
+     * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
529
+     *
530
+     * fetches the quota from LDAP and stores it as Nextcloud user value
531
+     * @param string $valueFromLDAP the quota attribute's value can be passed,
532
+     * to save the readAttribute request
533
+     * @return null
534
+     */
535
+    public function updateQuota($valueFromLDAP = null) {
536
+        if($this->wasRefreshed('quota')) {
537
+            return;
538
+        }
539
+
540
+        $quotaAttribute = $this->connection->ldapQuotaAttribute;
541
+        $defaultQuota = $this->connection->ldapQuotaDefault;
542
+        if($quotaAttribute === '' && $defaultQuota === '') {
543
+            return;
544
+        }
545
+
546
+        $quota = false;
547
+        if(is_null($valueFromLDAP) && $quotaAttribute !== '') {
548
+            $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
549
+            if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
550
+                $quota = $aQuota[0];
551
+            } else if(is_array($aQuota) && isset($aQuota[0])) {
552
+                $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG);
553
+            }
554
+        } else if ($this->verifyQuotaValue($valueFromLDAP)) {
555
+            $quota = $valueFromLDAP;
556
+        } else {
557
+            $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG);
558
+        }
559
+
560
+        if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
561
+            // quota not found using the LDAP attribute (or not parseable). Try the default quota
562
+            $quota = $defaultQuota;
563
+        } else if($quota === false) {
564
+            $this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG);
565
+            return;
566
+        }
567
+
568
+        $targetUser = $this->userManager->get($this->uid);
569
+        if ($targetUser instanceof IUser) {
570
+            $targetUser->setQuota($quota);
571
+        } else {
572
+            $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO);
573
+        }
574
+    }
575
+
576
+    private function verifyQuotaValue($quotaValue) {
577
+        return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
578
+    }
579
+
580
+    /**
581
+     * called by a post_login hook to save the avatar picture
582
+     *
583
+     * @param array $params
584
+     */
585
+    public function updateAvatarPostLogin($params) {
586
+        if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
587
+            $this->updateAvatar();
588
+        }
589
+    }
590
+
591
+    /**
592
+     * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
593
+     * @return bool
594
+     */
595
+    public function updateAvatar($force = false) {
596
+        if(!$force && $this->wasRefreshed('avatar')) {
597
+            return false;
598
+        }
599
+        $avatarImage = $this->getAvatarImage();
600
+        if($avatarImage === false) {
601
+            //not set, nothing left to do;
602
+            return false;
603
+        }
604
+
605
+        if(!$this->image->loadFromBase64(base64_encode($avatarImage))) {
606
+            return false;
607
+        }
608
+
609
+        // use the checksum before modifications
610
+        $checksum = md5($this->image->data());
611
+
612
+        if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
613
+            return true;
614
+        }
615
+
616
+        $isSet = $this->setOwnCloudAvatar();
617
+
618
+        if($isSet) {
619
+            // save checksum only after successful setting
620
+            $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
621
+        }
622
+
623
+        return $isSet;
624
+    }
625
+
626
+    /**
627
+     * @brief sets an image as Nextcloud avatar
628
+     * @return bool
629
+     */
630
+    private function setOwnCloudAvatar() {
631
+        if(!$this->image->valid()) {
632
+            $this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR);
633
+            return false;
634
+        }
635
+
636
+
637
+        //make sure it is a square and not bigger than 128x128
638
+        $size = min([$this->image->width(), $this->image->height(), 128]);
639
+        if(!$this->image->centerCrop($size)) {
640
+            $this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR);
641
+            return false;
642
+        }
643
+
644
+        if(!$this->fs->isLoaded()) {
645
+            $this->fs->setup($this->uid);
646
+        }
647
+
648
+        try {
649
+            $avatar = $this->avatarManager->getAvatar($this->uid);
650
+            $avatar->set($this->image);
651
+            return true;
652
+        } catch (\Exception $e) {
653
+            \OC::$server->getLogger()->logException($e, [
654
+                'message' => 'Could not set avatar for ' . $this->dn,
655
+                'level' => ILogger::INFO,
656
+                'app' => 'user_ldap',
657
+            ]);
658
+        }
659
+        return false;
660
+    }
661
+
662
+    /**
663
+     * @throws AttributeNotSet
664
+     * @throws \OC\ServerNotAvailableException
665
+     * @throws \OCP\PreConditionNotMetException
666
+     */
667
+    public function getExtStorageHome():string {
668
+        $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
669
+        if ($value !== '') {
670
+            return $value;
671
+        }
672
+
673
+        $value = $this->updateExtStorageHome();
674
+        if ($value !== '') {
675
+            return $value;
676
+        }
677
+
678
+        throw new AttributeNotSet(sprintf(
679
+            'external home storage attribute yield no value for %s', $this->getUsername()
680
+        ));
681
+    }
682
+
683
+    /**
684
+     * @throws \OCP\PreConditionNotMetException
685
+     * @throws \OC\ServerNotAvailableException
686
+     */
687
+    public function updateExtStorageHome(string $valueFromLDAP = null):string {
688
+        if ($valueFromLDAP === null) {
689
+            $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
690
+        } else {
691
+            $extHomeValues = [$valueFromLDAP];
692
+        }
693
+        if ($extHomeValues && isset($extHomeValues[0])) {
694
+            $extHome = $extHomeValues[0];
695
+            $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
696
+            return $extHome;
697
+        } else {
698
+            $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
699
+            return '';
700
+        }
701
+    }
702
+
703
+    /**
704
+     * called by a post_login hook to handle password expiry
705
+     *
706
+     * @param array $params
707
+     */
708
+    public function handlePasswordExpiry($params) {
709
+        $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
710
+        if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
711
+            return;//password expiry handling disabled
712
+        }
713
+        $uid = $params['uid'];
714
+        if (isset($uid) && $uid === $this->getUsername()) {
715
+            //retrieve relevant user attributes
716
+            $result = $this->access->search('objectclass=*', [$this->dn], ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
717
+
718
+            if (array_key_exists('pwdpolicysubentry', $result[0])) {
719
+                $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
720
+                if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
721
+                    $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
722
+                }
723
+            }
724
+
725
+            $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
726
+            $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
727
+            $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
728
+
729
+            //retrieve relevant password policy attributes
730
+            $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
731
+            $result = $this->connection->getFromCache($cacheKey);
732
+            if(is_null($result)) {
733
+                $result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
734
+                $this->connection->writeToCache($cacheKey, $result);
735
+            }
736
+
737
+            $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
738
+            $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
739
+            $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
740
+
741
+            //handle grace login
742
+            if (!empty($pwdGraceUseTime)) { //was this a grace login?
743
+                if (!empty($pwdGraceAuthNLimit)
744
+                    && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
745
+                    $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
746
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
747
+                    'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
748
+                } else { //no more grace login available
749
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
750
+                    'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
751
+                }
752
+                exit();
753
+            }
754
+            //handle pwdReset attribute
755
+            if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
756
+                $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
757
+                header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
758
+                'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
759
+                exit();
760
+            }
761
+            //handle password expiry warning
762
+            if (!empty($pwdChangedTime)) {
763
+                if (!empty($pwdMaxAge)
764
+                    && !empty($pwdExpireWarning)) {
765
+                    $pwdMaxAgeInt = (int)$pwdMaxAge[0];
766
+                    $pwdExpireWarningInt = (int)$pwdExpireWarning[0];
767
+                    if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
768
+                        $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
769
+                        $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
770
+                        $currentDateTime = new \DateTime();
771
+                        $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
772
+                        if ($secondsToExpiry <= $pwdExpireWarningInt) {
773
+                            //remove last password expiry warning if any
774
+                            $notification = $this->notificationManager->createNotification();
775
+                            $notification->setApp('user_ldap')
776
+                                ->setUser($uid)
777
+                                ->setObject('pwd_exp_warn', $uid)
778
+                            ;
779
+                            $this->notificationManager->markProcessed($notification);
780
+                            //create new password expiry warning
781
+                            $notification = $this->notificationManager->createNotification();
782
+                            $notification->setApp('user_ldap')
783
+                                ->setUser($uid)
784
+                                ->setDateTime($currentDateTime)
785
+                                ->setObject('pwd_exp_warn', $uid)
786
+                                ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
787
+                            ;
788
+                            $this->notificationManager->notify($notification);
789
+                        }
790
+                    }
791
+                }
792
+            }
793
+        }
794
+    }
795 795
 }
Please login to merge, or discard this patch.
Spacing   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -156,17 +156,17 @@  discard block
 block discarded – undo
156 156
 	 * @return null
157 157
 	 */
158 158
 	public function update() {
159
-		if(is_null($this->dn)) {
159
+		if (is_null($this->dn)) {
160 160
 			return null;
161 161
 		}
162 162
 
163 163
 		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
164 164
 				self::USER_PREFKEY_FIRSTLOGIN, 0);
165 165
 
166
-		if($this->needsRefresh()) {
166
+		if ($this->needsRefresh()) {
167 167
 			$this->updateEmail();
168 168
 			$this->updateQuota();
169
-			if($hasLoggedIn !== 0) {
169
+			if ($hasLoggedIn !== 0) {
170 170
 				//we do not need to try it, when the user has not been logged in
171 171
 				//before, because the file system will not be ready.
172 172
 				$this->updateAvatar();
@@ -184,12 +184,12 @@  discard block
 block discarded – undo
184 184
 	 */
185 185
 	public function markUser() {
186 186
 		$curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
187
-		if($curValue === '1') {
187
+		if ($curValue === '1') {
188 188
 			// the user is already marked, do not write to DB again
189 189
 			return;
190 190
 		}
191 191
 		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
192
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
192
+		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string) time());
193 193
 	}
194 194
 
195 195
 	/**
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 		$this->markRefreshTime();
201 201
 		//Quota
202 202
 		$attr = strtolower($this->connection->ldapQuotaAttribute);
203
-		if(isset($ldapEntry[$attr])) {
203
+		if (isset($ldapEntry[$attr])) {
204 204
 			$this->updateQuota($ldapEntry[$attr][0]);
205 205
 		} else {
206 206
 			if ($this->connection->ldapQuotaDefault !== '') {
@@ -212,12 +212,12 @@  discard block
 block discarded – undo
212 212
 		//displayName
213 213
 		$displayName = $displayName2 = '';
214 214
 		$attr = strtolower($this->connection->ldapUserDisplayName);
215
-		if(isset($ldapEntry[$attr])) {
216
-			$displayName = (string)$ldapEntry[$attr][0];
215
+		if (isset($ldapEntry[$attr])) {
216
+			$displayName = (string) $ldapEntry[$attr][0];
217 217
 		}
218 218
 		$attr = strtolower($this->connection->ldapUserDisplayName2);
219
-		if(isset($ldapEntry[$attr])) {
220
-			$displayName2 = (string)$ldapEntry[$attr][0];
219
+		if (isset($ldapEntry[$attr])) {
220
+			$displayName2 = (string) $ldapEntry[$attr][0];
221 221
 		}
222 222
 		if ($displayName !== '') {
223 223
 			$this->composeAndStoreDisplayName($displayName, $displayName2);
@@ -233,22 +233,22 @@  discard block
 block discarded – undo
233 233
 		//email must be stored after displayname, because it would cause a user
234 234
 		//change event that will trigger fetching the display name again
235 235
 		$attr = strtolower($this->connection->ldapEmailAttribute);
236
-		if(isset($ldapEntry[$attr])) {
236
+		if (isset($ldapEntry[$attr])) {
237 237
 			$this->updateEmail($ldapEntry[$attr][0]);
238 238
 		}
239 239
 		unset($attr);
240 240
 
241 241
 		// LDAP Username, needed for s2s sharing
242
-		if(isset($ldapEntry['uid'])) {
242
+		if (isset($ldapEntry['uid'])) {
243 243
 			$this->storeLDAPUserName($ldapEntry['uid'][0]);
244
-		} else if(isset($ldapEntry['samaccountname'])) {
244
+		} else if (isset($ldapEntry['samaccountname'])) {
245 245
 			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
246 246
 		}
247 247
 
248 248
 		//homePath
249
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
249
+		if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
250 250
 			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
251
-			if(isset($ldapEntry[$attr])) {
251
+			if (isset($ldapEntry[$attr])) {
252 252
 				$this->access->cacheUserHome(
253 253
 					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
254 254
 			}
@@ -257,14 +257,14 @@  discard block
 block discarded – undo
257 257
 		//memberOf groups
258 258
 		$cacheKey = 'getMemberOf'.$this->getUsername();
259 259
 		$groups = false;
260
-		if(isset($ldapEntry['memberof'])) {
260
+		if (isset($ldapEntry['memberof'])) {
261 261
 			$groups = $ldapEntry['memberof'];
262 262
 		}
263 263
 		$this->connection->writeToCache($cacheKey, $groups);
264 264
 
265 265
 		//external storage var
266 266
 		$attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
267
-		if(isset($ldapEntry[$attr])) {
267
+		if (isset($ldapEntry[$attr])) {
268 268
 			$this->updateExtStorageHome($ldapEntry[$attr][0]);
269 269
 		}
270 270
 		unset($attr);
@@ -273,8 +273,8 @@  discard block
 block discarded – undo
273 273
 		/** @var Connection $connection */
274 274
 		$connection = $this->access->getConnection();
275 275
 		$attributes = $connection->resolveRule('avatar');
276
-		foreach ($attributes as $attribute)  {
277
-			if(isset($ldapEntry[$attribute])) {
276
+		foreach ($attributes as $attribute) {
277
+			if (isset($ldapEntry[$attribute])) {
278 278
 				$this->avatarImage = $ldapEntry[$attribute][0];
279 279
 				// the call to the method that saves the avatar in the file
280 280
 				// system must be postponed after the login. It is to ensure
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 	 * @throws \Exception
310 310
 	 */
311 311
 	public function getHomePath($valueFromLDAP = null) {
312
-		$path = (string)$valueFromLDAP;
312
+		$path = (string) $valueFromLDAP;
313 313
 		$attr = null;
314 314
 
315 315
 		if (is_null($valueFromLDAP)
@@ -327,12 +327,12 @@  discard block
 block discarded – undo
327 327
 		if ($path !== '') {
328 328
 			//if attribute's value is an absolute path take this, otherwise append it to data dir
329 329
 			//check for / at the beginning or pattern c:\ resp. c:/
330
-			if(   '/' !== $path[0]
330
+			if ('/' !== $path[0]
331 331
 			   && !(3 < strlen($path) && ctype_alpha($path[0])
332 332
 				   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
333 333
 			) {
334 334
 				$path = $this->config->getSystemValue('datadirectory',
335
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
335
+						\OC::$SERVERROOT.'/data').'/'.$path;
336 336
 			}
337 337
 			//we need it to store it in the DB as well in case a user gets
338 338
 			//deleted so we can clean up afterwards
@@ -342,11 +342,11 @@  discard block
 block discarded – undo
342 342
 			return $path;
343 343
 		}
344 344
 
345
-		if(    !is_null($attr)
345
+		if (!is_null($attr)
346 346
 			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
347 347
 		) {
348 348
 			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
349
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
349
+			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: '.$this->getUsername());
350 350
 		}
351 351
 
352 352
 		//false will apply default behaviour as defined and done by OC_User
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 	public function getMemberOfGroups() {
358 358
 		$cacheKey = 'getMemberOf'.$this->getUsername();
359 359
 		$memberOfGroups = $this->connection->getFromCache($cacheKey);
360
-		if(!is_null($memberOfGroups)) {
360
+		if (!is_null($memberOfGroups)) {
361 361
 			return $memberOfGroups;
362 362
 		}
363 363
 		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 	 * @return string data (provided by LDAP) | false
371 371
 	 */
372 372
 	public function getAvatarImage() {
373
-		if(!is_null($this->avatarImage)) {
373
+		if (!is_null($this->avatarImage)) {
374 374
 			return $this->avatarImage;
375 375
 		}
376 376
 
@@ -378,9 +378,9 @@  discard block
 block discarded – undo
378 378
 		/** @var Connection $connection */
379 379
 		$connection = $this->access->getConnection();
380 380
 		$attributes = $connection->resolveRule('avatar');
381
-		foreach($attributes as $attribute) {
381
+		foreach ($attributes as $attribute) {
382 382
 			$result = $this->access->readAttribute($this->dn, $attribute);
383
-			if($result !== false && is_array($result) && isset($result[0])) {
383
+			if ($result !== false && is_array($result) && isset($result[0])) {
384 384
 				$this->avatarImage = $result[0];
385 385
 				break;
386 386
 			}
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
 		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
418 418
 			self::USER_PREFKEY_LASTREFRESH, 0);
419 419
 
420
-		if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
420
+		if ((time() - (int) $lastChecked) < (int) $this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
421 421
 			return false;
422 422
 		}
423 423
 		return  true;
@@ -442,12 +442,12 @@  discard block
 block discarded – undo
442 442
 	 * @return string the effective display name
443 443
 	 */
444 444
 	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
445
-		$displayName2 = (string)$displayName2;
446
-		if($displayName2 !== '') {
447
-			$displayName .= ' (' . $displayName2 . ')';
445
+		$displayName2 = (string) $displayName2;
446
+		if ($displayName2 !== '') {
447
+			$displayName .= ' ('.$displayName2.')';
448 448
 		}
449 449
 		$oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
450
-		if ($oldName !== $displayName)  {
450
+		if ($oldName !== $displayName) {
451 451
 			$this->store('displayName', $displayName);
452 452
 			$user = $this->userManager->get($this->getUsername());
453 453
 			if (!empty($oldName) && $user instanceof \OC\User\User) {
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 	 * @return bool
476 476
 	 */
477 477
 	private function wasRefreshed($feature) {
478
-		if(isset($this->refreshedFeatures[$feature])) {
478
+		if (isset($this->refreshedFeatures[$feature])) {
479 479
 			return true;
480 480
 		}
481 481
 		$this->refreshedFeatures[$feature] = 1;
@@ -488,23 +488,23 @@  discard block
 block discarded – undo
488 488
 	 * @return null
489 489
 	 */
490 490
 	public function updateEmail($valueFromLDAP = null) {
491
-		if($this->wasRefreshed('email')) {
491
+		if ($this->wasRefreshed('email')) {
492 492
 			return;
493 493
 		}
494
-		$email = (string)$valueFromLDAP;
495
-		if(is_null($valueFromLDAP)) {
494
+		$email = (string) $valueFromLDAP;
495
+		if (is_null($valueFromLDAP)) {
496 496
 			$emailAttribute = $this->connection->ldapEmailAttribute;
497 497
 			if ($emailAttribute !== '') {
498 498
 				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
499
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
500
-					$email = (string)$aEmail[0];
499
+				if (is_array($aEmail) && (count($aEmail) > 0)) {
500
+					$email = (string) $aEmail[0];
501 501
 				}
502 502
 			}
503 503
 		}
504 504
 		if ($email !== '') {
505 505
 			$user = $this->userManager->get($this->uid);
506 506
 			if (!is_null($user)) {
507
-				$currentEmail = (string)$user->getEMailAddress();
507
+				$currentEmail = (string) $user->getEMailAddress();
508 508
 				if ($currentEmail !== $email) {
509 509
 					$user->setEMailAddress($email);
510 510
 				}
@@ -533,35 +533,35 @@  discard block
 block discarded – undo
533 533
 	 * @return null
534 534
 	 */
535 535
 	public function updateQuota($valueFromLDAP = null) {
536
-		if($this->wasRefreshed('quota')) {
536
+		if ($this->wasRefreshed('quota')) {
537 537
 			return;
538 538
 		}
539 539
 
540 540
 		$quotaAttribute = $this->connection->ldapQuotaAttribute;
541 541
 		$defaultQuota = $this->connection->ldapQuotaDefault;
542
-		if($quotaAttribute === '' && $defaultQuota === '') {
542
+		if ($quotaAttribute === '' && $defaultQuota === '') {
543 543
 			return;
544 544
 		}
545 545
 
546 546
 		$quota = false;
547
-		if(is_null($valueFromLDAP) && $quotaAttribute !== '') {
547
+		if (is_null($valueFromLDAP) && $quotaAttribute !== '') {
548 548
 			$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
549
-			if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
549
+			if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
550 550
 				$quota = $aQuota[0];
551
-			} else if(is_array($aQuota) && isset($aQuota[0])) {
552
-				$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG);
551
+			} else if (is_array($aQuota) && isset($aQuota[0])) {
552
+				$this->log->log('no suitable LDAP quota found for user '.$this->uid.': ['.$aQuota[0].']', ILogger::DEBUG);
553 553
 			}
554 554
 		} else if ($this->verifyQuotaValue($valueFromLDAP)) {
555 555
 			$quota = $valueFromLDAP;
556 556
 		} else {
557
-			$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG);
557
+			$this->log->log('no suitable LDAP quota found for user '.$this->uid.': ['.$valueFromLDAP.']', ILogger::DEBUG);
558 558
 		}
559 559
 
560 560
 		if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
561 561
 			// quota not found using the LDAP attribute (or not parseable). Try the default quota
562 562
 			$quota = $defaultQuota;
563
-		} else if($quota === false) {
564
-			$this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG);
563
+		} else if ($quota === false) {
564
+			$this->log->log('no suitable default quota found for user '.$this->uid.': ['.$defaultQuota.']', ILogger::DEBUG);
565 565
 			return;
566 566
 		}
567 567
 
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
 		if ($targetUser instanceof IUser) {
570 570
 			$targetUser->setQuota($quota);
571 571
 		} else {
572
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO);
572
+			$this->log->log('trying to set a quota for user '.$this->uid.' but the user is missing', ILogger::INFO);
573 573
 		}
574 574
 	}
575 575
 
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 	 * @param array $params
584 584
 	 */
585 585
 	public function updateAvatarPostLogin($params) {
586
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
586
+		if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
587 587
 			$this->updateAvatar();
588 588
 		}
589 589
 	}
@@ -593,29 +593,29 @@  discard block
 block discarded – undo
593 593
 	 * @return bool
594 594
 	 */
595 595
 	public function updateAvatar($force = false) {
596
-		if(!$force && $this->wasRefreshed('avatar')) {
596
+		if (!$force && $this->wasRefreshed('avatar')) {
597 597
 			return false;
598 598
 		}
599 599
 		$avatarImage = $this->getAvatarImage();
600
-		if($avatarImage === false) {
600
+		if ($avatarImage === false) {
601 601
 			//not set, nothing left to do;
602 602
 			return false;
603 603
 		}
604 604
 
605
-		if(!$this->image->loadFromBase64(base64_encode($avatarImage))) {
605
+		if (!$this->image->loadFromBase64(base64_encode($avatarImage))) {
606 606
 			return false;
607 607
 		}
608 608
 
609 609
 		// use the checksum before modifications
610 610
 		$checksum = md5($this->image->data());
611 611
 
612
-		if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
612
+		if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
613 613
 			return true;
614 614
 		}
615 615
 
616 616
 		$isSet = $this->setOwnCloudAvatar();
617 617
 
618
-		if($isSet) {
618
+		if ($isSet) {
619 619
 			// save checksum only after successful setting
620 620
 			$this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
621 621
 		}
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 	 * @return bool
629 629
 	 */
630 630
 	private function setOwnCloudAvatar() {
631
-		if(!$this->image->valid()) {
631
+		if (!$this->image->valid()) {
632 632
 			$this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR);
633 633
 			return false;
634 634
 		}
@@ -636,12 +636,12 @@  discard block
 block discarded – undo
636 636
 
637 637
 		//make sure it is a square and not bigger than 128x128
638 638
 		$size = min([$this->image->width(), $this->image->height(), 128]);
639
-		if(!$this->image->centerCrop($size)) {
639
+		if (!$this->image->centerCrop($size)) {
640 640
 			$this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR);
641 641
 			return false;
642 642
 		}
643 643
 
644
-		if(!$this->fs->isLoaded()) {
644
+		if (!$this->fs->isLoaded()) {
645 645
 			$this->fs->setup($this->uid);
646 646
 		}
647 647
 
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
 			return true;
652 652
 		} catch (\Exception $e) {
653 653
 			\OC::$server->getLogger()->logException($e, [
654
-				'message' => 'Could not set avatar for ' . $this->dn,
654
+				'message' => 'Could not set avatar for '.$this->dn,
655 655
 				'level' => ILogger::INFO,
656 656
 				'app' => 'user_ldap',
657 657
 			]);
@@ -707,8 +707,8 @@  discard block
 block discarded – undo
707 707
 	 */
708 708
 	public function handlePasswordExpiry($params) {
709 709
 		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
710
-		if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
711
-			return;//password expiry handling disabled
710
+		if (empty($ppolicyDN) || ((int) $this->connection->turnOnPasswordChange !== 1)) {
711
+			return; //password expiry handling disabled
712 712
 		}
713 713
 		$uid = $params['uid'];
714 714
 		if (isset($uid) && $uid === $this->getUsername()) {
@@ -717,8 +717,8 @@  discard block
 block discarded – undo
717 717
 
718 718
 			if (array_key_exists('pwdpolicysubentry', $result[0])) {
719 719
 				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
720
-				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
721
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
720
+				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
721
+					$ppolicyDN = $pwdPolicySubentry[0]; //custom ppolicy DN
722 722
 				}
723 723
 			}
724 724
 
@@ -727,9 +727,9 @@  discard block
 block discarded – undo
727 727
 			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
728 728
 
729 729
 			//retrieve relevant password policy attributes
730
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
730
+			$cacheKey = 'ppolicyAttributes'.$ppolicyDN;
731 731
 			$result = $this->connection->getFromCache($cacheKey);
732
-			if(is_null($result)) {
732
+			if (is_null($result)) {
733 733
 				$result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
734 734
 				$this->connection->writeToCache($cacheKey, $result);
735 735
 			}
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
 			//handle grace login
742 742
 			if (!empty($pwdGraceUseTime)) { //was this a grace login?
743 743
 				if (!empty($pwdGraceAuthNLimit)
744
-					&& count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
744
+					&& count($pwdGraceUseTime) < (int) $pwdGraceAuthNLimit[0]) { //at least one more grace login available?
745 745
 					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
746 746
 					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
747 747
 					'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
@@ -762,9 +762,9 @@  discard block
 block discarded – undo
762 762
 			if (!empty($pwdChangedTime)) {
763 763
 				if (!empty($pwdMaxAge)
764 764
 					&& !empty($pwdExpireWarning)) {
765
-					$pwdMaxAgeInt = (int)$pwdMaxAge[0];
766
-					$pwdExpireWarningInt = (int)$pwdExpireWarning[0];
767
-					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
765
+					$pwdMaxAgeInt = (int) $pwdMaxAge[0];
766
+					$pwdExpireWarningInt = (int) $pwdExpireWarning[0];
767
+					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
768 768
 						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
769 769
 						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
770 770
 						$currentDateTime = new \DateTime();
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_LDAP.php 2 patches
Indentation   +1231 added lines, -1231 removed lines patch added patch discarded remove patch
@@ -49,1235 +49,1235 @@
 block discarded – undo
49 49
 use OCP\ILogger;
50 50
 
51 51
 class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend {
52
-	protected $enabled = false;
53
-
54
-	/**
55
-	 * @var string[] $cachedGroupMembers array of users with gid as key
56
-	 */
57
-	protected $cachedGroupMembers;
58
-
59
-	/**
60
-	 * @var string[] $cachedGroupsByMember array of groups with uid as key
61
-	 */
62
-	protected $cachedGroupsByMember;
63
-
64
-	/**
65
-	 * @var string[] $cachedNestedGroups array of groups with gid (DN) as key
66
-	 */
67
-	protected $cachedNestedGroups;
68
-
69
-	/** @var GroupPluginManager */
70
-	protected $groupPluginManager;
71
-
72
-	public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
73
-		parent::__construct($access);
74
-		$filter = $this->access->connection->ldapGroupFilter;
75
-		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
76
-		if(!empty($filter) && !empty($gassoc)) {
77
-			$this->enabled = true;
78
-		}
79
-
80
-		$this->cachedGroupMembers = new CappedMemoryCache();
81
-		$this->cachedGroupsByMember = new CappedMemoryCache();
82
-		$this->cachedNestedGroups = new CappedMemoryCache();
83
-		$this->groupPluginManager = $groupPluginManager;
84
-	}
85
-
86
-	/**
87
-	 * is user in group?
88
-	 * @param string $uid uid of the user
89
-	 * @param string $gid gid of the group
90
-	 * @return bool
91
-	 *
92
-	 * Checks whether the user is member of a group or not.
93
-	 */
94
-	public function inGroup($uid, $gid) {
95
-		if(!$this->enabled) {
96
-			return false;
97
-		}
98
-		$cacheKey = 'inGroup'.$uid.':'.$gid;
99
-		$inGroup = $this->access->connection->getFromCache($cacheKey);
100
-		if(!is_null($inGroup)) {
101
-			return (bool)$inGroup;
102
-		}
103
-
104
-		$userDN = $this->access->username2dn($uid);
105
-
106
-		if(isset($this->cachedGroupMembers[$gid])) {
107
-			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
108
-			return $isInGroup;
109
-		}
110
-
111
-		$cacheKeyMembers = 'inGroup-members:'.$gid;
112
-		$members = $this->access->connection->getFromCache($cacheKeyMembers);
113
-		if(!is_null($members)) {
114
-			$this->cachedGroupMembers[$gid] = $members;
115
-			$isInGroup = in_array($userDN, $members, true);
116
-			$this->access->connection->writeToCache($cacheKey, $isInGroup);
117
-			return $isInGroup;
118
-		}
119
-
120
-		$groupDN = $this->access->groupname2dn($gid);
121
-		// just in case
122
-		if(!$groupDN || !$userDN) {
123
-			$this->access->connection->writeToCache($cacheKey, false);
124
-			return false;
125
-		}
126
-
127
-		//check primary group first
128
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
129
-			$this->access->connection->writeToCache($cacheKey, true);
130
-			return true;
131
-		}
132
-
133
-		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
134
-		$members = $this->_groupMembers($groupDN);
135
-		if(!is_array($members) || count($members) === 0) {
136
-			$this->access->connection->writeToCache($cacheKey, false);
137
-			return false;
138
-		}
139
-
140
-		//extra work if we don't get back user DNs
141
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
142
-			$dns = [];
143
-			$filterParts = [];
144
-			$bytes = 0;
145
-			foreach($members as $mid) {
146
-				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
147
-				$filterParts[] = $filter;
148
-				$bytes += strlen($filter);
149
-				if($bytes >= 9000000) {
150
-					// AD has a default input buffer of 10 MB, we do not want
151
-					// to take even the chance to exceed it
152
-					$filter = $this->access->combineFilterWithOr($filterParts);
153
-					$bytes = 0;
154
-					$filterParts = [];
155
-					$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
156
-					$dns = array_merge($dns, $users);
157
-				}
158
-			}
159
-			if(count($filterParts) > 0) {
160
-				$filter = $this->access->combineFilterWithOr($filterParts);
161
-				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
162
-				$dns = array_merge($dns, $users);
163
-			}
164
-			$members = $dns;
165
-		}
166
-
167
-		$isInGroup = in_array($userDN, $members);
168
-		$this->access->connection->writeToCache($cacheKey, $isInGroup);
169
-		$this->access->connection->writeToCache($cacheKeyMembers, $members);
170
-		$this->cachedGroupMembers[$gid] = $members;
171
-
172
-		return $isInGroup;
173
-	}
174
-
175
-	/**
176
-	 * @param string $dnGroup
177
-	 * @return array
178
-	 *
179
-	 * For a group that has user membership defined by an LDAP search url attribute returns the users
180
-	 * that match the search url otherwise returns an empty array.
181
-	 */
182
-	public function getDynamicGroupMembers($dnGroup) {
183
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
184
-
185
-		if (empty($dynamicGroupMemberURL)) {
186
-			return [];
187
-		}
188
-
189
-		$dynamicMembers = [];
190
-		$memberURLs = $this->access->readAttribute(
191
-			$dnGroup,
192
-			$dynamicGroupMemberURL,
193
-			$this->access->connection->ldapGroupFilter
194
-		);
195
-		if ($memberURLs !== false) {
196
-			// this group has the 'memberURL' attribute so this is a dynamic group
197
-			// example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
198
-			// example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
199
-			$pos = strpos($memberURLs[0], '(');
200
-			if ($pos !== false) {
201
-				$memberUrlFilter = substr($memberURLs[0], $pos);
202
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
203
-				$dynamicMembers = [];
204
-				foreach($foundMembers as $value) {
205
-					$dynamicMembers[$value['dn'][0]] = 1;
206
-				}
207
-			} else {
208
-				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
209
-					'of group ' . $dnGroup, ILogger::DEBUG);
210
-			}
211
-		}
212
-		return $dynamicMembers;
213
-	}
214
-
215
-	/**
216
-	 * @param string $dnGroup
217
-	 * @param array|null &$seen
218
-	 * @return array|mixed|null
219
-	 * @throws \OC\ServerNotAvailableException
220
-	 */
221
-	private function _groupMembers($dnGroup, &$seen = null) {
222
-		if ($seen === null) {
223
-			$seen = [];
224
-		}
225
-		$allMembers = [];
226
-		if (array_key_exists($dnGroup, $seen)) {
227
-			// avoid loops
228
-			return [];
229
-		}
230
-		// used extensively in cron job, caching makes sense for nested groups
231
-		$cacheKey = '_groupMembers'.$dnGroup;
232
-		$groupMembers = $this->access->connection->getFromCache($cacheKey);
233
-		if($groupMembers !== null) {
234
-			return $groupMembers;
235
-		}
236
-		$seen[$dnGroup] = 1;
237
-		$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
238
-		if (is_array($members)) {
239
-			$fetcher = function($memberDN, &$seen) {
240
-				return $this->_groupMembers($memberDN, $seen);
241
-			};
242
-			$allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
243
-		}
244
-
245
-		$allMembers += $this->getDynamicGroupMembers($dnGroup);
246
-
247
-		$this->access->connection->writeToCache($cacheKey, $allMembers);
248
-		return $allMembers;
249
-	}
250
-
251
-	/**
252
-	 * @param string $DN
253
-	 * @param array|null &$seen
254
-	 * @return array
255
-	 * @throws \OC\ServerNotAvailableException
256
-	 */
257
-	private function _getGroupDNsFromMemberOf($DN) {
258
-		$groups = $this->access->readAttribute($DN, 'memberOf');
259
-		if (!is_array($groups)) {
260
-			return [];
261
-		}
262
-
263
-		$fetcher = function($groupDN) {
264
-			if (isset($this->cachedNestedGroups[$groupDN])) {
265
-				$nestedGroups = $this->cachedNestedGroups[$groupDN];
266
-			} else {
267
-				$nestedGroups = $this->access->readAttribute($groupDN, 'memberOf');
268
-				if (!is_array($nestedGroups)) {
269
-					$nestedGroups = [];
270
-				}
271
-				$this->cachedNestedGroups[$groupDN] = $nestedGroups;
272
-			}
273
-			return $nestedGroups;
274
-		};
275
-
276
-		$groups = $this->walkNestedGroups($DN, $fetcher, $groups);
277
-		return $this->access->groupsMatchFilter($groups);
278
-	}
279
-
280
-	/**
281
-	 * @param string $dn
282
-	 * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns
283
-	 * @param array $list
284
-	 * @return array
285
-	 */
286
-	private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array {
287
-		$nesting = (int) $this->access->connection->ldapNestedGroups;
288
-		// depending on the input, we either have a list of DNs or a list of LDAP records
289
-		// also, the output expects either DNs or records. Testing the first element should suffice.
290
-		$recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
291
-
292
-		if ($nesting !== 1) {
293
-			if($recordMode) {
294
-				// the keys are numeric, but should hold the DN
295
-				return array_reduce($list, function ($transformed, $record) use ($dn) {
296
-					if($record['dn'][0] != $dn) {
297
-						$transformed[$record['dn'][0]] = $record;
298
-					}
299
-					return $transformed;
300
-				}, []);
301
-			}
302
-			return $list;
303
-		}
304
-
305
-		$seen = [];
306
-		while ($record = array_pop($list)) {
307
-			$recordDN = $recordMode ? $record['dn'][0] : $record;
308
-			if ($recordDN === $dn || array_key_exists($recordDN, $seen)) {
309
-				// Prevent loops
310
-				continue;
311
-			}
312
-			$fetched = $fetcher($record, $seen);
313
-			$list = array_merge($list, $fetched);
314
-			$seen[$recordDN] = $record;
315
-		}
316
-
317
-		return $recordMode ? $seen : array_keys($seen);
318
-	}
319
-
320
-	/**
321
-	 * translates a gidNumber into an ownCloud internal name
322
-	 * @param string $gid as given by gidNumber on POSIX LDAP
323
-	 * @param string $dn a DN that belongs to the same domain as the group
324
-	 * @return string|bool
325
-	 */
326
-	public function gidNumber2Name($gid, $dn) {
327
-		$cacheKey = 'gidNumberToName' . $gid;
328
-		$groupName = $this->access->connection->getFromCache($cacheKey);
329
-		if(!is_null($groupName) && isset($groupName)) {
330
-			return $groupName;
331
-		}
332
-
333
-		//we need to get the DN from LDAP
334
-		$filter = $this->access->combineFilterWithAnd([
335
-			$this->access->connection->ldapGroupFilter,
336
-			'objectClass=posixGroup',
337
-			$this->access->connection->ldapGidNumber . '=' . $gid
338
-		]);
339
-		$result = $this->access->searchGroups($filter, ['dn'], 1);
340
-		if(empty($result)) {
341
-			return false;
342
-		}
343
-		$dn = $result[0]['dn'][0];
344
-
345
-		//and now the group name
346
-		//NOTE once we have separate ownCloud group IDs and group names we can
347
-		//directly read the display name attribute instead of the DN
348
-		$name = $this->access->dn2groupname($dn);
349
-
350
-		$this->access->connection->writeToCache($cacheKey, $name);
351
-
352
-		return $name;
353
-	}
354
-
355
-	/**
356
-	 * returns the entry's gidNumber
357
-	 * @param string $dn
358
-	 * @param string $attribute
359
-	 * @return string|bool
360
-	 */
361
-	private function getEntryGidNumber($dn, $attribute) {
362
-		$value = $this->access->readAttribute($dn, $attribute);
363
-		if(is_array($value) && !empty($value)) {
364
-			return $value[0];
365
-		}
366
-		return false;
367
-	}
368
-
369
-	/**
370
-	 * returns the group's primary ID
371
-	 * @param string $dn
372
-	 * @return string|bool
373
-	 */
374
-	public function getGroupGidNumber($dn) {
375
-		return $this->getEntryGidNumber($dn, 'gidNumber');
376
-	}
377
-
378
-	/**
379
-	 * returns the user's gidNumber
380
-	 * @param string $dn
381
-	 * @return string|bool
382
-	 */
383
-	public function getUserGidNumber($dn) {
384
-		$gidNumber = false;
385
-		if($this->access->connection->hasGidNumber) {
386
-			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
387
-			if($gidNumber === false) {
388
-				$this->access->connection->hasGidNumber = false;
389
-			}
390
-		}
391
-		return $gidNumber;
392
-	}
393
-
394
-	/**
395
-	 * returns a filter for a "users has specific gid" search or count operation
396
-	 *
397
-	 * @param string $groupDN
398
-	 * @param string $search
399
-	 * @return string
400
-	 * @throws \Exception
401
-	 */
402
-	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
403
-		$groupID = $this->getGroupGidNumber($groupDN);
404
-		if($groupID === false) {
405
-			throw new \Exception('Not a valid group');
406
-		}
407
-
408
-		$filterParts = [];
409
-		$filterParts[] = $this->access->getFilterForUserCount();
410
-		if ($search !== '') {
411
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
412
-		}
413
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
414
-
415
-		return $this->access->combineFilterWithAnd($filterParts);
416
-	}
417
-
418
-	/**
419
-	 * returns a list of users that have the given group as gid number
420
-	 *
421
-	 * @param string $groupDN
422
-	 * @param string $search
423
-	 * @param int $limit
424
-	 * @param int $offset
425
-	 * @return string[]
426
-	 */
427
-	public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
428
-		try {
429
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
430
-			$users = $this->access->fetchListOfUsers(
431
-				$filter,
432
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
433
-				$limit,
434
-				$offset
435
-			);
436
-			return $this->access->nextcloudUserNames($users);
437
-		} catch (\Exception $e) {
438
-			return [];
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * returns the number of users that have the given group as gid number
444
-	 *
445
-	 * @param string $groupDN
446
-	 * @param string $search
447
-	 * @param int $limit
448
-	 * @param int $offset
449
-	 * @return int
450
-	 */
451
-	public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
452
-		try {
453
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
454
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
455
-			return (int)$users;
456
-		} catch (\Exception $e) {
457
-			return 0;
458
-		}
459
-	}
460
-
461
-	/**
462
-	 * gets the gidNumber of a user
463
-	 * @param string $dn
464
-	 * @return string
465
-	 */
466
-	public function getUserGroupByGid($dn) {
467
-		$groupID = $this->getUserGidNumber($dn);
468
-		if($groupID !== false) {
469
-			$groupName = $this->gidNumber2Name($groupID, $dn);
470
-			if($groupName !== false) {
471
-				return $groupName;
472
-			}
473
-		}
474
-
475
-		return false;
476
-	}
477
-
478
-	/**
479
-	 * translates a primary group ID into an Nextcloud internal name
480
-	 * @param string $gid as given by primaryGroupID on AD
481
-	 * @param string $dn a DN that belongs to the same domain as the group
482
-	 * @return string|bool
483
-	 */
484
-	public function primaryGroupID2Name($gid, $dn) {
485
-		$cacheKey = 'primaryGroupIDtoName';
486
-		$groupNames = $this->access->connection->getFromCache($cacheKey);
487
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
488
-			return $groupNames[$gid];
489
-		}
490
-
491
-		$domainObjectSid = $this->access->getSID($dn);
492
-		if($domainObjectSid === false) {
493
-			return false;
494
-		}
495
-
496
-		//we need to get the DN from LDAP
497
-		$filter = $this->access->combineFilterWithAnd([
498
-			$this->access->connection->ldapGroupFilter,
499
-			'objectsid=' . $domainObjectSid . '-' . $gid
500
-		]);
501
-		$result = $this->access->searchGroups($filter, ['dn'], 1);
502
-		if(empty($result)) {
503
-			return false;
504
-		}
505
-		$dn = $result[0]['dn'][0];
506
-
507
-		//and now the group name
508
-		//NOTE once we have separate Nextcloud group IDs and group names we can
509
-		//directly read the display name attribute instead of the DN
510
-		$name = $this->access->dn2groupname($dn);
511
-
512
-		$this->access->connection->writeToCache($cacheKey, $name);
513
-
514
-		return $name;
515
-	}
516
-
517
-	/**
518
-	 * returns the entry's primary group ID
519
-	 * @param string $dn
520
-	 * @param string $attribute
521
-	 * @return string|bool
522
-	 */
523
-	private function getEntryGroupID($dn, $attribute) {
524
-		$value = $this->access->readAttribute($dn, $attribute);
525
-		if(is_array($value) && !empty($value)) {
526
-			return $value[0];
527
-		}
528
-		return false;
529
-	}
530
-
531
-	/**
532
-	 * returns the group's primary ID
533
-	 * @param string $dn
534
-	 * @return string|bool
535
-	 */
536
-	public function getGroupPrimaryGroupID($dn) {
537
-		return $this->getEntryGroupID($dn, 'primaryGroupToken');
538
-	}
539
-
540
-	/**
541
-	 * returns the user's primary group ID
542
-	 * @param string $dn
543
-	 * @return string|bool
544
-	 */
545
-	public function getUserPrimaryGroupIDs($dn) {
546
-		$primaryGroupID = false;
547
-		if($this->access->connection->hasPrimaryGroups) {
548
-			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
549
-			if($primaryGroupID === false) {
550
-				$this->access->connection->hasPrimaryGroups = false;
551
-			}
552
-		}
553
-		return $primaryGroupID;
554
-	}
555
-
556
-	/**
557
-	 * returns a filter for a "users in primary group" search or count operation
558
-	 *
559
-	 * @param string $groupDN
560
-	 * @param string $search
561
-	 * @return string
562
-	 * @throws \Exception
563
-	 */
564
-	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
565
-		$groupID = $this->getGroupPrimaryGroupID($groupDN);
566
-		if($groupID === false) {
567
-			throw new \Exception('Not a valid group');
568
-		}
569
-
570
-		$filterParts = [];
571
-		$filterParts[] = $this->access->getFilterForUserCount();
572
-		if ($search !== '') {
573
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
574
-		}
575
-		$filterParts[] = 'primaryGroupID=' . $groupID;
576
-
577
-		return $this->access->combineFilterWithAnd($filterParts);
578
-	}
579
-
580
-	/**
581
-	 * returns a list of users that have the given group as primary group
582
-	 *
583
-	 * @param string $groupDN
584
-	 * @param string $search
585
-	 * @param int $limit
586
-	 * @param int $offset
587
-	 * @return string[]
588
-	 */
589
-	public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
590
-		try {
591
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
592
-			$users = $this->access->fetchListOfUsers(
593
-				$filter,
594
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
595
-				$limit,
596
-				$offset
597
-			);
598
-			return $this->access->nextcloudUserNames($users);
599
-		} catch (\Exception $e) {
600
-			return [];
601
-		}
602
-	}
603
-
604
-	/**
605
-	 * returns the number of users that have the given group as primary group
606
-	 *
607
-	 * @param string $groupDN
608
-	 * @param string $search
609
-	 * @param int $limit
610
-	 * @param int $offset
611
-	 * @return int
612
-	 */
613
-	public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
614
-		try {
615
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
616
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
617
-			return (int)$users;
618
-		} catch (\Exception $e) {
619
-			return 0;
620
-		}
621
-	}
622
-
623
-	/**
624
-	 * gets the primary group of a user
625
-	 * @param string $dn
626
-	 * @return string
627
-	 */
628
-	public function getUserPrimaryGroup($dn) {
629
-		$groupID = $this->getUserPrimaryGroupIDs($dn);
630
-		if($groupID !== false) {
631
-			$groupName = $this->primaryGroupID2Name($groupID, $dn);
632
-			if($groupName !== false) {
633
-				return $groupName;
634
-			}
635
-		}
636
-
637
-		return false;
638
-	}
639
-
640
-	/**
641
-	 * Get all groups a user belongs to
642
-	 * @param string $uid Name of the user
643
-	 * @return array with group names
644
-	 *
645
-	 * This function fetches all groups a user belongs to. It does not check
646
-	 * if the user exists at all.
647
-	 *
648
-	 * This function includes groups based on dynamic group membership.
649
-	 */
650
-	public function getUserGroups($uid) {
651
-		if(!$this->enabled) {
652
-			return [];
653
-		}
654
-		$cacheKey = 'getUserGroups'.$uid;
655
-		$userGroups = $this->access->connection->getFromCache($cacheKey);
656
-		if(!is_null($userGroups)) {
657
-			return $userGroups;
658
-		}
659
-		$userDN = $this->access->username2dn($uid);
660
-		if(!$userDN) {
661
-			$this->access->connection->writeToCache($cacheKey, []);
662
-			return [];
663
-		}
664
-
665
-		$groups = [];
666
-		$primaryGroup = $this->getUserPrimaryGroup($userDN);
667
-		$gidGroupName = $this->getUserGroupByGid($userDN);
668
-
669
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
670
-
671
-		if (!empty($dynamicGroupMemberURL)) {
672
-			// look through dynamic groups to add them to the result array if needed
673
-			$groupsToMatch = $this->access->fetchListOfGroups(
674
-				$this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
675
-			foreach($groupsToMatch as $dynamicGroup) {
676
-				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
677
-					continue;
678
-				}
679
-				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
680
-				if ($pos !== false) {
681
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
682
-					// apply filter via ldap search to see if this user is in this
683
-					// dynamic group
684
-					$userMatch = $this->access->readAttribute(
685
-						$userDN,
686
-						$this->access->connection->ldapUserDisplayName,
687
-						$memberUrlFilter
688
-					);
689
-					if ($userMatch !== false) {
690
-						// match found so this user is in this group
691
-						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
692
-						if(is_string($groupName)) {
693
-							// be sure to never return false if the dn could not be
694
-							// resolved to a name, for whatever reason.
695
-							$groups[] = $groupName;
696
-						}
697
-					}
698
-				} else {
699
-					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
700
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
701
-				}
702
-			}
703
-		}
704
-
705
-		// if possible, read out membership via memberOf. It's far faster than
706
-		// performing a search, which still is a fallback later.
707
-		// memberof doesn't support memberuid, so skip it here.
708
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
709
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
710
-			&& strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
711
-			) {
712
-			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
713
-			if (is_array($groupDNs)) {
714
-				foreach ($groupDNs as $dn) {
715
-					$groupName = $this->access->dn2groupname($dn);
716
-					if(is_string($groupName)) {
717
-						// be sure to never return false if the dn could not be
718
-						// resolved to a name, for whatever reason.
719
-						$groups[] = $groupName;
720
-					}
721
-				}
722
-			}
723
-
724
-			if($primaryGroup !== false) {
725
-				$groups[] = $primaryGroup;
726
-			}
727
-			if($gidGroupName !== false) {
728
-				$groups[] = $gidGroupName;
729
-			}
730
-			$this->access->connection->writeToCache($cacheKey, $groups);
731
-			return $groups;
732
-		}
733
-
734
-		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
735
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
736
-			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
737
-		) {
738
-			$uid = $userDN;
739
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
740
-			$result = $this->access->readAttribute($userDN, 'uid');
741
-			if ($result === false) {
742
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
743
-					$this->access->connection->ldapHost, ILogger::DEBUG);
744
-				$uid = false;
745
-			} else {
746
-				$uid = $result[0];
747
-			}
748
-		} else {
749
-			// just in case
750
-			$uid = $userDN;
751
-		}
752
-
753
-		if($uid !== false) {
754
-			if (isset($this->cachedGroupsByMember[$uid])) {
755
-				$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
756
-			} else {
757
-				$groupsByMember = array_values($this->getGroupsByMember($uid));
758
-				$groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
759
-				$this->cachedGroupsByMember[$uid] = $groupsByMember;
760
-				$groups = array_merge($groups, $groupsByMember);
761
-			}
762
-		}
763
-
764
-		if($primaryGroup !== false) {
765
-			$groups[] = $primaryGroup;
766
-		}
767
-		if($gidGroupName !== false) {
768
-			$groups[] = $gidGroupName;
769
-		}
770
-
771
-		$groups = array_unique($groups, SORT_LOCALE_STRING);
772
-		$this->access->connection->writeToCache($cacheKey, $groups);
773
-
774
-		return $groups;
775
-	}
776
-
777
-	/**
778
-	 * @param string $dn
779
-	 * @param array|null &$seen
780
-	 * @return array
781
-	 */
782
-	private function getGroupsByMember($dn, &$seen = null) {
783
-		if ($seen === null) {
784
-			$seen = [];
785
-		}
786
-		if (array_key_exists($dn, $seen)) {
787
-			// avoid loops
788
-			return [];
789
-		}
790
-		$allGroups = [];
791
-		$seen[$dn] = true;
792
-		$filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn;
793
-		$groups = $this->access->fetchListOfGroups($filter,
794
-			[$this->access->connection->ldapGroupDisplayName, 'dn']);
795
-		if (is_array($groups)) {
796
-			$fetcher = function ($dn, &$seen) {
797
-				if(is_array($dn) && isset($dn['dn'][0])) {
798
-					$dn = $dn['dn'][0];
799
-				}
800
-				return $this->getGroupsByMember($dn, $seen);
801
-			};
802
-			$allGroups = $this->walkNestedGroups($dn, $fetcher, $groups);
803
-		}
804
-		$visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups));
805
-		return array_intersect_key($allGroups, array_flip($visibleGroups));
806
-	}
807
-
808
-	/**
809
-	 * get a list of all users in a group
810
-	 *
811
-	 * @param string $gid
812
-	 * @param string $search
813
-	 * @param int $limit
814
-	 * @param int $offset
815
-	 * @return array with user ids
816
-	 * @throws \Exception
817
-	 */
818
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
819
-		if(!$this->enabled) {
820
-			return [];
821
-		}
822
-		if(!$this->groupExists($gid)) {
823
-			return [];
824
-		}
825
-		$search = $this->access->escapeFilterPart($search, true);
826
-		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
827
-		// check for cache of the exact query
828
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
829
-		if(!is_null($groupUsers)) {
830
-			return $groupUsers;
831
-		}
832
-
833
-		// check for cache of the query without limit and offset
834
-		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
835
-		if(!is_null($groupUsers)) {
836
-			$groupUsers = array_slice($groupUsers, $offset, $limit);
837
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
838
-			return $groupUsers;
839
-		}
840
-
841
-		if($limit === -1) {
842
-			$limit = null;
843
-		}
844
-		$groupDN = $this->access->groupname2dn($gid);
845
-		if(!$groupDN) {
846
-			// group couldn't be found, return empty resultset
847
-			$this->access->connection->writeToCache($cacheKey, []);
848
-			return [];
849
-		}
850
-
851
-		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
852
-		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
853
-		$members = $this->_groupMembers($groupDN);
854
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
855
-			//in case users could not be retrieved, return empty result set
856
-			$this->access->connection->writeToCache($cacheKey, []);
857
-			return [];
858
-		}
859
-
860
-		$groupUsers = [];
861
-		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
862
-		$attrs = $this->access->userManager->getAttributes(true);
863
-		foreach($members as $member) {
864
-			if($isMemberUid) {
865
-				//we got uids, need to get their DNs to 'translate' them to user names
866
-				$filter = $this->access->combineFilterWithAnd([
867
-					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
868
-					$this->access->combineFilterWithAnd([
869
-						$this->access->getFilterPartForUserSearch($search),
870
-						$this->access->connection->ldapUserFilter
871
-					])
872
-				]);
873
-				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
874
-				if(count($ldap_users) < 1) {
875
-					continue;
876
-				}
877
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
878
-			} else {
879
-				//we got DNs, check if we need to filter by search or we can give back all of them
880
-				$uid = $this->access->dn2username($member);
881
-				if(!$uid) {
882
-					continue;
883
-				}
884
-
885
-				$cacheKey = 'userExistsOnLDAP' . $uid;
886
-				$userExists = $this->access->connection->getFromCache($cacheKey);
887
-				if($userExists === false) {
888
-					continue;
889
-				}
890
-				if($userExists === null || $search !== '') {
891
-					if (!$this->access->readAttribute($member,
892
-						$this->access->connection->ldapUserDisplayName,
893
-						$this->access->combineFilterWithAnd([
894
-							$this->access->getFilterPartForUserSearch($search),
895
-							$this->access->connection->ldapUserFilter
896
-						])))
897
-					{
898
-						if($search === '') {
899
-							$this->access->connection->writeToCache($cacheKey, false);
900
-						}
901
-						continue;
902
-					}
903
-					$this->access->connection->writeToCache($cacheKey, true);
904
-				}
905
-				$groupUsers[] = $uid;
906
-			}
907
-		}
908
-
909
-		$groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
910
-		natsort($groupUsers);
911
-		$this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
912
-		$groupUsers = array_slice($groupUsers, $offset, $limit);
913
-
914
-		$this->access->connection->writeToCache($cacheKey, $groupUsers);
915
-
916
-		return $groupUsers;
917
-	}
918
-
919
-	/**
920
-	 * returns the number of users in a group, who match the search term
921
-	 * @param string $gid the internal group name
922
-	 * @param string $search optional, a search string
923
-	 * @return int|bool
924
-	 */
925
-	public function countUsersInGroup($gid, $search = '') {
926
-		if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
927
-			return $this->groupPluginManager->countUsersInGroup($gid, $search);
928
-		}
929
-
930
-		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
931
-		if(!$this->enabled || !$this->groupExists($gid)) {
932
-			return false;
933
-		}
934
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
935
-		if(!is_null($groupUsers)) {
936
-			return $groupUsers;
937
-		}
938
-
939
-		$groupDN = $this->access->groupname2dn($gid);
940
-		if(!$groupDN) {
941
-			// group couldn't be found, return empty result set
942
-			$this->access->connection->writeToCache($cacheKey, false);
943
-			return false;
944
-		}
945
-
946
-		$members = $this->_groupMembers($groupDN);
947
-		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
948
-		if(!$members && $primaryUserCount === 0) {
949
-			//in case users could not be retrieved, return empty result set
950
-			$this->access->connection->writeToCache($cacheKey, false);
951
-			return false;
952
-		}
953
-
954
-		if ($search === '') {
955
-			$groupUsers = count($members) + $primaryUserCount;
956
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
957
-			return $groupUsers;
958
-		}
959
-		$search = $this->access->escapeFilterPart($search, true);
960
-		$isMemberUid =
961
-			(strtolower($this->access->connection->ldapGroupMemberAssocAttr)
962
-			=== 'memberuid');
963
-
964
-		//we need to apply the search filter
965
-		//alternatives that need to be checked:
966
-		//a) get all users by search filter and array_intersect them
967
-		//b) a, but only when less than 1k 10k ?k users like it is
968
-		//c) put all DNs|uids in a LDAP filter, combine with the search string
969
-		//   and let it count.
970
-		//For now this is not important, because the only use of this method
971
-		//does not supply a search string
972
-		$groupUsers = [];
973
-		foreach($members as $member) {
974
-			if($isMemberUid) {
975
-				//we got uids, need to get their DNs to 'translate' them to user names
976
-				$filter = $this->access->combineFilterWithAnd([
977
-					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
978
-					$this->access->getFilterPartForUserSearch($search)
979
-				]);
980
-				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
981
-				if(count($ldap_users) < 1) {
982
-					continue;
983
-				}
984
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
985
-			} else {
986
-				//we need to apply the search filter now
987
-				if(!$this->access->readAttribute($member,
988
-					$this->access->connection->ldapUserDisplayName,
989
-					$this->access->getFilterPartForUserSearch($search))) {
990
-					continue;
991
-				}
992
-				// dn2username will also check if the users belong to the allowed base
993
-				if($ocname = $this->access->dn2username($member)) {
994
-					$groupUsers[] = $ocname;
995
-				}
996
-			}
997
-		}
998
-
999
-		//and get users that have the group as primary
1000
-		$primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
1001
-
1002
-		return count($groupUsers) + $primaryUsers;
1003
-	}
1004
-
1005
-	/**
1006
-	 * get a list of all groups
1007
-	 *
1008
-	 * @param string $search
1009
-	 * @param $limit
1010
-	 * @param int $offset
1011
-	 * @return array with group names
1012
-	 *
1013
-	 * Returns a list with all groups (used by getGroups)
1014
-	 */
1015
-	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1016
-		if(!$this->enabled) {
1017
-			return [];
1018
-		}
1019
-		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
1020
-
1021
-		//Check cache before driving unnecessary searches
1022
-		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1023
-		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
1024
-		if(!is_null($ldap_groups)) {
1025
-			return $ldap_groups;
1026
-		}
1027
-
1028
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
1029
-		// error. With a limit of 0, we get 0 results. So we pass null.
1030
-		if($limit <= 0) {
1031
-			$limit = null;
1032
-		}
1033
-		$filter = $this->access->combineFilterWithAnd([
1034
-			$this->access->connection->ldapGroupFilter,
1035
-			$this->access->getFilterPartForGroupSearch($search)
1036
-		]);
1037
-		\OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
1038
-		$ldap_groups = $this->access->fetchListOfGroups($filter,
1039
-				[$this->access->connection->ldapGroupDisplayName, 'dn'],
1040
-				$limit,
1041
-				$offset);
1042
-		$ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
1043
-
1044
-		$this->access->connection->writeToCache($cacheKey, $ldap_groups);
1045
-		return $ldap_groups;
1046
-	}
1047
-
1048
-	/**
1049
-	 * get a list of all groups using a paged search
1050
-	 *
1051
-	 * @param string $search
1052
-	 * @param int $limit
1053
-	 * @param int $offset
1054
-	 * @return array with group names
1055
-	 *
1056
-	 * Returns a list with all groups
1057
-	 * Uses a paged search if available to override a
1058
-	 * server side search limit.
1059
-	 * (active directory has a limit of 1000 by default)
1060
-	 */
1061
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
1062
-		if(!$this->enabled) {
1063
-			return [];
1064
-		}
1065
-		$search = $this->access->escapeFilterPart($search, true);
1066
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1067
-		if ($pagingSize <= 0) {
1068
-			return $this->getGroupsChunk($search, $limit, $offset);
1069
-		}
1070
-		$maxGroups = 100000; // limit max results (just for safety reasons)
1071
-		if ($limit > -1) {
1072
-		   $overallLimit = min($limit + $offset, $maxGroups);
1073
-		} else {
1074
-		   $overallLimit = $maxGroups;
1075
-		}
1076
-		$chunkOffset = $offset;
1077
-		$allGroups = [];
1078
-		while ($chunkOffset < $overallLimit) {
1079
-			$chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1080
-			$ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1081
-			$nread = count($ldapGroups);
1082
-			\OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1083
-			if ($nread) {
1084
-				$allGroups = array_merge($allGroups, $ldapGroups);
1085
-				$chunkOffset += $nread;
1086
-			}
1087
-			if ($nread < $chunkLimit) {
1088
-				break;
1089
-			}
1090
-		}
1091
-		return $allGroups;
1092
-	}
1093
-
1094
-	/**
1095
-	 * @param string $group
1096
-	 * @return bool
1097
-	 */
1098
-	public function groupMatchesFilter($group) {
1099
-		return (strripos($group, $this->groupSearch) !== false);
1100
-	}
1101
-
1102
-	/**
1103
-	 * check if a group exists
1104
-	 * @param string $gid
1105
-	 * @return bool
1106
-	 */
1107
-	public function groupExists($gid) {
1108
-		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1109
-		if(!is_null($groupExists)) {
1110
-			return (bool)$groupExists;
1111
-		}
1112
-
1113
-		//getting dn, if false the group does not exist. If dn, it may be mapped
1114
-		//only, requires more checking.
1115
-		$dn = $this->access->groupname2dn($gid);
1116
-		if(!$dn) {
1117
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1118
-			return false;
1119
-		}
1120
-
1121
-		//if group really still exists, we will be able to read its objectclass
1122
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1123
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1124
-			return false;
1125
-		}
1126
-
1127
-		$this->access->connection->writeToCache('groupExists'.$gid, true);
1128
-		return true;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Check if backend implements actions
1133
-	 * @param int $actions bitwise-or'ed actions
1134
-	 * @return boolean
1135
-	 *
1136
-	 * Returns the supported actions as int to be
1137
-	 * compared with GroupInterface::CREATE_GROUP etc.
1138
-	 */
1139
-	public function implementsActions($actions) {
1140
-		return (bool)((GroupInterface::COUNT_USERS |
1141
-				$this->groupPluginManager->getImplementedActions()) & $actions);
1142
-	}
1143
-
1144
-	/**
1145
-	 * Return access for LDAP interaction.
1146
-	 * @return Access instance of Access for LDAP interaction
1147
-	 */
1148
-	public function getLDAPAccess($gid) {
1149
-		return $this->access;
1150
-	}
1151
-
1152
-	/**
1153
-	 * create a group
1154
-	 * @param string $gid
1155
-	 * @return bool
1156
-	 * @throws \Exception
1157
-	 */
1158
-	public function createGroup($gid) {
1159
-		if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1160
-			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1161
-				//updates group mapping
1162
-				$uuid = $this->access->getUUID($dn, false);
1163
-				if(is_string($uuid)) {
1164
-					$this->access->mapAndAnnounceIfApplicable(
1165
-						$this->access->getGroupMapper(),
1166
-						$dn,
1167
-						$gid,
1168
-						$uuid,
1169
-						false
1170
-					);
1171
-					$this->access->cacheGroupExists($gid);
1172
-				}
1173
-			}
1174
-			return $dn != null;
1175
-		}
1176
-		throw new \Exception('Could not create group in LDAP backend.');
1177
-	}
1178
-
1179
-	/**
1180
-	 * delete a group
1181
-	 * @param string $gid gid of the group to delete
1182
-	 * @return bool
1183
-	 * @throws \Exception
1184
-	 */
1185
-	public function deleteGroup($gid) {
1186
-		if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1187
-			if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1188
-				#delete group in nextcloud internal db
1189
-				$this->access->getGroupMapper()->unmap($gid);
1190
-				$this->access->connection->writeToCache("groupExists".$gid, false);
1191
-			}
1192
-			return $ret;
1193
-		}
1194
-		throw new \Exception('Could not delete group in LDAP backend.');
1195
-	}
1196
-
1197
-	/**
1198
-	 * Add a user to a group
1199
-	 * @param string $uid Name of the user to add to group
1200
-	 * @param string $gid Name of the group in which add the user
1201
-	 * @return bool
1202
-	 * @throws \Exception
1203
-	 */
1204
-	public function addToGroup($uid, $gid) {
1205
-		if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1206
-			if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1207
-				$this->access->connection->clearCache();
1208
-				unset($this->cachedGroupMembers[$gid]);
1209
-			}
1210
-			return $ret;
1211
-		}
1212
-		throw new \Exception('Could not add user to group in LDAP backend.');
1213
-	}
1214
-
1215
-	/**
1216
-	 * Removes a user from a group
1217
-	 * @param string $uid Name of the user to remove from group
1218
-	 * @param string $gid Name of the group from which remove the user
1219
-	 * @return bool
1220
-	 * @throws \Exception
1221
-	 */
1222
-	public function removeFromGroup($uid, $gid) {
1223
-		if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1224
-			if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1225
-				$this->access->connection->clearCache();
1226
-				unset($this->cachedGroupMembers[$gid]);
1227
-			}
1228
-			return $ret;
1229
-		}
1230
-		throw new \Exception('Could not remove user from group in LDAP backend.');
1231
-	}
1232
-
1233
-	/**
1234
-	 * Gets group details
1235
-	 * @param string $gid Name of the group
1236
-	 * @return array | false
1237
-	 * @throws \Exception
1238
-	 */
1239
-	public function getGroupDetails($gid) {
1240
-		if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1241
-			return $this->groupPluginManager->getGroupDetails($gid);
1242
-		}
1243
-		throw new \Exception('Could not get group details in LDAP backend.');
1244
-	}
1245
-
1246
-	/**
1247
-	 * Return LDAP connection resource from a cloned connection.
1248
-	 * The cloned connection needs to be closed manually.
1249
-	 * of the current access.
1250
-	 * @param string $gid
1251
-	 * @return resource of the LDAP connection
1252
-	 */
1253
-	public function getNewLDAPConnection($gid) {
1254
-		$connection = clone $this->access->getConnection();
1255
-		return $connection->getConnectionResource();
1256
-	}
1257
-
1258
-	/**
1259
-	 * @throws \OC\ServerNotAvailableException
1260
-	 */
1261
-	public function getDisplayName(string $gid): string {
1262
-		if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
1263
-			return $this->groupPluginManager->getDisplayName($gid);
1264
-		}
1265
-
1266
-		$cacheKey = 'group_getDisplayName' . $gid;
1267
-		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1268
-			return $displayName;
1269
-		}
1270
-
1271
-		$displayName = $this->access->readAttribute(
1272
-			$this->access->groupname2dn($gid),
1273
-			$this->access->connection->ldapGroupDisplayName);
1274
-
1275
-		if ($displayName && (count($displayName) > 0)) {
1276
-			$displayName = $displayName[0];
1277
-			$this->access->connection->writeToCache($cacheKey, $displayName);
1278
-			return $displayName;
1279
-		}
1280
-
1281
-		return '';
1282
-	}
52
+    protected $enabled = false;
53
+
54
+    /**
55
+     * @var string[] $cachedGroupMembers array of users with gid as key
56
+     */
57
+    protected $cachedGroupMembers;
58
+
59
+    /**
60
+     * @var string[] $cachedGroupsByMember array of groups with uid as key
61
+     */
62
+    protected $cachedGroupsByMember;
63
+
64
+    /**
65
+     * @var string[] $cachedNestedGroups array of groups with gid (DN) as key
66
+     */
67
+    protected $cachedNestedGroups;
68
+
69
+    /** @var GroupPluginManager */
70
+    protected $groupPluginManager;
71
+
72
+    public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
73
+        parent::__construct($access);
74
+        $filter = $this->access->connection->ldapGroupFilter;
75
+        $gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
76
+        if(!empty($filter) && !empty($gassoc)) {
77
+            $this->enabled = true;
78
+        }
79
+
80
+        $this->cachedGroupMembers = new CappedMemoryCache();
81
+        $this->cachedGroupsByMember = new CappedMemoryCache();
82
+        $this->cachedNestedGroups = new CappedMemoryCache();
83
+        $this->groupPluginManager = $groupPluginManager;
84
+    }
85
+
86
+    /**
87
+     * is user in group?
88
+     * @param string $uid uid of the user
89
+     * @param string $gid gid of the group
90
+     * @return bool
91
+     *
92
+     * Checks whether the user is member of a group or not.
93
+     */
94
+    public function inGroup($uid, $gid) {
95
+        if(!$this->enabled) {
96
+            return false;
97
+        }
98
+        $cacheKey = 'inGroup'.$uid.':'.$gid;
99
+        $inGroup = $this->access->connection->getFromCache($cacheKey);
100
+        if(!is_null($inGroup)) {
101
+            return (bool)$inGroup;
102
+        }
103
+
104
+        $userDN = $this->access->username2dn($uid);
105
+
106
+        if(isset($this->cachedGroupMembers[$gid])) {
107
+            $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
108
+            return $isInGroup;
109
+        }
110
+
111
+        $cacheKeyMembers = 'inGroup-members:'.$gid;
112
+        $members = $this->access->connection->getFromCache($cacheKeyMembers);
113
+        if(!is_null($members)) {
114
+            $this->cachedGroupMembers[$gid] = $members;
115
+            $isInGroup = in_array($userDN, $members, true);
116
+            $this->access->connection->writeToCache($cacheKey, $isInGroup);
117
+            return $isInGroup;
118
+        }
119
+
120
+        $groupDN = $this->access->groupname2dn($gid);
121
+        // just in case
122
+        if(!$groupDN || !$userDN) {
123
+            $this->access->connection->writeToCache($cacheKey, false);
124
+            return false;
125
+        }
126
+
127
+        //check primary group first
128
+        if($gid === $this->getUserPrimaryGroup($userDN)) {
129
+            $this->access->connection->writeToCache($cacheKey, true);
130
+            return true;
131
+        }
132
+
133
+        //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
134
+        $members = $this->_groupMembers($groupDN);
135
+        if(!is_array($members) || count($members) === 0) {
136
+            $this->access->connection->writeToCache($cacheKey, false);
137
+            return false;
138
+        }
139
+
140
+        //extra work if we don't get back user DNs
141
+        if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
142
+            $dns = [];
143
+            $filterParts = [];
144
+            $bytes = 0;
145
+            foreach($members as $mid) {
146
+                $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
147
+                $filterParts[] = $filter;
148
+                $bytes += strlen($filter);
149
+                if($bytes >= 9000000) {
150
+                    // AD has a default input buffer of 10 MB, we do not want
151
+                    // to take even the chance to exceed it
152
+                    $filter = $this->access->combineFilterWithOr($filterParts);
153
+                    $bytes = 0;
154
+                    $filterParts = [];
155
+                    $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
156
+                    $dns = array_merge($dns, $users);
157
+                }
158
+            }
159
+            if(count($filterParts) > 0) {
160
+                $filter = $this->access->combineFilterWithOr($filterParts);
161
+                $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
162
+                $dns = array_merge($dns, $users);
163
+            }
164
+            $members = $dns;
165
+        }
166
+
167
+        $isInGroup = in_array($userDN, $members);
168
+        $this->access->connection->writeToCache($cacheKey, $isInGroup);
169
+        $this->access->connection->writeToCache($cacheKeyMembers, $members);
170
+        $this->cachedGroupMembers[$gid] = $members;
171
+
172
+        return $isInGroup;
173
+    }
174
+
175
+    /**
176
+     * @param string $dnGroup
177
+     * @return array
178
+     *
179
+     * For a group that has user membership defined by an LDAP search url attribute returns the users
180
+     * that match the search url otherwise returns an empty array.
181
+     */
182
+    public function getDynamicGroupMembers($dnGroup) {
183
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
184
+
185
+        if (empty($dynamicGroupMemberURL)) {
186
+            return [];
187
+        }
188
+
189
+        $dynamicMembers = [];
190
+        $memberURLs = $this->access->readAttribute(
191
+            $dnGroup,
192
+            $dynamicGroupMemberURL,
193
+            $this->access->connection->ldapGroupFilter
194
+        );
195
+        if ($memberURLs !== false) {
196
+            // this group has the 'memberURL' attribute so this is a dynamic group
197
+            // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
198
+            // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
199
+            $pos = strpos($memberURLs[0], '(');
200
+            if ($pos !== false) {
201
+                $memberUrlFilter = substr($memberURLs[0], $pos);
202
+                $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
203
+                $dynamicMembers = [];
204
+                foreach($foundMembers as $value) {
205
+                    $dynamicMembers[$value['dn'][0]] = 1;
206
+                }
207
+            } else {
208
+                \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
209
+                    'of group ' . $dnGroup, ILogger::DEBUG);
210
+            }
211
+        }
212
+        return $dynamicMembers;
213
+    }
214
+
215
+    /**
216
+     * @param string $dnGroup
217
+     * @param array|null &$seen
218
+     * @return array|mixed|null
219
+     * @throws \OC\ServerNotAvailableException
220
+     */
221
+    private function _groupMembers($dnGroup, &$seen = null) {
222
+        if ($seen === null) {
223
+            $seen = [];
224
+        }
225
+        $allMembers = [];
226
+        if (array_key_exists($dnGroup, $seen)) {
227
+            // avoid loops
228
+            return [];
229
+        }
230
+        // used extensively in cron job, caching makes sense for nested groups
231
+        $cacheKey = '_groupMembers'.$dnGroup;
232
+        $groupMembers = $this->access->connection->getFromCache($cacheKey);
233
+        if($groupMembers !== null) {
234
+            return $groupMembers;
235
+        }
236
+        $seen[$dnGroup] = 1;
237
+        $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
238
+        if (is_array($members)) {
239
+            $fetcher = function($memberDN, &$seen) {
240
+                return $this->_groupMembers($memberDN, $seen);
241
+            };
242
+            $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
243
+        }
244
+
245
+        $allMembers += $this->getDynamicGroupMembers($dnGroup);
246
+
247
+        $this->access->connection->writeToCache($cacheKey, $allMembers);
248
+        return $allMembers;
249
+    }
250
+
251
+    /**
252
+     * @param string $DN
253
+     * @param array|null &$seen
254
+     * @return array
255
+     * @throws \OC\ServerNotAvailableException
256
+     */
257
+    private function _getGroupDNsFromMemberOf($DN) {
258
+        $groups = $this->access->readAttribute($DN, 'memberOf');
259
+        if (!is_array($groups)) {
260
+            return [];
261
+        }
262
+
263
+        $fetcher = function($groupDN) {
264
+            if (isset($this->cachedNestedGroups[$groupDN])) {
265
+                $nestedGroups = $this->cachedNestedGroups[$groupDN];
266
+            } else {
267
+                $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf');
268
+                if (!is_array($nestedGroups)) {
269
+                    $nestedGroups = [];
270
+                }
271
+                $this->cachedNestedGroups[$groupDN] = $nestedGroups;
272
+            }
273
+            return $nestedGroups;
274
+        };
275
+
276
+        $groups = $this->walkNestedGroups($DN, $fetcher, $groups);
277
+        return $this->access->groupsMatchFilter($groups);
278
+    }
279
+
280
+    /**
281
+     * @param string $dn
282
+     * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns
283
+     * @param array $list
284
+     * @return array
285
+     */
286
+    private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array {
287
+        $nesting = (int) $this->access->connection->ldapNestedGroups;
288
+        // depending on the input, we either have a list of DNs or a list of LDAP records
289
+        // also, the output expects either DNs or records. Testing the first element should suffice.
290
+        $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
291
+
292
+        if ($nesting !== 1) {
293
+            if($recordMode) {
294
+                // the keys are numeric, but should hold the DN
295
+                return array_reduce($list, function ($transformed, $record) use ($dn) {
296
+                    if($record['dn'][0] != $dn) {
297
+                        $transformed[$record['dn'][0]] = $record;
298
+                    }
299
+                    return $transformed;
300
+                }, []);
301
+            }
302
+            return $list;
303
+        }
304
+
305
+        $seen = [];
306
+        while ($record = array_pop($list)) {
307
+            $recordDN = $recordMode ? $record['dn'][0] : $record;
308
+            if ($recordDN === $dn || array_key_exists($recordDN, $seen)) {
309
+                // Prevent loops
310
+                continue;
311
+            }
312
+            $fetched = $fetcher($record, $seen);
313
+            $list = array_merge($list, $fetched);
314
+            $seen[$recordDN] = $record;
315
+        }
316
+
317
+        return $recordMode ? $seen : array_keys($seen);
318
+    }
319
+
320
+    /**
321
+     * translates a gidNumber into an ownCloud internal name
322
+     * @param string $gid as given by gidNumber on POSIX LDAP
323
+     * @param string $dn a DN that belongs to the same domain as the group
324
+     * @return string|bool
325
+     */
326
+    public function gidNumber2Name($gid, $dn) {
327
+        $cacheKey = 'gidNumberToName' . $gid;
328
+        $groupName = $this->access->connection->getFromCache($cacheKey);
329
+        if(!is_null($groupName) && isset($groupName)) {
330
+            return $groupName;
331
+        }
332
+
333
+        //we need to get the DN from LDAP
334
+        $filter = $this->access->combineFilterWithAnd([
335
+            $this->access->connection->ldapGroupFilter,
336
+            'objectClass=posixGroup',
337
+            $this->access->connection->ldapGidNumber . '=' . $gid
338
+        ]);
339
+        $result = $this->access->searchGroups($filter, ['dn'], 1);
340
+        if(empty($result)) {
341
+            return false;
342
+        }
343
+        $dn = $result[0]['dn'][0];
344
+
345
+        //and now the group name
346
+        //NOTE once we have separate ownCloud group IDs and group names we can
347
+        //directly read the display name attribute instead of the DN
348
+        $name = $this->access->dn2groupname($dn);
349
+
350
+        $this->access->connection->writeToCache($cacheKey, $name);
351
+
352
+        return $name;
353
+    }
354
+
355
+    /**
356
+     * returns the entry's gidNumber
357
+     * @param string $dn
358
+     * @param string $attribute
359
+     * @return string|bool
360
+     */
361
+    private function getEntryGidNumber($dn, $attribute) {
362
+        $value = $this->access->readAttribute($dn, $attribute);
363
+        if(is_array($value) && !empty($value)) {
364
+            return $value[0];
365
+        }
366
+        return false;
367
+    }
368
+
369
+    /**
370
+     * returns the group's primary ID
371
+     * @param string $dn
372
+     * @return string|bool
373
+     */
374
+    public function getGroupGidNumber($dn) {
375
+        return $this->getEntryGidNumber($dn, 'gidNumber');
376
+    }
377
+
378
+    /**
379
+     * returns the user's gidNumber
380
+     * @param string $dn
381
+     * @return string|bool
382
+     */
383
+    public function getUserGidNumber($dn) {
384
+        $gidNumber = false;
385
+        if($this->access->connection->hasGidNumber) {
386
+            $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
387
+            if($gidNumber === false) {
388
+                $this->access->connection->hasGidNumber = false;
389
+            }
390
+        }
391
+        return $gidNumber;
392
+    }
393
+
394
+    /**
395
+     * returns a filter for a "users has specific gid" search or count operation
396
+     *
397
+     * @param string $groupDN
398
+     * @param string $search
399
+     * @return string
400
+     * @throws \Exception
401
+     */
402
+    private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
403
+        $groupID = $this->getGroupGidNumber($groupDN);
404
+        if($groupID === false) {
405
+            throw new \Exception('Not a valid group');
406
+        }
407
+
408
+        $filterParts = [];
409
+        $filterParts[] = $this->access->getFilterForUserCount();
410
+        if ($search !== '') {
411
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
412
+        }
413
+        $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
414
+
415
+        return $this->access->combineFilterWithAnd($filterParts);
416
+    }
417
+
418
+    /**
419
+     * returns a list of users that have the given group as gid number
420
+     *
421
+     * @param string $groupDN
422
+     * @param string $search
423
+     * @param int $limit
424
+     * @param int $offset
425
+     * @return string[]
426
+     */
427
+    public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
428
+        try {
429
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
430
+            $users = $this->access->fetchListOfUsers(
431
+                $filter,
432
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
433
+                $limit,
434
+                $offset
435
+            );
436
+            return $this->access->nextcloudUserNames($users);
437
+        } catch (\Exception $e) {
438
+            return [];
439
+        }
440
+    }
441
+
442
+    /**
443
+     * returns the number of users that have the given group as gid number
444
+     *
445
+     * @param string $groupDN
446
+     * @param string $search
447
+     * @param int $limit
448
+     * @param int $offset
449
+     * @return int
450
+     */
451
+    public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
452
+        try {
453
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
454
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
455
+            return (int)$users;
456
+        } catch (\Exception $e) {
457
+            return 0;
458
+        }
459
+    }
460
+
461
+    /**
462
+     * gets the gidNumber of a user
463
+     * @param string $dn
464
+     * @return string
465
+     */
466
+    public function getUserGroupByGid($dn) {
467
+        $groupID = $this->getUserGidNumber($dn);
468
+        if($groupID !== false) {
469
+            $groupName = $this->gidNumber2Name($groupID, $dn);
470
+            if($groupName !== false) {
471
+                return $groupName;
472
+            }
473
+        }
474
+
475
+        return false;
476
+    }
477
+
478
+    /**
479
+     * translates a primary group ID into an Nextcloud internal name
480
+     * @param string $gid as given by primaryGroupID on AD
481
+     * @param string $dn a DN that belongs to the same domain as the group
482
+     * @return string|bool
483
+     */
484
+    public function primaryGroupID2Name($gid, $dn) {
485
+        $cacheKey = 'primaryGroupIDtoName';
486
+        $groupNames = $this->access->connection->getFromCache($cacheKey);
487
+        if(!is_null($groupNames) && isset($groupNames[$gid])) {
488
+            return $groupNames[$gid];
489
+        }
490
+
491
+        $domainObjectSid = $this->access->getSID($dn);
492
+        if($domainObjectSid === false) {
493
+            return false;
494
+        }
495
+
496
+        //we need to get the DN from LDAP
497
+        $filter = $this->access->combineFilterWithAnd([
498
+            $this->access->connection->ldapGroupFilter,
499
+            'objectsid=' . $domainObjectSid . '-' . $gid
500
+        ]);
501
+        $result = $this->access->searchGroups($filter, ['dn'], 1);
502
+        if(empty($result)) {
503
+            return false;
504
+        }
505
+        $dn = $result[0]['dn'][0];
506
+
507
+        //and now the group name
508
+        //NOTE once we have separate Nextcloud group IDs and group names we can
509
+        //directly read the display name attribute instead of the DN
510
+        $name = $this->access->dn2groupname($dn);
511
+
512
+        $this->access->connection->writeToCache($cacheKey, $name);
513
+
514
+        return $name;
515
+    }
516
+
517
+    /**
518
+     * returns the entry's primary group ID
519
+     * @param string $dn
520
+     * @param string $attribute
521
+     * @return string|bool
522
+     */
523
+    private function getEntryGroupID($dn, $attribute) {
524
+        $value = $this->access->readAttribute($dn, $attribute);
525
+        if(is_array($value) && !empty($value)) {
526
+            return $value[0];
527
+        }
528
+        return false;
529
+    }
530
+
531
+    /**
532
+     * returns the group's primary ID
533
+     * @param string $dn
534
+     * @return string|bool
535
+     */
536
+    public function getGroupPrimaryGroupID($dn) {
537
+        return $this->getEntryGroupID($dn, 'primaryGroupToken');
538
+    }
539
+
540
+    /**
541
+     * returns the user's primary group ID
542
+     * @param string $dn
543
+     * @return string|bool
544
+     */
545
+    public function getUserPrimaryGroupIDs($dn) {
546
+        $primaryGroupID = false;
547
+        if($this->access->connection->hasPrimaryGroups) {
548
+            $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
549
+            if($primaryGroupID === false) {
550
+                $this->access->connection->hasPrimaryGroups = false;
551
+            }
552
+        }
553
+        return $primaryGroupID;
554
+    }
555
+
556
+    /**
557
+     * returns a filter for a "users in primary group" search or count operation
558
+     *
559
+     * @param string $groupDN
560
+     * @param string $search
561
+     * @return string
562
+     * @throws \Exception
563
+     */
564
+    private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
565
+        $groupID = $this->getGroupPrimaryGroupID($groupDN);
566
+        if($groupID === false) {
567
+            throw new \Exception('Not a valid group');
568
+        }
569
+
570
+        $filterParts = [];
571
+        $filterParts[] = $this->access->getFilterForUserCount();
572
+        if ($search !== '') {
573
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
574
+        }
575
+        $filterParts[] = 'primaryGroupID=' . $groupID;
576
+
577
+        return $this->access->combineFilterWithAnd($filterParts);
578
+    }
579
+
580
+    /**
581
+     * returns a list of users that have the given group as primary group
582
+     *
583
+     * @param string $groupDN
584
+     * @param string $search
585
+     * @param int $limit
586
+     * @param int $offset
587
+     * @return string[]
588
+     */
589
+    public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
590
+        try {
591
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
592
+            $users = $this->access->fetchListOfUsers(
593
+                $filter,
594
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
595
+                $limit,
596
+                $offset
597
+            );
598
+            return $this->access->nextcloudUserNames($users);
599
+        } catch (\Exception $e) {
600
+            return [];
601
+        }
602
+    }
603
+
604
+    /**
605
+     * returns the number of users that have the given group as primary group
606
+     *
607
+     * @param string $groupDN
608
+     * @param string $search
609
+     * @param int $limit
610
+     * @param int $offset
611
+     * @return int
612
+     */
613
+    public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
614
+        try {
615
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
616
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
617
+            return (int)$users;
618
+        } catch (\Exception $e) {
619
+            return 0;
620
+        }
621
+    }
622
+
623
+    /**
624
+     * gets the primary group of a user
625
+     * @param string $dn
626
+     * @return string
627
+     */
628
+    public function getUserPrimaryGroup($dn) {
629
+        $groupID = $this->getUserPrimaryGroupIDs($dn);
630
+        if($groupID !== false) {
631
+            $groupName = $this->primaryGroupID2Name($groupID, $dn);
632
+            if($groupName !== false) {
633
+                return $groupName;
634
+            }
635
+        }
636
+
637
+        return false;
638
+    }
639
+
640
+    /**
641
+     * Get all groups a user belongs to
642
+     * @param string $uid Name of the user
643
+     * @return array with group names
644
+     *
645
+     * This function fetches all groups a user belongs to. It does not check
646
+     * if the user exists at all.
647
+     *
648
+     * This function includes groups based on dynamic group membership.
649
+     */
650
+    public function getUserGroups($uid) {
651
+        if(!$this->enabled) {
652
+            return [];
653
+        }
654
+        $cacheKey = 'getUserGroups'.$uid;
655
+        $userGroups = $this->access->connection->getFromCache($cacheKey);
656
+        if(!is_null($userGroups)) {
657
+            return $userGroups;
658
+        }
659
+        $userDN = $this->access->username2dn($uid);
660
+        if(!$userDN) {
661
+            $this->access->connection->writeToCache($cacheKey, []);
662
+            return [];
663
+        }
664
+
665
+        $groups = [];
666
+        $primaryGroup = $this->getUserPrimaryGroup($userDN);
667
+        $gidGroupName = $this->getUserGroupByGid($userDN);
668
+
669
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
670
+
671
+        if (!empty($dynamicGroupMemberURL)) {
672
+            // look through dynamic groups to add them to the result array if needed
673
+            $groupsToMatch = $this->access->fetchListOfGroups(
674
+                $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
675
+            foreach($groupsToMatch as $dynamicGroup) {
676
+                if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
677
+                    continue;
678
+                }
679
+                $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
680
+                if ($pos !== false) {
681
+                    $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
682
+                    // apply filter via ldap search to see if this user is in this
683
+                    // dynamic group
684
+                    $userMatch = $this->access->readAttribute(
685
+                        $userDN,
686
+                        $this->access->connection->ldapUserDisplayName,
687
+                        $memberUrlFilter
688
+                    );
689
+                    if ($userMatch !== false) {
690
+                        // match found so this user is in this group
691
+                        $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
692
+                        if(is_string($groupName)) {
693
+                            // be sure to never return false if the dn could not be
694
+                            // resolved to a name, for whatever reason.
695
+                            $groups[] = $groupName;
696
+                        }
697
+                    }
698
+                } else {
699
+                    \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
700
+                        'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
701
+                }
702
+            }
703
+        }
704
+
705
+        // if possible, read out membership via memberOf. It's far faster than
706
+        // performing a search, which still is a fallback later.
707
+        // memberof doesn't support memberuid, so skip it here.
708
+        if((int)$this->access->connection->hasMemberOfFilterSupport === 1
709
+            && (int)$this->access->connection->useMemberOfToDetectMembership === 1
710
+            && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
711
+            ) {
712
+            $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
713
+            if (is_array($groupDNs)) {
714
+                foreach ($groupDNs as $dn) {
715
+                    $groupName = $this->access->dn2groupname($dn);
716
+                    if(is_string($groupName)) {
717
+                        // be sure to never return false if the dn could not be
718
+                        // resolved to a name, for whatever reason.
719
+                        $groups[] = $groupName;
720
+                    }
721
+                }
722
+            }
723
+
724
+            if($primaryGroup !== false) {
725
+                $groups[] = $primaryGroup;
726
+            }
727
+            if($gidGroupName !== false) {
728
+                $groups[] = $gidGroupName;
729
+            }
730
+            $this->access->connection->writeToCache($cacheKey, $groups);
731
+            return $groups;
732
+        }
733
+
734
+        //uniqueMember takes DN, memberuid the uid, so we need to distinguish
735
+        if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
736
+            || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
737
+        ) {
738
+            $uid = $userDN;
739
+        } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
740
+            $result = $this->access->readAttribute($userDN, 'uid');
741
+            if ($result === false) {
742
+                \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
743
+                    $this->access->connection->ldapHost, ILogger::DEBUG);
744
+                $uid = false;
745
+            } else {
746
+                $uid = $result[0];
747
+            }
748
+        } else {
749
+            // just in case
750
+            $uid = $userDN;
751
+        }
752
+
753
+        if($uid !== false) {
754
+            if (isset($this->cachedGroupsByMember[$uid])) {
755
+                $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
756
+            } else {
757
+                $groupsByMember = array_values($this->getGroupsByMember($uid));
758
+                $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
759
+                $this->cachedGroupsByMember[$uid] = $groupsByMember;
760
+                $groups = array_merge($groups, $groupsByMember);
761
+            }
762
+        }
763
+
764
+        if($primaryGroup !== false) {
765
+            $groups[] = $primaryGroup;
766
+        }
767
+        if($gidGroupName !== false) {
768
+            $groups[] = $gidGroupName;
769
+        }
770
+
771
+        $groups = array_unique($groups, SORT_LOCALE_STRING);
772
+        $this->access->connection->writeToCache($cacheKey, $groups);
773
+
774
+        return $groups;
775
+    }
776
+
777
+    /**
778
+     * @param string $dn
779
+     * @param array|null &$seen
780
+     * @return array
781
+     */
782
+    private function getGroupsByMember($dn, &$seen = null) {
783
+        if ($seen === null) {
784
+            $seen = [];
785
+        }
786
+        if (array_key_exists($dn, $seen)) {
787
+            // avoid loops
788
+            return [];
789
+        }
790
+        $allGroups = [];
791
+        $seen[$dn] = true;
792
+        $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn;
793
+        $groups = $this->access->fetchListOfGroups($filter,
794
+            [$this->access->connection->ldapGroupDisplayName, 'dn']);
795
+        if (is_array($groups)) {
796
+            $fetcher = function ($dn, &$seen) {
797
+                if(is_array($dn) && isset($dn['dn'][0])) {
798
+                    $dn = $dn['dn'][0];
799
+                }
800
+                return $this->getGroupsByMember($dn, $seen);
801
+            };
802
+            $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups);
803
+        }
804
+        $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups));
805
+        return array_intersect_key($allGroups, array_flip($visibleGroups));
806
+    }
807
+
808
+    /**
809
+     * get a list of all users in a group
810
+     *
811
+     * @param string $gid
812
+     * @param string $search
813
+     * @param int $limit
814
+     * @param int $offset
815
+     * @return array with user ids
816
+     * @throws \Exception
817
+     */
818
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
819
+        if(!$this->enabled) {
820
+            return [];
821
+        }
822
+        if(!$this->groupExists($gid)) {
823
+            return [];
824
+        }
825
+        $search = $this->access->escapeFilterPart($search, true);
826
+        $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
827
+        // check for cache of the exact query
828
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
829
+        if(!is_null($groupUsers)) {
830
+            return $groupUsers;
831
+        }
832
+
833
+        // check for cache of the query without limit and offset
834
+        $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
835
+        if(!is_null($groupUsers)) {
836
+            $groupUsers = array_slice($groupUsers, $offset, $limit);
837
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
838
+            return $groupUsers;
839
+        }
840
+
841
+        if($limit === -1) {
842
+            $limit = null;
843
+        }
844
+        $groupDN = $this->access->groupname2dn($gid);
845
+        if(!$groupDN) {
846
+            // group couldn't be found, return empty resultset
847
+            $this->access->connection->writeToCache($cacheKey, []);
848
+            return [];
849
+        }
850
+
851
+        $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
852
+        $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
853
+        $members = $this->_groupMembers($groupDN);
854
+        if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
855
+            //in case users could not be retrieved, return empty result set
856
+            $this->access->connection->writeToCache($cacheKey, []);
857
+            return [];
858
+        }
859
+
860
+        $groupUsers = [];
861
+        $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
862
+        $attrs = $this->access->userManager->getAttributes(true);
863
+        foreach($members as $member) {
864
+            if($isMemberUid) {
865
+                //we got uids, need to get their DNs to 'translate' them to user names
866
+                $filter = $this->access->combineFilterWithAnd([
867
+                    str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
868
+                    $this->access->combineFilterWithAnd([
869
+                        $this->access->getFilterPartForUserSearch($search),
870
+                        $this->access->connection->ldapUserFilter
871
+                    ])
872
+                ]);
873
+                $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
874
+                if(count($ldap_users) < 1) {
875
+                    continue;
876
+                }
877
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
878
+            } else {
879
+                //we got DNs, check if we need to filter by search or we can give back all of them
880
+                $uid = $this->access->dn2username($member);
881
+                if(!$uid) {
882
+                    continue;
883
+                }
884
+
885
+                $cacheKey = 'userExistsOnLDAP' . $uid;
886
+                $userExists = $this->access->connection->getFromCache($cacheKey);
887
+                if($userExists === false) {
888
+                    continue;
889
+                }
890
+                if($userExists === null || $search !== '') {
891
+                    if (!$this->access->readAttribute($member,
892
+                        $this->access->connection->ldapUserDisplayName,
893
+                        $this->access->combineFilterWithAnd([
894
+                            $this->access->getFilterPartForUserSearch($search),
895
+                            $this->access->connection->ldapUserFilter
896
+                        ])))
897
+                    {
898
+                        if($search === '') {
899
+                            $this->access->connection->writeToCache($cacheKey, false);
900
+                        }
901
+                        continue;
902
+                    }
903
+                    $this->access->connection->writeToCache($cacheKey, true);
904
+                }
905
+                $groupUsers[] = $uid;
906
+            }
907
+        }
908
+
909
+        $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
910
+        natsort($groupUsers);
911
+        $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
912
+        $groupUsers = array_slice($groupUsers, $offset, $limit);
913
+
914
+        $this->access->connection->writeToCache($cacheKey, $groupUsers);
915
+
916
+        return $groupUsers;
917
+    }
918
+
919
+    /**
920
+     * returns the number of users in a group, who match the search term
921
+     * @param string $gid the internal group name
922
+     * @param string $search optional, a search string
923
+     * @return int|bool
924
+     */
925
+    public function countUsersInGroup($gid, $search = '') {
926
+        if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
927
+            return $this->groupPluginManager->countUsersInGroup($gid, $search);
928
+        }
929
+
930
+        $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
931
+        if(!$this->enabled || !$this->groupExists($gid)) {
932
+            return false;
933
+        }
934
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
935
+        if(!is_null($groupUsers)) {
936
+            return $groupUsers;
937
+        }
938
+
939
+        $groupDN = $this->access->groupname2dn($gid);
940
+        if(!$groupDN) {
941
+            // group couldn't be found, return empty result set
942
+            $this->access->connection->writeToCache($cacheKey, false);
943
+            return false;
944
+        }
945
+
946
+        $members = $this->_groupMembers($groupDN);
947
+        $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
948
+        if(!$members && $primaryUserCount === 0) {
949
+            //in case users could not be retrieved, return empty result set
950
+            $this->access->connection->writeToCache($cacheKey, false);
951
+            return false;
952
+        }
953
+
954
+        if ($search === '') {
955
+            $groupUsers = count($members) + $primaryUserCount;
956
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
957
+            return $groupUsers;
958
+        }
959
+        $search = $this->access->escapeFilterPart($search, true);
960
+        $isMemberUid =
961
+            (strtolower($this->access->connection->ldapGroupMemberAssocAttr)
962
+            === 'memberuid');
963
+
964
+        //we need to apply the search filter
965
+        //alternatives that need to be checked:
966
+        //a) get all users by search filter and array_intersect them
967
+        //b) a, but only when less than 1k 10k ?k users like it is
968
+        //c) put all DNs|uids in a LDAP filter, combine with the search string
969
+        //   and let it count.
970
+        //For now this is not important, because the only use of this method
971
+        //does not supply a search string
972
+        $groupUsers = [];
973
+        foreach($members as $member) {
974
+            if($isMemberUid) {
975
+                //we got uids, need to get their DNs to 'translate' them to user names
976
+                $filter = $this->access->combineFilterWithAnd([
977
+                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
978
+                    $this->access->getFilterPartForUserSearch($search)
979
+                ]);
980
+                $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
981
+                if(count($ldap_users) < 1) {
982
+                    continue;
983
+                }
984
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]);
985
+            } else {
986
+                //we need to apply the search filter now
987
+                if(!$this->access->readAttribute($member,
988
+                    $this->access->connection->ldapUserDisplayName,
989
+                    $this->access->getFilterPartForUserSearch($search))) {
990
+                    continue;
991
+                }
992
+                // dn2username will also check if the users belong to the allowed base
993
+                if($ocname = $this->access->dn2username($member)) {
994
+                    $groupUsers[] = $ocname;
995
+                }
996
+            }
997
+        }
998
+
999
+        //and get users that have the group as primary
1000
+        $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
1001
+
1002
+        return count($groupUsers) + $primaryUsers;
1003
+    }
1004
+
1005
+    /**
1006
+     * get a list of all groups
1007
+     *
1008
+     * @param string $search
1009
+     * @param $limit
1010
+     * @param int $offset
1011
+     * @return array with group names
1012
+     *
1013
+     * Returns a list with all groups (used by getGroups)
1014
+     */
1015
+    protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1016
+        if(!$this->enabled) {
1017
+            return [];
1018
+        }
1019
+        $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
1020
+
1021
+        //Check cache before driving unnecessary searches
1022
+        \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1023
+        $ldap_groups = $this->access->connection->getFromCache($cacheKey);
1024
+        if(!is_null($ldap_groups)) {
1025
+            return $ldap_groups;
1026
+        }
1027
+
1028
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
1029
+        // error. With a limit of 0, we get 0 results. So we pass null.
1030
+        if($limit <= 0) {
1031
+            $limit = null;
1032
+        }
1033
+        $filter = $this->access->combineFilterWithAnd([
1034
+            $this->access->connection->ldapGroupFilter,
1035
+            $this->access->getFilterPartForGroupSearch($search)
1036
+        ]);
1037
+        \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
1038
+        $ldap_groups = $this->access->fetchListOfGroups($filter,
1039
+                [$this->access->connection->ldapGroupDisplayName, 'dn'],
1040
+                $limit,
1041
+                $offset);
1042
+        $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
1043
+
1044
+        $this->access->connection->writeToCache($cacheKey, $ldap_groups);
1045
+        return $ldap_groups;
1046
+    }
1047
+
1048
+    /**
1049
+     * get a list of all groups using a paged search
1050
+     *
1051
+     * @param string $search
1052
+     * @param int $limit
1053
+     * @param int $offset
1054
+     * @return array with group names
1055
+     *
1056
+     * Returns a list with all groups
1057
+     * Uses a paged search if available to override a
1058
+     * server side search limit.
1059
+     * (active directory has a limit of 1000 by default)
1060
+     */
1061
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
1062
+        if(!$this->enabled) {
1063
+            return [];
1064
+        }
1065
+        $search = $this->access->escapeFilterPart($search, true);
1066
+        $pagingSize = (int)$this->access->connection->ldapPagingSize;
1067
+        if ($pagingSize <= 0) {
1068
+            return $this->getGroupsChunk($search, $limit, $offset);
1069
+        }
1070
+        $maxGroups = 100000; // limit max results (just for safety reasons)
1071
+        if ($limit > -1) {
1072
+            $overallLimit = min($limit + $offset, $maxGroups);
1073
+        } else {
1074
+            $overallLimit = $maxGroups;
1075
+        }
1076
+        $chunkOffset = $offset;
1077
+        $allGroups = [];
1078
+        while ($chunkOffset < $overallLimit) {
1079
+            $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1080
+            $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1081
+            $nread = count($ldapGroups);
1082
+            \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1083
+            if ($nread) {
1084
+                $allGroups = array_merge($allGroups, $ldapGroups);
1085
+                $chunkOffset += $nread;
1086
+            }
1087
+            if ($nread < $chunkLimit) {
1088
+                break;
1089
+            }
1090
+        }
1091
+        return $allGroups;
1092
+    }
1093
+
1094
+    /**
1095
+     * @param string $group
1096
+     * @return bool
1097
+     */
1098
+    public function groupMatchesFilter($group) {
1099
+        return (strripos($group, $this->groupSearch) !== false);
1100
+    }
1101
+
1102
+    /**
1103
+     * check if a group exists
1104
+     * @param string $gid
1105
+     * @return bool
1106
+     */
1107
+    public function groupExists($gid) {
1108
+        $groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1109
+        if(!is_null($groupExists)) {
1110
+            return (bool)$groupExists;
1111
+        }
1112
+
1113
+        //getting dn, if false the group does not exist. If dn, it may be mapped
1114
+        //only, requires more checking.
1115
+        $dn = $this->access->groupname2dn($gid);
1116
+        if(!$dn) {
1117
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1118
+            return false;
1119
+        }
1120
+
1121
+        //if group really still exists, we will be able to read its objectclass
1122
+        if(!is_array($this->access->readAttribute($dn, ''))) {
1123
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1124
+            return false;
1125
+        }
1126
+
1127
+        $this->access->connection->writeToCache('groupExists'.$gid, true);
1128
+        return true;
1129
+    }
1130
+
1131
+    /**
1132
+     * Check if backend implements actions
1133
+     * @param int $actions bitwise-or'ed actions
1134
+     * @return boolean
1135
+     *
1136
+     * Returns the supported actions as int to be
1137
+     * compared with GroupInterface::CREATE_GROUP etc.
1138
+     */
1139
+    public function implementsActions($actions) {
1140
+        return (bool)((GroupInterface::COUNT_USERS |
1141
+                $this->groupPluginManager->getImplementedActions()) & $actions);
1142
+    }
1143
+
1144
+    /**
1145
+     * Return access for LDAP interaction.
1146
+     * @return Access instance of Access for LDAP interaction
1147
+     */
1148
+    public function getLDAPAccess($gid) {
1149
+        return $this->access;
1150
+    }
1151
+
1152
+    /**
1153
+     * create a group
1154
+     * @param string $gid
1155
+     * @return bool
1156
+     * @throws \Exception
1157
+     */
1158
+    public function createGroup($gid) {
1159
+        if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1160
+            if ($dn = $this->groupPluginManager->createGroup($gid)) {
1161
+                //updates group mapping
1162
+                $uuid = $this->access->getUUID($dn, false);
1163
+                if(is_string($uuid)) {
1164
+                    $this->access->mapAndAnnounceIfApplicable(
1165
+                        $this->access->getGroupMapper(),
1166
+                        $dn,
1167
+                        $gid,
1168
+                        $uuid,
1169
+                        false
1170
+                    );
1171
+                    $this->access->cacheGroupExists($gid);
1172
+                }
1173
+            }
1174
+            return $dn != null;
1175
+        }
1176
+        throw new \Exception('Could not create group in LDAP backend.');
1177
+    }
1178
+
1179
+    /**
1180
+     * delete a group
1181
+     * @param string $gid gid of the group to delete
1182
+     * @return bool
1183
+     * @throws \Exception
1184
+     */
1185
+    public function deleteGroup($gid) {
1186
+        if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1187
+            if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1188
+                #delete group in nextcloud internal db
1189
+                $this->access->getGroupMapper()->unmap($gid);
1190
+                $this->access->connection->writeToCache("groupExists".$gid, false);
1191
+            }
1192
+            return $ret;
1193
+        }
1194
+        throw new \Exception('Could not delete group in LDAP backend.');
1195
+    }
1196
+
1197
+    /**
1198
+     * Add a user to a group
1199
+     * @param string $uid Name of the user to add to group
1200
+     * @param string $gid Name of the group in which add the user
1201
+     * @return bool
1202
+     * @throws \Exception
1203
+     */
1204
+    public function addToGroup($uid, $gid) {
1205
+        if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1206
+            if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1207
+                $this->access->connection->clearCache();
1208
+                unset($this->cachedGroupMembers[$gid]);
1209
+            }
1210
+            return $ret;
1211
+        }
1212
+        throw new \Exception('Could not add user to group in LDAP backend.');
1213
+    }
1214
+
1215
+    /**
1216
+     * Removes a user from a group
1217
+     * @param string $uid Name of the user to remove from group
1218
+     * @param string $gid Name of the group from which remove the user
1219
+     * @return bool
1220
+     * @throws \Exception
1221
+     */
1222
+    public function removeFromGroup($uid, $gid) {
1223
+        if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1224
+            if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1225
+                $this->access->connection->clearCache();
1226
+                unset($this->cachedGroupMembers[$gid]);
1227
+            }
1228
+            return $ret;
1229
+        }
1230
+        throw new \Exception('Could not remove user from group in LDAP backend.');
1231
+    }
1232
+
1233
+    /**
1234
+     * Gets group details
1235
+     * @param string $gid Name of the group
1236
+     * @return array | false
1237
+     * @throws \Exception
1238
+     */
1239
+    public function getGroupDetails($gid) {
1240
+        if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1241
+            return $this->groupPluginManager->getGroupDetails($gid);
1242
+        }
1243
+        throw new \Exception('Could not get group details in LDAP backend.');
1244
+    }
1245
+
1246
+    /**
1247
+     * Return LDAP connection resource from a cloned connection.
1248
+     * The cloned connection needs to be closed manually.
1249
+     * of the current access.
1250
+     * @param string $gid
1251
+     * @return resource of the LDAP connection
1252
+     */
1253
+    public function getNewLDAPConnection($gid) {
1254
+        $connection = clone $this->access->getConnection();
1255
+        return $connection->getConnectionResource();
1256
+    }
1257
+
1258
+    /**
1259
+     * @throws \OC\ServerNotAvailableException
1260
+     */
1261
+    public function getDisplayName(string $gid): string {
1262
+        if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
1263
+            return $this->groupPluginManager->getDisplayName($gid);
1264
+        }
1265
+
1266
+        $cacheKey = 'group_getDisplayName' . $gid;
1267
+        if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1268
+            return $displayName;
1269
+        }
1270
+
1271
+        $displayName = $this->access->readAttribute(
1272
+            $this->access->groupname2dn($gid),
1273
+            $this->access->connection->ldapGroupDisplayName);
1274
+
1275
+        if ($displayName && (count($displayName) > 0)) {
1276
+            $displayName = $displayName[0];
1277
+            $this->access->connection->writeToCache($cacheKey, $displayName);
1278
+            return $displayName;
1279
+        }
1280
+
1281
+        return '';
1282
+    }
1283 1283
 }
Please login to merge, or discard this patch.
Spacing   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		parent::__construct($access);
74 74
 		$filter = $this->access->connection->ldapGroupFilter;
75 75
 		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
76
-		if(!empty($filter) && !empty($gassoc)) {
76
+		if (!empty($filter) && !empty($gassoc)) {
77 77
 			$this->enabled = true;
78 78
 		}
79 79
 
@@ -92,25 +92,25 @@  discard block
 block discarded – undo
92 92
 	 * Checks whether the user is member of a group or not.
93 93
 	 */
94 94
 	public function inGroup($uid, $gid) {
95
-		if(!$this->enabled) {
95
+		if (!$this->enabled) {
96 96
 			return false;
97 97
 		}
98 98
 		$cacheKey = 'inGroup'.$uid.':'.$gid;
99 99
 		$inGroup = $this->access->connection->getFromCache($cacheKey);
100
-		if(!is_null($inGroup)) {
101
-			return (bool)$inGroup;
100
+		if (!is_null($inGroup)) {
101
+			return (bool) $inGroup;
102 102
 		}
103 103
 
104 104
 		$userDN = $this->access->username2dn($uid);
105 105
 
106
-		if(isset($this->cachedGroupMembers[$gid])) {
106
+		if (isset($this->cachedGroupMembers[$gid])) {
107 107
 			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
108 108
 			return $isInGroup;
109 109
 		}
110 110
 
111 111
 		$cacheKeyMembers = 'inGroup-members:'.$gid;
112 112
 		$members = $this->access->connection->getFromCache($cacheKeyMembers);
113
-		if(!is_null($members)) {
113
+		if (!is_null($members)) {
114 114
 			$this->cachedGroupMembers[$gid] = $members;
115 115
 			$isInGroup = in_array($userDN, $members, true);
116 116
 			$this->access->connection->writeToCache($cacheKey, $isInGroup);
@@ -119,34 +119,34 @@  discard block
 block discarded – undo
119 119
 
120 120
 		$groupDN = $this->access->groupname2dn($gid);
121 121
 		// just in case
122
-		if(!$groupDN || !$userDN) {
122
+		if (!$groupDN || !$userDN) {
123 123
 			$this->access->connection->writeToCache($cacheKey, false);
124 124
 			return false;
125 125
 		}
126 126
 
127 127
 		//check primary group first
128
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
128
+		if ($gid === $this->getUserPrimaryGroup($userDN)) {
129 129
 			$this->access->connection->writeToCache($cacheKey, true);
130 130
 			return true;
131 131
 		}
132 132
 
133 133
 		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
134 134
 		$members = $this->_groupMembers($groupDN);
135
-		if(!is_array($members) || count($members) === 0) {
135
+		if (!is_array($members) || count($members) === 0) {
136 136
 			$this->access->connection->writeToCache($cacheKey, false);
137 137
 			return false;
138 138
 		}
139 139
 
140 140
 		//extra work if we don't get back user DNs
141
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
141
+		if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
142 142
 			$dns = [];
143 143
 			$filterParts = [];
144 144
 			$bytes = 0;
145
-			foreach($members as $mid) {
145
+			foreach ($members as $mid) {
146 146
 				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
147 147
 				$filterParts[] = $filter;
148 148
 				$bytes += strlen($filter);
149
-				if($bytes >= 9000000) {
149
+				if ($bytes >= 9000000) {
150 150
 					// AD has a default input buffer of 10 MB, we do not want
151 151
 					// to take even the chance to exceed it
152 152
 					$filter = $this->access->combineFilterWithOr($filterParts);
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 					$dns = array_merge($dns, $users);
157 157
 				}
158 158
 			}
159
-			if(count($filterParts) > 0) {
159
+			if (count($filterParts) > 0) {
160 160
 				$filter = $this->access->combineFilterWithOr($filterParts);
161 161
 				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
162 162
 				$dns = array_merge($dns, $users);
@@ -199,14 +199,14 @@  discard block
 block discarded – undo
199 199
 			$pos = strpos($memberURLs[0], '(');
200 200
 			if ($pos !== false) {
201 201
 				$memberUrlFilter = substr($memberURLs[0], $pos);
202
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
202
+				$foundMembers = $this->access->searchUsers($memberUrlFilter, 'dn');
203 203
 				$dynamicMembers = [];
204
-				foreach($foundMembers as $value) {
204
+				foreach ($foundMembers as $value) {
205 205
 					$dynamicMembers[$value['dn'][0]] = 1;
206 206
 				}
207 207
 			} else {
208 208
 				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
209
-					'of group ' . $dnGroup, ILogger::DEBUG);
209
+					'of group '.$dnGroup, ILogger::DEBUG);
210 210
 			}
211 211
 		}
212 212
 		return $dynamicMembers;
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		// used extensively in cron job, caching makes sense for nested groups
231 231
 		$cacheKey = '_groupMembers'.$dnGroup;
232 232
 		$groupMembers = $this->access->connection->getFromCache($cacheKey);
233
-		if($groupMembers !== null) {
233
+		if ($groupMembers !== null) {
234 234
 			return $groupMembers;
235 235
 		}
236 236
 		$seen[$dnGroup] = 1;
@@ -290,10 +290,10 @@  discard block
 block discarded – undo
290 290
 		$recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
291 291
 
292 292
 		if ($nesting !== 1) {
293
-			if($recordMode) {
293
+			if ($recordMode) {
294 294
 				// the keys are numeric, but should hold the DN
295
-				return array_reduce($list, function ($transformed, $record) use ($dn) {
296
-					if($record['dn'][0] != $dn) {
295
+				return array_reduce($list, function($transformed, $record) use ($dn) {
296
+					if ($record['dn'][0] != $dn) {
297 297
 						$transformed[$record['dn'][0]] = $record;
298 298
 					}
299 299
 					return $transformed;
@@ -324,9 +324,9 @@  discard block
 block discarded – undo
324 324
 	 * @return string|bool
325 325
 	 */
326 326
 	public function gidNumber2Name($gid, $dn) {
327
-		$cacheKey = 'gidNumberToName' . $gid;
327
+		$cacheKey = 'gidNumberToName'.$gid;
328 328
 		$groupName = $this->access->connection->getFromCache($cacheKey);
329
-		if(!is_null($groupName) && isset($groupName)) {
329
+		if (!is_null($groupName) && isset($groupName)) {
330 330
 			return $groupName;
331 331
 		}
332 332
 
@@ -334,10 +334,10 @@  discard block
 block discarded – undo
334 334
 		$filter = $this->access->combineFilterWithAnd([
335 335
 			$this->access->connection->ldapGroupFilter,
336 336
 			'objectClass=posixGroup',
337
-			$this->access->connection->ldapGidNumber . '=' . $gid
337
+			$this->access->connection->ldapGidNumber.'='.$gid
338 338
 		]);
339 339
 		$result = $this->access->searchGroups($filter, ['dn'], 1);
340
-		if(empty($result)) {
340
+		if (empty($result)) {
341 341
 			return false;
342 342
 		}
343 343
 		$dn = $result[0]['dn'][0];
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 	 */
361 361
 	private function getEntryGidNumber($dn, $attribute) {
362 362
 		$value = $this->access->readAttribute($dn, $attribute);
363
-		if(is_array($value) && !empty($value)) {
363
+		if (is_array($value) && !empty($value)) {
364 364
 			return $value[0];
365 365
 		}
366 366
 		return false;
@@ -382,9 +382,9 @@  discard block
 block discarded – undo
382 382
 	 */
383 383
 	public function getUserGidNumber($dn) {
384 384
 		$gidNumber = false;
385
-		if($this->access->connection->hasGidNumber) {
385
+		if ($this->access->connection->hasGidNumber) {
386 386
 			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
387
-			if($gidNumber === false) {
387
+			if ($gidNumber === false) {
388 388
 				$this->access->connection->hasGidNumber = false;
389 389
 			}
390 390
 		}
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 	 */
402 402
 	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
403 403
 		$groupID = $this->getGroupGidNumber($groupDN);
404
-		if($groupID === false) {
404
+		if ($groupID === false) {
405 405
 			throw new \Exception('Not a valid group');
406 406
 		}
407 407
 
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		if ($search !== '') {
411 411
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
412 412
 		}
413
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
413
+		$filterParts[] = $this->access->connection->ldapGidNumber.'='.$groupID;
414 414
 
415 415
 		return $this->access->combineFilterWithAnd($filterParts);
416 416
 	}
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 		try {
453 453
 			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
454 454
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
455
-			return (int)$users;
455
+			return (int) $users;
456 456
 		} catch (\Exception $e) {
457 457
 			return 0;
458 458
 		}
@@ -465,9 +465,9 @@  discard block
 block discarded – undo
465 465
 	 */
466 466
 	public function getUserGroupByGid($dn) {
467 467
 		$groupID = $this->getUserGidNumber($dn);
468
-		if($groupID !== false) {
468
+		if ($groupID !== false) {
469 469
 			$groupName = $this->gidNumber2Name($groupID, $dn);
470
-			if($groupName !== false) {
470
+			if ($groupName !== false) {
471 471
 				return $groupName;
472 472
 			}
473 473
 		}
@@ -484,22 +484,22 @@  discard block
 block discarded – undo
484 484
 	public function primaryGroupID2Name($gid, $dn) {
485 485
 		$cacheKey = 'primaryGroupIDtoName';
486 486
 		$groupNames = $this->access->connection->getFromCache($cacheKey);
487
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
487
+		if (!is_null($groupNames) && isset($groupNames[$gid])) {
488 488
 			return $groupNames[$gid];
489 489
 		}
490 490
 
491 491
 		$domainObjectSid = $this->access->getSID($dn);
492
-		if($domainObjectSid === false) {
492
+		if ($domainObjectSid === false) {
493 493
 			return false;
494 494
 		}
495 495
 
496 496
 		//we need to get the DN from LDAP
497 497
 		$filter = $this->access->combineFilterWithAnd([
498 498
 			$this->access->connection->ldapGroupFilter,
499
-			'objectsid=' . $domainObjectSid . '-' . $gid
499
+			'objectsid='.$domainObjectSid.'-'.$gid
500 500
 		]);
501 501
 		$result = $this->access->searchGroups($filter, ['dn'], 1);
502
-		if(empty($result)) {
502
+		if (empty($result)) {
503 503
 			return false;
504 504
 		}
505 505
 		$dn = $result[0]['dn'][0];
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 	 */
523 523
 	private function getEntryGroupID($dn, $attribute) {
524 524
 		$value = $this->access->readAttribute($dn, $attribute);
525
-		if(is_array($value) && !empty($value)) {
525
+		if (is_array($value) && !empty($value)) {
526 526
 			return $value[0];
527 527
 		}
528 528
 		return false;
@@ -544,9 +544,9 @@  discard block
 block discarded – undo
544 544
 	 */
545 545
 	public function getUserPrimaryGroupIDs($dn) {
546 546
 		$primaryGroupID = false;
547
-		if($this->access->connection->hasPrimaryGroups) {
547
+		if ($this->access->connection->hasPrimaryGroups) {
548 548
 			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
549
-			if($primaryGroupID === false) {
549
+			if ($primaryGroupID === false) {
550 550
 				$this->access->connection->hasPrimaryGroups = false;
551 551
 			}
552 552
 		}
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 	 */
564 564
 	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
565 565
 		$groupID = $this->getGroupPrimaryGroupID($groupDN);
566
-		if($groupID === false) {
566
+		if ($groupID === false) {
567 567
 			throw new \Exception('Not a valid group');
568 568
 		}
569 569
 
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
 		if ($search !== '') {
573 573
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
574 574
 		}
575
-		$filterParts[] = 'primaryGroupID=' . $groupID;
575
+		$filterParts[] = 'primaryGroupID='.$groupID;
576 576
 
577 577
 		return $this->access->combineFilterWithAnd($filterParts);
578 578
 	}
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 		try {
615 615
 			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
616 616
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
617
-			return (int)$users;
617
+			return (int) $users;
618 618
 		} catch (\Exception $e) {
619 619
 			return 0;
620 620
 		}
@@ -627,9 +627,9 @@  discard block
 block discarded – undo
627 627
 	 */
628 628
 	public function getUserPrimaryGroup($dn) {
629 629
 		$groupID = $this->getUserPrimaryGroupIDs($dn);
630
-		if($groupID !== false) {
630
+		if ($groupID !== false) {
631 631
 			$groupName = $this->primaryGroupID2Name($groupID, $dn);
632
-			if($groupName !== false) {
632
+			if ($groupName !== false) {
633 633
 				return $groupName;
634 634
 			}
635 635
 		}
@@ -648,16 +648,16 @@  discard block
 block discarded – undo
648 648
 	 * This function includes groups based on dynamic group membership.
649 649
 	 */
650 650
 	public function getUserGroups($uid) {
651
-		if(!$this->enabled) {
651
+		if (!$this->enabled) {
652 652
 			return [];
653 653
 		}
654 654
 		$cacheKey = 'getUserGroups'.$uid;
655 655
 		$userGroups = $this->access->connection->getFromCache($cacheKey);
656
-		if(!is_null($userGroups)) {
656
+		if (!is_null($userGroups)) {
657 657
 			return $userGroups;
658 658
 		}
659 659
 		$userDN = $this->access->username2dn($uid);
660
-		if(!$userDN) {
660
+		if (!$userDN) {
661 661
 			$this->access->connection->writeToCache($cacheKey, []);
662 662
 			return [];
663 663
 		}
@@ -671,14 +671,14 @@  discard block
 block discarded – undo
671 671
 		if (!empty($dynamicGroupMemberURL)) {
672 672
 			// look through dynamic groups to add them to the result array if needed
673 673
 			$groupsToMatch = $this->access->fetchListOfGroups(
674
-				$this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
675
-			foreach($groupsToMatch as $dynamicGroup) {
674
+				$this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
675
+			foreach ($groupsToMatch as $dynamicGroup) {
676 676
 				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
677 677
 					continue;
678 678
 				}
679 679
 				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
680 680
 				if ($pos !== false) {
681
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
681
+					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
682 682
 					// apply filter via ldap search to see if this user is in this
683 683
 					// dynamic group
684 684
 					$userMatch = $this->access->readAttribute(
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 					if ($userMatch !== false) {
690 690
 						// match found so this user is in this group
691 691
 						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
692
-						if(is_string($groupName)) {
692
+						if (is_string($groupName)) {
693 693
 							// be sure to never return false if the dn could not be
694 694
 							// resolved to a name, for whatever reason.
695 695
 							$groups[] = $groupName;
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 					}
698 698
 				} else {
699 699
 					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
700
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
700
+						'of group '.print_r($dynamicGroup, true), ILogger::DEBUG);
701 701
 				}
702 702
 			}
703 703
 		}
@@ -705,15 +705,15 @@  discard block
 block discarded – undo
705 705
 		// if possible, read out membership via memberOf. It's far faster than
706 706
 		// performing a search, which still is a fallback later.
707 707
 		// memberof doesn't support memberuid, so skip it here.
708
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
709
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
708
+		if ((int) $this->access->connection->hasMemberOfFilterSupport === 1
709
+			&& (int) $this->access->connection->useMemberOfToDetectMembership === 1
710 710
 			&& strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
711 711
 			) {
712 712
 			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
713 713
 			if (is_array($groupDNs)) {
714 714
 				foreach ($groupDNs as $dn) {
715 715
 					$groupName = $this->access->dn2groupname($dn);
716
-					if(is_string($groupName)) {
716
+					if (is_string($groupName)) {
717 717
 						// be sure to never return false if the dn could not be
718 718
 						// resolved to a name, for whatever reason.
719 719
 						$groups[] = $groupName;
@@ -721,10 +721,10 @@  discard block
 block discarded – undo
721 721
 				}
722 722
 			}
723 723
 
724
-			if($primaryGroup !== false) {
724
+			if ($primaryGroup !== false) {
725 725
 				$groups[] = $primaryGroup;
726 726
 			}
727
-			if($gidGroupName !== false) {
727
+			if ($gidGroupName !== false) {
728 728
 				$groups[] = $gidGroupName;
729 729
 			}
730 730
 			$this->access->connection->writeToCache($cacheKey, $groups);
@@ -732,14 +732,14 @@  discard block
 block discarded – undo
732 732
 		}
733 733
 
734 734
 		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
735
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
735
+		if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
736 736
 			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
737 737
 		) {
738 738
 			$uid = $userDN;
739
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
739
+		} else if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
740 740
 			$result = $this->access->readAttribute($userDN, 'uid');
741 741
 			if ($result === false) {
742
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
742
+				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN '.$userDN.' on '.
743 743
 					$this->access->connection->ldapHost, ILogger::DEBUG);
744 744
 				$uid = false;
745 745
 			} else {
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 			$uid = $userDN;
751 751
 		}
752 752
 
753
-		if($uid !== false) {
753
+		if ($uid !== false) {
754 754
 			if (isset($this->cachedGroupsByMember[$uid])) {
755 755
 				$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
756 756
 			} else {
@@ -761,10 +761,10 @@  discard block
 block discarded – undo
761 761
 			}
762 762
 		}
763 763
 
764
-		if($primaryGroup !== false) {
764
+		if ($primaryGroup !== false) {
765 765
 			$groups[] = $primaryGroup;
766 766
 		}
767
-		if($gidGroupName !== false) {
767
+		if ($gidGroupName !== false) {
768 768
 			$groups[] = $gidGroupName;
769 769
 		}
770 770
 
@@ -793,8 +793,8 @@  discard block
 block discarded – undo
793 793
 		$groups = $this->access->fetchListOfGroups($filter,
794 794
 			[$this->access->connection->ldapGroupDisplayName, 'dn']);
795 795
 		if (is_array($groups)) {
796
-			$fetcher = function ($dn, &$seen) {
797
-				if(is_array($dn) && isset($dn['dn'][0])) {
796
+			$fetcher = function($dn, &$seen) {
797
+				if (is_array($dn) && isset($dn['dn'][0])) {
798 798
 					$dn = $dn['dn'][0];
799 799
 				}
800 800
 				return $this->getGroupsByMember($dn, $seen);
@@ -816,33 +816,33 @@  discard block
 block discarded – undo
816 816
 	 * @throws \Exception
817 817
 	 */
818 818
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
819
-		if(!$this->enabled) {
819
+		if (!$this->enabled) {
820 820
 			return [];
821 821
 		}
822
-		if(!$this->groupExists($gid)) {
822
+		if (!$this->groupExists($gid)) {
823 823
 			return [];
824 824
 		}
825 825
 		$search = $this->access->escapeFilterPart($search, true);
826 826
 		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
827 827
 		// check for cache of the exact query
828 828
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
829
-		if(!is_null($groupUsers)) {
829
+		if (!is_null($groupUsers)) {
830 830
 			return $groupUsers;
831 831
 		}
832 832
 
833 833
 		// check for cache of the query without limit and offset
834 834
 		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
835
-		if(!is_null($groupUsers)) {
835
+		if (!is_null($groupUsers)) {
836 836
 			$groupUsers = array_slice($groupUsers, $offset, $limit);
837 837
 			$this->access->connection->writeToCache($cacheKey, $groupUsers);
838 838
 			return $groupUsers;
839 839
 		}
840 840
 
841
-		if($limit === -1) {
841
+		if ($limit === -1) {
842 842
 			$limit = null;
843 843
 		}
844 844
 		$groupDN = $this->access->groupname2dn($gid);
845
-		if(!$groupDN) {
845
+		if (!$groupDN) {
846 846
 			// group couldn't be found, return empty resultset
847 847
 			$this->access->connection->writeToCache($cacheKey, []);
848 848
 			return [];
@@ -851,7 +851,7 @@  discard block
 block discarded – undo
851 851
 		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
852 852
 		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
853 853
 		$members = $this->_groupMembers($groupDN);
854
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
854
+		if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
855 855
 			//in case users could not be retrieved, return empty result set
856 856
 			$this->access->connection->writeToCache($cacheKey, []);
857 857
 			return [];
@@ -860,8 +860,8 @@  discard block
 block discarded – undo
860 860
 		$groupUsers = [];
861 861
 		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
862 862
 		$attrs = $this->access->userManager->getAttributes(true);
863
-		foreach($members as $member) {
864
-			if($isMemberUid) {
863
+		foreach ($members as $member) {
864
+			if ($isMemberUid) {
865 865
 				//we got uids, need to get their DNs to 'translate' them to user names
866 866
 				$filter = $this->access->combineFilterWithAnd([
867 867
 					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
@@ -871,23 +871,23 @@  discard block
 block discarded – undo
871 871
 					])
872 872
 				]);
873 873
 				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
874
-				if(count($ldap_users) < 1) {
874
+				if (count($ldap_users) < 1) {
875 875
 					continue;
876 876
 				}
877 877
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
878 878
 			} else {
879 879
 				//we got DNs, check if we need to filter by search or we can give back all of them
880 880
 				$uid = $this->access->dn2username($member);
881
-				if(!$uid) {
881
+				if (!$uid) {
882 882
 					continue;
883 883
 				}
884 884
 
885
-				$cacheKey = 'userExistsOnLDAP' . $uid;
885
+				$cacheKey = 'userExistsOnLDAP'.$uid;
886 886
 				$userExists = $this->access->connection->getFromCache($cacheKey);
887
-				if($userExists === false) {
887
+				if ($userExists === false) {
888 888
 					continue;
889 889
 				}
890
-				if($userExists === null || $search !== '') {
890
+				if ($userExists === null || $search !== '') {
891 891
 					if (!$this->access->readAttribute($member,
892 892
 						$this->access->connection->ldapUserDisplayName,
893 893
 						$this->access->combineFilterWithAnd([
@@ -895,7 +895,7 @@  discard block
 block discarded – undo
895 895
 							$this->access->connection->ldapUserFilter
896 896
 						])))
897 897
 					{
898
-						if($search === '') {
898
+						if ($search === '') {
899 899
 							$this->access->connection->writeToCache($cacheKey, false);
900 900
 						}
901 901
 						continue;
@@ -928,16 +928,16 @@  discard block
 block discarded – undo
928 928
 		}
929 929
 
930 930
 		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
931
-		if(!$this->enabled || !$this->groupExists($gid)) {
931
+		if (!$this->enabled || !$this->groupExists($gid)) {
932 932
 			return false;
933 933
 		}
934 934
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
935
-		if(!is_null($groupUsers)) {
935
+		if (!is_null($groupUsers)) {
936 936
 			return $groupUsers;
937 937
 		}
938 938
 
939 939
 		$groupDN = $this->access->groupname2dn($gid);
940
-		if(!$groupDN) {
940
+		if (!$groupDN) {
941 941
 			// group couldn't be found, return empty result set
942 942
 			$this->access->connection->writeToCache($cacheKey, false);
943 943
 			return false;
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 
946 946
 		$members = $this->_groupMembers($groupDN);
947 947
 		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
948
-		if(!$members && $primaryUserCount === 0) {
948
+		if (!$members && $primaryUserCount === 0) {
949 949
 			//in case users could not be retrieved, return empty result set
950 950
 			$this->access->connection->writeToCache($cacheKey, false);
951 951
 			return false;
@@ -970,27 +970,27 @@  discard block
 block discarded – undo
970 970
 		//For now this is not important, because the only use of this method
971 971
 		//does not supply a search string
972 972
 		$groupUsers = [];
973
-		foreach($members as $member) {
974
-			if($isMemberUid) {
973
+		foreach ($members as $member) {
974
+			if ($isMemberUid) {
975 975
 				//we got uids, need to get their DNs to 'translate' them to user names
976 976
 				$filter = $this->access->combineFilterWithAnd([
977 977
 					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
978 978
 					$this->access->getFilterPartForUserSearch($search)
979 979
 				]);
980 980
 				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
981
-				if(count($ldap_users) < 1) {
981
+				if (count($ldap_users) < 1) {
982 982
 					continue;
983 983
 				}
984 984
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
985 985
 			} else {
986 986
 				//we need to apply the search filter now
987
-				if(!$this->access->readAttribute($member,
987
+				if (!$this->access->readAttribute($member,
988 988
 					$this->access->connection->ldapUserDisplayName,
989 989
 					$this->access->getFilterPartForUserSearch($search))) {
990 990
 					continue;
991 991
 				}
992 992
 				// dn2username will also check if the users belong to the allowed base
993
-				if($ocname = $this->access->dn2username($member)) {
993
+				if ($ocname = $this->access->dn2username($member)) {
994 994
 					$groupUsers[] = $ocname;
995 995
 				}
996 996
 			}
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
 	 * Returns a list with all groups (used by getGroups)
1014 1014
 	 */
1015 1015
 	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1016
-		if(!$this->enabled) {
1016
+		if (!$this->enabled) {
1017 1017
 			return [];
1018 1018
 		}
1019 1019
 		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
@@ -1021,13 +1021,13 @@  discard block
 block discarded – undo
1021 1021
 		//Check cache before driving unnecessary searches
1022 1022
 		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1023 1023
 		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
1024
-		if(!is_null($ldap_groups)) {
1024
+		if (!is_null($ldap_groups)) {
1025 1025
 			return $ldap_groups;
1026 1026
 		}
1027 1027
 
1028 1028
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
1029 1029
 		// error. With a limit of 0, we get 0 results. So we pass null.
1030
-		if($limit <= 0) {
1030
+		if ($limit <= 0) {
1031 1031
 			$limit = null;
1032 1032
 		}
1033 1033
 		$filter = $this->access->combineFilterWithAnd([
@@ -1059,11 +1059,11 @@  discard block
 block discarded – undo
1059 1059
 	 * (active directory has a limit of 1000 by default)
1060 1060
 	 */
1061 1061
 	public function getGroups($search = '', $limit = -1, $offset = 0) {
1062
-		if(!$this->enabled) {
1062
+		if (!$this->enabled) {
1063 1063
 			return [];
1064 1064
 		}
1065 1065
 		$search = $this->access->escapeFilterPart($search, true);
1066
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1066
+		$pagingSize = (int) $this->access->connection->ldapPagingSize;
1067 1067
 		if ($pagingSize <= 0) {
1068 1068
 			return $this->getGroupsChunk($search, $limit, $offset);
1069 1069
 		}
@@ -1106,20 +1106,20 @@  discard block
 block discarded – undo
1106 1106
 	 */
1107 1107
 	public function groupExists($gid) {
1108 1108
 		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1109
-		if(!is_null($groupExists)) {
1110
-			return (bool)$groupExists;
1109
+		if (!is_null($groupExists)) {
1110
+			return (bool) $groupExists;
1111 1111
 		}
1112 1112
 
1113 1113
 		//getting dn, if false the group does not exist. If dn, it may be mapped
1114 1114
 		//only, requires more checking.
1115 1115
 		$dn = $this->access->groupname2dn($gid);
1116
-		if(!$dn) {
1116
+		if (!$dn) {
1117 1117
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1118 1118
 			return false;
1119 1119
 		}
1120 1120
 
1121 1121
 		//if group really still exists, we will be able to read its objectclass
1122
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1122
+		if (!is_array($this->access->readAttribute($dn, ''))) {
1123 1123
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1124 1124
 			return false;
1125 1125
 		}
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
 	 * compared with GroupInterface::CREATE_GROUP etc.
1138 1138
 	 */
1139 1139
 	public function implementsActions($actions) {
1140
-		return (bool)((GroupInterface::COUNT_USERS |
1140
+		return (bool) ((GroupInterface::COUNT_USERS |
1141 1141
 				$this->groupPluginManager->getImplementedActions()) & $actions);
1142 1142
 	}
1143 1143
 
@@ -1160,7 +1160,7 @@  discard block
 block discarded – undo
1160 1160
 			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1161 1161
 				//updates group mapping
1162 1162
 				$uuid = $this->access->getUUID($dn, false);
1163
-				if(is_string($uuid)) {
1163
+				if (is_string($uuid)) {
1164 1164
 					$this->access->mapAndAnnounceIfApplicable(
1165 1165
 						$this->access->getGroupMapper(),
1166 1166
 						$dn,
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
 			return $this->groupPluginManager->getDisplayName($gid);
1264 1264
 		}
1265 1265
 
1266
-		$cacheKey = 'group_getDisplayName' . $gid;
1266
+		$cacheKey = 'group_getDisplayName'.$gid;
1267 1267
 		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1268 1268
 			return $displayName;
1269 1269
 		}
Please login to merge, or discard this patch.
apps/user_ldap/lib/Wizard.php 2 patches
Indentation   +1314 added lines, -1314 removed lines patch added patch discarded remove patch
@@ -42,1320 +42,1320 @@
 block discarded – undo
42 42
 use OCP\ILogger;
43 43
 
44 44
 class Wizard extends LDAPUtility {
45
-	/** @var \OCP\IL10N */
46
-	static protected $l;
47
-	protected $access;
48
-	protected $cr;
49
-	protected $configuration;
50
-	protected $result;
51
-	protected $resultCache = [];
52
-
53
-	const LRESULT_PROCESSED_OK = 2;
54
-	const LRESULT_PROCESSED_INVALID = 3;
55
-	const LRESULT_PROCESSED_SKIP = 4;
56
-
57
-	const LFILTER_LOGIN      = 2;
58
-	const LFILTER_USER_LIST  = 3;
59
-	const LFILTER_GROUP_LIST = 4;
60
-
61
-	const LFILTER_MODE_ASSISTED = 2;
62
-	const LFILTER_MODE_RAW = 1;
63
-
64
-	const LDAP_NW_TIMEOUT = 4;
65
-
66
-	/**
67
-	 * Constructor
68
-	 * @param Configuration $configuration an instance of Configuration
69
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
70
-	 * @param Access $access
71
-	 */
72
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73
-		parent::__construct($ldap);
74
-		$this->configuration = $configuration;
75
-		if(is_null(Wizard::$l)) {
76
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
77
-		}
78
-		$this->access = $access;
79
-		$this->result = new WizardResult();
80
-	}
81
-
82
-	public function  __destruct() {
83
-		if($this->result->hasChanges()) {
84
-			$this->configuration->saveConfiguration();
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * counts entries in the LDAP directory
90
-	 *
91
-	 * @param string $filter the LDAP search filter
92
-	 * @param string $type a string being either 'users' or 'groups';
93
-	 * @return int
94
-	 * @throws \Exception
95
-	 */
96
-	public function countEntries(string $filter, string $type): int {
97
-		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
-		if($type === 'users') {
99
-			$reqs[] = 'ldapUserFilter';
100
-		}
101
-		if(!$this->checkRequirements($reqs)) {
102
-			throw new \Exception('Requirements not met', 400);
103
-		}
104
-
105
-		$attr = ['dn']; // default
106
-		$limit = 1001;
107
-		if($type === 'groups') {
108
-			$result =  $this->access->countGroups($filter, $attr, $limit);
109
-		} else if($type === 'users') {
110
-			$result = $this->access->countUsers($filter, $attr, $limit);
111
-		} else if ($type === 'objects') {
112
-			$result = $this->access->countObjects($limit);
113
-		} else {
114
-			throw new \Exception('Internal error: Invalid object type', 500);
115
-		}
116
-
117
-		return (int)$result;
118
-	}
119
-
120
-	/**
121
-	 * formats the return value of a count operation to the string to be
122
-	 * inserted.
123
-	 *
124
-	 * @param int $count
125
-	 * @return string
126
-	 */
127
-	private function formatCountResult(int $count): string {
128
-		if($count > 1000) {
129
-			return '> 1000';
130
-		}
131
-		return (string)$count;
132
-	}
133
-
134
-	public function countGroups() {
135
-		$filter = $this->configuration->ldapGroupFilter;
136
-
137
-		if(empty($filter)) {
138
-			$output = self::$l->n('%s group found', '%s groups found', 0, [0]);
139
-			$this->result->addChange('ldap_group_count', $output);
140
-			return $this->result;
141
-		}
142
-
143
-		try {
144
-			$groupsTotal = $this->countEntries($filter, 'groups');
145
-		} catch (\Exception $e) {
146
-			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
148
-				throw $e;
149
-			}
150
-			return false;
151
-		}
152
-		$output = self::$l->n(
153
-			'%s group found',
154
-			'%s groups found',
155
-			$groupsTotal,
156
-			[$this->formatCountResult($groupsTotal)]
157
-		);
158
-		$this->result->addChange('ldap_group_count', $output);
159
-		return $this->result;
160
-	}
161
-
162
-	/**
163
-	 * @return WizardResult
164
-	 * @throws \Exception
165
-	 */
166
-	public function countUsers() {
167
-		$filter = $this->access->getFilterForUserCount();
168
-
169
-		$usersTotal = $this->countEntries($filter, 'users');
170
-		$output = self::$l->n(
171
-			'%s user found',
172
-			'%s users found',
173
-			$usersTotal,
174
-			[$this->formatCountResult($usersTotal)]
175
-		);
176
-		$this->result->addChange('ldap_user_count', $output);
177
-		return $this->result;
178
-	}
179
-
180
-	/**
181
-	 * counts any objects in the currently set base dn
182
-	 *
183
-	 * @return WizardResult
184
-	 * @throws \Exception
185
-	 */
186
-	public function countInBaseDN() {
187
-		// we don't need to provide a filter in this case
188
-		$total = $this->countEntries('', 'objects');
189
-		if($total === false) {
190
-			throw new \Exception('invalid results received');
191
-		}
192
-		$this->result->addChange('ldap_test_base', $total);
193
-		return $this->result;
194
-	}
195
-
196
-	/**
197
-	 * counts users with a specified attribute
198
-	 * @param string $attr
199
-	 * @param bool $existsCheck
200
-	 * @return int|bool
201
-	 */
202
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
203
-		if(!$this->checkRequirements(['ldapHost',
204
-			'ldapPort',
205
-			'ldapBase',
206
-			'ldapUserFilter',
207
-		])) {
208
-			return  false;
209
-		}
210
-
211
-		$filter = $this->access->combineFilterWithAnd([
212
-			$this->configuration->ldapUserFilter,
213
-			$attr . '=*'
214
-		]);
215
-
216
-		$limit = ($existsCheck === false) ? null : 1;
217
-
218
-		return $this->access->countUsers($filter, ['dn'], $limit);
219
-	}
220
-
221
-	/**
222
-	 * detects the display name attribute. If a setting is already present that
223
-	 * returns at least one hit, the detection will be canceled.
224
-	 * @return WizardResult|bool
225
-	 * @throws \Exception
226
-	 */
227
-	public function detectUserDisplayNameAttribute() {
228
-		if(!$this->checkRequirements(['ldapHost',
229
-			'ldapPort',
230
-			'ldapBase',
231
-			'ldapUserFilter',
232
-		])) {
233
-			return  false;
234
-		}
235
-
236
-		$attr = $this->configuration->ldapUserDisplayName;
237
-		if ($attr !== '' && $attr !== 'displayName') {
238
-			// most likely not the default value with upper case N,
239
-			// verify it still produces a result
240
-			$count = (int)$this->countUsersWithAttribute($attr, true);
241
-			if($count > 0) {
242
-				//no change, but we sent it back to make sure the user interface
243
-				//is still correct, even if the ajax call was cancelled meanwhile
244
-				$this->result->addChange('ldap_display_name', $attr);
245
-				return $this->result;
246
-			}
247
-		}
248
-
249
-		// first attribute that has at least one result wins
250
-		$displayNameAttrs = ['displayname', 'cn'];
251
-		foreach ($displayNameAttrs as $attr) {
252
-			$count = (int)$this->countUsersWithAttribute($attr, true);
253
-
254
-			if($count > 0) {
255
-				$this->applyFind('ldap_display_name', $attr);
256
-				return $this->result;
257
-			}
258
-		}
259
-
260
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
261
-	}
262
-
263
-	/**
264
-	 * detects the most often used email attribute for users applying to the
265
-	 * user list filter. If a setting is already present that returns at least
266
-	 * one hit, the detection will be canceled.
267
-	 * @return WizardResult|bool
268
-	 */
269
-	public function detectEmailAttribute() {
270
-		if(!$this->checkRequirements(['ldapHost',
271
-			'ldapPort',
272
-			'ldapBase',
273
-			'ldapUserFilter',
274
-		])) {
275
-			return  false;
276
-		}
277
-
278
-		$attr = $this->configuration->ldapEmailAttribute;
279
-		if ($attr !== '') {
280
-			$count = (int)$this->countUsersWithAttribute($attr, true);
281
-			if($count > 0) {
282
-				return false;
283
-			}
284
-			$writeLog = true;
285
-		} else {
286
-			$writeLog = false;
287
-		}
288
-
289
-		$emailAttributes = ['mail', 'mailPrimaryAddress'];
290
-		$winner = '';
291
-		$maxUsers = 0;
292
-		foreach($emailAttributes as $attr) {
293
-			$count = $this->countUsersWithAttribute($attr);
294
-			if($count > $maxUsers) {
295
-				$maxUsers = $count;
296
-				$winner = $attr;
297
-			}
298
-		}
299
-
300
-		if($winner !== '') {
301
-			$this->applyFind('ldap_email_attr', $winner);
302
-			if($writeLog) {
303
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
-					'automatically been reset, because the original value ' .
305
-					'did not return any results.', ILogger::INFO);
306
-			}
307
-		}
308
-
309
-		return $this->result;
310
-	}
311
-
312
-	/**
313
-	 * @return WizardResult
314
-	 * @throws \Exception
315
-	 */
316
-	public function determineAttributes() {
317
-		if(!$this->checkRequirements(['ldapHost',
318
-			'ldapPort',
319
-			'ldapBase',
320
-			'ldapUserFilter',
321
-		])) {
322
-			return  false;
323
-		}
324
-
325
-		$attributes = $this->getUserAttributes();
326
-
327
-		natcasesort($attributes);
328
-		$attributes = array_values($attributes);
329
-
330
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331
-
332
-		$selected = $this->configuration->ldapLoginFilterAttributes;
333
-		if(is_array($selected) && !empty($selected)) {
334
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
335
-		}
336
-
337
-		return $this->result;
338
-	}
339
-
340
-	/**
341
-	 * detects the available LDAP attributes
342
-	 * @return array|false The instance's WizardResult instance
343
-	 * @throws \Exception
344
-	 */
345
-	private function getUserAttributes() {
346
-		if(!$this->checkRequirements(['ldapHost',
347
-			'ldapPort',
348
-			'ldapBase',
349
-			'ldapUserFilter',
350
-		])) {
351
-			return  false;
352
-		}
353
-		$cr = $this->getConnection();
354
-		if(!$cr) {
355
-			throw new \Exception('Could not connect to LDAP');
356
-		}
357
-
358
-		$base = $this->configuration->ldapBase[0];
359
-		$filter = $this->configuration->ldapUserFilter;
360
-		$rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
361
-		if(!$this->ldap->isResource($rr)) {
362
-			return false;
363
-		}
364
-		$er = $this->ldap->firstEntry($cr, $rr);
365
-		$attributes = $this->ldap->getAttributes($cr, $er);
366
-		$pureAttributes = [];
367
-		for($i = 0; $i < $attributes['count']; $i++) {
368
-			$pureAttributes[] = $attributes[$i];
369
-		}
370
-
371
-		return $pureAttributes;
372
-	}
373
-
374
-	/**
375
-	 * detects the available LDAP groups
376
-	 * @return WizardResult|false the instance's WizardResult instance
377
-	 */
378
-	public function determineGroupsForGroups() {
379
-		return $this->determineGroups('ldap_groupfilter_groups',
380
-									  'ldapGroupFilterGroups',
381
-									  false);
382
-	}
383
-
384
-	/**
385
-	 * detects the available LDAP groups
386
-	 * @return WizardResult|false the instance's WizardResult instance
387
-	 */
388
-	public function determineGroupsForUsers() {
389
-		return $this->determineGroups('ldap_userfilter_groups',
390
-									  'ldapUserFilterGroups');
391
-	}
392
-
393
-	/**
394
-	 * detects the available LDAP groups
395
-	 * @param string $dbKey
396
-	 * @param string $confKey
397
-	 * @param bool $testMemberOf
398
-	 * @return WizardResult|false the instance's WizardResult instance
399
-	 * @throws \Exception
400
-	 */
401
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
-		if(!$this->checkRequirements(['ldapHost',
403
-			'ldapPort',
404
-			'ldapBase',
405
-		])) {
406
-			return  false;
407
-		}
408
-		$cr = $this->getConnection();
409
-		if(!$cr) {
410
-			throw new \Exception('Could not connect to LDAP');
411
-		}
412
-
413
-		$this->fetchGroups($dbKey, $confKey);
414
-
415
-		if($testMemberOf) {
416
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417
-			$this->result->markChange();
418
-			if(!$this->configuration->hasMemberOfFilterSupport) {
419
-				throw new \Exception('memberOf is not supported by the server');
420
-			}
421
-		}
422
-
423
-		return $this->result;
424
-	}
425
-
426
-	/**
427
-	 * fetches all groups from LDAP and adds them to the result object
428
-	 *
429
-	 * @param string $dbKey
430
-	 * @param string $confKey
431
-	 * @return array $groupEntries
432
-	 * @throws \Exception
433
-	 */
434
-	public function fetchGroups($dbKey, $confKey) {
435
-		$obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
436
-
437
-		$filterParts = [];
438
-		foreach($obclasses as $obclass) {
439
-			$filterParts[] = 'objectclass='.$obclass;
440
-		}
441
-		//we filter for everything
442
-		//- that looks like a group and
443
-		//- has the group display name set
444
-		$filter = $this->access->combineFilterWithOr($filterParts);
445
-		$filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']);
446
-
447
-		$groupNames = [];
448
-		$groupEntries = [];
449
-		$limit = 400;
450
-		$offset = 0;
451
-		do {
452
-			// we need to request dn additionally here, otherwise memberOf
453
-			// detection will fail later
454
-			$result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
455
-			foreach($result as $item) {
456
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457
-					// just in case - no issue known
458
-					continue;
459
-				}
460
-				$groupNames[] = $item['cn'][0];
461
-				$groupEntries[] = $item;
462
-			}
463
-			$offset += $limit;
464
-		} while ($this->access->hasMoreResults());
465
-
466
-		if(count($groupNames) > 0) {
467
-			natsort($groupNames);
468
-			$this->result->addOptions($dbKey, array_values($groupNames));
469
-		} else {
470
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
471
-		}
472
-
473
-		$setFeatures = $this->configuration->$confKey;
474
-		if(is_array($setFeatures) && !empty($setFeatures)) {
475
-			//something is already configured? pre-select it.
476
-			$this->result->addChange($dbKey, $setFeatures);
477
-		}
478
-		return $groupEntries;
479
-	}
480
-
481
-	public function determineGroupMemberAssoc() {
482
-		if(!$this->checkRequirements(['ldapHost',
483
-			'ldapPort',
484
-			'ldapGroupFilter',
485
-		])) {
486
-			return  false;
487
-		}
488
-		$attribute = $this->detectGroupMemberAssoc();
489
-		if($attribute === false) {
490
-			return false;
491
-		}
492
-		$this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
493
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
494
-
495
-		return $this->result;
496
-	}
497
-
498
-	/**
499
-	 * Detects the available object classes
500
-	 * @return WizardResult|false the instance's WizardResult instance
501
-	 * @throws \Exception
502
-	 */
503
-	public function determineGroupObjectClasses() {
504
-		if(!$this->checkRequirements(['ldapHost',
505
-			'ldapPort',
506
-			'ldapBase',
507
-		])) {
508
-			return  false;
509
-		}
510
-		$cr = $this->getConnection();
511
-		if(!$cr) {
512
-			throw new \Exception('Could not connect to LDAP');
513
-		}
514
-
515
-		$obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*'];
516
-		$this->determineFeature($obclasses,
517
-								'objectclass',
518
-								'ldap_groupfilter_objectclass',
519
-								'ldapGroupFilterObjectclass',
520
-								false);
521
-
522
-		return $this->result;
523
-	}
524
-
525
-	/**
526
-	 * detects the available object classes
527
-	 * @return WizardResult
528
-	 * @throws \Exception
529
-	 */
530
-	public function determineUserObjectClasses() {
531
-		if(!$this->checkRequirements(['ldapHost',
532
-			'ldapPort',
533
-			'ldapBase',
534
-		])) {
535
-			return  false;
536
-		}
537
-		$cr = $this->getConnection();
538
-		if(!$cr) {
539
-			throw new \Exception('Could not connect to LDAP');
540
-		}
541
-
542
-		$obclasses = ['inetOrgPerson', 'person', 'organizationalPerson',
543
-			'user', 'posixAccount', '*'];
544
-		$filter = $this->configuration->ldapUserFilter;
545
-		//if filter is empty, it is probably the first time the wizard is called
546
-		//then, apply suggestions.
547
-		$this->determineFeature($obclasses,
548
-								'objectclass',
549
-								'ldap_userfilter_objectclass',
550
-								'ldapUserFilterObjectclass',
551
-								empty($filter));
552
-
553
-		return $this->result;
554
-	}
555
-
556
-	/**
557
-	 * @return WizardResult|false
558
-	 * @throws \Exception
559
-	 */
560
-	public function getGroupFilter() {
561
-		if(!$this->checkRequirements(['ldapHost',
562
-			'ldapPort',
563
-			'ldapBase',
564
-		])) {
565
-			return false;
566
-		}
567
-		//make sure the use display name is set
568
-		$displayName = $this->configuration->ldapGroupDisplayName;
569
-		if ($displayName === '') {
570
-			$d = $this->configuration->getDefaults();
571
-			$this->applyFind('ldap_group_display_name',
572
-							 $d['ldap_group_display_name']);
573
-		}
574
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
575
-
576
-		$this->applyFind('ldap_group_filter', $filter);
577
-		return $this->result;
578
-	}
579
-
580
-	/**
581
-	 * @return WizardResult|false
582
-	 * @throws \Exception
583
-	 */
584
-	public function getUserListFilter() {
585
-		if(!$this->checkRequirements(['ldapHost',
586
-			'ldapPort',
587
-			'ldapBase',
588
-		])) {
589
-			return false;
590
-		}
591
-		//make sure the use display name is set
592
-		$displayName = $this->configuration->ldapUserDisplayName;
593
-		if ($displayName === '') {
594
-			$d = $this->configuration->getDefaults();
595
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
596
-		}
597
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
-		if(!$filter) {
599
-			throw new \Exception('Cannot create filter');
600
-		}
601
-
602
-		$this->applyFind('ldap_userlist_filter', $filter);
603
-		return $this->result;
604
-	}
605
-
606
-	/**
607
-	 * @return bool|WizardResult
608
-	 * @throws \Exception
609
-	 */
610
-	public function getUserLoginFilter() {
611
-		if(!$this->checkRequirements(['ldapHost',
612
-			'ldapPort',
613
-			'ldapBase',
614
-			'ldapUserFilter',
615
-		])) {
616
-			return false;
617
-		}
618
-
619
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
-		if(!$filter) {
621
-			throw new \Exception('Cannot create filter');
622
-		}
623
-
624
-		$this->applyFind('ldap_login_filter', $filter);
625
-		return $this->result;
626
-	}
627
-
628
-	/**
629
-	 * @return bool|WizardResult
630
-	 * @param string $loginName
631
-	 * @throws \Exception
632
-	 */
633
-	public function testLoginName($loginName) {
634
-		if(!$this->checkRequirements(['ldapHost',
635
-			'ldapPort',
636
-			'ldapBase',
637
-			'ldapLoginFilter',
638
-		])) {
639
-			return false;
640
-		}
641
-
642
-		$cr = $this->access->connection->getConnectionResource();
643
-		if(!$this->ldap->isResource($cr)) {
644
-			throw new \Exception('connection error');
645
-		}
646
-
647
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648
-			=== false) {
649
-			throw new \Exception('missing placeholder');
650
-		}
651
-
652
-		$users = $this->access->countUsersByLoginName($loginName);
653
-		if($this->ldap->errno($cr) !== 0) {
654
-			throw new \Exception($this->ldap->error($cr));
655
-		}
656
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
657
-		$this->result->addChange('ldap_test_loginname', $users);
658
-		$this->result->addChange('ldap_test_effective_filter', $filter);
659
-		return $this->result;
660
-	}
661
-
662
-	/**
663
-	 * Tries to determine the port, requires given Host, User DN and Password
664
-	 * @return WizardResult|false WizardResult on success, false otherwise
665
-	 * @throws \Exception
666
-	 */
667
-	public function guessPortAndTLS() {
668
-		if(!$this->checkRequirements(['ldapHost',
669
-		])) {
670
-			return false;
671
-		}
672
-		$this->checkHost();
673
-		$portSettings = $this->getPortSettingsToTry();
674
-
675
-		if(!is_array($portSettings)) {
676
-			throw new \Exception(print_r($portSettings, true));
677
-		}
678
-
679
-		//proceed from the best configuration and return on first success
680
-		foreach($portSettings as $setting) {
681
-			$p = $setting['port'];
682
-			$t = $setting['tls'];
683
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
684
-			//connectAndBind may throw Exception, it needs to be catched by the
685
-			//callee of this method
686
-
687
-			try {
688
-				$settingsFound = $this->connectAndBind($p, $t);
689
-			} catch (\Exception $e) {
690
-				// any reply other than -1 (= cannot connect) is already okay,
691
-				// because then we found the server
692
-				// unavailable startTLS returns -11
693
-				if($e->getCode() > 0) {
694
-					$settingsFound = true;
695
-				} else {
696
-					throw $e;
697
-				}
698
-			}
699
-
700
-			if ($settingsFound === true) {
701
-				$config = [
702
-					'ldapPort' => $p,
703
-					'ldapTLS' => (int)$t
704
-				];
705
-				$this->configuration->setConfiguration($config);
706
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
707
-				$this->result->addChange('ldap_port', $p);
708
-				return $this->result;
709
-			}
710
-		}
711
-
712
-		//custom port, undetected (we do not brute force)
713
-		return false;
714
-	}
715
-
716
-	/**
717
-	 * tries to determine a base dn from User DN or LDAP Host
718
-	 * @return WizardResult|false WizardResult on success, false otherwise
719
-	 */
720
-	public function guessBaseDN() {
721
-		if(!$this->checkRequirements(['ldapHost',
722
-			'ldapPort',
723
-		])) {
724
-			return false;
725
-		}
726
-
727
-		//check whether a DN is given in the agent name (99.9% of all cases)
728
-		$base = null;
729
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
730
-		if($i !== false) {
731
-			$base = substr($this->configuration->ldapAgentName, $i);
732
-			if($this->testBaseDN($base)) {
733
-				$this->applyFind('ldap_base', $base);
734
-				return $this->result;
735
-			}
736
-		}
737
-
738
-		//this did not help :(
739
-		//Let's see whether we can parse the Host URL and convert the domain to
740
-		//a base DN
741
-		$helper = new Helper(\OC::$server->getConfig());
742
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
-		if(!$domain) {
744
-			return false;
745
-		}
746
-
747
-		$dparts = explode('.', $domain);
748
-		while(count($dparts) > 0) {
749
-			$base2 = 'dc=' . implode(',dc=', $dparts);
750
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
751
-				$this->applyFind('ldap_base', $base2);
752
-				return $this->result;
753
-			}
754
-			array_shift($dparts);
755
-		}
756
-
757
-		return false;
758
-	}
759
-
760
-	/**
761
-	 * sets the found value for the configuration key in the WizardResult
762
-	 * as well as in the Configuration instance
763
-	 * @param string $key the configuration key
764
-	 * @param string $value the (detected) value
765
-	 *
766
-	 */
767
-	private function applyFind($key, $value) {
768
-		$this->result->addChange($key, $value);
769
-		$this->configuration->setConfiguration([$key => $value]);
770
-	}
771
-
772
-	/**
773
-	 * Checks, whether a port was entered in the Host configuration
774
-	 * field. In this case the port will be stripped off, but also stored as
775
-	 * setting.
776
-	 */
777
-	private function checkHost() {
778
-		$host = $this->configuration->ldapHost;
779
-		$hostInfo = parse_url($host);
780
-
781
-		//removes Port from Host
782
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
783
-			$port = $hostInfo['port'];
784
-			$host = str_replace(':'.$port, '', $host);
785
-			$this->applyFind('ldap_host', $host);
786
-			$this->applyFind('ldap_port', $port);
787
-		}
788
-	}
789
-
790
-	/**
791
-	 * tries to detect the group member association attribute which is
792
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
793
-	 * @return string|false, string with the attribute name, false on error
794
-	 * @throws \Exception
795
-	 */
796
-	private function detectGroupMemberAssoc() {
797
-		$possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber'];
798
-		$filter = $this->configuration->ldapGroupFilter;
799
-		if(empty($filter)) {
800
-			return false;
801
-		}
802
-		$cr = $this->getConnection();
803
-		if(!$cr) {
804
-			throw new \Exception('Could not connect to LDAP');
805
-		}
806
-		$base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
807
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
-		if(!$this->ldap->isResource($rr)) {
809
-			return false;
810
-		}
811
-		$er = $this->ldap->firstEntry($cr, $rr);
812
-		while(is_resource($er)) {
813
-			$this->ldap->getDN($cr, $er);
814
-			$attrs = $this->ldap->getAttributes($cr, $er);
815
-			$result = [];
816
-			$possibleAttrsCount = count($possibleAttrs);
817
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
818
-				if(isset($attrs[$possibleAttrs[$i]])) {
819
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820
-				}
821
-			}
822
-			if(!empty($result)) {
823
-				natsort($result);
824
-				return key($result);
825
-			}
826
-
827
-			$er = $this->ldap->nextEntry($cr, $er);
828
-		}
829
-
830
-		return false;
831
-	}
832
-
833
-	/**
834
-	 * Checks whether for a given BaseDN results will be returned
835
-	 * @param string $base the BaseDN to test
836
-	 * @return bool true on success, false otherwise
837
-	 * @throws \Exception
838
-	 */
839
-	private function testBaseDN($base) {
840
-		$cr = $this->getConnection();
841
-		if(!$cr) {
842
-			throw new \Exception('Could not connect to LDAP');
843
-		}
844
-
845
-		//base is there, let's validate it. If we search for anything, we should
846
-		//get a result set > 0 on a proper base
847
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
848
-		if(!$this->ldap->isResource($rr)) {
849
-			$errorNo  = $this->ldap->errno($cr);
850
-			$errorMsg = $this->ldap->error($cr);
851
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
852
-							' Error '.$errorNo.': '.$errorMsg, ILogger::INFO);
853
-			return false;
854
-		}
855
-		$entries = $this->ldap->countEntries($cr, $rr);
856
-		return ($entries !== false) && ($entries > 0);
857
-	}
858
-
859
-	/**
860
-	 * Checks whether the server supports memberOf in LDAP Filter.
861
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
862
-	 * a configured objectClass. I.e. not necessarily for all available groups
863
-	 * memberOf does work.
864
-	 *
865
-	 * @return bool true if it does, false otherwise
866
-	 * @throws \Exception
867
-	 */
868
-	private function testMemberOf() {
869
-		$cr = $this->getConnection();
870
-		if(!$cr) {
871
-			throw new \Exception('Could not connect to LDAP');
872
-		}
873
-		$result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
874
-		if(is_int($result) &&  $result > 0) {
875
-			return true;
876
-		}
877
-		return false;
878
-	}
879
-
880
-	/**
881
-	 * creates an LDAP Filter from given configuration
882
-	 * @param integer $filterType int, for which use case the filter shall be created
883
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
884
-	 * self::LFILTER_GROUP_LIST
885
-	 * @return string|false string with the filter on success, false otherwise
886
-	 * @throws \Exception
887
-	 */
888
-	private function composeLdapFilter($filterType) {
889
-		$filter = '';
890
-		$parts = 0;
891
-		switch ($filterType) {
892
-			case self::LFILTER_USER_LIST:
893
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
894
-				//glue objectclasses
895
-				if(is_array($objcs) && count($objcs) > 0) {
896
-					$filter .= '(|';
897
-					foreach($objcs as $objc) {
898
-						$filter .= '(objectclass=' . $objc . ')';
899
-					}
900
-					$filter .= ')';
901
-					$parts++;
902
-				}
903
-				//glue group memberships
904
-				if($this->configuration->hasMemberOfFilterSupport) {
905
-					$cns = $this->configuration->ldapUserFilterGroups;
906
-					if(is_array($cns) && count($cns) > 0) {
907
-						$filter .= '(|';
908
-						$cr = $this->getConnection();
909
-						if(!$cr) {
910
-							throw new \Exception('Could not connect to LDAP');
911
-						}
912
-						$base = $this->configuration->ldapBase[0];
913
-						foreach($cns as $cn) {
914
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']);
915
-							if(!$this->ldap->isResource($rr)) {
916
-								continue;
917
-							}
918
-							$er = $this->ldap->firstEntry($cr, $rr);
919
-							$attrs = $this->ldap->getAttributes($cr, $er);
920
-							$dn = $this->ldap->getDN($cr, $er);
921
-							if ($dn === false || $dn === '') {
922
-								continue;
923
-							}
924
-							$filterPart = '(memberof=' . $dn . ')';
925
-							if(isset($attrs['primaryGroupToken'])) {
926
-								$pgt = $attrs['primaryGroupToken'][0];
927
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
929
-							}
930
-							$filter .= $filterPart;
931
-						}
932
-						$filter .= ')';
933
-					}
934
-					$parts++;
935
-				}
936
-				//wrap parts in AND condition
937
-				if($parts > 1) {
938
-					$filter = '(&' . $filter . ')';
939
-				}
940
-				if ($filter === '') {
941
-					$filter = '(objectclass=*)';
942
-				}
943
-				break;
944
-
945
-			case self::LFILTER_GROUP_LIST:
946
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
947
-				//glue objectclasses
948
-				if(is_array($objcs) && count($objcs) > 0) {
949
-					$filter .= '(|';
950
-					foreach($objcs as $objc) {
951
-						$filter .= '(objectclass=' . $objc . ')';
952
-					}
953
-					$filter .= ')';
954
-					$parts++;
955
-				}
956
-				//glue group memberships
957
-				$cns = $this->configuration->ldapGroupFilterGroups;
958
-				if(is_array($cns) && count($cns) > 0) {
959
-					$filter .= '(|';
960
-					foreach($cns as $cn) {
961
-						$filter .= '(cn=' . $cn . ')';
962
-					}
963
-					$filter .= ')';
964
-				}
965
-				$parts++;
966
-				//wrap parts in AND condition
967
-				if($parts > 1) {
968
-					$filter = '(&' . $filter . ')';
969
-				}
970
-				break;
971
-
972
-			case self::LFILTER_LOGIN:
973
-				$ulf = $this->configuration->ldapUserFilter;
974
-				$loginpart = '=%uid';
975
-				$filterUsername = '';
976
-				$userAttributes = $this->getUserAttributes();
977
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
978
-				$parts = 0;
979
-
980
-				if($this->configuration->ldapLoginFilterUsername === '1') {
981
-					$attr = '';
982
-					if(isset($userAttributes['uid'])) {
983
-						$attr = 'uid';
984
-					} else if(isset($userAttributes['samaccountname'])) {
985
-						$attr = 'samaccountname';
986
-					} else if(isset($userAttributes['cn'])) {
987
-						//fallback
988
-						$attr = 'cn';
989
-					}
990
-					if ($attr !== '') {
991
-						$filterUsername = '(' . $attr . $loginpart . ')';
992
-						$parts++;
993
-					}
994
-				}
995
-
996
-				$filterEmail = '';
997
-				if($this->configuration->ldapLoginFilterEmail === '1') {
998
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999
-					$parts++;
1000
-				}
1001
-
1002
-				$filterAttributes = '';
1003
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005
-					$filterAttributes = '(|';
1006
-					foreach($attrsToFilter as $attribute) {
1007
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1008
-					}
1009
-					$filterAttributes .= ')';
1010
-					$parts++;
1011
-				}
1012
-
1013
-				$filterLogin = '';
1014
-				if($parts > 1) {
1015
-					$filterLogin = '(|';
1016
-				}
1017
-				$filterLogin .= $filterUsername;
1018
-				$filterLogin .= $filterEmail;
1019
-				$filterLogin .= $filterAttributes;
1020
-				if($parts > 1) {
1021
-					$filterLogin .= ')';
1022
-				}
1023
-
1024
-				$filter = '(&'.$ulf.$filterLogin.')';
1025
-				break;
1026
-		}
1027
-
1028
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG);
1029
-
1030
-		return $filter;
1031
-	}
1032
-
1033
-	/**
1034
-	 * Connects and Binds to an LDAP Server
1035
-	 *
1036
-	 * @param int $port the port to connect with
1037
-	 * @param bool $tls whether startTLS is to be used
1038
-	 * @return bool
1039
-	 * @throws \Exception
1040
-	 */
1041
-	private function connectAndBind($port, $tls) {
1042
-		//connect, does not really trigger any server communication
1043
-		$host = $this->configuration->ldapHost;
1044
-		$hostInfo = parse_url($host);
1045
-		if(!$hostInfo) {
1046
-			throw new \Exception(self::$l->t('Invalid Host'));
1047
-		}
1048
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049
-		$cr = $this->ldap->connect($host, $port);
1050
-		if(!is_resource($cr)) {
1051
-			throw new \Exception(self::$l->t('Invalid Host'));
1052
-		}
1053
-
1054
-		//set LDAP options
1055
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1056
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1057
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058
-
1059
-		try {
1060
-			if($tls) {
1061
-				$isTlsWorking = @$this->ldap->startTls($cr);
1062
-				if(!$isTlsWorking) {
1063
-					return false;
1064
-				}
1065
-			}
1066
-
1067
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG);
1068
-			//interesting part: do the bind!
1069
-			$login = $this->ldap->bind($cr,
1070
-				$this->configuration->ldapAgentName,
1071
-				$this->configuration->ldapAgentPassword
1072
-			);
1073
-			$errNo = $this->ldap->errno($cr);
1074
-			$error = ldap_error($cr);
1075
-			$this->ldap->unbind($cr);
1076
-		} catch(ServerNotAvailableException $e) {
1077
-			return false;
1078
-		}
1079
-
1080
-		if($login === true) {
1081
-			$this->ldap->unbind($cr);
1082
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1083
-			return true;
1084
-		}
1085
-
1086
-		if($errNo === -1) {
1087
-			//host, port or TLS wrong
1088
-			return false;
1089
-		}
1090
-		throw new \Exception($error, $errNo);
1091
-	}
1092
-
1093
-	/**
1094
-	 * checks whether a valid combination of agent and password has been
1095
-	 * provided (either two values or nothing for anonymous connect)
1096
-	 * @return bool, true if everything is fine, false otherwise
1097
-	 */
1098
-	private function checkAgentRequirements() {
1099
-		$agent = $this->configuration->ldapAgentName;
1100
-		$pwd = $this->configuration->ldapAgentPassword;
1101
-
1102
-		return
1103
-			($agent !== '' && $pwd !== '')
1104
-			||  ($agent === '' && $pwd === '')
1105
-		;
1106
-	}
1107
-
1108
-	/**
1109
-	 * @param array $reqs
1110
-	 * @return bool
1111
-	 */
1112
-	private function checkRequirements($reqs) {
1113
-		$this->checkAgentRequirements();
1114
-		foreach($reqs as $option) {
1115
-			$value = $this->configuration->$option;
1116
-			if(empty($value)) {
1117
-				return false;
1118
-			}
1119
-		}
1120
-		return true;
1121
-	}
1122
-
1123
-	/**
1124
-	 * does a cumulativeSearch on LDAP to get different values of a
1125
-	 * specified attribute
1126
-	 * @param string[] $filters array, the filters that shall be used in the search
1127
-	 * @param string $attr the attribute of which a list of values shall be returned
1128
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1129
-	 * The lower, the faster
1130
-	 * @param string $maxF string. if not null, this variable will have the filter that
1131
-	 * yields most result entries
1132
-	 * @return array|false an array with the values on success, false otherwise
1133
-	 */
1134
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1135
-		$dnRead = [];
1136
-		$foundItems = [];
1137
-		$maxEntries = 0;
1138
-		if(!is_array($this->configuration->ldapBase)
1139
-		   || !isset($this->configuration->ldapBase[0])) {
1140
-			return false;
1141
-		}
1142
-		$base = $this->configuration->ldapBase[0];
1143
-		$cr = $this->getConnection();
1144
-		if(!$this->ldap->isResource($cr)) {
1145
-			return false;
1146
-		}
1147
-		$lastFilter = null;
1148
-		if(isset($filters[count($filters)-1])) {
1149
-			$lastFilter = $filters[count($filters)-1];
1150
-		}
1151
-		foreach($filters as $filter) {
1152
-			if($lastFilter === $filter && count($foundItems) > 0) {
1153
-				//skip when the filter is a wildcard and results were found
1154
-				continue;
1155
-			}
1156
-			// 20k limit for performance and reason
1157
-			$rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
1158
-			if(!$this->ldap->isResource($rr)) {
1159
-				continue;
1160
-			}
1161
-			$entries = $this->ldap->countEntries($cr, $rr);
1162
-			$getEntryFunc = 'firstEntry';
1163
-			if(($entries !== false) && ($entries > 0)) {
1164
-				if(!is_null($maxF) && $entries > $maxEntries) {
1165
-					$maxEntries = $entries;
1166
-					$maxF = $filter;
1167
-				}
1168
-				$dnReadCount = 0;
1169
-				do {
1170
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1171
-					$getEntryFunc = 'nextEntry';
1172
-					if(!$this->ldap->isResource($entry)) {
1173
-						continue 2;
1174
-					}
1175
-					$rr = $entry; //will be expected by nextEntry next round
1176
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1177
-					$dn = $this->ldap->getDN($cr, $entry);
1178
-					if($dn === false || in_array($dn, $dnRead)) {
1179
-						continue;
1180
-					}
1181
-					$newItems = [];
1182
-					$state = $this->getAttributeValuesFromEntry($attributes,
1183
-																$attr,
1184
-																$newItems);
1185
-					$dnReadCount++;
1186
-					$foundItems = array_merge($foundItems, $newItems);
1187
-					$this->resultCache[$dn][$attr] = $newItems;
1188
-					$dnRead[] = $dn;
1189
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1190
-						|| $this->ldap->isResource($entry))
1191
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192
-			}
1193
-		}
1194
-
1195
-		return array_unique($foundItems);
1196
-	}
1197
-
1198
-	/**
1199
-	 * determines if and which $attr are available on the LDAP server
1200
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1201
-	 * @param string $attr the attribute to look for
1202
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1203
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1204
-	 * Configuration class
1205
-	 * @param bool $po whether the objectClass with most result entries
1206
-	 * shall be pre-selected via the result
1207
-	 * @return array|false list of found items.
1208
-	 * @throws \Exception
1209
-	 */
1210
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211
-		$cr = $this->getConnection();
1212
-		if(!$cr) {
1213
-			throw new \Exception('Could not connect to LDAP');
1214
-		}
1215
-		$p = 'objectclass=';
1216
-		foreach($objectclasses as $key => $value) {
1217
-			$objectclasses[$key] = $p.$value;
1218
-		}
1219
-		$maxEntryObjC = '';
1220
-
1221
-		//how deep to dig?
1222
-		//When looking for objectclasses, testing few entries is sufficient,
1223
-		$dig = 3;
1224
-
1225
-		$availableFeatures =
1226
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227
-											   $dig, $maxEntryObjC);
1228
-		if(is_array($availableFeatures)
1229
-		   && count($availableFeatures) > 0) {
1230
-			natcasesort($availableFeatures);
1231
-			//natcasesort keeps indices, but we must get rid of them for proper
1232
-			//sorting in the web UI. Therefore: array_values
1233
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1234
-		} else {
1235
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1236
-		}
1237
-
1238
-		$setFeatures = $this->configuration->$confkey;
1239
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1240
-			//something is already configured? pre-select it.
1241
-			$this->result->addChange($dbkey, $setFeatures);
1242
-		} else if ($po && $maxEntryObjC !== '') {
1243
-			//pre-select objectclass with most result entries
1244
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1245
-			$this->applyFind($dbkey, $maxEntryObjC);
1246
-			$this->result->addChange($dbkey, $maxEntryObjC);
1247
-		}
1248
-
1249
-		return $availableFeatures;
1250
-	}
1251
-
1252
-	/**
1253
-	 * appends a list of values fr
1254
-	 * @param resource $result the return value from ldap_get_attributes
1255
-	 * @param string $attribute the attribute values to look for
1256
-	 * @param array &$known new values will be appended here
1257
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1258
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259
-	 */
1260
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
-		if(!is_array($result)
1262
-		   || !isset($result['count'])
1263
-		   || !$result['count'] > 0) {
1264
-			return self::LRESULT_PROCESSED_INVALID;
1265
-		}
1266
-
1267
-		// strtolower on all keys for proper comparison
1268
-		$result = \OCP\Util::mb_array_change_key_case($result);
1269
-		$attribute = strtolower($attribute);
1270
-		if(isset($result[$attribute])) {
1271
-			foreach($result[$attribute] as $key => $val) {
1272
-				if($key === 'count') {
1273
-					continue;
1274
-				}
1275
-				if(!in_array($val, $known)) {
1276
-					$known[] = $val;
1277
-				}
1278
-			}
1279
-			return self::LRESULT_PROCESSED_OK;
1280
-		} else {
1281
-			return self::LRESULT_PROCESSED_SKIP;
1282
-		}
1283
-	}
1284
-
1285
-	/**
1286
-	 * @return bool|mixed
1287
-	 */
1288
-	private function getConnection() {
1289
-		if(!is_null($this->cr)) {
1290
-			return $this->cr;
1291
-		}
1292
-
1293
-		$cr = $this->ldap->connect(
1294
-			$this->configuration->ldapHost,
1295
-			$this->configuration->ldapPort
1296
-		);
1297
-
1298
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
-		if($this->configuration->ldapTLS === 1) {
1302
-			$this->ldap->startTls($cr);
1303
-		}
1304
-
1305
-		$lo = @$this->ldap->bind($cr,
1306
-								 $this->configuration->ldapAgentName,
1307
-								 $this->configuration->ldapAgentPassword);
1308
-		if($lo === true) {
1309
-			$this->$cr = $cr;
1310
-			return $cr;
1311
-		}
1312
-
1313
-		return false;
1314
-	}
1315
-
1316
-	/**
1317
-	 * @return array
1318
-	 */
1319
-	private function getDefaultLdapPortSettings() {
1320
-		static $settings = [
1321
-			['port' => 7636, 'tls' => false],
1322
-			['port' =>  636, 'tls' => false],
1323
-			['port' => 7389, 'tls' => true],
1324
-			['port' =>  389, 'tls' => true],
1325
-			['port' => 7389, 'tls' => false],
1326
-			['port' =>  389, 'tls' => false],
1327
-		];
1328
-		return $settings;
1329
-	}
1330
-
1331
-	/**
1332
-	 * @return array
1333
-	 */
1334
-	private function getPortSettingsToTry() {
1335
-		//389 ← LDAP / Unencrypted or StartTLS
1336
-		//636 ← LDAPS / SSL
1337
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1338
-		$host = $this->configuration->ldapHost;
1339
-		$port = (int)$this->configuration->ldapPort;
1340
-		$portSettings = [];
1341
-
1342
-		//In case the port is already provided, we will check this first
1343
-		if($port > 0) {
1344
-			$hostInfo = parse_url($host);
1345
-			if(!(is_array($hostInfo)
1346
-				&& isset($hostInfo['scheme'])
1347
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348
-				$portSettings[] = ['port' => $port, 'tls' => true];
1349
-			}
1350
-			$portSettings[] =['port' => $port, 'tls' => false];
1351
-		}
1352
-
1353
-		//default ports
1354
-		$portSettings = array_merge($portSettings,
1355
-									$this->getDefaultLdapPortSettings());
1356
-
1357
-		return $portSettings;
1358
-	}
45
+    /** @var \OCP\IL10N */
46
+    static protected $l;
47
+    protected $access;
48
+    protected $cr;
49
+    protected $configuration;
50
+    protected $result;
51
+    protected $resultCache = [];
52
+
53
+    const LRESULT_PROCESSED_OK = 2;
54
+    const LRESULT_PROCESSED_INVALID = 3;
55
+    const LRESULT_PROCESSED_SKIP = 4;
56
+
57
+    const LFILTER_LOGIN      = 2;
58
+    const LFILTER_USER_LIST  = 3;
59
+    const LFILTER_GROUP_LIST = 4;
60
+
61
+    const LFILTER_MODE_ASSISTED = 2;
62
+    const LFILTER_MODE_RAW = 1;
63
+
64
+    const LDAP_NW_TIMEOUT = 4;
65
+
66
+    /**
67
+     * Constructor
68
+     * @param Configuration $configuration an instance of Configuration
69
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
70
+     * @param Access $access
71
+     */
72
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73
+        parent::__construct($ldap);
74
+        $this->configuration = $configuration;
75
+        if(is_null(Wizard::$l)) {
76
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
77
+        }
78
+        $this->access = $access;
79
+        $this->result = new WizardResult();
80
+    }
81
+
82
+    public function  __destruct() {
83
+        if($this->result->hasChanges()) {
84
+            $this->configuration->saveConfiguration();
85
+        }
86
+    }
87
+
88
+    /**
89
+     * counts entries in the LDAP directory
90
+     *
91
+     * @param string $filter the LDAP search filter
92
+     * @param string $type a string being either 'users' or 'groups';
93
+     * @return int
94
+     * @throws \Exception
95
+     */
96
+    public function countEntries(string $filter, string $type): int {
97
+        $reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
+        if($type === 'users') {
99
+            $reqs[] = 'ldapUserFilter';
100
+        }
101
+        if(!$this->checkRequirements($reqs)) {
102
+            throw new \Exception('Requirements not met', 400);
103
+        }
104
+
105
+        $attr = ['dn']; // default
106
+        $limit = 1001;
107
+        if($type === 'groups') {
108
+            $result =  $this->access->countGroups($filter, $attr, $limit);
109
+        } else if($type === 'users') {
110
+            $result = $this->access->countUsers($filter, $attr, $limit);
111
+        } else if ($type === 'objects') {
112
+            $result = $this->access->countObjects($limit);
113
+        } else {
114
+            throw new \Exception('Internal error: Invalid object type', 500);
115
+        }
116
+
117
+        return (int)$result;
118
+    }
119
+
120
+    /**
121
+     * formats the return value of a count operation to the string to be
122
+     * inserted.
123
+     *
124
+     * @param int $count
125
+     * @return string
126
+     */
127
+    private function formatCountResult(int $count): string {
128
+        if($count > 1000) {
129
+            return '> 1000';
130
+        }
131
+        return (string)$count;
132
+    }
133
+
134
+    public function countGroups() {
135
+        $filter = $this->configuration->ldapGroupFilter;
136
+
137
+        if(empty($filter)) {
138
+            $output = self::$l->n('%s group found', '%s groups found', 0, [0]);
139
+            $this->result->addChange('ldap_group_count', $output);
140
+            return $this->result;
141
+        }
142
+
143
+        try {
144
+            $groupsTotal = $this->countEntries($filter, 'groups');
145
+        } catch (\Exception $e) {
146
+            //400 can be ignored, 500 is forwarded
147
+            if($e->getCode() === 500) {
148
+                throw $e;
149
+            }
150
+            return false;
151
+        }
152
+        $output = self::$l->n(
153
+            '%s group found',
154
+            '%s groups found',
155
+            $groupsTotal,
156
+            [$this->formatCountResult($groupsTotal)]
157
+        );
158
+        $this->result->addChange('ldap_group_count', $output);
159
+        return $this->result;
160
+    }
161
+
162
+    /**
163
+     * @return WizardResult
164
+     * @throws \Exception
165
+     */
166
+    public function countUsers() {
167
+        $filter = $this->access->getFilterForUserCount();
168
+
169
+        $usersTotal = $this->countEntries($filter, 'users');
170
+        $output = self::$l->n(
171
+            '%s user found',
172
+            '%s users found',
173
+            $usersTotal,
174
+            [$this->formatCountResult($usersTotal)]
175
+        );
176
+        $this->result->addChange('ldap_user_count', $output);
177
+        return $this->result;
178
+    }
179
+
180
+    /**
181
+     * counts any objects in the currently set base dn
182
+     *
183
+     * @return WizardResult
184
+     * @throws \Exception
185
+     */
186
+    public function countInBaseDN() {
187
+        // we don't need to provide a filter in this case
188
+        $total = $this->countEntries('', 'objects');
189
+        if($total === false) {
190
+            throw new \Exception('invalid results received');
191
+        }
192
+        $this->result->addChange('ldap_test_base', $total);
193
+        return $this->result;
194
+    }
195
+
196
+    /**
197
+     * counts users with a specified attribute
198
+     * @param string $attr
199
+     * @param bool $existsCheck
200
+     * @return int|bool
201
+     */
202
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
203
+        if(!$this->checkRequirements(['ldapHost',
204
+            'ldapPort',
205
+            'ldapBase',
206
+            'ldapUserFilter',
207
+        ])) {
208
+            return  false;
209
+        }
210
+
211
+        $filter = $this->access->combineFilterWithAnd([
212
+            $this->configuration->ldapUserFilter,
213
+            $attr . '=*'
214
+        ]);
215
+
216
+        $limit = ($existsCheck === false) ? null : 1;
217
+
218
+        return $this->access->countUsers($filter, ['dn'], $limit);
219
+    }
220
+
221
+    /**
222
+     * detects the display name attribute. If a setting is already present that
223
+     * returns at least one hit, the detection will be canceled.
224
+     * @return WizardResult|bool
225
+     * @throws \Exception
226
+     */
227
+    public function detectUserDisplayNameAttribute() {
228
+        if(!$this->checkRequirements(['ldapHost',
229
+            'ldapPort',
230
+            'ldapBase',
231
+            'ldapUserFilter',
232
+        ])) {
233
+            return  false;
234
+        }
235
+
236
+        $attr = $this->configuration->ldapUserDisplayName;
237
+        if ($attr !== '' && $attr !== 'displayName') {
238
+            // most likely not the default value with upper case N,
239
+            // verify it still produces a result
240
+            $count = (int)$this->countUsersWithAttribute($attr, true);
241
+            if($count > 0) {
242
+                //no change, but we sent it back to make sure the user interface
243
+                //is still correct, even if the ajax call was cancelled meanwhile
244
+                $this->result->addChange('ldap_display_name', $attr);
245
+                return $this->result;
246
+            }
247
+        }
248
+
249
+        // first attribute that has at least one result wins
250
+        $displayNameAttrs = ['displayname', 'cn'];
251
+        foreach ($displayNameAttrs as $attr) {
252
+            $count = (int)$this->countUsersWithAttribute($attr, true);
253
+
254
+            if($count > 0) {
255
+                $this->applyFind('ldap_display_name', $attr);
256
+                return $this->result;
257
+            }
258
+        }
259
+
260
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
261
+    }
262
+
263
+    /**
264
+     * detects the most often used email attribute for users applying to the
265
+     * user list filter. If a setting is already present that returns at least
266
+     * one hit, the detection will be canceled.
267
+     * @return WizardResult|bool
268
+     */
269
+    public function detectEmailAttribute() {
270
+        if(!$this->checkRequirements(['ldapHost',
271
+            'ldapPort',
272
+            'ldapBase',
273
+            'ldapUserFilter',
274
+        ])) {
275
+            return  false;
276
+        }
277
+
278
+        $attr = $this->configuration->ldapEmailAttribute;
279
+        if ($attr !== '') {
280
+            $count = (int)$this->countUsersWithAttribute($attr, true);
281
+            if($count > 0) {
282
+                return false;
283
+            }
284
+            $writeLog = true;
285
+        } else {
286
+            $writeLog = false;
287
+        }
288
+
289
+        $emailAttributes = ['mail', 'mailPrimaryAddress'];
290
+        $winner = '';
291
+        $maxUsers = 0;
292
+        foreach($emailAttributes as $attr) {
293
+            $count = $this->countUsersWithAttribute($attr);
294
+            if($count > $maxUsers) {
295
+                $maxUsers = $count;
296
+                $winner = $attr;
297
+            }
298
+        }
299
+
300
+        if($winner !== '') {
301
+            $this->applyFind('ldap_email_attr', $winner);
302
+            if($writeLog) {
303
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
+                    'automatically been reset, because the original value ' .
305
+                    'did not return any results.', ILogger::INFO);
306
+            }
307
+        }
308
+
309
+        return $this->result;
310
+    }
311
+
312
+    /**
313
+     * @return WizardResult
314
+     * @throws \Exception
315
+     */
316
+    public function determineAttributes() {
317
+        if(!$this->checkRequirements(['ldapHost',
318
+            'ldapPort',
319
+            'ldapBase',
320
+            'ldapUserFilter',
321
+        ])) {
322
+            return  false;
323
+        }
324
+
325
+        $attributes = $this->getUserAttributes();
326
+
327
+        natcasesort($attributes);
328
+        $attributes = array_values($attributes);
329
+
330
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331
+
332
+        $selected = $this->configuration->ldapLoginFilterAttributes;
333
+        if(is_array($selected) && !empty($selected)) {
334
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
335
+        }
336
+
337
+        return $this->result;
338
+    }
339
+
340
+    /**
341
+     * detects the available LDAP attributes
342
+     * @return array|false The instance's WizardResult instance
343
+     * @throws \Exception
344
+     */
345
+    private function getUserAttributes() {
346
+        if(!$this->checkRequirements(['ldapHost',
347
+            'ldapPort',
348
+            'ldapBase',
349
+            'ldapUserFilter',
350
+        ])) {
351
+            return  false;
352
+        }
353
+        $cr = $this->getConnection();
354
+        if(!$cr) {
355
+            throw new \Exception('Could not connect to LDAP');
356
+        }
357
+
358
+        $base = $this->configuration->ldapBase[0];
359
+        $filter = $this->configuration->ldapUserFilter;
360
+        $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
361
+        if(!$this->ldap->isResource($rr)) {
362
+            return false;
363
+        }
364
+        $er = $this->ldap->firstEntry($cr, $rr);
365
+        $attributes = $this->ldap->getAttributes($cr, $er);
366
+        $pureAttributes = [];
367
+        for($i = 0; $i < $attributes['count']; $i++) {
368
+            $pureAttributes[] = $attributes[$i];
369
+        }
370
+
371
+        return $pureAttributes;
372
+    }
373
+
374
+    /**
375
+     * detects the available LDAP groups
376
+     * @return WizardResult|false the instance's WizardResult instance
377
+     */
378
+    public function determineGroupsForGroups() {
379
+        return $this->determineGroups('ldap_groupfilter_groups',
380
+                                        'ldapGroupFilterGroups',
381
+                                        false);
382
+    }
383
+
384
+    /**
385
+     * detects the available LDAP groups
386
+     * @return WizardResult|false the instance's WizardResult instance
387
+     */
388
+    public function determineGroupsForUsers() {
389
+        return $this->determineGroups('ldap_userfilter_groups',
390
+                                        'ldapUserFilterGroups');
391
+    }
392
+
393
+    /**
394
+     * detects the available LDAP groups
395
+     * @param string $dbKey
396
+     * @param string $confKey
397
+     * @param bool $testMemberOf
398
+     * @return WizardResult|false the instance's WizardResult instance
399
+     * @throws \Exception
400
+     */
401
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
+        if(!$this->checkRequirements(['ldapHost',
403
+            'ldapPort',
404
+            'ldapBase',
405
+        ])) {
406
+            return  false;
407
+        }
408
+        $cr = $this->getConnection();
409
+        if(!$cr) {
410
+            throw new \Exception('Could not connect to LDAP');
411
+        }
412
+
413
+        $this->fetchGroups($dbKey, $confKey);
414
+
415
+        if($testMemberOf) {
416
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417
+            $this->result->markChange();
418
+            if(!$this->configuration->hasMemberOfFilterSupport) {
419
+                throw new \Exception('memberOf is not supported by the server');
420
+            }
421
+        }
422
+
423
+        return $this->result;
424
+    }
425
+
426
+    /**
427
+     * fetches all groups from LDAP and adds them to the result object
428
+     *
429
+     * @param string $dbKey
430
+     * @param string $confKey
431
+     * @return array $groupEntries
432
+     * @throws \Exception
433
+     */
434
+    public function fetchGroups($dbKey, $confKey) {
435
+        $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
436
+
437
+        $filterParts = [];
438
+        foreach($obclasses as $obclass) {
439
+            $filterParts[] = 'objectclass='.$obclass;
440
+        }
441
+        //we filter for everything
442
+        //- that looks like a group and
443
+        //- has the group display name set
444
+        $filter = $this->access->combineFilterWithOr($filterParts);
445
+        $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']);
446
+
447
+        $groupNames = [];
448
+        $groupEntries = [];
449
+        $limit = 400;
450
+        $offset = 0;
451
+        do {
452
+            // we need to request dn additionally here, otherwise memberOf
453
+            // detection will fail later
454
+            $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
455
+            foreach($result as $item) {
456
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457
+                    // just in case - no issue known
458
+                    continue;
459
+                }
460
+                $groupNames[] = $item['cn'][0];
461
+                $groupEntries[] = $item;
462
+            }
463
+            $offset += $limit;
464
+        } while ($this->access->hasMoreResults());
465
+
466
+        if(count($groupNames) > 0) {
467
+            natsort($groupNames);
468
+            $this->result->addOptions($dbKey, array_values($groupNames));
469
+        } else {
470
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
471
+        }
472
+
473
+        $setFeatures = $this->configuration->$confKey;
474
+        if(is_array($setFeatures) && !empty($setFeatures)) {
475
+            //something is already configured? pre-select it.
476
+            $this->result->addChange($dbKey, $setFeatures);
477
+        }
478
+        return $groupEntries;
479
+    }
480
+
481
+    public function determineGroupMemberAssoc() {
482
+        if(!$this->checkRequirements(['ldapHost',
483
+            'ldapPort',
484
+            'ldapGroupFilter',
485
+        ])) {
486
+            return  false;
487
+        }
488
+        $attribute = $this->detectGroupMemberAssoc();
489
+        if($attribute === false) {
490
+            return false;
491
+        }
492
+        $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
493
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
494
+
495
+        return $this->result;
496
+    }
497
+
498
+    /**
499
+     * Detects the available object classes
500
+     * @return WizardResult|false the instance's WizardResult instance
501
+     * @throws \Exception
502
+     */
503
+    public function determineGroupObjectClasses() {
504
+        if(!$this->checkRequirements(['ldapHost',
505
+            'ldapPort',
506
+            'ldapBase',
507
+        ])) {
508
+            return  false;
509
+        }
510
+        $cr = $this->getConnection();
511
+        if(!$cr) {
512
+            throw new \Exception('Could not connect to LDAP');
513
+        }
514
+
515
+        $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*'];
516
+        $this->determineFeature($obclasses,
517
+                                'objectclass',
518
+                                'ldap_groupfilter_objectclass',
519
+                                'ldapGroupFilterObjectclass',
520
+                                false);
521
+
522
+        return $this->result;
523
+    }
524
+
525
+    /**
526
+     * detects the available object classes
527
+     * @return WizardResult
528
+     * @throws \Exception
529
+     */
530
+    public function determineUserObjectClasses() {
531
+        if(!$this->checkRequirements(['ldapHost',
532
+            'ldapPort',
533
+            'ldapBase',
534
+        ])) {
535
+            return  false;
536
+        }
537
+        $cr = $this->getConnection();
538
+        if(!$cr) {
539
+            throw new \Exception('Could not connect to LDAP');
540
+        }
541
+
542
+        $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson',
543
+            'user', 'posixAccount', '*'];
544
+        $filter = $this->configuration->ldapUserFilter;
545
+        //if filter is empty, it is probably the first time the wizard is called
546
+        //then, apply suggestions.
547
+        $this->determineFeature($obclasses,
548
+                                'objectclass',
549
+                                'ldap_userfilter_objectclass',
550
+                                'ldapUserFilterObjectclass',
551
+                                empty($filter));
552
+
553
+        return $this->result;
554
+    }
555
+
556
+    /**
557
+     * @return WizardResult|false
558
+     * @throws \Exception
559
+     */
560
+    public function getGroupFilter() {
561
+        if(!$this->checkRequirements(['ldapHost',
562
+            'ldapPort',
563
+            'ldapBase',
564
+        ])) {
565
+            return false;
566
+        }
567
+        //make sure the use display name is set
568
+        $displayName = $this->configuration->ldapGroupDisplayName;
569
+        if ($displayName === '') {
570
+            $d = $this->configuration->getDefaults();
571
+            $this->applyFind('ldap_group_display_name',
572
+                                $d['ldap_group_display_name']);
573
+        }
574
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
575
+
576
+        $this->applyFind('ldap_group_filter', $filter);
577
+        return $this->result;
578
+    }
579
+
580
+    /**
581
+     * @return WizardResult|false
582
+     * @throws \Exception
583
+     */
584
+    public function getUserListFilter() {
585
+        if(!$this->checkRequirements(['ldapHost',
586
+            'ldapPort',
587
+            'ldapBase',
588
+        ])) {
589
+            return false;
590
+        }
591
+        //make sure the use display name is set
592
+        $displayName = $this->configuration->ldapUserDisplayName;
593
+        if ($displayName === '') {
594
+            $d = $this->configuration->getDefaults();
595
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
596
+        }
597
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
+        if(!$filter) {
599
+            throw new \Exception('Cannot create filter');
600
+        }
601
+
602
+        $this->applyFind('ldap_userlist_filter', $filter);
603
+        return $this->result;
604
+    }
605
+
606
+    /**
607
+     * @return bool|WizardResult
608
+     * @throws \Exception
609
+     */
610
+    public function getUserLoginFilter() {
611
+        if(!$this->checkRequirements(['ldapHost',
612
+            'ldapPort',
613
+            'ldapBase',
614
+            'ldapUserFilter',
615
+        ])) {
616
+            return false;
617
+        }
618
+
619
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
+        if(!$filter) {
621
+            throw new \Exception('Cannot create filter');
622
+        }
623
+
624
+        $this->applyFind('ldap_login_filter', $filter);
625
+        return $this->result;
626
+    }
627
+
628
+    /**
629
+     * @return bool|WizardResult
630
+     * @param string $loginName
631
+     * @throws \Exception
632
+     */
633
+    public function testLoginName($loginName) {
634
+        if(!$this->checkRequirements(['ldapHost',
635
+            'ldapPort',
636
+            'ldapBase',
637
+            'ldapLoginFilter',
638
+        ])) {
639
+            return false;
640
+        }
641
+
642
+        $cr = $this->access->connection->getConnectionResource();
643
+        if(!$this->ldap->isResource($cr)) {
644
+            throw new \Exception('connection error');
645
+        }
646
+
647
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648
+            === false) {
649
+            throw new \Exception('missing placeholder');
650
+        }
651
+
652
+        $users = $this->access->countUsersByLoginName($loginName);
653
+        if($this->ldap->errno($cr) !== 0) {
654
+            throw new \Exception($this->ldap->error($cr));
655
+        }
656
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
657
+        $this->result->addChange('ldap_test_loginname', $users);
658
+        $this->result->addChange('ldap_test_effective_filter', $filter);
659
+        return $this->result;
660
+    }
661
+
662
+    /**
663
+     * Tries to determine the port, requires given Host, User DN and Password
664
+     * @return WizardResult|false WizardResult on success, false otherwise
665
+     * @throws \Exception
666
+     */
667
+    public function guessPortAndTLS() {
668
+        if(!$this->checkRequirements(['ldapHost',
669
+        ])) {
670
+            return false;
671
+        }
672
+        $this->checkHost();
673
+        $portSettings = $this->getPortSettingsToTry();
674
+
675
+        if(!is_array($portSettings)) {
676
+            throw new \Exception(print_r($portSettings, true));
677
+        }
678
+
679
+        //proceed from the best configuration and return on first success
680
+        foreach($portSettings as $setting) {
681
+            $p = $setting['port'];
682
+            $t = $setting['tls'];
683
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
684
+            //connectAndBind may throw Exception, it needs to be catched by the
685
+            //callee of this method
686
+
687
+            try {
688
+                $settingsFound = $this->connectAndBind($p, $t);
689
+            } catch (\Exception $e) {
690
+                // any reply other than -1 (= cannot connect) is already okay,
691
+                // because then we found the server
692
+                // unavailable startTLS returns -11
693
+                if($e->getCode() > 0) {
694
+                    $settingsFound = true;
695
+                } else {
696
+                    throw $e;
697
+                }
698
+            }
699
+
700
+            if ($settingsFound === true) {
701
+                $config = [
702
+                    'ldapPort' => $p,
703
+                    'ldapTLS' => (int)$t
704
+                ];
705
+                $this->configuration->setConfiguration($config);
706
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
707
+                $this->result->addChange('ldap_port', $p);
708
+                return $this->result;
709
+            }
710
+        }
711
+
712
+        //custom port, undetected (we do not brute force)
713
+        return false;
714
+    }
715
+
716
+    /**
717
+     * tries to determine a base dn from User DN or LDAP Host
718
+     * @return WizardResult|false WizardResult on success, false otherwise
719
+     */
720
+    public function guessBaseDN() {
721
+        if(!$this->checkRequirements(['ldapHost',
722
+            'ldapPort',
723
+        ])) {
724
+            return false;
725
+        }
726
+
727
+        //check whether a DN is given in the agent name (99.9% of all cases)
728
+        $base = null;
729
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
730
+        if($i !== false) {
731
+            $base = substr($this->configuration->ldapAgentName, $i);
732
+            if($this->testBaseDN($base)) {
733
+                $this->applyFind('ldap_base', $base);
734
+                return $this->result;
735
+            }
736
+        }
737
+
738
+        //this did not help :(
739
+        //Let's see whether we can parse the Host URL and convert the domain to
740
+        //a base DN
741
+        $helper = new Helper(\OC::$server->getConfig());
742
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
+        if(!$domain) {
744
+            return false;
745
+        }
746
+
747
+        $dparts = explode('.', $domain);
748
+        while(count($dparts) > 0) {
749
+            $base2 = 'dc=' . implode(',dc=', $dparts);
750
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
751
+                $this->applyFind('ldap_base', $base2);
752
+                return $this->result;
753
+            }
754
+            array_shift($dparts);
755
+        }
756
+
757
+        return false;
758
+    }
759
+
760
+    /**
761
+     * sets the found value for the configuration key in the WizardResult
762
+     * as well as in the Configuration instance
763
+     * @param string $key the configuration key
764
+     * @param string $value the (detected) value
765
+     *
766
+     */
767
+    private function applyFind($key, $value) {
768
+        $this->result->addChange($key, $value);
769
+        $this->configuration->setConfiguration([$key => $value]);
770
+    }
771
+
772
+    /**
773
+     * Checks, whether a port was entered in the Host configuration
774
+     * field. In this case the port will be stripped off, but also stored as
775
+     * setting.
776
+     */
777
+    private function checkHost() {
778
+        $host = $this->configuration->ldapHost;
779
+        $hostInfo = parse_url($host);
780
+
781
+        //removes Port from Host
782
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
783
+            $port = $hostInfo['port'];
784
+            $host = str_replace(':'.$port, '', $host);
785
+            $this->applyFind('ldap_host', $host);
786
+            $this->applyFind('ldap_port', $port);
787
+        }
788
+    }
789
+
790
+    /**
791
+     * tries to detect the group member association attribute which is
792
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
793
+     * @return string|false, string with the attribute name, false on error
794
+     * @throws \Exception
795
+     */
796
+    private function detectGroupMemberAssoc() {
797
+        $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber'];
798
+        $filter = $this->configuration->ldapGroupFilter;
799
+        if(empty($filter)) {
800
+            return false;
801
+        }
802
+        $cr = $this->getConnection();
803
+        if(!$cr) {
804
+            throw new \Exception('Could not connect to LDAP');
805
+        }
806
+        $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
807
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
+        if(!$this->ldap->isResource($rr)) {
809
+            return false;
810
+        }
811
+        $er = $this->ldap->firstEntry($cr, $rr);
812
+        while(is_resource($er)) {
813
+            $this->ldap->getDN($cr, $er);
814
+            $attrs = $this->ldap->getAttributes($cr, $er);
815
+            $result = [];
816
+            $possibleAttrsCount = count($possibleAttrs);
817
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
818
+                if(isset($attrs[$possibleAttrs[$i]])) {
819
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820
+                }
821
+            }
822
+            if(!empty($result)) {
823
+                natsort($result);
824
+                return key($result);
825
+            }
826
+
827
+            $er = $this->ldap->nextEntry($cr, $er);
828
+        }
829
+
830
+        return false;
831
+    }
832
+
833
+    /**
834
+     * Checks whether for a given BaseDN results will be returned
835
+     * @param string $base the BaseDN to test
836
+     * @return bool true on success, false otherwise
837
+     * @throws \Exception
838
+     */
839
+    private function testBaseDN($base) {
840
+        $cr = $this->getConnection();
841
+        if(!$cr) {
842
+            throw new \Exception('Could not connect to LDAP');
843
+        }
844
+
845
+        //base is there, let's validate it. If we search for anything, we should
846
+        //get a result set > 0 on a proper base
847
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
848
+        if(!$this->ldap->isResource($rr)) {
849
+            $errorNo  = $this->ldap->errno($cr);
850
+            $errorMsg = $this->ldap->error($cr);
851
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
852
+                            ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO);
853
+            return false;
854
+        }
855
+        $entries = $this->ldap->countEntries($cr, $rr);
856
+        return ($entries !== false) && ($entries > 0);
857
+    }
858
+
859
+    /**
860
+     * Checks whether the server supports memberOf in LDAP Filter.
861
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
862
+     * a configured objectClass. I.e. not necessarily for all available groups
863
+     * memberOf does work.
864
+     *
865
+     * @return bool true if it does, false otherwise
866
+     * @throws \Exception
867
+     */
868
+    private function testMemberOf() {
869
+        $cr = $this->getConnection();
870
+        if(!$cr) {
871
+            throw new \Exception('Could not connect to LDAP');
872
+        }
873
+        $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
874
+        if(is_int($result) &&  $result > 0) {
875
+            return true;
876
+        }
877
+        return false;
878
+    }
879
+
880
+    /**
881
+     * creates an LDAP Filter from given configuration
882
+     * @param integer $filterType int, for which use case the filter shall be created
883
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
884
+     * self::LFILTER_GROUP_LIST
885
+     * @return string|false string with the filter on success, false otherwise
886
+     * @throws \Exception
887
+     */
888
+    private function composeLdapFilter($filterType) {
889
+        $filter = '';
890
+        $parts = 0;
891
+        switch ($filterType) {
892
+            case self::LFILTER_USER_LIST:
893
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
894
+                //glue objectclasses
895
+                if(is_array($objcs) && count($objcs) > 0) {
896
+                    $filter .= '(|';
897
+                    foreach($objcs as $objc) {
898
+                        $filter .= '(objectclass=' . $objc . ')';
899
+                    }
900
+                    $filter .= ')';
901
+                    $parts++;
902
+                }
903
+                //glue group memberships
904
+                if($this->configuration->hasMemberOfFilterSupport) {
905
+                    $cns = $this->configuration->ldapUserFilterGroups;
906
+                    if(is_array($cns) && count($cns) > 0) {
907
+                        $filter .= '(|';
908
+                        $cr = $this->getConnection();
909
+                        if(!$cr) {
910
+                            throw new \Exception('Could not connect to LDAP');
911
+                        }
912
+                        $base = $this->configuration->ldapBase[0];
913
+                        foreach($cns as $cn) {
914
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']);
915
+                            if(!$this->ldap->isResource($rr)) {
916
+                                continue;
917
+                            }
918
+                            $er = $this->ldap->firstEntry($cr, $rr);
919
+                            $attrs = $this->ldap->getAttributes($cr, $er);
920
+                            $dn = $this->ldap->getDN($cr, $er);
921
+                            if ($dn === false || $dn === '') {
922
+                                continue;
923
+                            }
924
+                            $filterPart = '(memberof=' . $dn . ')';
925
+                            if(isset($attrs['primaryGroupToken'])) {
926
+                                $pgt = $attrs['primaryGroupToken'][0];
927
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
929
+                            }
930
+                            $filter .= $filterPart;
931
+                        }
932
+                        $filter .= ')';
933
+                    }
934
+                    $parts++;
935
+                }
936
+                //wrap parts in AND condition
937
+                if($parts > 1) {
938
+                    $filter = '(&' . $filter . ')';
939
+                }
940
+                if ($filter === '') {
941
+                    $filter = '(objectclass=*)';
942
+                }
943
+                break;
944
+
945
+            case self::LFILTER_GROUP_LIST:
946
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
947
+                //glue objectclasses
948
+                if(is_array($objcs) && count($objcs) > 0) {
949
+                    $filter .= '(|';
950
+                    foreach($objcs as $objc) {
951
+                        $filter .= '(objectclass=' . $objc . ')';
952
+                    }
953
+                    $filter .= ')';
954
+                    $parts++;
955
+                }
956
+                //glue group memberships
957
+                $cns = $this->configuration->ldapGroupFilterGroups;
958
+                if(is_array($cns) && count($cns) > 0) {
959
+                    $filter .= '(|';
960
+                    foreach($cns as $cn) {
961
+                        $filter .= '(cn=' . $cn . ')';
962
+                    }
963
+                    $filter .= ')';
964
+                }
965
+                $parts++;
966
+                //wrap parts in AND condition
967
+                if($parts > 1) {
968
+                    $filter = '(&' . $filter . ')';
969
+                }
970
+                break;
971
+
972
+            case self::LFILTER_LOGIN:
973
+                $ulf = $this->configuration->ldapUserFilter;
974
+                $loginpart = '=%uid';
975
+                $filterUsername = '';
976
+                $userAttributes = $this->getUserAttributes();
977
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
978
+                $parts = 0;
979
+
980
+                if($this->configuration->ldapLoginFilterUsername === '1') {
981
+                    $attr = '';
982
+                    if(isset($userAttributes['uid'])) {
983
+                        $attr = 'uid';
984
+                    } else if(isset($userAttributes['samaccountname'])) {
985
+                        $attr = 'samaccountname';
986
+                    } else if(isset($userAttributes['cn'])) {
987
+                        //fallback
988
+                        $attr = 'cn';
989
+                    }
990
+                    if ($attr !== '') {
991
+                        $filterUsername = '(' . $attr . $loginpart . ')';
992
+                        $parts++;
993
+                    }
994
+                }
995
+
996
+                $filterEmail = '';
997
+                if($this->configuration->ldapLoginFilterEmail === '1') {
998
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999
+                    $parts++;
1000
+                }
1001
+
1002
+                $filterAttributes = '';
1003
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005
+                    $filterAttributes = '(|';
1006
+                    foreach($attrsToFilter as $attribute) {
1007
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
1008
+                    }
1009
+                    $filterAttributes .= ')';
1010
+                    $parts++;
1011
+                }
1012
+
1013
+                $filterLogin = '';
1014
+                if($parts > 1) {
1015
+                    $filterLogin = '(|';
1016
+                }
1017
+                $filterLogin .= $filterUsername;
1018
+                $filterLogin .= $filterEmail;
1019
+                $filterLogin .= $filterAttributes;
1020
+                if($parts > 1) {
1021
+                    $filterLogin .= ')';
1022
+                }
1023
+
1024
+                $filter = '(&'.$ulf.$filterLogin.')';
1025
+                break;
1026
+        }
1027
+
1028
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG);
1029
+
1030
+        return $filter;
1031
+    }
1032
+
1033
+    /**
1034
+     * Connects and Binds to an LDAP Server
1035
+     *
1036
+     * @param int $port the port to connect with
1037
+     * @param bool $tls whether startTLS is to be used
1038
+     * @return bool
1039
+     * @throws \Exception
1040
+     */
1041
+    private function connectAndBind($port, $tls) {
1042
+        //connect, does not really trigger any server communication
1043
+        $host = $this->configuration->ldapHost;
1044
+        $hostInfo = parse_url($host);
1045
+        if(!$hostInfo) {
1046
+            throw new \Exception(self::$l->t('Invalid Host'));
1047
+        }
1048
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049
+        $cr = $this->ldap->connect($host, $port);
1050
+        if(!is_resource($cr)) {
1051
+            throw new \Exception(self::$l->t('Invalid Host'));
1052
+        }
1053
+
1054
+        //set LDAP options
1055
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1056
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1057
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058
+
1059
+        try {
1060
+            if($tls) {
1061
+                $isTlsWorking = @$this->ldap->startTls($cr);
1062
+                if(!$isTlsWorking) {
1063
+                    return false;
1064
+                }
1065
+            }
1066
+
1067
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG);
1068
+            //interesting part: do the bind!
1069
+            $login = $this->ldap->bind($cr,
1070
+                $this->configuration->ldapAgentName,
1071
+                $this->configuration->ldapAgentPassword
1072
+            );
1073
+            $errNo = $this->ldap->errno($cr);
1074
+            $error = ldap_error($cr);
1075
+            $this->ldap->unbind($cr);
1076
+        } catch(ServerNotAvailableException $e) {
1077
+            return false;
1078
+        }
1079
+
1080
+        if($login === true) {
1081
+            $this->ldap->unbind($cr);
1082
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1083
+            return true;
1084
+        }
1085
+
1086
+        if($errNo === -1) {
1087
+            //host, port or TLS wrong
1088
+            return false;
1089
+        }
1090
+        throw new \Exception($error, $errNo);
1091
+    }
1092
+
1093
+    /**
1094
+     * checks whether a valid combination of agent and password has been
1095
+     * provided (either two values or nothing for anonymous connect)
1096
+     * @return bool, true if everything is fine, false otherwise
1097
+     */
1098
+    private function checkAgentRequirements() {
1099
+        $agent = $this->configuration->ldapAgentName;
1100
+        $pwd = $this->configuration->ldapAgentPassword;
1101
+
1102
+        return
1103
+            ($agent !== '' && $pwd !== '')
1104
+            ||  ($agent === '' && $pwd === '')
1105
+        ;
1106
+    }
1107
+
1108
+    /**
1109
+     * @param array $reqs
1110
+     * @return bool
1111
+     */
1112
+    private function checkRequirements($reqs) {
1113
+        $this->checkAgentRequirements();
1114
+        foreach($reqs as $option) {
1115
+            $value = $this->configuration->$option;
1116
+            if(empty($value)) {
1117
+                return false;
1118
+            }
1119
+        }
1120
+        return true;
1121
+    }
1122
+
1123
+    /**
1124
+     * does a cumulativeSearch on LDAP to get different values of a
1125
+     * specified attribute
1126
+     * @param string[] $filters array, the filters that shall be used in the search
1127
+     * @param string $attr the attribute of which a list of values shall be returned
1128
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1129
+     * The lower, the faster
1130
+     * @param string $maxF string. if not null, this variable will have the filter that
1131
+     * yields most result entries
1132
+     * @return array|false an array with the values on success, false otherwise
1133
+     */
1134
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1135
+        $dnRead = [];
1136
+        $foundItems = [];
1137
+        $maxEntries = 0;
1138
+        if(!is_array($this->configuration->ldapBase)
1139
+           || !isset($this->configuration->ldapBase[0])) {
1140
+            return false;
1141
+        }
1142
+        $base = $this->configuration->ldapBase[0];
1143
+        $cr = $this->getConnection();
1144
+        if(!$this->ldap->isResource($cr)) {
1145
+            return false;
1146
+        }
1147
+        $lastFilter = null;
1148
+        if(isset($filters[count($filters)-1])) {
1149
+            $lastFilter = $filters[count($filters)-1];
1150
+        }
1151
+        foreach($filters as $filter) {
1152
+            if($lastFilter === $filter && count($foundItems) > 0) {
1153
+                //skip when the filter is a wildcard and results were found
1154
+                continue;
1155
+            }
1156
+            // 20k limit for performance and reason
1157
+            $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
1158
+            if(!$this->ldap->isResource($rr)) {
1159
+                continue;
1160
+            }
1161
+            $entries = $this->ldap->countEntries($cr, $rr);
1162
+            $getEntryFunc = 'firstEntry';
1163
+            if(($entries !== false) && ($entries > 0)) {
1164
+                if(!is_null($maxF) && $entries > $maxEntries) {
1165
+                    $maxEntries = $entries;
1166
+                    $maxF = $filter;
1167
+                }
1168
+                $dnReadCount = 0;
1169
+                do {
1170
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1171
+                    $getEntryFunc = 'nextEntry';
1172
+                    if(!$this->ldap->isResource($entry)) {
1173
+                        continue 2;
1174
+                    }
1175
+                    $rr = $entry; //will be expected by nextEntry next round
1176
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1177
+                    $dn = $this->ldap->getDN($cr, $entry);
1178
+                    if($dn === false || in_array($dn, $dnRead)) {
1179
+                        continue;
1180
+                    }
1181
+                    $newItems = [];
1182
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1183
+                                                                $attr,
1184
+                                                                $newItems);
1185
+                    $dnReadCount++;
1186
+                    $foundItems = array_merge($foundItems, $newItems);
1187
+                    $this->resultCache[$dn][$attr] = $newItems;
1188
+                    $dnRead[] = $dn;
1189
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1190
+                        || $this->ldap->isResource($entry))
1191
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192
+            }
1193
+        }
1194
+
1195
+        return array_unique($foundItems);
1196
+    }
1197
+
1198
+    /**
1199
+     * determines if and which $attr are available on the LDAP server
1200
+     * @param string[] $objectclasses the objectclasses to use as search filter
1201
+     * @param string $attr the attribute to look for
1202
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1203
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1204
+     * Configuration class
1205
+     * @param bool $po whether the objectClass with most result entries
1206
+     * shall be pre-selected via the result
1207
+     * @return array|false list of found items.
1208
+     * @throws \Exception
1209
+     */
1210
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211
+        $cr = $this->getConnection();
1212
+        if(!$cr) {
1213
+            throw new \Exception('Could not connect to LDAP');
1214
+        }
1215
+        $p = 'objectclass=';
1216
+        foreach($objectclasses as $key => $value) {
1217
+            $objectclasses[$key] = $p.$value;
1218
+        }
1219
+        $maxEntryObjC = '';
1220
+
1221
+        //how deep to dig?
1222
+        //When looking for objectclasses, testing few entries is sufficient,
1223
+        $dig = 3;
1224
+
1225
+        $availableFeatures =
1226
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227
+                                                $dig, $maxEntryObjC);
1228
+        if(is_array($availableFeatures)
1229
+           && count($availableFeatures) > 0) {
1230
+            natcasesort($availableFeatures);
1231
+            //natcasesort keeps indices, but we must get rid of them for proper
1232
+            //sorting in the web UI. Therefore: array_values
1233
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1234
+        } else {
1235
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1236
+        }
1237
+
1238
+        $setFeatures = $this->configuration->$confkey;
1239
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1240
+            //something is already configured? pre-select it.
1241
+            $this->result->addChange($dbkey, $setFeatures);
1242
+        } else if ($po && $maxEntryObjC !== '') {
1243
+            //pre-select objectclass with most result entries
1244
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1245
+            $this->applyFind($dbkey, $maxEntryObjC);
1246
+            $this->result->addChange($dbkey, $maxEntryObjC);
1247
+        }
1248
+
1249
+        return $availableFeatures;
1250
+    }
1251
+
1252
+    /**
1253
+     * appends a list of values fr
1254
+     * @param resource $result the return value from ldap_get_attributes
1255
+     * @param string $attribute the attribute values to look for
1256
+     * @param array &$known new values will be appended here
1257
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1258
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259
+     */
1260
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
+        if(!is_array($result)
1262
+           || !isset($result['count'])
1263
+           || !$result['count'] > 0) {
1264
+            return self::LRESULT_PROCESSED_INVALID;
1265
+        }
1266
+
1267
+        // strtolower on all keys for proper comparison
1268
+        $result = \OCP\Util::mb_array_change_key_case($result);
1269
+        $attribute = strtolower($attribute);
1270
+        if(isset($result[$attribute])) {
1271
+            foreach($result[$attribute] as $key => $val) {
1272
+                if($key === 'count') {
1273
+                    continue;
1274
+                }
1275
+                if(!in_array($val, $known)) {
1276
+                    $known[] = $val;
1277
+                }
1278
+            }
1279
+            return self::LRESULT_PROCESSED_OK;
1280
+        } else {
1281
+            return self::LRESULT_PROCESSED_SKIP;
1282
+        }
1283
+    }
1284
+
1285
+    /**
1286
+     * @return bool|mixed
1287
+     */
1288
+    private function getConnection() {
1289
+        if(!is_null($this->cr)) {
1290
+            return $this->cr;
1291
+        }
1292
+
1293
+        $cr = $this->ldap->connect(
1294
+            $this->configuration->ldapHost,
1295
+            $this->configuration->ldapPort
1296
+        );
1297
+
1298
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
+        if($this->configuration->ldapTLS === 1) {
1302
+            $this->ldap->startTls($cr);
1303
+        }
1304
+
1305
+        $lo = @$this->ldap->bind($cr,
1306
+                                    $this->configuration->ldapAgentName,
1307
+                                    $this->configuration->ldapAgentPassword);
1308
+        if($lo === true) {
1309
+            $this->$cr = $cr;
1310
+            return $cr;
1311
+        }
1312
+
1313
+        return false;
1314
+    }
1315
+
1316
+    /**
1317
+     * @return array
1318
+     */
1319
+    private function getDefaultLdapPortSettings() {
1320
+        static $settings = [
1321
+            ['port' => 7636, 'tls' => false],
1322
+            ['port' =>  636, 'tls' => false],
1323
+            ['port' => 7389, 'tls' => true],
1324
+            ['port' =>  389, 'tls' => true],
1325
+            ['port' => 7389, 'tls' => false],
1326
+            ['port' =>  389, 'tls' => false],
1327
+        ];
1328
+        return $settings;
1329
+    }
1330
+
1331
+    /**
1332
+     * @return array
1333
+     */
1334
+    private function getPortSettingsToTry() {
1335
+        //389 ← LDAP / Unencrypted or StartTLS
1336
+        //636 ← LDAPS / SSL
1337
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1338
+        $host = $this->configuration->ldapHost;
1339
+        $port = (int)$this->configuration->ldapPort;
1340
+        $portSettings = [];
1341
+
1342
+        //In case the port is already provided, we will check this first
1343
+        if($port > 0) {
1344
+            $hostInfo = parse_url($host);
1345
+            if(!(is_array($hostInfo)
1346
+                && isset($hostInfo['scheme'])
1347
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348
+                $portSettings[] = ['port' => $port, 'tls' => true];
1349
+            }
1350
+            $portSettings[] =['port' => $port, 'tls' => false];
1351
+        }
1352
+
1353
+        //default ports
1354
+        $portSettings = array_merge($portSettings,
1355
+                                    $this->getDefaultLdapPortSettings());
1356
+
1357
+        return $portSettings;
1358
+    }
1359 1359
 
1360 1360
 
1361 1361
 }
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73 73
 		parent::__construct($ldap);
74 74
 		$this->configuration = $configuration;
75
-		if(is_null(Wizard::$l)) {
75
+		if (is_null(Wizard::$l)) {
76 76
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
77 77
 		}
78 78
 		$this->access = $access;
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 	}
81 81
 
82 82
 	public function  __destruct() {
83
-		if($this->result->hasChanges()) {
83
+		if ($this->result->hasChanges()) {
84 84
 			$this->configuration->saveConfiguration();
85 85
 		}
86 86
 	}
@@ -95,18 +95,18 @@  discard block
 block discarded – undo
95 95
 	 */
96 96
 	public function countEntries(string $filter, string $type): int {
97 97
 		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
-		if($type === 'users') {
98
+		if ($type === 'users') {
99 99
 			$reqs[] = 'ldapUserFilter';
100 100
 		}
101
-		if(!$this->checkRequirements($reqs)) {
101
+		if (!$this->checkRequirements($reqs)) {
102 102
 			throw new \Exception('Requirements not met', 400);
103 103
 		}
104 104
 
105 105
 		$attr = ['dn']; // default
106 106
 		$limit = 1001;
107
-		if($type === 'groups') {
108
-			$result =  $this->access->countGroups($filter, $attr, $limit);
109
-		} else if($type === 'users') {
107
+		if ($type === 'groups') {
108
+			$result = $this->access->countGroups($filter, $attr, $limit);
109
+		} else if ($type === 'users') {
110 110
 			$result = $this->access->countUsers($filter, $attr, $limit);
111 111
 		} else if ($type === 'objects') {
112 112
 			$result = $this->access->countObjects($limit);
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			throw new \Exception('Internal error: Invalid object type', 500);
115 115
 		}
116 116
 
117
-		return (int)$result;
117
+		return (int) $result;
118 118
 	}
119 119
 
120 120
 	/**
@@ -125,16 +125,16 @@  discard block
 block discarded – undo
125 125
 	 * @return string
126 126
 	 */
127 127
 	private function formatCountResult(int $count): string {
128
-		if($count > 1000) {
128
+		if ($count > 1000) {
129 129
 			return '> 1000';
130 130
 		}
131
-		return (string)$count;
131
+		return (string) $count;
132 132
 	}
133 133
 
134 134
 	public function countGroups() {
135 135
 		$filter = $this->configuration->ldapGroupFilter;
136 136
 
137
-		if(empty($filter)) {
137
+		if (empty($filter)) {
138 138
 			$output = self::$l->n('%s group found', '%s groups found', 0, [0]);
139 139
 			$this->result->addChange('ldap_group_count', $output);
140 140
 			return $this->result;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			$groupsTotal = $this->countEntries($filter, 'groups');
145 145
 		} catch (\Exception $e) {
146 146
 			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
147
+			if ($e->getCode() === 500) {
148 148
 				throw $e;
149 149
 			}
150 150
 			return false;
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 	public function countInBaseDN() {
187 187
 		// we don't need to provide a filter in this case
188 188
 		$total = $this->countEntries('', 'objects');
189
-		if($total === false) {
189
+		if ($total === false) {
190 190
 			throw new \Exception('invalid results received');
191 191
 		}
192 192
 		$this->result->addChange('ldap_test_base', $total);
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * @return int|bool
201 201
 	 */
202 202
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
203
-		if(!$this->checkRequirements(['ldapHost',
203
+		if (!$this->checkRequirements(['ldapHost',
204 204
 			'ldapPort',
205 205
 			'ldapBase',
206 206
 			'ldapUserFilter',
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 
211 211
 		$filter = $this->access->combineFilterWithAnd([
212 212
 			$this->configuration->ldapUserFilter,
213
-			$attr . '=*'
213
+			$attr.'=*'
214 214
 		]);
215 215
 
216 216
 		$limit = ($existsCheck === false) ? null : 1;
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	 * @throws \Exception
226 226
 	 */
227 227
 	public function detectUserDisplayNameAttribute() {
228
-		if(!$this->checkRequirements(['ldapHost',
228
+		if (!$this->checkRequirements(['ldapHost',
229 229
 			'ldapPort',
230 230
 			'ldapBase',
231 231
 			'ldapUserFilter',
@@ -237,8 +237,8 @@  discard block
 block discarded – undo
237 237
 		if ($attr !== '' && $attr !== 'displayName') {
238 238
 			// most likely not the default value with upper case N,
239 239
 			// verify it still produces a result
240
-			$count = (int)$this->countUsersWithAttribute($attr, true);
241
-			if($count > 0) {
240
+			$count = (int) $this->countUsersWithAttribute($attr, true);
241
+			if ($count > 0) {
242 242
 				//no change, but we sent it back to make sure the user interface
243 243
 				//is still correct, even if the ajax call was cancelled meanwhile
244 244
 				$this->result->addChange('ldap_display_name', $attr);
@@ -249,9 +249,9 @@  discard block
 block discarded – undo
249 249
 		// first attribute that has at least one result wins
250 250
 		$displayNameAttrs = ['displayname', 'cn'];
251 251
 		foreach ($displayNameAttrs as $attr) {
252
-			$count = (int)$this->countUsersWithAttribute($attr, true);
252
+			$count = (int) $this->countUsersWithAttribute($attr, true);
253 253
 
254
-			if($count > 0) {
254
+			if ($count > 0) {
255 255
 				$this->applyFind('ldap_display_name', $attr);
256 256
 				return $this->result;
257 257
 			}
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 	 * @return WizardResult|bool
268 268
 	 */
269 269
 	public function detectEmailAttribute() {
270
-		if(!$this->checkRequirements(['ldapHost',
270
+		if (!$this->checkRequirements(['ldapHost',
271 271
 			'ldapPort',
272 272
 			'ldapBase',
273 273
 			'ldapUserFilter',
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 
278 278
 		$attr = $this->configuration->ldapEmailAttribute;
279 279
 		if ($attr !== '') {
280
-			$count = (int)$this->countUsersWithAttribute($attr, true);
281
-			if($count > 0) {
280
+			$count = (int) $this->countUsersWithAttribute($attr, true);
281
+			if ($count > 0) {
282 282
 				return false;
283 283
 			}
284 284
 			$writeLog = true;
@@ -289,19 +289,19 @@  discard block
 block discarded – undo
289 289
 		$emailAttributes = ['mail', 'mailPrimaryAddress'];
290 290
 		$winner = '';
291 291
 		$maxUsers = 0;
292
-		foreach($emailAttributes as $attr) {
292
+		foreach ($emailAttributes as $attr) {
293 293
 			$count = $this->countUsersWithAttribute($attr);
294
-			if($count > $maxUsers) {
294
+			if ($count > $maxUsers) {
295 295
 				$maxUsers = $count;
296 296
 				$winner = $attr;
297 297
 			}
298 298
 		}
299 299
 
300
-		if($winner !== '') {
300
+		if ($winner !== '') {
301 301
 			$this->applyFind('ldap_email_attr', $winner);
302
-			if($writeLog) {
303
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
-					'automatically been reset, because the original value ' .
302
+			if ($writeLog) {
303
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
304
+					'automatically been reset, because the original value '.
305 305
 					'did not return any results.', ILogger::INFO);
306 306
 			}
307 307
 		}
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 	 * @throws \Exception
315 315
 	 */
316 316
 	public function determineAttributes() {
317
-		if(!$this->checkRequirements(['ldapHost',
317
+		if (!$this->checkRequirements(['ldapHost',
318 318
 			'ldapPort',
319 319
 			'ldapBase',
320 320
 			'ldapUserFilter',
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331 331
 
332 332
 		$selected = $this->configuration->ldapLoginFilterAttributes;
333
-		if(is_array($selected) && !empty($selected)) {
333
+		if (is_array($selected) && !empty($selected)) {
334 334
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
335 335
 		}
336 336
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 	 * @throws \Exception
344 344
 	 */
345 345
 	private function getUserAttributes() {
346
-		if(!$this->checkRequirements(['ldapHost',
346
+		if (!$this->checkRequirements(['ldapHost',
347 347
 			'ldapPort',
348 348
 			'ldapBase',
349 349
 			'ldapUserFilter',
@@ -351,20 +351,20 @@  discard block
 block discarded – undo
351 351
 			return  false;
352 352
 		}
353 353
 		$cr = $this->getConnection();
354
-		if(!$cr) {
354
+		if (!$cr) {
355 355
 			throw new \Exception('Could not connect to LDAP');
356 356
 		}
357 357
 
358 358
 		$base = $this->configuration->ldapBase[0];
359 359
 		$filter = $this->configuration->ldapUserFilter;
360 360
 		$rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
361
-		if(!$this->ldap->isResource($rr)) {
361
+		if (!$this->ldap->isResource($rr)) {
362 362
 			return false;
363 363
 		}
364 364
 		$er = $this->ldap->firstEntry($cr, $rr);
365 365
 		$attributes = $this->ldap->getAttributes($cr, $er);
366 366
 		$pureAttributes = [];
367
-		for($i = 0; $i < $attributes['count']; $i++) {
367
+		for ($i = 0; $i < $attributes['count']; $i++) {
368 368
 			$pureAttributes[] = $attributes[$i];
369 369
 		}
370 370
 
@@ -399,23 +399,23 @@  discard block
 block discarded – undo
399 399
 	 * @throws \Exception
400 400
 	 */
401 401
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
-		if(!$this->checkRequirements(['ldapHost',
402
+		if (!$this->checkRequirements(['ldapHost',
403 403
 			'ldapPort',
404 404
 			'ldapBase',
405 405
 		])) {
406 406
 			return  false;
407 407
 		}
408 408
 		$cr = $this->getConnection();
409
-		if(!$cr) {
409
+		if (!$cr) {
410 410
 			throw new \Exception('Could not connect to LDAP');
411 411
 		}
412 412
 
413 413
 		$this->fetchGroups($dbKey, $confKey);
414 414
 
415
-		if($testMemberOf) {
415
+		if ($testMemberOf) {
416 416
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417 417
 			$this->result->markChange();
418
-			if(!$this->configuration->hasMemberOfFilterSupport) {
418
+			if (!$this->configuration->hasMemberOfFilterSupport) {
419 419
 				throw new \Exception('memberOf is not supported by the server');
420 420
 			}
421 421
 		}
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 		$obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
436 436
 
437 437
 		$filterParts = [];
438
-		foreach($obclasses as $obclass) {
438
+		foreach ($obclasses as $obclass) {
439 439
 			$filterParts[] = 'objectclass='.$obclass;
440 440
 		}
441 441
 		//we filter for everything
@@ -452,8 +452,8 @@  discard block
 block discarded – undo
452 452
 			// we need to request dn additionally here, otherwise memberOf
453 453
 			// detection will fail later
454 454
 			$result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
455
-			foreach($result as $item) {
456
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
455
+			foreach ($result as $item) {
456
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457 457
 					// just in case - no issue known
458 458
 					continue;
459 459
 				}
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 			$offset += $limit;
464 464
 		} while ($this->access->hasMoreResults());
465 465
 
466
-		if(count($groupNames) > 0) {
466
+		if (count($groupNames) > 0) {
467 467
 			natsort($groupNames);
468 468
 			$this->result->addOptions($dbKey, array_values($groupNames));
469 469
 		} else {
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 		}
472 472
 
473 473
 		$setFeatures = $this->configuration->$confKey;
474
-		if(is_array($setFeatures) && !empty($setFeatures)) {
474
+		if (is_array($setFeatures) && !empty($setFeatures)) {
475 475
 			//something is already configured? pre-select it.
476 476
 			$this->result->addChange($dbKey, $setFeatures);
477 477
 		}
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
 	}
480 480
 
481 481
 	public function determineGroupMemberAssoc() {
482
-		if(!$this->checkRequirements(['ldapHost',
482
+		if (!$this->checkRequirements(['ldapHost',
483 483
 			'ldapPort',
484 484
 			'ldapGroupFilter',
485 485
 		])) {
486 486
 			return  false;
487 487
 		}
488 488
 		$attribute = $this->detectGroupMemberAssoc();
489
-		if($attribute === false) {
489
+		if ($attribute === false) {
490 490
 			return false;
491 491
 		}
492 492
 		$this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
@@ -501,14 +501,14 @@  discard block
 block discarded – undo
501 501
 	 * @throws \Exception
502 502
 	 */
503 503
 	public function determineGroupObjectClasses() {
504
-		if(!$this->checkRequirements(['ldapHost',
504
+		if (!$this->checkRequirements(['ldapHost',
505 505
 			'ldapPort',
506 506
 			'ldapBase',
507 507
 		])) {
508 508
 			return  false;
509 509
 		}
510 510
 		$cr = $this->getConnection();
511
-		if(!$cr) {
511
+		if (!$cr) {
512 512
 			throw new \Exception('Could not connect to LDAP');
513 513
 		}
514 514
 
@@ -528,14 +528,14 @@  discard block
 block discarded – undo
528 528
 	 * @throws \Exception
529 529
 	 */
530 530
 	public function determineUserObjectClasses() {
531
-		if(!$this->checkRequirements(['ldapHost',
531
+		if (!$this->checkRequirements(['ldapHost',
532 532
 			'ldapPort',
533 533
 			'ldapBase',
534 534
 		])) {
535 535
 			return  false;
536 536
 		}
537 537
 		$cr = $this->getConnection();
538
-		if(!$cr) {
538
+		if (!$cr) {
539 539
 			throw new \Exception('Could not connect to LDAP');
540 540
 		}
541 541
 
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 	 * @throws \Exception
559 559
 	 */
560 560
 	public function getGroupFilter() {
561
-		if(!$this->checkRequirements(['ldapHost',
561
+		if (!$this->checkRequirements(['ldapHost',
562 562
 			'ldapPort',
563 563
 			'ldapBase',
564 564
 		])) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 	 * @throws \Exception
583 583
 	 */
584 584
 	public function getUserListFilter() {
585
-		if(!$this->checkRequirements(['ldapHost',
585
+		if (!$this->checkRequirements(['ldapHost',
586 586
 			'ldapPort',
587 587
 			'ldapBase',
588 588
 		])) {
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
596 596
 		}
597 597
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
-		if(!$filter) {
598
+		if (!$filter) {
599 599
 			throw new \Exception('Cannot create filter');
600 600
 		}
601 601
 
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 	 * @throws \Exception
609 609
 	 */
610 610
 	public function getUserLoginFilter() {
611
-		if(!$this->checkRequirements(['ldapHost',
611
+		if (!$this->checkRequirements(['ldapHost',
612 612
 			'ldapPort',
613 613
 			'ldapBase',
614 614
 			'ldapUserFilter',
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 
619 619
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
-		if(!$filter) {
620
+		if (!$filter) {
621 621
 			throw new \Exception('Cannot create filter');
622 622
 		}
623 623
 
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 	 * @throws \Exception
632 632
 	 */
633 633
 	public function testLoginName($loginName) {
634
-		if(!$this->checkRequirements(['ldapHost',
634
+		if (!$this->checkRequirements(['ldapHost',
635 635
 			'ldapPort',
636 636
 			'ldapBase',
637 637
 			'ldapLoginFilter',
@@ -640,17 +640,17 @@  discard block
 block discarded – undo
640 640
 		}
641 641
 
642 642
 		$cr = $this->access->connection->getConnectionResource();
643
-		if(!$this->ldap->isResource($cr)) {
643
+		if (!$this->ldap->isResource($cr)) {
644 644
 			throw new \Exception('connection error');
645 645
 		}
646 646
 
647
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648 648
 			=== false) {
649 649
 			throw new \Exception('missing placeholder');
650 650
 		}
651 651
 
652 652
 		$users = $this->access->countUsersByLoginName($loginName);
653
-		if($this->ldap->errno($cr) !== 0) {
653
+		if ($this->ldap->errno($cr) !== 0) {
654 654
 			throw new \Exception($this->ldap->error($cr));
655 655
 		}
656 656
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -665,22 +665,22 @@  discard block
 block discarded – undo
665 665
 	 * @throws \Exception
666 666
 	 */
667 667
 	public function guessPortAndTLS() {
668
-		if(!$this->checkRequirements(['ldapHost',
668
+		if (!$this->checkRequirements(['ldapHost',
669 669
 		])) {
670 670
 			return false;
671 671
 		}
672 672
 		$this->checkHost();
673 673
 		$portSettings = $this->getPortSettingsToTry();
674 674
 
675
-		if(!is_array($portSettings)) {
675
+		if (!is_array($portSettings)) {
676 676
 			throw new \Exception(print_r($portSettings, true));
677 677
 		}
678 678
 
679 679
 		//proceed from the best configuration and return on first success
680
-		foreach($portSettings as $setting) {
680
+		foreach ($portSettings as $setting) {
681 681
 			$p = $setting['port'];
682 682
 			$t = $setting['tls'];
683
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
683
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, ILogger::DEBUG);
684 684
 			//connectAndBind may throw Exception, it needs to be catched by the
685 685
 			//callee of this method
686 686
 
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 				// any reply other than -1 (= cannot connect) is already okay,
691 691
 				// because then we found the server
692 692
 				// unavailable startTLS returns -11
693
-				if($e->getCode() > 0) {
693
+				if ($e->getCode() > 0) {
694 694
 					$settingsFound = true;
695 695
 				} else {
696 696
 					throw $e;
@@ -700,10 +700,10 @@  discard block
 block discarded – undo
700 700
 			if ($settingsFound === true) {
701 701
 				$config = [
702 702
 					'ldapPort' => $p,
703
-					'ldapTLS' => (int)$t
703
+					'ldapTLS' => (int) $t
704 704
 				];
705 705
 				$this->configuration->setConfiguration($config);
706
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
706
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, ILogger::DEBUG);
707 707
 				$this->result->addChange('ldap_port', $p);
708 708
 				return $this->result;
709 709
 			}
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 	 * @return WizardResult|false WizardResult on success, false otherwise
719 719
 	 */
720 720
 	public function guessBaseDN() {
721
-		if(!$this->checkRequirements(['ldapHost',
721
+		if (!$this->checkRequirements(['ldapHost',
722 722
 			'ldapPort',
723 723
 		])) {
724 724
 			return false;
@@ -727,9 +727,9 @@  discard block
 block discarded – undo
727 727
 		//check whether a DN is given in the agent name (99.9% of all cases)
728 728
 		$base = null;
729 729
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
730
-		if($i !== false) {
730
+		if ($i !== false) {
731 731
 			$base = substr($this->configuration->ldapAgentName, $i);
732
-			if($this->testBaseDN($base)) {
732
+			if ($this->testBaseDN($base)) {
733 733
 				$this->applyFind('ldap_base', $base);
734 734
 				return $this->result;
735 735
 			}
@@ -740,13 +740,13 @@  discard block
 block discarded – undo
740 740
 		//a base DN
741 741
 		$helper = new Helper(\OC::$server->getConfig());
742 742
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
-		if(!$domain) {
743
+		if (!$domain) {
744 744
 			return false;
745 745
 		}
746 746
 
747 747
 		$dparts = explode('.', $domain);
748
-		while(count($dparts) > 0) {
749
-			$base2 = 'dc=' . implode(',dc=', $dparts);
748
+		while (count($dparts) > 0) {
749
+			$base2 = 'dc='.implode(',dc=', $dparts);
750 750
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
751 751
 				$this->applyFind('ldap_base', $base2);
752 752
 				return $this->result;
@@ -779,7 +779,7 @@  discard block
 block discarded – undo
779 779
 		$hostInfo = parse_url($host);
780 780
 
781 781
 		//removes Port from Host
782
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
783 783
 			$port = $hostInfo['port'];
784 784
 			$host = str_replace(':'.$port, '', $host);
785 785
 			$this->applyFind('ldap_host', $host);
@@ -796,30 +796,30 @@  discard block
 block discarded – undo
796 796
 	private function detectGroupMemberAssoc() {
797 797
 		$possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber'];
798 798
 		$filter = $this->configuration->ldapGroupFilter;
799
-		if(empty($filter)) {
799
+		if (empty($filter)) {
800 800
 			return false;
801 801
 		}
802 802
 		$cr = $this->getConnection();
803
-		if(!$cr) {
803
+		if (!$cr) {
804 804
 			throw new \Exception('Could not connect to LDAP');
805 805
 		}
806 806
 		$base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
807 807
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
-		if(!$this->ldap->isResource($rr)) {
808
+		if (!$this->ldap->isResource($rr)) {
809 809
 			return false;
810 810
 		}
811 811
 		$er = $this->ldap->firstEntry($cr, $rr);
812
-		while(is_resource($er)) {
812
+		while (is_resource($er)) {
813 813
 			$this->ldap->getDN($cr, $er);
814 814
 			$attrs = $this->ldap->getAttributes($cr, $er);
815 815
 			$result = [];
816 816
 			$possibleAttrsCount = count($possibleAttrs);
817
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
818
-				if(isset($attrs[$possibleAttrs[$i]])) {
817
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
818
+				if (isset($attrs[$possibleAttrs[$i]])) {
819 819
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820 820
 				}
821 821
 			}
822
-			if(!empty($result)) {
822
+			if (!empty($result)) {
823 823
 				natsort($result);
824 824
 				return key($result);
825 825
 			}
@@ -838,14 +838,14 @@  discard block
 block discarded – undo
838 838
 	 */
839 839
 	private function testBaseDN($base) {
840 840
 		$cr = $this->getConnection();
841
-		if(!$cr) {
841
+		if (!$cr) {
842 842
 			throw new \Exception('Could not connect to LDAP');
843 843
 		}
844 844
 
845 845
 		//base is there, let's validate it. If we search for anything, we should
846 846
 		//get a result set > 0 on a proper base
847 847
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
848
-		if(!$this->ldap->isResource($rr)) {
848
+		if (!$this->ldap->isResource($rr)) {
849 849
 			$errorNo  = $this->ldap->errno($cr);
850 850
 			$errorMsg = $this->ldap->error($cr);
851 851
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -867,11 +867,11 @@  discard block
 block discarded – undo
867 867
 	 */
868 868
 	private function testMemberOf() {
869 869
 		$cr = $this->getConnection();
870
-		if(!$cr) {
870
+		if (!$cr) {
871 871
 			throw new \Exception('Could not connect to LDAP');
872 872
 		}
873 873
 		$result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
874
-		if(is_int($result) &&  $result > 0) {
874
+		if (is_int($result) && $result > 0) {
875 875
 			return true;
876 876
 		}
877 877
 		return false;
@@ -892,27 +892,27 @@  discard block
 block discarded – undo
892 892
 			case self::LFILTER_USER_LIST:
893 893
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
894 894
 				//glue objectclasses
895
-				if(is_array($objcs) && count($objcs) > 0) {
895
+				if (is_array($objcs) && count($objcs) > 0) {
896 896
 					$filter .= '(|';
897
-					foreach($objcs as $objc) {
898
-						$filter .= '(objectclass=' . $objc . ')';
897
+					foreach ($objcs as $objc) {
898
+						$filter .= '(objectclass='.$objc.')';
899 899
 					}
900 900
 					$filter .= ')';
901 901
 					$parts++;
902 902
 				}
903 903
 				//glue group memberships
904
-				if($this->configuration->hasMemberOfFilterSupport) {
904
+				if ($this->configuration->hasMemberOfFilterSupport) {
905 905
 					$cns = $this->configuration->ldapUserFilterGroups;
906
-					if(is_array($cns) && count($cns) > 0) {
906
+					if (is_array($cns) && count($cns) > 0) {
907 907
 						$filter .= '(|';
908 908
 						$cr = $this->getConnection();
909
-						if(!$cr) {
909
+						if (!$cr) {
910 910
 							throw new \Exception('Could not connect to LDAP');
911 911
 						}
912 912
 						$base = $this->configuration->ldapBase[0];
913
-						foreach($cns as $cn) {
914
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']);
915
-							if(!$this->ldap->isResource($rr)) {
913
+						foreach ($cns as $cn) {
914
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, ['dn', 'primaryGroupToken']);
915
+							if (!$this->ldap->isResource($rr)) {
916 916
 								continue;
917 917
 							}
918 918
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -921,11 +921,11 @@  discard block
 block discarded – undo
921 921
 							if ($dn === false || $dn === '') {
922 922
 								continue;
923 923
 							}
924
-							$filterPart = '(memberof=' . $dn . ')';
925
-							if(isset($attrs['primaryGroupToken'])) {
924
+							$filterPart = '(memberof='.$dn.')';
925
+							if (isset($attrs['primaryGroupToken'])) {
926 926
 								$pgt = $attrs['primaryGroupToken'][0];
927
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
927
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
928
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
929 929
 							}
930 930
 							$filter .= $filterPart;
931 931
 						}
@@ -934,8 +934,8 @@  discard block
 block discarded – undo
934 934
 					$parts++;
935 935
 				}
936 936
 				//wrap parts in AND condition
937
-				if($parts > 1) {
938
-					$filter = '(&' . $filter . ')';
937
+				if ($parts > 1) {
938
+					$filter = '(&'.$filter.')';
939 939
 				}
940 940
 				if ($filter === '') {
941 941
 					$filter = '(objectclass=*)';
@@ -945,27 +945,27 @@  discard block
 block discarded – undo
945 945
 			case self::LFILTER_GROUP_LIST:
946 946
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
947 947
 				//glue objectclasses
948
-				if(is_array($objcs) && count($objcs) > 0) {
948
+				if (is_array($objcs) && count($objcs) > 0) {
949 949
 					$filter .= '(|';
950
-					foreach($objcs as $objc) {
951
-						$filter .= '(objectclass=' . $objc . ')';
950
+					foreach ($objcs as $objc) {
951
+						$filter .= '(objectclass='.$objc.')';
952 952
 					}
953 953
 					$filter .= ')';
954 954
 					$parts++;
955 955
 				}
956 956
 				//glue group memberships
957 957
 				$cns = $this->configuration->ldapGroupFilterGroups;
958
-				if(is_array($cns) && count($cns) > 0) {
958
+				if (is_array($cns) && count($cns) > 0) {
959 959
 					$filter .= '(|';
960
-					foreach($cns as $cn) {
961
-						$filter .= '(cn=' . $cn . ')';
960
+					foreach ($cns as $cn) {
961
+						$filter .= '(cn='.$cn.')';
962 962
 					}
963 963
 					$filter .= ')';
964 964
 				}
965 965
 				$parts++;
966 966
 				//wrap parts in AND condition
967
-				if($parts > 1) {
968
-					$filter = '(&' . $filter . ')';
967
+				if ($parts > 1) {
968
+					$filter = '(&'.$filter.')';
969 969
 				}
970 970
 				break;
971 971
 
@@ -977,47 +977,47 @@  discard block
 block discarded – undo
977 977
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
978 978
 				$parts = 0;
979 979
 
980
-				if($this->configuration->ldapLoginFilterUsername === '1') {
980
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
981 981
 					$attr = '';
982
-					if(isset($userAttributes['uid'])) {
982
+					if (isset($userAttributes['uid'])) {
983 983
 						$attr = 'uid';
984
-					} else if(isset($userAttributes['samaccountname'])) {
984
+					} else if (isset($userAttributes['samaccountname'])) {
985 985
 						$attr = 'samaccountname';
986
-					} else if(isset($userAttributes['cn'])) {
986
+					} else if (isset($userAttributes['cn'])) {
987 987
 						//fallback
988 988
 						$attr = 'cn';
989 989
 					}
990 990
 					if ($attr !== '') {
991
-						$filterUsername = '(' . $attr . $loginpart . ')';
991
+						$filterUsername = '('.$attr.$loginpart.')';
992 992
 						$parts++;
993 993
 					}
994 994
 				}
995 995
 
996 996
 				$filterEmail = '';
997
-				if($this->configuration->ldapLoginFilterEmail === '1') {
997
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
998 998
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999 999
 					$parts++;
1000 1000
 				}
1001 1001
 
1002 1002
 				$filterAttributes = '';
1003 1003
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005 1005
 					$filterAttributes = '(|';
1006
-					foreach($attrsToFilter as $attribute) {
1007
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1006
+					foreach ($attrsToFilter as $attribute) {
1007
+						$filterAttributes .= '('.$attribute.$loginpart.')';
1008 1008
 					}
1009 1009
 					$filterAttributes .= ')';
1010 1010
 					$parts++;
1011 1011
 				}
1012 1012
 
1013 1013
 				$filterLogin = '';
1014
-				if($parts > 1) {
1014
+				if ($parts > 1) {
1015 1015
 					$filterLogin = '(|';
1016 1016
 				}
1017 1017
 				$filterLogin .= $filterUsername;
1018 1018
 				$filterLogin .= $filterEmail;
1019 1019
 				$filterLogin .= $filterAttributes;
1020
-				if($parts > 1) {
1020
+				if ($parts > 1) {
1021 1021
 					$filterLogin .= ')';
1022 1022
 				}
1023 1023
 
@@ -1042,12 +1042,12 @@  discard block
 block discarded – undo
1042 1042
 		//connect, does not really trigger any server communication
1043 1043
 		$host = $this->configuration->ldapHost;
1044 1044
 		$hostInfo = parse_url($host);
1045
-		if(!$hostInfo) {
1045
+		if (!$hostInfo) {
1046 1046
 			throw new \Exception(self::$l->t('Invalid Host'));
1047 1047
 		}
1048 1048
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049 1049
 		$cr = $this->ldap->connect($host, $port);
1050
-		if(!is_resource($cr)) {
1050
+		if (!is_resource($cr)) {
1051 1051
 			throw new \Exception(self::$l->t('Invalid Host'));
1052 1052
 		}
1053 1053
 
@@ -1057,9 +1057,9 @@  discard block
 block discarded – undo
1057 1057
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058 1058
 
1059 1059
 		try {
1060
-			if($tls) {
1060
+			if ($tls) {
1061 1061
 				$isTlsWorking = @$this->ldap->startTls($cr);
1062
-				if(!$isTlsWorking) {
1062
+				if (!$isTlsWorking) {
1063 1063
 					return false;
1064 1064
 				}
1065 1065
 			}
@@ -1073,17 +1073,17 @@  discard block
 block discarded – undo
1073 1073
 			$errNo = $this->ldap->errno($cr);
1074 1074
 			$error = ldap_error($cr);
1075 1075
 			$this->ldap->unbind($cr);
1076
-		} catch(ServerNotAvailableException $e) {
1076
+		} catch (ServerNotAvailableException $e) {
1077 1077
 			return false;
1078 1078
 		}
1079 1079
 
1080
-		if($login === true) {
1080
+		if ($login === true) {
1081 1081
 			$this->ldap->unbind($cr);
1082
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1082
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.(int) $tls, ILogger::DEBUG);
1083 1083
 			return true;
1084 1084
 		}
1085 1085
 
1086
-		if($errNo === -1) {
1086
+		if ($errNo === -1) {
1087 1087
 			//host, port or TLS wrong
1088 1088
 			return false;
1089 1089
 		}
@@ -1111,9 +1111,9 @@  discard block
 block discarded – undo
1111 1111
 	 */
1112 1112
 	private function checkRequirements($reqs) {
1113 1113
 		$this->checkAgentRequirements();
1114
-		foreach($reqs as $option) {
1114
+		foreach ($reqs as $option) {
1115 1115
 			$value = $this->configuration->$option;
1116
-			if(empty($value)) {
1116
+			if (empty($value)) {
1117 1117
 				return false;
1118 1118
 			}
1119 1119
 		}
@@ -1135,33 +1135,33 @@  discard block
 block discarded – undo
1135 1135
 		$dnRead = [];
1136 1136
 		$foundItems = [];
1137 1137
 		$maxEntries = 0;
1138
-		if(!is_array($this->configuration->ldapBase)
1138
+		if (!is_array($this->configuration->ldapBase)
1139 1139
 		   || !isset($this->configuration->ldapBase[0])) {
1140 1140
 			return false;
1141 1141
 		}
1142 1142
 		$base = $this->configuration->ldapBase[0];
1143 1143
 		$cr = $this->getConnection();
1144
-		if(!$this->ldap->isResource($cr)) {
1144
+		if (!$this->ldap->isResource($cr)) {
1145 1145
 			return false;
1146 1146
 		}
1147 1147
 		$lastFilter = null;
1148
-		if(isset($filters[count($filters)-1])) {
1149
-			$lastFilter = $filters[count($filters)-1];
1148
+		if (isset($filters[count($filters) - 1])) {
1149
+			$lastFilter = $filters[count($filters) - 1];
1150 1150
 		}
1151
-		foreach($filters as $filter) {
1152
-			if($lastFilter === $filter && count($foundItems) > 0) {
1151
+		foreach ($filters as $filter) {
1152
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1153 1153
 				//skip when the filter is a wildcard and results were found
1154 1154
 				continue;
1155 1155
 			}
1156 1156
 			// 20k limit for performance and reason
1157 1157
 			$rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
1158
-			if(!$this->ldap->isResource($rr)) {
1158
+			if (!$this->ldap->isResource($rr)) {
1159 1159
 				continue;
1160 1160
 			}
1161 1161
 			$entries = $this->ldap->countEntries($cr, $rr);
1162 1162
 			$getEntryFunc = 'firstEntry';
1163
-			if(($entries !== false) && ($entries > 0)) {
1164
-				if(!is_null($maxF) && $entries > $maxEntries) {
1163
+			if (($entries !== false) && ($entries > 0)) {
1164
+				if (!is_null($maxF) && $entries > $maxEntries) {
1165 1165
 					$maxEntries = $entries;
1166 1166
 					$maxF = $filter;
1167 1167
 				}
@@ -1169,13 +1169,13 @@  discard block
 block discarded – undo
1169 1169
 				do {
1170 1170
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1171 1171
 					$getEntryFunc = 'nextEntry';
1172
-					if(!$this->ldap->isResource($entry)) {
1172
+					if (!$this->ldap->isResource($entry)) {
1173 1173
 						continue 2;
1174 1174
 					}
1175 1175
 					$rr = $entry; //will be expected by nextEntry next round
1176 1176
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1177 1177
 					$dn = $this->ldap->getDN($cr, $entry);
1178
-					if($dn === false || in_array($dn, $dnRead)) {
1178
+					if ($dn === false || in_array($dn, $dnRead)) {
1179 1179
 						continue;
1180 1180
 					}
1181 1181
 					$newItems = [];
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
 					$foundItems = array_merge($foundItems, $newItems);
1187 1187
 					$this->resultCache[$dn][$attr] = $newItems;
1188 1188
 					$dnRead[] = $dn;
1189
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1189
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1190 1190
 						|| $this->ldap->isResource($entry))
1191 1191
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192 1192
 			}
@@ -1209,11 +1209,11 @@  discard block
 block discarded – undo
1209 1209
 	 */
1210 1210
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211 1211
 		$cr = $this->getConnection();
1212
-		if(!$cr) {
1212
+		if (!$cr) {
1213 1213
 			throw new \Exception('Could not connect to LDAP');
1214 1214
 		}
1215 1215
 		$p = 'objectclass=';
1216
-		foreach($objectclasses as $key => $value) {
1216
+		foreach ($objectclasses as $key => $value) {
1217 1217
 			$objectclasses[$key] = $p.$value;
1218 1218
 		}
1219 1219
 		$maxEntryObjC = '';
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
 		$availableFeatures =
1226 1226
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227 1227
 											   $dig, $maxEntryObjC);
1228
-		if(is_array($availableFeatures)
1228
+		if (is_array($availableFeatures)
1229 1229
 		   && count($availableFeatures) > 0) {
1230 1230
 			natcasesort($availableFeatures);
1231 1231
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 		}
1237 1237
 
1238 1238
 		$setFeatures = $this->configuration->$confkey;
1239
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1239
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1240 1240
 			//something is already configured? pre-select it.
1241 1241
 			$this->result->addChange($dbkey, $setFeatures);
1242 1242
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1258,7 +1258,7 @@  discard block
 block discarded – undo
1258 1258
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259 1259
 	 */
1260 1260
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
-		if(!is_array($result)
1261
+		if (!is_array($result)
1262 1262
 		   || !isset($result['count'])
1263 1263
 		   || !$result['count'] > 0) {
1264 1264
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1267,12 +1267,12 @@  discard block
 block discarded – undo
1267 1267
 		// strtolower on all keys for proper comparison
1268 1268
 		$result = \OCP\Util::mb_array_change_key_case($result);
1269 1269
 		$attribute = strtolower($attribute);
1270
-		if(isset($result[$attribute])) {
1271
-			foreach($result[$attribute] as $key => $val) {
1272
-				if($key === 'count') {
1270
+		if (isset($result[$attribute])) {
1271
+			foreach ($result[$attribute] as $key => $val) {
1272
+				if ($key === 'count') {
1273 1273
 					continue;
1274 1274
 				}
1275
-				if(!in_array($val, $known)) {
1275
+				if (!in_array($val, $known)) {
1276 1276
 					$known[] = $val;
1277 1277
 				}
1278 1278
 			}
@@ -1286,7 +1286,7 @@  discard block
 block discarded – undo
1286 1286
 	 * @return bool|mixed
1287 1287
 	 */
1288 1288
 	private function getConnection() {
1289
-		if(!is_null($this->cr)) {
1289
+		if (!is_null($this->cr)) {
1290 1290
 			return $this->cr;
1291 1291
 		}
1292 1292
 
@@ -1298,14 +1298,14 @@  discard block
 block discarded – undo
1298 1298
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299 1299
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300 1300
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
-		if($this->configuration->ldapTLS === 1) {
1301
+		if ($this->configuration->ldapTLS === 1) {
1302 1302
 			$this->ldap->startTls($cr);
1303 1303
 		}
1304 1304
 
1305 1305
 		$lo = @$this->ldap->bind($cr,
1306 1306
 								 $this->configuration->ldapAgentName,
1307 1307
 								 $this->configuration->ldapAgentPassword);
1308
-		if($lo === true) {
1308
+		if ($lo === true) {
1309 1309
 			$this->$cr = $cr;
1310 1310
 			return $cr;
1311 1311
 		}
@@ -1336,18 +1336,18 @@  discard block
 block discarded – undo
1336 1336
 		//636 ← LDAPS / SSL
1337 1337
 		//7xxx ← UCS. need to be checked first, because both ports may be open
1338 1338
 		$host = $this->configuration->ldapHost;
1339
-		$port = (int)$this->configuration->ldapPort;
1339
+		$port = (int) $this->configuration->ldapPort;
1340 1340
 		$portSettings = [];
1341 1341
 
1342 1342
 		//In case the port is already provided, we will check this first
1343
-		if($port > 0) {
1343
+		if ($port > 0) {
1344 1344
 			$hostInfo = parse_url($host);
1345
-			if(!(is_array($hostInfo)
1345
+			if (!(is_array($hostInfo)
1346 1346
 				&& isset($hostInfo['scheme'])
1347 1347
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348 1348
 				$portSettings[] = ['port' => $port, 'tls' => true];
1349 1349
 			}
1350
-			$portSettings[] =['port' => $port, 'tls' => false];
1350
+			$portSettings[] = ['port' => $port, 'tls' => false];
1351 1351
 		}
1352 1352
 
1353 1353
 		//default ports
Please login to merge, or discard this patch.