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

LdapContactsSuggestions   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 315
Duplicated Lines 6.98 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 22
loc 315
rs 8.3999
c 0
b 0
f 0
wmc 38
lcom 1
cbo 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A SetConfig() 0 13 1
A SetAllowedEmails() 0 6 1
B Process() 0 23 5
C findNameAndEmail() 22 32 8
D ldapSearch() 0 96 15
A escape() 0 12 2
A logLdapError() 0 11 4
A SetLogger() 0 9 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
class LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISuggestions
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 $sAccessDn = '';
19
20
	/**
21
	 * @var string
22
	 */
23
	private $sAccessPassword = '';
24
25
	/**
26
	 * @var string
27
	 */
28
	private $sUsersDn = '';
29
30
	/**
31
	 * @var string
32
	 */
33
	private $sObjectClass = 'inetOrgPerson';
34
35
	/**
36
	 * @var string
37
	 */
38
	private $sNameField = 'givenname';
39
40
	/**
41
	 * @var string
42
	 */
43
	private $sEmailField = 'mail';
44
45
	/**
46
	 * @var \MailSo\Log\Logger
47
	 */
48
	private $oLogger = null;
49
50
	/**
51
	 * @var string
52
	 */
53
	private $sAllowedEmails = '';
54
55
	/**
56
	 * @param string $sHostName
57
	 * @param int $iHostPort
58
	 * @param string $sAccessDn
59
	 * @param string $sAccessPassword
60
	 * @param string $sUsersDn
61
	 * @param string $sObjectClass
62
	 * @param string $sNameField
63
	 * @param string $sEmailField
64
	 *
65
	 * @return \LdapContactsSuggestions
66
	 */
67
	public function SetConfig($sHostName, $iHostPort, $sAccessDn, $sAccessPassword, $sUsersDn, $sObjectClass, $sNameField, $sEmailField)
68
	{
69
		$this->sHostName = $sHostName;
70
		$this->iHostPort = $iHostPort;
71
		$this->sAccessDn = $sAccessDn;
72
		$this->sAccessPassword = $sAccessPassword;
73
		$this->sUsersDn = $sUsersDn;
74
		$this->sObjectClass = $sObjectClass;
75
		$this->sNameField = $sNameField;
76
		$this->sEmailField = $sEmailField;
77
78
		return $this;
79
	}
80
81
	/**
82
	 * @param string $sAllowedEmails
83
	 *
84
	 * @return \LdapContactsSuggestions
85
	 */
86
	public function SetAllowedEmails($sAllowedEmails)
87
	{
88
		$this->sAllowedEmails = $sAllowedEmails;
89
90
		return $this;
91
	}
92
93
	/**
94
	 * @param \RainLoop\Model\Account $oAccount
95
	 * @param string $sQuery
96
	 * @param int $iLimit = 20
97
	 *
98
	 * @return array
99
	 */
100
	public function Process($oAccount, $sQuery, $iLimit = 20)
101
	{
102
		$sQuery = \trim($sQuery);
103
104
		if (2 > \strlen($sQuery))
105
		{
106
			return array();
107
		}
108
		else if (!$oAccount || !\RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $this->sAllowedEmails))
109
		{
110
			return array();
111
		}
112
113
		$aResult = $this->ldapSearch($oAccount, $sQuery);
114
115
		$aResult = \RainLoop\Utils::RemoveSuggestionDuplicates($aResult);
116
		if ($iLimit < \count($aResult))
117
		{
118
			$aResult = \array_slice($aResult, 0, $iLimit);
119
		}
120
121
		return $aResult;
122
	}
123
124
	/**
125
	 * @param array $aLdapItem
126
	 * @param array $aEmailFields
127
	 * @param array $aNameFields
128
	 *
129
	 * @return array
130
	 */
131
	private function findNameAndEmail($aLdapItem, $aEmailFields, $aNameFields)
132
	{
133
		$sEmail = $sName = '';
134
		if ($aLdapItem)
0 ignored issues
show
Bug Best Practice introduced by
The expression $aLdapItem of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
135
		{
136 View Code Duplication
			foreach ($aEmailFields as $sField)
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...
137
			{
138
				if (!empty($aLdapItem[$sField][0]))
139
				{
140
					$sEmail = \trim($aLdapItem[$sField][0]);
141
					if (!empty($sEmail))
142
					{
143
						break;
144
					}
145
				}
146
			}
147
148 View Code Duplication
			foreach ($aNameFields as $sField)
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...
149
			{
150
				if (!empty($aLdapItem[$sField][0]))
151
				{
152
					$sName = \trim($aLdapItem[$sField][0]);
153
					if (!empty($sName))
154
					{
155
						break;
156
					}
157
				}
158
			}
159
		}
160
161
		return array($sEmail, $sName);
162
	}
163
164
	/**
165
	 * @param \RainLoop\Model\Account $oAccount
166
	 * @param string $sQuery
167
	 *
168
	 * @return array
169
	 */
170
	private function ldapSearch($oAccount, $sQuery)
171
	{
172
		$sSearchEscaped = $this->escape($sQuery);
173
174
		$aResult = array();
175
		$oCon = @\ldap_connect($this->sHostName, $this->iHostPort);
176
		if ($oCon)
177
		{
178
			$this->oLogger->Write('ldap_connect: connected', \MailSo\Log\Enumerations\Type::INFO, 'LDAP');
179
180
			@\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...
181
182
			if (!@\ldap_bind($oCon, $this->sAccessDn, $this->sAccessPassword))
183
			{
184
				$this->logLdapError($oCon, 'ldap_bind');
185
				return $aResult;
186
			}
187
188
			$sDomain = \MailSo\Base\Utils::GetDomainFromEmail($oAccount->Email());
189
			$sSearchDn = \strtr($this->sUsersDn, array(
190
				'{domain}' => $sDomain,
191
				'{domain:dc}' => 'dc='.\strtr($sDomain, array('.' => ',dc=')),
192
				'{email}' => $oAccount->Email(),
193
				'{email:user}' => \MailSo\Base\Utils::GetAccountNameFromEmail($oAccount->Email()),
194
				'{email:domain}' => $sDomain,
195
				'{login}' => $oAccount->Login(),
196
				'{imap:login}' => $oAccount->Login(),
197
				'{imap:host}' => $oAccount->DomainIncHost(),
198
				'{imap:port}' => $oAccount->DomainIncPort()
199
			));
200
201
			$aEmails = empty($this->sEmailField) ? array() : \explode(',', $this->sEmailField);
202
			$aNames = empty($this->sNameField) ? array() : \explode(',', $this->sNameField);
203
204
			$aEmails = \array_map('trim', $aEmails);
205
			$aNames = \array_map('trim', $aNames);
206
207
			$aFields = \array_merge($aEmails, $aNames);
208
209
			$aItems = array();
210
			$sSubFilter = '';
211
			foreach ($aFields as $sItem)
212
			{
213
				if (!empty($sItem))
214
				{
215
					$aItems[] = $sItem;
216
					$sSubFilter .= '('.$sItem.'=*'.$sSearchEscaped.'*)';
217
				}
218
			}
219
220
			$sFilter = '(&(objectclass='.$this->sObjectClass.')';
221
			$sFilter .= (1 < count($aItems) ? '(|' : '').$sSubFilter.(1 < count($aItems) ? ')' : '');
222
			$sFilter .= ')';
223
224
			$this->oLogger->Write('ldap_search: start: '.$sSearchDn.' / '.$sFilter, \MailSo\Log\Enumerations\Type::INFO, 'LDAP');
225
			$oS = @\ldap_search($oCon, $sSearchDn, $sFilter, $aItems, 0, 30, 30);
226
			if ($oS)
227
			{
228
				$aEntries = @\ldap_get_entries($oCon, $oS);
229
				if (is_array($aEntries))
230
				{
231
					if (isset($aEntries['count']))
232
					{
233
						unset($aEntries['count']);
234
					}
235
236
					foreach ($aEntries as $aItem)
237
					{
238
						if ($aItem)
239
						{
240
							$sName = $sEmail = '';
241
							list ($sEmail, $sName) = $this->findNameAndEmail($aItem, $aEmails, $aNames);
242
							if (!empty($sEmail))
243
							{
244
								$aResult[] = array($sEmail, $sName);
245
							}
246
						}
247
					}
248
				}
249
				else
250
				{
251
					$this->logLdapError($oCon, 'ldap_get_entries');
252
				}
253
			}
254
			else
255
			{
256
				$this->logLdapError($oCon, 'ldap_search');
257
			}
258
		}
259
		else
260
		{
261
			return $aResult;
262
		}
263
264
		return $aResult;
265
	}
266
267
	/**
268
	 * @param string $sStr
269
	 *
270
	 * @return string
271
	 */
272
	public function escape($sStr)
273
	{
274
		$aNewChars = array();
275
		$aChars = array('\\', '*', '(', ')', \chr(0));
276
277
		foreach ($aChars as $iIndex => $sValue)
278
		{
279
			$aNewChars[$iIndex] = '\\'.\str_pad(\dechex(\ord($sValue)), 2, '0');
280
		}
281
282
		return \str_replace($aChars, $aNewChars, $sStr);
283
	}
284
285
	/**
286
	 * @param mixed $oCon
287
	 * @param string $sCmd
288
	 *
289
	 * @return string
290
	 */
291
	public function logLdapError($oCon, $sCmd)
292
	{
293
		if ($this->oLogger)
294
		{
295
			$sError = $oCon ? @\ldap_error($oCon) : '';
296
			$iErrno = $oCon ? @\ldap_errno($oCon) : 0;
297
298
			$this->oLogger->Write($sCmd.' error: '.$sError.' ('.$iErrno.')',
299
				\MailSo\Log\Enumerations\Type::WARNING, 'LDAP');
300
		}
301
	}
302
303
	/**
304
	 * @param \MailSo\Log\Logger $oLogger
305
	 *
306
	 * @return \LdapContactsSuggestions
307
	 */
308
	public function SetLogger($oLogger)
309
	{
310
		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...
311
		{
312
			$this->oLogger = $oLogger;
313
		}
314
315
		return $this;
316
	}
317
}
318