GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

CalDavClient::setAuthenticationType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 1
1
<?php namespace CalDAVClient\Facade;
2
3
/**
4
 * Copyright 2017 OpenStack Foundation
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 * http://www.apache.org/licenses/LICENSE-2.0
9
 * Unless required by applicable law or agreed to in writing, software
10
 * distributed under the License is distributed on an "AS IS" BASIS,
11
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
 * See the License for the specific language governing permissions and
13
 * limitations under the License.
14
 **/
15
16
use CalDAVClient\Facade\Exceptions\ConflictException;
17
use CalDAVClient\Facade\Exceptions\ForbiddenException;
18
use CalDAVClient\Facade\Requests\CalDAVRequestFactory;
19
use CalDAVClient\Facade\Requests\CalendarQueryFilter;
20
use CalDAVClient\Facade\Requests\EventRequestVO;
21
use CalDAVClient\Facade\Requests\MakeCalendarRequestVO;
22
use CalDAVClient\Facade\Responses\CalendarDeletedResponse;
23
use CalDAVClient\Facade\Responses\CalendarHomesResponse;
24
use CalDAVClient\Facade\Responses\CalendarSyncInfoResponse;
25
use CalDAVClient\Facade\Responses\EventCreatedResponse;
26
use CalDAVClient\Facade\Responses\EventDeletedResponse;
27
use CalDAVClient\Facade\Responses\EventUpdatedResponse;
28
use CalDAVClient\Facade\Responses\GetCalendarResponse;
29
use CalDAVClient\Facade\Responses\GetCalendarsResponse;
30
use CalDAVClient\Facade\Responses\ResourceCollectionResponse;
31
use CalDAVClient\Facade\Responses\UserPrincipalResponse;
32
use CalDAVClient\Facade\Utils\RequestFactory;
33
use CalDAVClient\ICalDavClient;
34
use CalDAVClient\Facade\Exceptions\NotFoundResourceException;
35
use CalDAVClient\Facade\Exceptions\ServerErrorException;
36
use CalDAVClient\Facade\Exceptions\UserUnAuthorizedException;
37
use GuzzleHttp\Client;
38
use GuzzleHttp\Exception\ClientException;
39
use GuzzleHttp\Psr7\Request;
40
41
/**
42
 * Class CalDavClient
43
 * @package CalDAVClient\Facade
44
 */
45
final class CalDavClient implements ICalDavClient
46
{
47
48
    /**
49
     * As indicated in Section 3.10 of [RFC2445], the URL of calendar object
50
     * resources containing (an arbitrary set of) calendaring and scheduling
51
     * information may be suffixed by ".ics", and the URL of calendar object
52
     * resources containing free or busy time information may be suffixed by
53
     * ".ifb".
54
     */
55
56
    const SchedulingInformationSuffix   = '.ics';
57
58
    const FreeBusyTimeInformationSuffix = '.ics';
59
60
    const ETagHeader           = 'ETag';
61
62
    const DAVHeader            = 'DAV';
63
64
    const CalendarAccessOption = 'calendar-access';
65
66
    const DefaultAuthType      = 'basic';
67
68
    /**
69
     * @var string
70
     */
71
    private $server_url;
72
73
    /**
74
     * @var string
75
     */
76
    private $user;
77
78
    /**
79
     * @var string
80
     */
81
    private $password;
82
83
    /**
84
     * @var string
85
     */
86
    private $authtype = self::DefaultAuthType;
87
88
    /**
89
     * @var Client
90
     */
91
    private $client;
92
93
    /**
94
     * @var int
95
     */
96
    private $timeout = 60;
97
98
    /**
99
     * @var array
100
     */
101
    private $headers = [];
102
103
    /**
104
     * CalDavClient constructor.
105
     * @param string $server_url
106
     * @param string|null $user
107
     * @param string|null $password
108
     * @param string $authtype
109
     * @param array $headers Additional headers to send with each request
110
     */
111
    public function __construct($server_url, $user = null, $password = null, $authtype = self::DefaultAuthType, $headers=[])
112
    {
113
        $this->server_url = $server_url;
114
        $this->user       = $user;
115
        $this->password   = $password;
116
        $this->authtype   = $authtype;
117
        $this->setHeaders($headers);
118
119
        $this->client     = new Client();
120
    }
121
122
    /**
123
     * @param string $server_url
124
     * @return void
125
     */
126
    public function setServerUrl($server_url)
127
    {
128
        $this->server_url = $server_url;
129
    }
130
131
    /**
132
     * @param string $username
133
     * @param string $password
134
     * @return void
135
     */
136
    public function setCredentials($username, $password)
137
    {
138
        $this->user     = $username;
139
        $this->password = $password;
140
    }
141
142
    public function setAuthenticationType($authtype) {
143
        $this->authtype = $authtype;
144
    }
145
146
    /**
147
     * Set headers that will be sent with each request
148
     *
149
     * @param array $headers
150
     */
151
    public function setHeaders($headers = []) {
152
        $this->headers = $headers;
153
    }
154
    
155
    /**
156
     * @param Request $http_request
157
     * @return mixed|\Psr\Http\Message\ResponseInterface
158
     * @throws \GuzzleHttp\Exception\GuzzleException
159
     */
160
    private function makeRequest(Request $http_request){
161
        try{
162
            $options = [
163
                'timeout' => $this->timeout
164
            ];
165
            switch (strtolower(trim($this->authtype))) {
166
                case "basic":
167
                case "digest":
168
                case "ntlm":
169
                    $options['auth'] = [$this->user, $this->password, $this->authtype];
170
                    break;
171
            }
172
173
            if (!empty($this->headers)) {
174
                $options['headers'] = $this->headers;
175
            }
176
177
            return $this->client->send($http_request, $options);
178
        }
179
        catch (ClientException $ex){
180
            switch($ex->getCode()){
181
                case 401:
182
                    throw new UserUnAuthorizedException();
183
                    break;
184
                case 403:
185
                    throw new ForbiddenException();
186
                    break;
187
                case 404:
188
                    throw new NotFoundResourceException();
189
                    break;
190
                case 409:
191
                    throw new ConflictException($ex->getMessage(), $ex->getCode());
192
                    break;
193
                default:
194
                    throw new ServerErrorException($ex->getMessage(), $ex->getCode());
195
                    break;
196
            }
197
        }
198
    }
199
200
    /**
201
     * @return bool
202
     * @throws \GuzzleHttp\Exception\GuzzleException
203
     */
204
    public function isValidServer()
205
    {
206
207
        $http_response = $this->makeRequest(
208
            RequestFactory::createOptionsRequest($this->server_url)
209
        );
210
211
        $res     = $http_response->hasHeader(self::DAVHeader);
212
        $options = [];
213
        if($res){
214
            $val = $http_response->getHeaderLine(self::DAVHeader);
215
            if(!empty($val)){
216
                $options = explode(', ', $val);
217
            }
218
        }
219
220
        return $res && count($options) > 0 && in_array(self::CalendarAccessOption, $options);
221
    }
222
223
    /**
224
     * @return UserPrincipalResponse
225
     */
226
    public function getUserPrincipal()
227
    {
228
        $http_response = $this->makeRequest(
229
            RequestFactory::createPropFindRequest
230
            (
231
                $this->server_url,
232
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::PrincipalRequestType)->getContent(),
233
                0
234
            )
235
        );
236
237
        return new UserPrincipalResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
238
    }
239
240
    /**
241
     * @param string $principal_url
242
     * @return CalendarHomesResponse
243
     * @throws \GuzzleHttp\Exception\GuzzleException
244
     */
245
    public function getCalendarHome($principal_url)
246
    {
247
        $http_response = $this->makeRequest(
248
            RequestFactory::createPropFindRequest
249
            (
250
                $principal_url,
251
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarHomeRequestType)->getContent(),
252
                0
253
            )
254
        );
255
256
        return new CalendarHomesResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
257
    }
258
259
    /**
260
     * @param string $calendar_home_set
261
     * @param MakeCalendarRequestVO $vo
262
     * @see https://tools.ietf.org/html/rfc4791#section-5.3.1
263
     * @return string|boolean
264
     * @throws \GuzzleHttp\Exception\GuzzleException
265
     */
266
    public function createCalendar($calendar_home_set, MakeCalendarRequestVO $vo)
267
    {
268
        $uid           = $vo->getUID();
269
        $resource_name = $vo->getResourceName();
270
271
        $resource_url  = $calendar_home_set . ($resource_name ? $resource_name : $uid);
272
        $http_response = $this->makeRequest(
273
            RequestFactory::createMakeCalendarRequest
274
            (
275
                $resource_url,
276
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarCreateRequestType, [$vo])->getContent()
277
            )
278
        );
279
280
        return $http_response->getStatusCode() == 201 ? $resource_url : false;
281
    }
282
283
    /**
284
     * @param string $calendar_home_set_url
285
     * @return GetCalendarsResponse
286
     * @throws \GuzzleHttp\Exception\GuzzleException
287
     */
288
    public function getCalendars($calendar_home_set_url)
289
    {
290
        $http_response = $this->makeRequest(
291
            RequestFactory::createPropFindRequest
292
            (
293
                $calendar_home_set_url,
294
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarsRequestType)->getContent()
295
            )
296
        );
297
298
        return new GetCalendarsResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
299
    }
300
301
    /**
302
     * @param string $calendar_url
303
     * @return GetCalendarResponse
304
     * @throws \GuzzleHttp\Exception\GuzzleException
305
     */
306
    public function getCalendar($calendar_url)
307
    {
308
        $http_response = $this->makeRequest(
309
            RequestFactory::createPropFindRequest
310
            (
311
                $calendar_url,
312
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarRequestType)->getContent(),
313
                0
314
            )
315
        );
316
317
        return new GetCalendarResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
318
    }
319
320
321
    /**
322
     * @param string $calendar_url
323
     * @param string $sync_token
324
     * @return CalendarSyncInfoResponse
325
     * @throws \GuzzleHttp\Exception\GuzzleException
326
     */
327
    public function getCalendarSyncInfo($calendar_url, $sync_token)
328
    {
329
330
        $http_response = $this->makeRequest(
331
            RequestFactory::createReportRequest
332
            (
333
                $calendar_url,
334
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarSyncRequestType, [$sync_token])->getContent()
335
            )
336
        );
337
338
        return new CalendarSyncInfoResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
339
    }
340
341
    /**
342
     * @param string $calendar_url
343
     * @param EventRequestVO $vo
344
     * @return EventCreatedResponse
345
     * @throws \GuzzleHttp\Exception\GuzzleException
346
     */
347
    public function createEvent($calendar_url, EventRequestVO $vo)
348
    {
349
        $uid           = $vo->getUID();
350
        $resource_url  = $calendar_url.$uid.self::SchedulingInformationSuffix;
351
        $http_response = $this->makeRequest(
352
            RequestFactory::createPutRequest
353
            (
354
                $resource_url,
355
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::EventCreateRequestType, [$vo])->getContent()
356
            )
357
        );
358
        $etag = $http_response->hasHeader(self::ETagHeader) ? $http_response->getHeaderLine(self::ETagHeader) : null;
359
        return new EventCreatedResponse
360
        (
361
            $uid,
362
            $etag,
363
            $resource_url,
364
            (string)$http_response->getBody(),
365
            $http_response->getStatusCode()
366
        );
367
    }
368
369
    /**
370
     * @param string $calendar_url
371
     * @param EventRequestVO $vo
372
     * @param string $etag
373
     * @return EventUpdatedResponse
374
     * @throws \GuzzleHttp\Exception\GuzzleException
375
     */
376
    public function updateEvent($calendar_url, EventRequestVO $vo, $etag = null)
377
    {
378
        $uid           = $vo->getUID();
379
        $resource_url  = $calendar_url.$uid.self::SchedulingInformationSuffix;
380
        $http_response = $this->makeRequest(
381
            RequestFactory::createPutRequest
382
            (
383
                $resource_url,
384
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::EventUpdateRequestType, [$vo])->getContent(),
385
                $etag
386
            )
387
        );
388
        $etag = $http_response->hasHeader(self::ETagHeader) ? $http_response->getHeaderLine(self::ETagHeader) : null;
389
        return new EventUpdatedResponse
390
        (
391
            $uid,
392
            $etag,
393
            $resource_url,
394
            (string)$http_response->getBody(),
395
            $http_response->getStatusCode()
396
        );
397
    }
398
399
    /**
400
     * @param string $calendar_url
401
     * @param string $uid
402
     * @param string $etag
403
     * @return EventDeletedResponse
404
     * @throws \GuzzleHttp\Exception\GuzzleException
405
     */
406
    public function deleteEvent($calendar_url, $uid, $etag = null)
407
    {
408
        $http_response = $this->makeRequest(
409
            RequestFactory::createDeleteRequest
410
            (
411
                $calendar_url.$uid.self::SchedulingInformationSuffix,
412
                $etag
413
            )
414
        );
415
416
        return new EventDeletedResponse
417
        (
418
            (string)$http_response->getBody(), $http_response->getStatusCode()
419
        );
420
    }
421
422
    /**
423
     * @param string $event_url
424
     * @return string
425
     * @throws \GuzzleHttp\Exception\GuzzleException
426
     */
427
    public function getEventVCardBy($event_url){
428
        $http_response = $this->makeRequest(
429
            RequestFactory::createGetRequest
430
            (
431
                $event_url
432
            )
433
        );
434
435
        $ical = (string)$http_response->getBody();
436
        return $ical;
437
    }
438
439
    /**
440
     * @param string $calendar_url
441
     * @param array $events_urls
442
     * @return ResourceCollectionResponse
443
     * @throws \GuzzleHttp\Exception\GuzzleException
444
     */
445
    public function getEventsBy($calendar_url, array $events_urls)
446
    {
447
        $http_response = $this->makeRequest(
448
            RequestFactory::createReportRequest
449
            (
450
                $calendar_url,
451
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarMultiGetRequestType, [$events_urls])->getContent()
452
            )
453
        );
454
455
        return new ResourceCollectionResponse
456
        (
457
            $this->server_url,
458
            (string)$http_response->getBody(),
459
            $http_response->getStatusCode()
460
        );
461
    }
462
463
    /**
464
     * @param string $calendar_url
465
     * @param CalendarQueryFilter $filter
466
     * @return ResourceCollectionResponse
467
     * @throws \GuzzleHttp\Exception\GuzzleException
468
     */
469
    public function getEventsByQuery($calendar_url, CalendarQueryFilter $filter)
470
    {
471
472
        $http_response = $this->makeRequest(
473
            RequestFactory::createReportRequest
474
            (
475
                $calendar_url,
476
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarQueryRequestType, [$filter])->getContent()
477
            )
478
        );
479
480
        return new ResourceCollectionResponse
481
        (
482
            $this->server_url,
483
            (string)$http_response->getBody(),
484
            $http_response->getStatusCode()
485
        );
486
    }
487
488
    /**
489
     * @param string $calendar_url
490
     * @param string|null $etag
491
     * @return CalendarDeletedResponse
492
     * @throws \GuzzleHttp\Exception\GuzzleException
493
     */
494
    public function deleteCalendar($calendar_url, $etag = null)
495
    {
496
        $http_response = $this->makeRequest(
497
            RequestFactory::createDeleteRequest
498
            (
499
                $calendar_url,
500
                $etag
501
            )
502
        );
503
504
        return new CalendarDeletedResponse
505
        (
506
            (string)$http_response->getBody(), $http_response->getStatusCode()
507
        );
508
    }
509
}
510