Completed
Push — master ( d717b9...62e6fb )
by Rain
02:21 queued 50s
created

LdapContactsSuggestions::ldapSearch()   F

Complexity

Conditions 16
Paths 195

Size

Total Lines 100

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
nc 195
nop 2
dl 0
loc 100
rs 3.82
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 LdapContactsSuggestions implements \RainLoop\Providers\Suggestions\ISuggestions
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 = NULL;
19
20
	/**
21
	 * @var string
22
	 */
23
	private $sAccessPassword = NULL;
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
		if (0 < \strlen($sAccessDn))
72
		{
73
			$this->sAccessDn = $sAccessDn;
74
			$this->sAccessPassword = $sAccessPassword;
75
		}
76
		$this->sUsersDn = $sUsersDn;
77
		$this->sObjectClass = $sObjectClass;
78
		$this->sNameField = $sNameField;
79
		$this->sEmailField = $sEmailField;
80
81
		return $this;
82
	}
83
84
	/**
85
	 * @param string $sAllowedEmails
86
	 *
87
	 * @return \LdapContactsSuggestions
88
	 */
89
	public function SetAllowedEmails($sAllowedEmails)
90
	{
91
		$this->sAllowedEmails = $sAllowedEmails;
92
93
		return $this;
94
	}
95
96
	/**
97
	 * @param \RainLoop\Model\Account $oAccount
98
	 * @param string $sQuery
99
	 * @param int $iLimit = 20
100
	 *
101
	 * @return array
102
	 */
103
	public function Process($oAccount, $sQuery, $iLimit = 20)
104
	{
105
		$sQuery = \trim($sQuery);
106
107
		if (2 > \strlen($sQuery))
108
		{
109
			return array();
110
		}
111
		else if (!$oAccount || !\RainLoop\Plugins\Helper::ValidateWildcardValues($oAccount->Email(), $this->sAllowedEmails))
112
		{
113
			return array();
114
		}
115
116
		$aResult = $this->ldapSearch($oAccount, $sQuery);
117
118
		$aResult = \RainLoop\Utils::RemoveSuggestionDuplicates($aResult);
119
		if ($iLimit < \count($aResult))
120
		{
121
			$aResult = \array_slice($aResult, 0, $iLimit);
122
		}
123
124
		return $aResult;
125
	}
126
127
	/**
128
	 * @param array $aLdapItem
129
	 * @param array $aEmailFields
130
	 * @param array $aNameFields
131
	 *
132
	 * @return array
133
	 */
134
	private function findNameAndEmail($aLdapItem, $aEmailFields, $aNameFields)
135
	{
136
		$sEmail = $sName = '';
137
		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...
138
		{
139 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...
140
			{
141
				if (!empty($aLdapItem[$sField][0]))
142
				{
143
					$sEmail = \trim($aLdapItem[$sField][0]);
144
					if (!empty($sEmail))
145
					{
146
						break;
147
					}
148
				}
149
			}
150
151 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...
152
			{
153
				if (!empty($aLdapItem[$sField][0]))
154
				{
155
					$sName = \trim($aLdapItem[$sField][0]);
156
					if (!empty($sName))
157
					{
158
						break;
159
					}
160
				}
161
			}
162
		}
163
164
		return array($sEmail, $sName);
165
	}
166
167
	/**
168
	 * @param \RainLoop\Model\Account $oAccount
169
	 * @param string $sQuery
170
	 *
171
	 * @return array
172
	 */
173
	private function ldapSearch($oAccount, $sQuery)
174
	{
175
		$sSearchEscaped = $this->escape($sQuery);
176
177
		$aResult = array();
178
		$oCon = @\ldap_connect($this->sHostName, $this->iHostPort);
179
		if ($oCon)
180
		{
181
			$this->oLogger->Write('ldap_connect: connected', \MailSo\Log\Enumerations\Type::INFO, 'LDAP');
182
183
			@\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...
184
185
			if (!@\ldap_bind($oCon, $this->sAccessDn, $this->sAccessPassword))
186
			{
187
				if ( is_null($this->sAccessDn) ) {
188
					$this->logLdapError($oCon, 'ldap_bind (anonymous)');
189
				} else {
190
					$this->logLdapError($oCon, 'ldap_bind');
191
				}
192
				return $aResult;
193
			}
194
195
			$sDomain = \MailSo\Base\Utils::GetDomainFromEmail($oAccount->Email());
196
			$sSearchDn = \strtr($this->sUsersDn, array(
197
				'{domain}' => $sDomain,
198
				'{domain:dc}' => 'dc='.\strtr($sDomain, array('.' => ',dc=')),
199
				'{email}' => $oAccount->Email(),
200
				'{email:user}' => \MailSo\Base\Utils::GetAccountNameFromEmail($oAccount->Email()),
201
				'{email:domain}' => $sDomain,
202
				'{login}' => $oAccount->Login(),
203
				'{imap:login}' => $oAccount->Login(),
204
				'{imap:host}' => $oAccount->DomainIncHost(),
205
				'{imap:port}' => $oAccount->DomainIncPort()
206
			));
207
208
			$aEmails = empty($this->sEmailField) ? array() : \explode(',', $this->sEmailField);
209
			$aNames = empty($this->sNameField) ? array() : \explode(',', $this->sNameField);
210
211
			$aEmails = \array_map('trim', $aEmails);
212
			$aNames = \array_map('trim', $aNames);
213
214
			$aFields = \array_merge($aEmails, $aNames);
215
216
			$aItems = array();
217
			$sSubFilter = '';
218
			foreach ($aFields as $sItem)
219
			{
220
				if (!empty($sItem))
221
				{
222
					$aItems[] = $sItem;
223
					$sSubFilter .= '('.$sItem.'=*'.$sSearchEscaped.'*)';
224
				}
225
			}
226
227
			$sFilter = '(&(objectclass='.$this->sObjectClass.')';
228
			$sFilter .= (1 < count($aItems) ? '(|' : '').$sSubFilter.(1 < count($aItems) ? ')' : '');
229
			$sFilter .= ')';
230
231
			$this->oLogger->Write('ldap_search: start: '.$sSearchDn.' / '.$sFilter, \MailSo\Log\Enumerations\Type::INFO, 'LDAP');
232
			$oS = @\ldap_search($oCon, $sSearchDn, $sFilter, $aItems, 0, 30, 30);
233
			if ($oS)
234
			{
235
				$aEntries = @\ldap_get_entries($oCon, $oS);
236
				if (is_array($aEntries))
237
				{
238
					if (isset($aEntries['count']))
239
					{
240
						unset($aEntries['count']);
241
					}
242
243
					foreach ($aEntries as $aItem)
244
					{
245
						if ($aItem)
246
						{
247
							$sName = $sEmail = '';
248
							list ($sEmail, $sName) = $this->findNameAndEmail($aItem, $aEmails, $aNames);
249
							if (!empty($sEmail))
250
							{
251
								$aResult[] = array($sEmail, $sName);
252
							}
253
						}
254
					}
255
				}
256
				else
257
				{
258
					$this->logLdapError($oCon, 'ldap_get_entries');
259
				}
260
			}
261
			else
262
			{
263
				$this->logLdapError($oCon, 'ldap_search');
264
			}
265
		}
266
		else
267
		{
268
			return $aResult;
269
		}
270
271
		return $aResult;
272
	}
273
274
	/**
275
	 * @param string $sStr
276
	 *
277
	 * @return string
278
	 */
279
	public function escape($sStr)
280
	{
281
		$aNewChars = array();
282
		$aChars = array('\\', '*', '(', ')', \chr(0));
283
284
		foreach ($aChars as $iIndex => $sValue)
285
		{
286
			$aNewChars[$iIndex] = '\\'.\str_pad(\dechex(\ord($sValue)), 2, '0');
287
		}
288
289
		return \str_replace($aChars, $aNewChars, $sStr);
290
	}
291
292
	/**
293
	 * @param mixed $oCon
294
	 * @param string $sCmd
295
	 *
296
	 * @return string
297
	 */
298
	public function logLdapError($oCon, $sCmd)
299
	{
300
		if ($this->oLogger)
301
		{
302
			$sError = $oCon ? @\ldap_error($oCon) : '';
303
			$iErrno = $oCon ? @\ldap_errno($oCon) : 0;
304
305
			$this->oLogger->Write($sCmd.' error: '.$sError.' ('.$iErrno.')',
306
				\MailSo\Log\Enumerations\Type::WARNING, 'LDAP');
307
		}
308
	}
309
310
	/**
311
	 * @param \MailSo\Log\Logger $oLogger
312
	 *
313
	 * @return \LdapContactsSuggestions
314
	 */
315
	public function SetLogger($oLogger)
316
	{
317
		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...
318
		{
319
			$this->oLogger = $oLogger;
320
		}
321
322
		return $this;
323
	}
324
}
325