Completed
Push — master ( 65f5e6...649e1f )
by Gareth
03:56
created

ExchangeWebServices::fromUsernameAndPassword()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 5
nc 1
nop 4
crap 1
1
<?php
2
/**
3
 * Contains ExchangeWebServices.
4
 */
5
6
7
namespace garethp\ews\API;
8
9
use garethp\ews\API\Exception\ExchangeException;
10
use garethp\ews\API\Exception\NoResponseReturnedException;
11
use garethp\ews\API\Exception\ServiceUnavailableException;
12
use garethp\ews\API\Exception\UnauthorizedException;
13
use garethp\ews\API\ExchangeWebServices\MiddlewareFactory;
14
use garethp\ews\API\Message;
15
use garethp\ews\API\Type\EmailAddressType;
16
use \Closure;
17
18
/**
19
 * Base class of the Exchange Web Services application.
20
 *
21
 *
22
 *
23
 * @package php-ews\Client
24
 *
25
 * @method Type AddDelegate($request)
26
 * @method Type ApplyConversationAction($request)
27
 * @method Type ConvertId($request)
28
 * @method Type CopyFolder($request)
29
 * @method Type CopyItem($request)
30
 * @method Type CreateAttachment($request)
31
 * @method Type CreateFolder($request)
32
 * @method Type CreateItem($request)
33
 * @method Type CreateManagedFolder($request)
34
 * @method Type CreateUserConfiguration($request)
35
 * @method Type DeleteAttachment($request)
36
 * @method Type DeleteFolder($request)
37
 * @method Type DeleteItem($request)
38
 * @method Type DeleteUserConfiguration($request)
39
 * @method Type DisconnectPhoneCall($request)
40
 * @method Type EmptyFolder($request)
41
 * @method Type ExpandDL($request)
42
 * @method Type ExportItems($request)
43
 * @method Type FindConversation($request)
44
 * @method Type FindFolder($request)
45
 * @method Type FindItem($request)
46
 * @method Type FindMessageTrackingReport($request)
47
 * @method Type GetAttachment($request)
48
 * @method Type GetDelegate($request)
49
 * @method Type GetEvents($request)
50
 * @method Type GetFolder($request)
51
 * @method Type GetInboxRules($request)
52
 * @method Type GetItem($request)
53
 * @method Type GetMailTips($request)
54
 * @method Type GetMessageTrackingReport($request)
55
 * @method Type GetPasswordExpirationDate($request)
56
 * @method Type GetPhoneCallInformation($request)
57
 * @method Type GetRoomLists($request)
58
 * @method Type GetRooms($request)
59
 * @method Type GetServerTimeZones($request)
60
 * @method Type GetServiceConfiguration($request)
61
 * @method Type GetSharingFolder($request)
62
 * @method Type GetSharingMetadata($request)
63
 * @method Type GetStreamingEvents($request)
64
 * @method Type GetUserAvailability($request)
65
 * @method Type GetUserConfiguration($request)
66
 * @method Type GetUserOofSettings($request)
67
 * @method Type MoveFolder($request)
68
 * @method Type MoveItem($request)
69
 * @method Type PlayOnPhone($request)
70
 * @method Type RefreshSharingFolder($request)
71
 * @method Type RemoveDelegate($request)
72
 * @method Type ResolveNames($request)
73
 * @method Type SendItem($request)
74
 * @method Type SetUserOofSettings($request)
75
 * @method Type Subscribe($request)
76
 * @method Type SyncFolderHierarchy($request)
77
 * @method Type SyncFolderItems($request)
78
 * @method Type Unsubscribe($request)
79
 * @method Type UpdateDelegate($request)
80
 * @method Type UpdateFolder($request)
81
 * @method Type UpdateInboxRules($request)
82
 * @method Type UpdateItem($request)
83
 * @method Type UpdateUserConfiguration($request)
84
 * @method Type UploadItems($request)
85
 */
86
class ExchangeWebServices
87
{
88
    const VERSION_2007 = 'Exchange2007';
89
90
    const VERSION_2007_SP1 = 'Exchange2007_SP1';
91
92
    const VERSION_2010 = 'Exchange2010';
93
94
    const VERSION_2010_SP1 = 'Exchange2010_SP1';
95
96
    const VERSION_2010_SP2 = 'Exchange2010_SP2';
97
98
    const VERSION_2013 = 'Exchange2013';
99
100
    const VERSION_2013_SP1 = 'Exchange2013_SP1';
101
102
    /**
103
     * Password to use when connecting to the Exchange server.
104
     *
105
     * @var string
106
     */
107
    protected $password = null;
108
109
    /**
110
     * Location of the Exchange server.
111
     *
112
     * @var string
113
     */
114
    protected $server = null;
115
116
    /**
117
     * SOAP client used to make the request
118
     *
119
     * @var NTLMSoapClient
120
     */
121
    protected $soap = null;
122
123
    /**
124
     * Username to use when connecting to the Exchange server.
125
     *
126
     * @var string
127
     */
128
    protected $username = null;
129
130
    /**
131
     * @var EmailAddressType
132
     */
133
    protected $primarySmtpMailbox = null;
134
135
    protected static $middlewareStack = false;
136
137
    /**
138
     * A setting to check whether or not responses should be drilled down before being
139
     * returned. Setting this to false
140
     * will return the raw responses without any filtering
141
     *
142
     * @var bool
143
     */
144
    protected $drillDownResponses = true;
145
146
    /**
147
     * Miscrosoft Exchange version that we are going to connect to
148
     *
149
     * @var string
150
     */
151
    protected $version = null;
152
153
    protected $options = null;
154
155
    /**
156
     * The timezone for the client
157
     *
158
     * @var bool
159
     */
160
    protected $timezone = false;
161
162
    /**
163
     * @return EmailAddressType
164
     */
165 26
    public function getPrimarySmtpMailbox()
166
    {
167 26
        return $this->primarySmtpMailbox;
168
    }
169
170 1
    public function getPrimarySmtpEmailAddress()
171
    {
172 1
        if ($this->primarySmtpMailbox == null) {
173 1
            return null;
174
        }
175
176 1
        return $this->primarySmtpMailbox->getEmailAddress();
177
    }
178
179 2
    public function setPrimarySmtpEmailAddress($emailAddress)
180
    {
181 2
        $mailbox = new EmailAddressType();
182 2
        $mailbox->setEmailAddress($emailAddress);
183 2
        $this->primarySmtpMailbox = $mailbox;
184
185 2
        return $this;
186
    }
187
188
    /**
189
     * @param boolean $timezone
190
     */
191
    public function setTimezone($timezone)
192
    {
193
        $this->timezone = $timezone;
194
    }
195
196
    /**
197
     * @return string
198
     */
199
    public function getVersion()
200
    {
201
        return $this->version;
202
    }
203
204
    /**
205
     * @return string
206
     */
207
    public function getServer()
208
    {
209
        return $this->server;
210
    }
211
212
    /**
213
     * Constructor for the ExchangeWebServices class
214
     *
215
     * @param string $server
216
     * @param string $username
217
     * @param string $password
218
     * @param array $options
219
     */
220 34
    protected function __construct($server = null, $username = null, $password = null, $options = array())
221
    {
222 34
        if ($server !== null) {
223
            $this->createClient(
224
                $server,
225
                ExchangeWebServicesAuth::fromUsernameAndPassword($username, $password),
226
                $options
227
            );
228
        }
229
230 34
        $this->buildMiddlewareStack();
231 34
    }
232
233 33
    public static function fromUsernameAndPassword($server, $username, $password, $options)
234
    {
235 33
        $self = new self();
236 33
        $self->createClient($server, ExchangeWebServicesAuth::fromUsernameAndPassword($username, $password), $options);
237 33
        $self->options = $options;
238
239 33
        return $self;
240
    }
241
242 1
    public static function fromCallbackToken($server, $token, $options)
243
    {
244 1
        $self = new self();
245 1
        $self->createClient($server, ExchangeWebServicesAuth::fromCallbackToken($token), $options);
246 1
        $self->options = $options;
247
248 1
        return $self;
249
    }
250
251 34
    protected function createClient($server, $auth, $options)
252
    {
253 34
        $location = 'https://' . $this->cleanServerUrl($server) . '/EWS/Exchange.asmx';
254
255 34
        $options = array_replace_recursive([
256 34
            'version' => self::VERSION_2007,
257 34
            'trace' => 1,
258 34
            'exceptions' => true,
259 34
            'classmap' => ClassMap::getClassMap(),
260
            'drillDownResponses' => true
261 34
        ], $options);
262
263 34
        $this->server = $server;
264 34
        $this->version = $options['version'];
265
266 34
        $this->soap = new NTLMSoapClient(
267 34
            $location,
268 34
            $auth,
269 34
            dirname(__FILE__) . '/../../Resources/wsdl/services.wsdl',
270
            $options
271 34
        );
272
273 34
        if (isset($options['primarySmtpEmailAddress'])) {
274 1
            $this->setPrimarySmtpEmailAddress($options['primarySmtpEmailAddress']);
275 1
        }
276
277 34
        if (isset($options['impersonation'])) {
278 1
            $this->setPrimarySmtpEmailAddress($options['impersonation']);
279 1
        }
280
281 34
        $this->drillDownResponses = $options['drillDownResponses'];
282 34
    }
283
284
    /**
285
     * @codeCoverageIgnore
286
     *
287
     * @param $name
288
     * @param $arguments
289
     * @return Type
290
     * @throws \garethp\ews\API\Exception
291
     */
292
    public function __call($name, $arguments)
293
    {
294
        $request = MiddlewareRequest::newRequest($name, $arguments, $this->options);
295
        $response = $this->executeMiddlewareStack(self::$middlewareStack, $request);
0 ignored issues
show
Documentation introduced by
self::$middlewareStack is of type boolean, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
296
        $response = $response->getResponse();
297
        return $response;
298
        return $this->processResponse($response);
0 ignored issues
show
Unused Code introduced by
return $this->processResponse($response); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
299
    }
300
301
    /**
302
     * Returns the SOAP Client that may be used to make calls against the server
303
     *
304
     * @return NTLMSoapClient
305
     */
306 2
    public function getClient()
307
    {
308 2
        return $this->soap;
309
    }
310
311
    /**
312
     * Cleans the server URL for usage
313
     *
314
     * @param $server
315
     * @return string
316
     */
317 41
    public function cleanServerUrl($server)
318
    {
319 41
        $url = parse_url($server);
320 41
        if (!isset($url['host']) && isset($url['path'])) {
321 36
            $url['host'] = $url['path'];
322 36
            unset($url['path']);
323 36
        }
324
325 41
        $server = $url['host'];
326 41
        if (isset($url['port'])) {
327 2
            $server .= ':' . $url['port'];
328 2
        }
329
330 41
        if (isset($url['path'])) {
331 4
            $server .= $url['path'];
332 4
        }
333
334 41
        $server = rtrim($server, "/");
335
336 41
        return $server;
337
    }
338
339
    /**
340
     * Process a response to verify that it succeeded and take the appropriate
341
     * action
342
     *
343
     * @param \garethp\ews\API\Message\BaseResponseMessageType $response
344
     * @return Type[]
345
     * @throws \garethp\ews\API\Exception
346
     */
347
    protected function processResponse($response)
348
    {
349
        // If the soap call failed then we need to thow an exception.
350
        $code = $this->getClient()->getResponseCode();
351
        $this->handleNonSuccessfulResponses($response, $code);
352
353
        if (!$this->drillDownResponses) {
354
            return $response;
355
        }
356
357
        if (!$response->exists('responseMessages')) {
358
            return $response;
359
        }
360
361
        $response = $response->getResponseMessages();
362
        $response = $this->drillDownResponseLevels($response);
363
364
        return $response;
365
    }
366
367
    /**
368
     * @param $response
369
     * @return array
370
     * @throws \garethp\ews\API\Exception
371
     */
372
    public function drillDownResponseLevels($response)
373
    {
374
        $items = $this->getItemsFromResponse($response);
375
376
        if (count($items) == 1) {
377
            reset($items);
378
            $key = key($items);
379
            $methodName = "get$key";
380
            $response = $response->$methodName();
381
382
            return $this->drillDownResponseLevels($response);
383
        }
384
385
        if (is_array($items) && isset($items[1]) && $items[1] instanceof Message\ResponseMessageType) {
0 ignored issues
show
Bug introduced by
The class garethp\ews\API\Message\ResponseMessageType 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...
386
            $response = array();
387
            foreach ($items as $responseItem) {
388
                $response[] = $this->drillDownResponseLevels($responseItem);
389
            }
390
391
            return $response;
392
        }
393
394
        return $response;
395
    }
396
397
    /**
398
     * @param $response
399
     * @return array
400
     * @throws ExchangeException
401
     */
402
    protected function getItemsFromResponse($response)
403
    {
404
        $items = array();
405
        if ($response instanceof Type) {
406
            $items = $response->getNonNullItems();
407
        }
408
409
        if (is_array($response)) {
410
            $items = $response;
411
        }
412
413
        if ($response instanceof Message\ResponseMessageType) {
0 ignored issues
show
Bug introduced by
The class garethp\ews\API\Message\ResponseMessageType 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...
414
            if ($response->getResponseClass() !== "Success") {
415
                throw new ExchangeException($response->getMessageText());
416
            }
417
418
            unset($items['responseClass']);
419
            unset($items['responseCode']);
420
        }
421
422
        return $items;
423
    }
424
425
    /**
426
     * @param Message\BaseResponseMessageType $response
427
     * @param $code
428
     * @throws ExchangeException
429
     * @throws NoResponseReturnedException
430
     * @throws ServiceUnavailableException
431
     * @throws UnauthorizedException
432
     */
433
    protected function handleNonSuccessfulResponses($response, $code)
434
    {
435
        if ($code == 401) {
436
            throw new UnauthorizedException();
437
        }
438
439
        if ($code == 503) {
440
            throw new ServiceUnavailableException();
441
        }
442
443
        if ($code >= 300) {
444
            throw new ExchangeException('SOAP client returned status of ' . $code, $code);
445
        }
446
447
        if (empty($response) || empty($response->getNonNullResponseMessages())) {
448
            throw new NoResponseReturnedException();
449
        }
450
    }
451
452 34
    protected function buildMiddlewareStack()
453
    {
454 34
        if (self::$middlewareStack === false) {
455 1
            self::$middlewareStack = [
0 ignored issues
show
Documentation Bug introduced by
It seems like array(\garethp\ews\API\E...equestToPagedResults()) of type array<integer,object<Clo..."4":"object<Closure>"}> is incompatible with the declared type boolean of property $middlewareStack.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
456
                //Make the actual SOAP call
457 1
                MiddlewareFactory::getSoapCall(),
458
459
                //Transform an object of type Type to an XML Object
460 1
                MiddlewareFactory::getTypeToXMLObject(),
461
462
                //The SyncScope option isn't available for Exchange 2007 SP1 and below
463 1
                MiddlewareFactory::getStripSyncScopeForExchange2007(),
464
465
                //Add response processing
466 1
                MiddlewareFactory::getProcessResponse(),
467
468
                //Adds last request to FindFolder and FindItem responses
469 1
                MiddlewareFactory::getAddLastRequestToPagedResults()
470 1
            ];
471 1
        }
472 34
    }
473
474
    /**
475
     * @param array $middlewareStack
476
     * @param MiddlewareRequest $request
477
     * @return MiddlewareResponse
478
     */
479 28
    protected function executeMiddlewareStack(array $middlewareStack, MiddlewareRequest $request)
480
    {
481 28
        $newStack = [];
482 28
        foreach ($middlewareStack as $key => $current) {
483
            /** @var $current callable */
484
            $last = function () { };
485
486 28
            if ($key != 0) {
487
                $last = $newStack[$key - 1];
488
            }
489
490 28
            $current = Closure::bind($current, $this, $this);
491
            $newStack[] = function (MiddlewareRequest $request) use ($current, $last) {
492
                return $current($request, $last);
493
            };
494
        }
495
496
        /** @var $newStack callable[] */
497
        $newStack = array_reverse($newStack);
498
499
        $top = $newStack[0];
500
501
        /** @var $top callable */
502
        return $top($request);
503
    }
504
}
505