Completed
Push — master ( 71718d...90a3d2 )
by Rain
04:31
created

ChangePasswordLdapDriver::ChangePassword()   F

Complexity

Conditions 20
Paths 398

Size

Total Lines 106
Code Lines 68

Duplication

Lines 34
Ratio 32.08 %

Importance

Changes 0
Metric Value
cc 20
eloc 68
nc 398
nop 3
dl 34
loc 106
rs 3.6338
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
class ChangePasswordLdapDriver implements \RainLoop\Providers\ChangePassword\ChangePasswordInterface
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
{
5
	/**
6
	 * @var string
7
	 */
8
	private $sHostName = '127.0.0.1';
9
10
	/**
11
	 * @var int
12
	 */
13
	private $iHostPort = 389;
14
15
	/**
16
	 * @var string
17
	 */
18
	private $sUserDnFormat = '';
19
20
	/**
21
	 * @var string
22
	 */
23
	private $sPasswordField = 'userPassword';
24
25
	/**
26
	 * @var string
27
	 */
28
	private $sPasswordEncType = 'SHA';
29
30
	/**
31
	 * @var \MailSo\Log\Logger
32
	 */
33
	private $oLogger = null;
34
35
	/**
36
	 * @var string
37
	 */
38
	private $sAllowedEmails = '';
39
40
	/**
41
	 * @param string $sHostName
42
	 * @param int $iHostPort
43
	 * @param string $sUserDnFormat
44
	 * @param string $sPasswordField
45
	 * @param string $sPasswordEncType
46
	 *
47
	 * @return \ChangePasswordLdapDriver
48
	 */
49
	public function SetConfig($sHostName, $iHostPort, $sUserDnFormat, $sPasswordField, $sPasswordEncType)
50
	{
51
		$this->sHostName = $sHostName;
52
		$this->iHostPort = $iHostPort;
53
		$this->sUserDnFormat = $sUserDnFormat;
54
		$this->sPasswordField = $sPasswordField;
55
		$this->sPasswordEncType = $sPasswordEncType;
56
57
		return $this;
58
	}
59
60
	/**
61
	 * @param string $sAllowedEmails
62
	 *
63
	 * @return \ChangePasswordLdapDriver
64
	 */
65
	public function SetAllowedEmails($sAllowedEmails)
66
	{
67
		$this->sAllowedEmails = $sAllowedEmails;
68
69
		return $this;
70
	}
71
72
	/**
73
	 * @param \MailSo\Log\Logger $oLogger
74
	 *
75
	 * @return \ChangePasswordLdapDriver
76
	 */
77
	public function SetLogger($oLogger)
78
	{
79
		if ($oLogger instanceof \MailSo\Log\Logger)
0 ignored issues
show
Bug introduced by
The class MailSo\Log\Logger does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
80
		{
81
			$this->oLogger = $oLogger;
82
		}
83
84
		return $this;
85
	}
86
87
	/**
88
	 * @param \RainLoop\Account $oAccount
89
	 *
90
	 * @return bool
91
	 */
92
	public function PasswordChangePossibility($oAccount)
93
	{
94
		return $oAccount && $oAccount->Email() &&
95
			\RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $this->sAllowedEmails);
96
	}
97
98
	/**
99
	 * @param \RainLoop\Model\Account $oAccount
100
	 * @param string $sPrevPassword
101
	 * @param string $sNewPassword
102
	 *
103
	 * @return bool
104
	 */
105
	public function ChangePassword(\RainLoop\Account $oAccount, $sPrevPassword, $sNewPassword)
106
	{
107
		$bResult = false;
108
109
		try
110
		{
111
			$sDomain = \MailSo\Base\Utils::GetDomainFromEmail($oAccount->Email());
112
			$sUserDn = \strtr($this->sUserDnFormat, array(
113
				'{domain}' => $sDomain,
114
				'{domain:dc}' => 'dc='.\strtr($sDomain, array('.' => ',dc=')),
115
				'{email}' => $oAccount->Email(),
116
				'{email:user}' => \MailSo\Base\Utils::GetAccountNameFromEmail($oAccount->Email()),
117
				'{email:domain}' => $sDomain,
118
				'{login}' => $oAccount->Login(),
119
				'{imap:login}' => $oAccount->Login(),
120
				'{imap:host}' => $oAccount->DomainIncHost(),
121
				'{imap:port}' => $oAccount->DomainIncPort()
122
			));
123
124
			$oCon = @\ldap_connect($this->sHostName, $this->iHostPort);
125
			if ($oCon)
126
			{
127
				@\ldap_set_option($oCon, LDAP_OPT_PROTOCOL_VERSION, 3);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
128
129 View Code Duplication
				if (!@\ldap_bind($oCon, $sUserDn, $sPrevPassword))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
				{
131
					if ($this->oLogger)
132
					{
133
						$sError = $oCon ? @\ldap_error($oCon) : '';
134
						$iErrno = $oCon ? @\ldap_errno($oCon) : 0;
135
136
						$this->oLogger->Write('ldap_bind error: '.$sError.' ('.$iErrno.')',
137
							\MailSo\Log\Enumerations\Type::WARNING, 'LDAP');
138
					}
139
140
					return false;
141
				}
142
			}
143
			else
144
			{
145
				return false;
146
			}
147
148
			$sSshaSalt = '';
149
			$sShaPrefix = '{SHA}';
150
			$sEncodedNewPassword = $sNewPassword;
151
			switch (\strtolower($this->sPasswordEncType))
152
			{
153
				case 'ssha':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
154
					$sSshaSalt = $this->getSalt(4);
155
					$sShaPrefix = '{SSHA}';
156
				case 'sha':
157
					switch (true)
158
					{
159
						default:
160 View Code Duplication
						case \function_exists('sha1'):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
							$sEncodedNewPassword = $sShaPrefix.\base64_encode(\sha1($sNewPassword.$sSshaSalt, true).$sSshaSalt);
162
							break;
163 View Code Duplication
						case \function_exists('hash'):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
							$sEncodedNewPassword = $sShaPrefix.\base64_encode(\hash('sha1', $sNewPassword, true).$sSshaSalt);
165
							break;
166
						case \function_exists('mhash') && defined('MHASH_SHA1'):
167
							$sEncodedNewPassword = $sShaPrefix.\base64_encode(\mhash(MHASH_SHA1, $sNewPassword).$sSshaSalt);
168
							break;
169
					}
170
					break;
171
				case 'md5':
172
					$sEncodedNewPassword = '{MD5}'.\base64_encode(\pack('H*', \md5($sNewPassword)));
173
					break;
174
				case 'crypt':
175
					$sEncodedNewPassword = '{CRYPT}'.\crypt($sNewPassword, $this->getSalt(2));
176
					break;
177
			}
178
179
			$aEntry = array();
180
			$aEntry[$this->sPasswordField] = (string) $sEncodedNewPassword;
181
182 View Code Duplication
			if (!!@\ldap_modify($oCon, $sUserDn, $aEntry))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
			{
184
				$bResult = true;
185
			}
186
			else
187
			{
188
				if ($this->oLogger)
189
				{
190
					$sError = $oCon ? @\ldap_error($oCon) : '';
191
					$iErrno = $oCon ? @\ldap_errno($oCon) : 0;
192
193
					$this->oLogger->Write('ldap_modify error: '.$sError.' ('.$iErrno.')',
194
						\MailSo\Log\Enumerations\Type::WARNING, 'LDAP');
195
				}
196
			}
197
		}
198
		catch (\Exception $oException)
199
		{
200
			if ($this->oLogger)
201
			{
202
				$this->oLogger->WriteException($oException,
203
					\MailSo\Log\Enumerations\Type::WARNING, 'LDAP');
204
			}
205
206
			$bResult = false;
207
		}
208
209
		return $bResult;
210
	}
211
212
	/**
213
	 * @param int $iLength
214
	 *
215
	 * @return string
216
	 */
217
	private function getSalt($iLength)
218
	{
219
		$sChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
220
		$iCharsLength = \strlen($sChars);
221
222
		$sResult = '';
223
		while (\strlen($sResult) < $iLength)
224
		{
225
			$sResult .= \substr($sChars, \rand() % $iCharsLength, 1);
226
		}
227
228
		return $sResult;
229
	}
230
}
231