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.
Passed
Push — master ( d37d24...53797f )
by sebastian
12:33
created

CalDavClient::getEventVCardBy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
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
            )
234
        );
235
236
        return new UserPrincipalResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
237
    }
238
239
    /**
240
     * @param string $principal_url
241
     * @return CalendarHomesResponse
242
     * @throws \GuzzleHttp\Exception\GuzzleException
243
     */
244
    public function getCalendarHome($principal_url)
245
    {
246
        $http_response = $this->makeRequest(
247
            RequestFactory::createPropFindRequest
248
            (
249
                $principal_url,
250
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarHomeRequestType)->getContent()
251
            )
252
        );
253
254
        return new CalendarHomesResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
255
    }
256
257
    /**
258
     * @param string $calendar_home_set
259
     * @param MakeCalendarRequestVO $vo
260
     * @see https://tools.ietf.org/html/rfc4791#section-5.3.1
261
     * @return string|boolean
262
     * @throws \GuzzleHttp\Exception\GuzzleException
263
     */
264
    public function createCalendar($calendar_home_set, MakeCalendarRequestVO $vo)
265
    {
266
        $uid           = $vo->getUID();
267
        $resource_name = $vo->getResourceName();
268
269
        $resource_url  = $calendar_home_set . ($resource_name ? $resource_name : $uid);
270
        $http_response = $this->makeRequest(
271
            RequestFactory::createMakeCalendarRequest
272
            (
273
                $resource_url,
274
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarCreateRequestType, [$vo])->getContent()
275
            )
276
        );
277
278
        return $http_response->getStatusCode() == 201 ? $resource_url : false;
279
    }
280
281
    /**
282
     * @param string $calendar_home_set_url
283
     * @return GetCalendarsResponse
284
     * @throws \GuzzleHttp\Exception\GuzzleException
285
     */
286
    public function getCalendars($calendar_home_set_url)
287
    {
288
        $http_response = $this->makeRequest(
289
            RequestFactory::createPropFindRequest
290
            (
291
                $calendar_home_set_url,
292
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarsRequestType)->getContent()
293
            )
294
        );
295
296
        return new GetCalendarsResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
297
    }
298
299
    /**
300
     * @param string $calendar_url
301
     * @return GetCalendarResponse
302
     * @throws \GuzzleHttp\Exception\GuzzleException
303
     */
304
    public function getCalendar($calendar_url)
305
    {
306
        $http_response = $this->makeRequest(
307
            RequestFactory::createPropFindRequest
308
            (
309
                $calendar_url,
310
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarRequestType)->getContent(),
311
                0
312
            )
313
        );
314
315
        return new GetCalendarResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
316
    }
317
318
319
    /**
320
     * @param string $calendar_url
321
     * @param string $sync_token
322
     * @return CalendarSyncInfoResponse
323
     * @throws \GuzzleHttp\Exception\GuzzleException
324
     */
325
    public function getCalendarSyncInfo($calendar_url, $sync_token)
326
    {
327
328
        $http_response = $this->makeRequest(
329
            RequestFactory::createReportRequest
330
            (
331
                $calendar_url,
332
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarSyncRequestType, [$sync_token])->getContent()
333
            )
334
        );
335
336
        return new CalendarSyncInfoResponse($this->server_url, (string)$http_response->getBody(), $http_response->getStatusCode());
337
    }
338
339
    /**
340
     * @param string $calendar_url
341
     * @param EventRequestVO $vo
342
     * @return EventCreatedResponse
343
     * @throws \GuzzleHttp\Exception\GuzzleException
344
     */
345
    public function createEvent($calendar_url, EventRequestVO $vo)
346
    {
347
        $uid           = $vo->getUID();
348
        $resource_url  = $calendar_url.$uid.self::SchedulingInformationSuffix;
349
        $http_response = $this->makeRequest(
350
            RequestFactory::createPutRequest
351
            (
352
                $resource_url,
353
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::EventCreateRequestType, [$vo])->getContent()
354
            )
355
        );
356
        $etag = $http_response->hasHeader(self::ETagHeader) ? $http_response->getHeaderLine(self::ETagHeader) : null;
357
        return new EventCreatedResponse
358
        (
359
            $uid,
360
            $etag,
361
            $resource_url,
362
            (string)$http_response->getBody(),
363
            $http_response->getStatusCode()
364
        );
365
    }
366
367
    /**
368
     * @param string $calendar_url
369
     * @param EventRequestVO $vo
370
     * @param string $etag
371
     * @return EventUpdatedResponse
372
     * @throws \GuzzleHttp\Exception\GuzzleException
373
     */
374
    public function updateEvent($calendar_url, EventRequestVO $vo, $etag = null)
375
    {
376
        $uid           = $vo->getUID();
377
        $resource_url  = $calendar_url.$uid.self::SchedulingInformationSuffix;
378
        $http_response = $this->makeRequest(
379
            RequestFactory::createPutRequest
380
            (
381
                $resource_url,
382
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::EventUpdateRequestType, [$vo])->getContent(),
383
                $etag
384
            )
385
        );
386
        $etag = $http_response->hasHeader(self::ETagHeader) ? $http_response->getHeaderLine(self::ETagHeader) : null;
387
        return new EventUpdatedResponse
388
        (
389
            $uid,
390
            $etag,
391
            $resource_url,
392
            (string)$http_response->getBody(),
393
            $http_response->getStatusCode()
394
        );
395
    }
396
397
    /**
398
     * @param string $calendar_url
399
     * @param string $uid
400
     * @param string $etag
401
     * @return EventDeletedResponse
402
     * @throws \GuzzleHttp\Exception\GuzzleException
403
     */
404
    public function deleteEvent($calendar_url, $uid, $etag = null)
405
    {
406
        $http_response = $this->makeRequest(
407
            RequestFactory::createDeleteRequest
408
            (
409
                $calendar_url.$uid.self::SchedulingInformationSuffix,
410
                $etag
411
            )
412
        );
413
414
        return new EventDeletedResponse
415
        (
416
            (string)$http_response->getBody(), $http_response->getStatusCode()
417
        );
418
    }
419
420
    /**
421
     * @param string $event_url
422
     * @return string
423
     * @throws \GuzzleHttp\Exception\GuzzleException
424
     */
425
    public function getEventVCardBy($event_url){
426
        $http_response = $this->makeRequest(
427
            RequestFactory::createGetRequest
428
            (
429
                $event_url
430
            )
431
        );
432
433
        $ical = (string)$http_response->getBody();
434
        return $ical;
435
    }
436
437
    /**
438
     * @param string $calendar_url
439
     * @param array $events_urls
440
     * @return ResourceCollectionResponse
441
     * @throws \GuzzleHttp\Exception\GuzzleException
442
     */
443
    public function getEventsBy($calendar_url, array $events_urls)
444
    {
445
        $http_response = $this->makeRequest(
446
            RequestFactory::createReportRequest
447
            (
448
                $calendar_url,
449
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarMultiGetRequestType, [$events_urls])->getContent()
450
            )
451
        );
452
453
        return new ResourceCollectionResponse
454
        (
455
            $this->server_url,
456
            (string)$http_response->getBody(),
457
            $http_response->getStatusCode()
458
        );
459
    }
460
461
    /**
462
     * @param string $calendar_url
463
     * @param CalendarQueryFilter $filter
464
     * @return ResourceCollectionResponse
465
     * @throws \GuzzleHttp\Exception\GuzzleException
466
     */
467
    public function getEventsByQuery($calendar_url, CalendarQueryFilter $filter)
468
    {
469
470
        $http_response = $this->makeRequest(
471
            RequestFactory::createReportRequest
472
            (
473
                $calendar_url,
474
                CalDAVRequestFactory::getInstance()->build(CalDAVRequestFactory::CalendarQueryRequestType, [$filter])->getContent()
475
            )
476
        );
477
478
        return new ResourceCollectionResponse
479
        (
480
            $this->server_url,
481
            (string)$http_response->getBody(),
482
            $http_response->getStatusCode()
483
        );
484
    }
485
486
    /**
487
     * @param string $calendar_url
488
     * @param string|null $etag
489
     * @return CalendarDeletedResponse
490
     * @throws \GuzzleHttp\Exception\GuzzleException
491
     */
492
    public function deleteCalendar($calendar_url, $etag = null)
493
    {
494
        $http_response = $this->makeRequest(
495
            RequestFactory::createDeleteRequest
496
            (
497
                $calendar_url,
498
                $etag
499
            )
500
        );
501
502
        return new CalendarDeletedResponse
503
        (
504
            (string)$http_response->getBody(), $http_response->getStatusCode()
505
        );
506
    }
507
}
508