DAVTalk.pm

filter: Statementstmt 61.7% 171 / 277 Branchbran 53.7% 71 / 132 Conditioncond 37.7% 23 / 61 MC/DCmcdc 16.2% 6 / 37 Subroutinesub 75.0% 24 / 32 Podpod 100% 19 / 19 totaltotal 56.2% 314 / 558 CC 98 SCAR 40.4
CC
98
Cov
56%
GetPropsArray
240.0
SafeRequest
93.5
GetCurrentUserPrincipal
42.0
CRAP 57.0
↑ Summary DAVTalk/XMLParser.pm »
1 package Net::DAVTalk;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use DateTime::Format::ISO8601;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use DateTime::TimeZone;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Tie::DataUUID qw{$uuid};
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use XML::Spice;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶use Net::DAVTalk::XMLParser;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use MIME::Base64 qw(encode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 4 ▶use Encode qw(encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use URI::Escape qw(uri_escape uri_unescape);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 4 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 =head1 NAME
19  
20 Net::DAVTalk - Interface to talk to DAV servers
21  
22 =head1 VERSION
23  
24 Version 0.24
25  
26 =cut
27  
28 4 our $VERSION = '0.26';
29  
30 =head1 SYNOPSIS
31  
32 Net::DAVTalk is was originally designed as a service module for Net::CalDAVTalk
33 and Net::CardDAVTalk, abstracting the process of connecting to a DAV server and
34 parsing the XML responses.
35  
36 Example:
37  
38 use Net::DAVTalk;
39 use XML::Spice;
40  
41 my $davtalk = Net::DAVTalk->new(
42 url => "https://dav.example.com/",
43 user => "foo\@example.com",
44 password => "letmein",
45 headers => { Cookie => "123", Referer => "456" },
46 );
47  
48 $davtalk->Request(
49 'MKCALENDAR',
50 "$calendarId/",
51 x('C:mkcalendar', $Self->NS(),
52 x('D:set',
53 x('D:prop', @Properties),
54 ),
55 ),
56 );
57  
58 $davtalk->Request(
59 'DELETE',
60 "$calendarId/",
61 );
62  
63 =head1 SUBROUTINES/METHODS
64  
65 =head2 $class->new(%Options)
66  
67 Options:
68  
69 url: either full https?:// url, or relative base path on the
70 server to the DAV endpoint
71  
72 host, scheme and port: alternative to using full URL.
73 If URL doesn't start with https?:// then these will be used to
74 construct the endpoint URI.
75  
76 expandurl and wellknown: if these are set, then the wellknown
77 name (caldav and carddav are both defined) will be used to
78 resolve /.well-known/$wellknown to find the current-user-principal
79 URI, and then THAT will be resovlved to find the $wellknown-home-set
80 URI, which will be used as the URL for all further actions on
81 this object.
82  
83 user and password: if these are set, perform basic authentication.
84 user and access_token: if these are set, perform Bearer (OAUTH2)
85 authentication.
86  
87 headers: a hashref of additional headers to add to every request
88  
89 SSL_options: a hashref of SSL options to pass down to the default
90 user agent
91 =cut
92  
93 # General methods
94  
95 10 ▶sub new {
Subroutine new: called CC=4 SCAR=17.0
Pod documented
96 10 my ($Class, %Params) = @_;
97  
98 10 ▶ unless ($Params{url}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Params{"url"}) 0 10 10
99 0 confess "URL not supplied";
100 }
101  
102 # Assume url points to xyz-home-set, otherwise expand the url
103 10 ▶ if (delete $Params{expandurl}) {
Branch: 1 branch
BranchTrueFalseTotal
if (delete $Params{"expandurl"}) 0 10 10
104 # Locating Services for CalDAV and CardDAV (RFC6764)
105 0 my $PrincipalURL = $Class->GetCurrentUserPrincipal(%Params);
106 0 $Params{principal} = $PrincipalURL;
107  
108 0 my $HomeSet = $Class->GetHomeSet(
109 %Params,
110 url => $PrincipalURL,
111 );
112  
113 0 $Params{url} = $HomeSet;
114 }
115  
116 10 ▶ my $Self = bless \%Params, ref($Class) || $Class;
Condition33%1/3
ref $Class || $Class
l!l&&r!l&&!r
0100
MC/DC0%0/2
ref $Class || $Class
ref $Class $Class
Truth table33%1/3
A || B
A= ref $ClassB= $Class
ABresult
1X1
011
000
117 10 $Self->SetURL($Params{url});
118 10 $Self->SetPrincipalURL($Params{principal});
119 10 $Self->ns(D => 'DAV:');
120  
121 10 return $Self;
122 }
123  
124 =head2 my $ua = $Self->ua();
125 =head2 $Self->ua($setua);
126  
127 Get or set the useragent (HTTP::Tiny or compatible) that will be used to make
128 the requests:
129  
130 e.g.
131  
132 my $ua = $Self->ua();
133  
134 $Self->ua(HTTP::Tiny->new(agent => "MyAgent/1.0", timeout => 5));
135  
136 =cut
137  
138 23 ▶sub ua {
Subroutine ua: called CC=3 SCAR=11.2
Pod documented
139 23 my $Self = shift;
140 23 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 9 14 23
141 9 $Self->{ua} = shift;
142 }
143 else {
144 $Self->{ua} ||= HTTP::Tiny->new(
145 agent => "Net-DAVTalk/$VERSION",
146 SSL_options => $Self->{SSL_options},
147 14 ▶ );
Condition33%1/3
$Self->{"ua"} ||= "HTTP::Tiny"->new("agent", "Net-DAVTalk/$Net::DAVTalk::VERSION", "SSL_options", $Self->{"SSL_options"})
l!l&&r!l&&!r
1400
MC/DC0%0/2
$Self->{"ua"} ||= "HTTP::Tiny"->new("agent", "Net-DAVTalk/$Net::DAVTalk::VERSION", "SSL_options", $Self->{"SSL_options"})
$Self->{"ua"} "HTTP::Tiny"->new("agent", "Net-DAVTalk/$Net::DAVTalk::VERSION", "SSL_options", $Self->{"SSL_options"})
Truth table33%1/3
A ||= B
A= $Self->{"ua"}B= "HTTP::Tiny"->new("agent", "Net-DAVTalk/$Net::DAVTalk::VERSION", "SSL_options", $Self->{"SSL_options"})
ABresult
1X1
011
000
148 }
149 23 return $Self->{ua};
150 }
151  
152 =head2 $Self->SetURL($url)
153  
154 Change the endpoint URL for an existing connection.
155  
156 =cut
157  
158 10 ▶sub SetURL {
Subroutine SetURL: called CC=6 SCAR=18.8
Pod documented
159 10 my ($Self, $URL) = @_;
160  
161 10 $URL =~ s{/$}{}; # remove any trailing slash
162  
163 10 ▶ if ($URL =~ m{^https?://}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($URL =~ m[^https?://]) { } 10 0 10
164 10 my ($HTTPS, $Hostname, $Port, $BasePath)
165 = $URL =~ m{^http(s)?://([^/:]+)(?::(\d+))?(.*)?};
166  
167 10 ▶ unless ($Hostname) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Hostname) 0 10 10
168 0 confess "Invalid hostname in '$URL'";
169 }
170  
171 10 ▶ $Self->{scheme} = $HTTPS ? 'https' : 'http';
Branch: 1 branch
BranchTrueFalseTotal
$HTTPS ? : 1 9 10
172 10 $Self->{host} = $Hostname;
173 10 ▶ $Self->{port} = ($Port || ($HTTPS ? 443 : 80));
Branch: 1 branch
BranchTrueFalseTotal
$HTTPS ? : 1 9 10
Condition33%1/3
$Port || ($HTTPS ? 443 : 80)
l!l&&r!l&&!r
0100
MC/DC0%0/2
$Port || ($HTTPS ? 443 : 80)
$Port ($HTTPS ? 443 : 80)
Truth table33%1/3
A || B
A= $PortB= ($HTTPS ? 443 : 80)
ABresult
1X1
011
000
174 10 $Self->{basepath} = $BasePath;
175 }
176 else {
177 0 $Self->{basepath} = $URL;
178 }
179  
180 10 $Self->{url} = "$Self->{scheme}://$Self->{host}:$Self->{port}$Self->{basepath}";
181  
182 10 return $Self->{url};
183 }
184  
185 =head2 $Self->SetPrincipalURL($url)
186  
187 Set the URL to the DAV Principal
188  
189 =cut
190  
191 10 ▶sub SetPrincipalURL {
Subroutine SetPrincipalURL: called CC=1 SCAR=0.0
Pod documented
192 10 my ($Self, $PrincipalURL) = @_;
193  
194 10 return $Self->{principal} = $PrincipalURL;
195 }
196  
197 =head2 $Self->fullpath($shortpath)
198  
199 Convert from a relative path to a full path:
200  
201 e.g
202 my $path = $Dav->fullpath('Default');
203 ## /dav/calendars/user/foo/Default
204  
205 NOTE: a you can pass a non-relative full path (leading /)
206 to this function and it will be returned unchanged.
207  
208 =cut
209  
210 0 ▶sub fullpath {
Subroutine fullpath: not called CC=2 SCAR=17.9
Pod documented
211 0 my $Self = shift;
212 0 my $path = shift;
213 0 my $basepath = $Self->{basepath};
214 0 ▶ return $path if $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
if $path =~ m[^/] 0 0 0
215 0 return "$basepath/$path";
216 }
217  
218 =head2 $Self->shortpath($fullpath)
219  
220 Convert from a full path to a relative path
221  
222 e.g
223 my $path = $Dav->fullpath('/dav/calendars/user/foo/Default');
224 ## Default
225  
226 NOTE: if the full path is outside the basepath of the object, it
227 will be unchanged.
228  
229 my $path = $Dav->fullpath('/dav/calendars/user/bar/Default');
230 ## /dav/calendars/user/bar/Default
231  
232 =cut
233  
234 0 ▶sub shortpath {
Subroutine shortpath: not called CC=2 SCAR=17.9
Pod documented
235 0 my $Self = shift;
236 0 my $origpath = shift;
237 0 my $basepath = $Self->{basepath};
238 0 my $path = $origpath;
239 0 $path =~ s{^$basepath/?}{};
240 0 ▶ return ($path eq '' ? $origpath : $path);
Branch: 1 branch
BranchTrueFalseTotal
$path eq '' ? : 0 0 0
241 }
242  
243 =head2 $Self->Request($method, $path, $content, %headers)
244  
245 The whole point of the module! Perform a DAV request against the
246 endpoint, returning the response as a parsed hash.
247  
248 method: http method, i.e. GET, PROPFIND, MKCOL, DELETE, etc
249  
250 path: relative to base url. With a leading slash, relative to
251 server root, i.e. "Default/", "/dav/calendars/user/foo/Default".
252  
253 content: if the method takes a body, raw bytes to send
254  
255 headers: additional headers to add to request, i.e (Depth => 1)
256  
257 In the event of timeout or most HTTP errors, an exception will be raised.
258  
259 =head2 $Self->SafeRequest($method, $path, $content, %headers)
260  
261 my $Result = $DAVTalk->SafeRequest($method, $path, $content, %headers)
262  
263 This is mostly Request, but it won't throw an exception on most errors.
264  
265 Instead, it always returns a reference to a hash with these entries:
266  
267 payload - a structured representation of the DAV response, if possible;
268 this is the same thing that the ->Request method returns
269 http_response - the underlying HTTP response from HTTP::Tiny
270 error - a string describing the error condition, if any
271  
272 The C<Request> method uses C<SafeRequest> under the hood, converting error
273 results into exceptions.
274  
275 =cut
276  
277 14 ▶sub SafeRequest {
Subroutine SafeRequest: called CC=26 SCAR=45.4
Pod documented
278 14 my ($Self, $Method, $Path, $Content, %Headers) = @_;
279  
280 # setup request {{{
281  
282 14 ▶ $Content = '' unless defined $Content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Content 0 14 14
283 14 my $Bytes = encode('UTF-8', $Content);
284  
285 14 my $ua = $Self->ua();
286  
287 14 ▶ $Headers{'Content-Type'} //= 'application/xml; charset=utf-8';
Condition50%1/2
$Headers{"Content-Type"} //= "application/xml; charset=utf-8"
l!l
014
MC/DC0%0/1
$Headers{"Content-Type"} //= "application/xml; charset=utf-8"
$Headers{"Content-Type"}
Truth table50%1/2
A
A= $Headers{"Content-Type"}
Aresult
11
00
288  
289 14 ▶ if ($Self->{user}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"user"}) 0 14 14
290 0 $Headers{'Authorization'} = $Self->auth_header();
291 }
292  
293 0 ▶ %Headers = (%Headers, %{$Self->{headers}}) if $Self->{headers};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"headers"} 0 14 14
294  
295 # XXX - Accept-Encoding for gzip, etc?
296  
297 # }}}
298  
299 # send request {{{
300  
301 14 my $URI = $Self->request_url($Path);
302  
303 14 my $Response = $ua->request($Method, $URI, {
304 headers => \%Headers,
305 content => $Bytes,
306 });
307  
308 14 ▶ if ($Response->{status} == '599' and $Response->{content} =~ m/timed out/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Response->{"status"} == 599 and $Response->{"content"} =~ /timed out/i) 0 14 14
Condition33%1/3
$Response->{"status"} == 599 and $Response->{"content"} =~ /timed out/i
!ll&&!rl&&r
1400
MC/DC0%0/2
$Response->{"status"} == 599 and $Response->{"content"} =~ /timed out/i
$Response->{"status"} == 599 $Response->{"content"} =~ /timed out/i
Truth table33%1/3
A and B
A= $Response->{"status"} == 599B= $Response->{"content"} =~ /timed out/i
ABresult
0X0
100
111
309 return {
310 0 http_response => $Response,
311 error => "Error with $Method for $URI (504, Gateway Timeout)",
312 };
313 }
314  
315 14 my $count = 0;
316 14 ▶ while ($Response->{status} =~ m{^30[1278]} and (++$count < 10)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Response->{"status"} =~ /^30[1278]/ and ++$count < 10) 0 14 14
Condition33%1/3
$Response->{"status"} =~ /^30[1278]/ and ++$count < 10
!ll&&!rl&&r
1400
MC/DC0%0/2
$Response->{"status"} =~ /^30[1278]/ and ++$count < 10
$Response->{"status"} =~ /^30[1278]/ ++$count < 10
Truth table33%1/3
A and B
A= $Response->{"status"} =~ /^30[1278]/B= ++$count < 10
ABresult
0X0
100
111
317 0 my $location = URI->new_abs($Response->{headers}{location}, $URI);
318 0 ▶ if ($ENV{DEBUGDAV}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"DEBUGDAV"}) 0 0 0
319 0 warn "******** REDIRECT ($count) $Response->{status} to $location\n";
320 }
321  
322 0 $Response = $ua->request($Method, $location, {
323 headers => \%Headers,
324 content => $Bytes,
325 });
326  
327 0 ▶ if ($Response->{status} == '599' and $Response->{content} =~ m/timed out/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Response->{"status"} == 599 and $Response->{"content"} =~ /timed out/i) 0 0 0
Condition0%0/3
$Response->{"status"} == 599 and $Response->{"content"} =~ /timed out/i
!ll&&!rl&&r
000
MC/DC0%0/2
$Response->{"status"} == 599 and $Response->{"content"} =~ /timed out/i
$Response->{"status"} == 599 $Response->{"content"} =~ /timed out/i
Truth table0%0/3
A and B
A= $Response->{"status"} == 599B= $Response->{"content"} =~ /timed out/i
ABresult
0X0
100
111
328 return {
329 0 http_response => $Response,
330 error => "Error with $Method for $location (504, Gateway Timeout)",
331 };
332 }
333 }
334  
335 # one is enough
336  
337 14 ▶ my $ResponseContent = $Response->{content} || '';
Condition50%1/2
$Response->{'content'} || ''
l!l
140
MC/DC0%0/1
$Response->{'content'} || ''
$Response->{'content'}
Truth table50%1/2
A
A= $Response->{'content'}
Aresult
11
00
338  
339 14 ▶ if ($ENV{DEBUGDAV}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"DEBUGDAV"}) 0 14 14
340 0 warn "<<<<<<<< $Method $URI HTTP/1.1\n$Bytes\n" .
341 ">>>>>>>> $Response->{protocol} $Response->{status} $Response->{reason}\n$ResponseContent\n" .
342 "========\n\n";
343 }
344  
345 14 ▶ if ($Method eq 'REPORT' && $Response->{status} == 403) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Method eq "REPORT" and $Response->{"status"} == 403) 0 14 14
Condition33%1/3
$Method eq "REPORT" and $Response->{"status"} == 403
!ll&&!rl&&r
0140
MC/DC0%0/2
$Method eq "REPORT" and $Response->{"status"} == 403
$Method eq "REPORT" $Response->{"status"} == 403
Truth table33%1/3
A and B
A= $Method eq "REPORT"B= $Response->{"status"} == 403
ABresult
0X0
100
111
346 # maybe invalid sync token, need to return that fact
347 0 my $Xml = xmlToHash($ResponseContent);
348 0 ▶ if (exists $Xml->{"{DAV:}valid-sync-token"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Xml->{"{DAV:}valid-sync-token"}) 0 0 0
349 # This weird "return error in payload" behavior is legacy behavior, and
350 # quite possibly should be changed. It's the only place we returned an
351 # "error" in the hashref from Request before writing SafeRequest.
352 # -- rjbs, 2026-02-11
353 return {
354 0 http_response => $Response,
355 payload => { error => "valid-sync-token" },
356 };
357 }
358 }
359  
360 14 ▶ unless ($Response->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Response->{"success"}) 0 14 14
361 return {
362 0 http_response => $Response,
363 error => "ERROR WITH REQUEST\n"
364 . "<<<<<<<< $Method $URI HTTP/1.1\n$Bytes\n"
365 . ">>>>>>>> $Response->{protocol} $Response->{status} $Response->{reason}\n$ResponseContent\n"
366 . "========\n\n",
367 };
368 }
369  
370 14 ▶ if ((grep { $Method eq $_ } qw{GET DELETE}) or ($Response->{status} != 207) or (not $ResponseContent)) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$Method eq $_;} "GET", "DELETE" or $Response->{"status"} != 207 or not $ResponseContent) 0 14 14
Condition33%2/6
grep {$Method eq $_;} "GET", "DELETE" or $Response->{"status"} != 207 or not $ResponseContent
l!l&&r!l&&!r
0014
grep {$Method eq $_;} "GET", "DELETE" or $Response->{"status"} != 207
l!l&&r!l&&!r
0014
MC/DC0%0/3
grep {$Method eq $_;} "GET", "DELETE" or $Response->{"status"} != 207 or not $ResponseContent
grep {$Method eq $_;} "GET", "DELETE" $Response->{"status"} != 207 not $ResponseContent
Truth table25%1/4
A or B or not(C)
A= grep {$Method eq $_;} "GET", "DELETE"B= $Response->{"status"} != 207C= not $ResponseContent
ABCresult
1XX1
01X1
0011
0000
371 return {
372 0 http_response => $Response,
373 payload => { content => $ResponseContent },
374 };
375 }
376  
377 # }}}
378  
379 # parse XML response {{{
380 14 my $Xml = xmlToHash($ResponseContent);
381  
382 # Normalise XML
383  
384 14 ▶ if (exists($Xml->{"{DAV:}response"})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Xml->{"{DAV:}response"}) 13 1 14
385 13 ▶ if (ref($Xml->{"{DAV:}response"}) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Xml->{"{DAV:}response"} ne "ARRAY") 5 8 13
386 5 $Xml->{"{DAV:}response"} = [ $Xml->{"{DAV:}response"} ];
387 }
388  
389 13 foreach my $Response (@{$Xml->{"{DAV:}response"}}) {
390 25 ▶ if (exists($Response->{"{DAV:}propstat"})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Response->{"{DAV:}propstat"}) 14 11 25
391 14 ▶ unless (ref($Response->{"{DAV:}propstat"}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $Response->{"{DAV:}propstat"} eq "ARRAY") 13 1 14
392 13 $Response->{"{DAV:}propstat"} = [$Response->{"{DAV:}propstat"}];
393 }
394 }
395 }
396 }
397  
398 return {
399 14 http_response => $Response,
400 payload => $Xml,
401 };
402  
403 # }}}
404 }
405  
406 14 ▶sub Request {
Subroutine Request: called CC=2 SCAR=7.4
Pod documented
407 14 my ($Self, @Rest) = @_;
408 14 my ($Struct) = $Self->SafeRequest(@Rest);
409  
410 14 ▶ if ($Struct->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Struct->{"error"}) 0 14 14
411 0 confess $Struct->{error};
412 }
413  
414 14 return $Struct->{payload};
415 }
416  
417 =head2 $Self->GetProps($Path, @Props)
418  
419 perform a propfind on a particular path and get the properties back
420  
421 =cut
422  
423 0 ▶sub GetProps {
Subroutine GetProps: not called CC=2 SCAR=17.9
Pod documented
424 0 my ($Self, $Path, @Props) = @_;
425 0 my @res = $Self->GetPropsArray($Path, @Props);
426 0 ▶ return wantarray ? map { $_->[0] } @res : $res[0][0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
427 }
428  
429 =head2 $Self->GetPropsArray($Path, @Props)
430  
431 perform a propfind on a particular path and get the properties back
432 as an array of one or more items
433  
434 =cut
435  
436 0 ▶sub GetPropsArray {
Subroutine GetPropsArray: not called CC=15 SCAR=54.8
Pod documented
437 0 my ($Self, $Path, @Props) = @_;
438  
439 # Fetch one or more properties.
440 # Use [ 'prop', 'sub', 'item' ] to dig into result structure
441  
442 0 my $NS_D = $Self->ns('D');
443  
444 my $Response = $Self->Request(
445 'PROPFIND',
446 $Path,
447 x('D:propfind', $Self->NS(),
448 x('D:prop',
449 0 ▶ map { ref $_ ? x($_->[0]): x($_) } @Props,
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 0 0
450 ),
451 ),
452 Depth => 0,
453 );
454  
455 0 my @Results;
456 0 ▶ foreach my $Response (@{$Response->{"{$NS_D}response"} || []}) {
Condition0%0/2
$$Response{"{$NS_D}response"} || []
l!l
00
MC/DC0%0/1
$$Response{"{$NS_D}response"} || []
$$Response{"{$NS_D}response"}
Truth table0%0/2
A
A= $$Response{"{$NS_D}response"}
Aresult
11
00
457 0 ▶ foreach my $Propstat (@{$Response->{"{$NS_D}propstat"} || []}) {
Condition0%0/2
$$Response{"{$NS_D}propstat"} || []
l!l
00
MC/DC0%0/1
$$Response{"{$NS_D}propstat"} || []
$$Response{"{$NS_D}propstat"}
Truth table0%0/2
A
A= $$Response{"{$NS_D}propstat"}
Aresult
11
00
458 0 ▶ my $PropData = $Propstat->{"{$NS_D}prop"} || next;
Condition0%0/2
$$Propstat{"{$NS_D}prop"} || (next)
l!l
00
MC/DC0%0/1
$$Propstat{"{$NS_D}prop"} || (next)
$$Propstat{"{$NS_D}prop"}
Truth table0%0/2
A
A= $$Propstat{"{$NS_D}prop"}
Aresult
11
00
459 0 for my $Prop (@Props) {
460 0 my @Values = ($PropData);
461  
462 # Array ref means we need to git through structure
463 0 ▶ foreach my $Key (ref $Prop ? @$Prop : $Prop) {
Branch: 1 branch
BranchTrueFalseTotal
ref $Prop ? : 0 0 0
464 0 my @New;
465 0 foreach my $Result (@Values) {
466 0 ▶ if ($Key =~ m/:/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Key =~ /:/) { } 0 0 0
467 0 my ($N, $P) = split /:/, $Key;
468 0 my $NS = $Self->ns($N);
469 0 $Result = $Result->{"{$NS}$P"};
470 } else {
471 0 $Result = $Result->{$Key};
472 }
473 0 ▶ if (ref($Result) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $Result eq 'ARRAY') { } 0 0 0
elsif (defined $Result) { } 0 0 0
474 0 push @New, @$Result;
475 }
476 elsif (defined $Result) {
477 0 push @New, $Result;
478 }
479 }
480 0 @Values = @New;
481 }
482  
483 0 push @Results, [ map { $_->{content} } @Values ];
484 }
485 }
486 }
487  
488 0 ▶ return wantarray ? @Results : $Results[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
489 }
490  
491 =head2 $Self->SyncCollection($Path, %Args)
492  
493 WebDAV Collection Synchronization (RFC 6578): a sync-collection REPORT
494 on the collection at $Path, at sync-level 1, from $Args{syncToken} or,
495 without one, from nothing (every member is reported as added).
496  
497 Returns, in list context:
498  
499 * Added: hash of href to etag - members added or changed
500 * Removed: array of href - members removed
501 * Errors: array of descriptive strings
502 * SyncToken: the new opaque DAV:sync-token
503  
504 and in scalar context just Added.
505  
506 A server may truncate the results (RFC 6578 section 3.6), marking the
507 response with a 507 status on the collection itself. The REPORT is then
508 repeated from the token that came with it until the results are whole,
509 so one call always reports every change; a member reported again in a
510 later round counts as what that round says. If a truncated response
511 comes back with the token it was asked from, the server is not moving
512 on: what has arrived so far is returned with an error.
513  
514 Dies if the server gives no sync-token: such a response cannot be
515 synced from again.
516  
517 Arguments:
518  
519 * syncToken - the token to sync from (none, undef or '' for a full sync)
520 * raw - return hrefs as the server wrote them, instead of unescaped as
521 every other href from this module is (see request_url)
522 * MaxRounds - give up (die) after this many truncated responses
523 (default 1000)
524  
525 =cut
526  
527 10 ▶sub SyncCollection {
Subroutine SyncCollection: called CC=27 SCAR=33.6
Pod documented
528 10 my ($Self, $Path, %Args) = @_;
529  
530 10 ▶ confess "Need a collection path" unless defined $Path and length $Path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Path and length $Path 0 10 10
Condition33%1/3
defined $Path and length $Path
!ll&&!rl&&r
0010
MC/DC0%0/2
defined $Path and length $Path
defined $Path length $Path
Truth table33%1/3
A and B
A= defined $PathB= length $Path
ABresult
0X0
100
111
531 10 $Path =~ s{/$}{};
532  
533 10 my $NS_D = $Self->ns('D');
534 10 my $Token = $Args{syncToken};
535 10 ▶ my $MaxRounds = defined $Args{MaxRounds} ? $Args{MaxRounds} : 1000;
Branch: 1 branch
BranchTrueFalseTotal
defined $Args{'MaxRounds'} ? : 1 9 10
536 10 my (%Added, %Removed, @Errors);
537  
538 10 for (my $Round = 1; ; $Round++) {
539 14 ▶ my $Response = $Self->Request(
Branch: 1 branch
BranchTrueFalseTotal
defined $Token && length $Token ? : 5 9 14
Condition66%2/3
defined $Token and length $Token
!ll&&!rl&&r
905
MC/DC50%1/2
defined $Token and length $Token
defined $Token length $Token
Truth table66%2/3
A and B
A= defined $TokenB= length $Token
ABresult
0X0
100
111
540 'REPORT',
541 "$Path/",
542 x('D:sync-collection', $Self->NS(),
543 x('D:sync-token', ((defined $Token and length $Token) ? ($Token) : ())),
544 x('D:sync-level', 1),
545 x('D:prop',
546 x('D:getetag'),
547 ),
548 ),
549 );
550  
551 14 my $NewToken = $Response->{"{$NS_D}sync-token"}{content};
552 14 ▶ confess "No sync-token in the sync-collection response for $Path"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $NewToken and length $NewToken 1 13 14
Condition66%2/3
defined $NewToken and length $NewToken
!ll&&!rl&&r
1013
MC/DC50%1/2
defined $NewToken and length $NewToken
defined $NewToken length $NewToken
Truth table66%2/3
A and B
A= defined $NewTokenB= length $NewToken
ABresult
0X0
100
111
553 unless defined $NewToken and length $NewToken;
554  
555 13 my $Truncated;
556 13 ▶ foreach my $Item (@{$Response->{"{$NS_D}response"} || []}) {
Condition100%2/2
$$Response{"{$NS_D}response"} || []
l!l
121
MC/DC100%1/1
$$Response{"{$NS_D}response"} || []
$$Response{"{$NS_D}response"}
Truth table100%2/2
A
A= $$Response{"{$NS_D}response"}
Aresult
11
00
557 24 my $href = $Item->{"{$NS_D}href"}{content};
558 24 ▶ next unless defined $href and length $href;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $href and length $href 0 24 24
Condition33%1/3
defined $href and length $href
!ll&&!rl&&r
0024
MC/DC0%0/2
defined $href and length $href
defined $href length $href
Truth table33%1/3
A and B
A= defined $hrefB= length $href
ABresult
0X0
100
111
559 24 ▶ $href = uri_unescape($href) unless $Args{raw};
Branch: 1 branch
BranchTrueFalseTotal
unless $Args{"raw"} 23 1 24
560  
561 # For members that have been removed, the DAV:response MUST
562 # contain one DAV:status with a value set to '404 Not Found' and
563 # MUST NOT contain any DAV:propstat element. A 507 there is on the
564 # request-URI itself, and says the results were truncated.
565 24 ▶ unless ($Item->{"{$NS_D}propstat"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($$Item{"{$NS_D}propstat"}) 11 13 24
566 11 my $Status = $Item->{"{$NS_D}status"}{content};
567 11 ▶ $Status = '' unless defined $Status;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Status 0 11 11
568 11 ▶ if ($Status =~ m/ 404 /) {
Branch: 2 branches
BranchTrueFalseTotal
if ($Status =~ / 404 /) { } 4 7 11
elsif ($Status =~ / 507 /) { } 6 1 7
569 4 delete $Added{$href};
570 4 $Removed{$href} = 1;
571 }
572 elsif ($Status =~ m/ 507 /) {
573 6 $Truncated = 1;
574 }
575 else {
576 1 push @Errors, "Odd status in non-propstat response $href: $Status";
577 }
578 11 next;
579 }
580  
581 # iCloud lists the collection itself, with an etag, among the
582 # changes (and refuses its URL in a multiget): a collection is not
583 # a member to sync
584 13 ▶ next if $href =~ m{/$};
Branch: 1 branch
BranchTrueFalseTotal
if $href =~ m[/$] 1 12 13
585  
586 # For members that have changed (i.e., are new or have had their
587 # mapped resource modified), the DAV:response MUST contain at
588 # least one DAV:propstat element and MUST NOT contain any
589 # DAV:status element.
590 12 foreach my $Propstat (@{$Item->{"{$NS_D}propstat"}}) {
591 13 my $Status = $Propstat->{"{$NS_D}status"}{content};
592 13 ▶ $Status = '' unless defined $Status;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Status 0 13 13
593 13 ▶ if ($Status =~ m/ 200 /) {
Branch: 2 branches
BranchTrueFalseTotal
if ($Status =~ / 200 /) { } 12 1 13
elsif ($Status =~ / 404 /) { } 1 0 1
594 12 $Added{$href} = $Propstat->{"{$NS_D}prop"}{"{$NS_D}getetag"}{content};
595 12 delete $Removed{$href};
596 }
597 elsif ($Status =~ m/ 404 /) {
598 # a property the server does not have: not an error
599 }
600 else {
601 0 push @Errors, "Odd status in propstat response $href: $Status";
602 }
603 }
604 }
605  
606 13 ▶ my $Stuck = (defined $Token and $NewToken eq $Token);
Condition100%3/3
defined $Token && $NewToken eq $Token
!ll&&!rl&&r
841
MC/DC100%2/2
defined $Token && $NewToken eq $Token
defined $Token $NewToken eq $Token
Truth table100%3/3
A && B
A= defined $TokenB= $NewToken eq $Token
ABresult
0X0
100
111
607 13 $Token = $NewToken;
608 13 ▶ last unless $Truncated;
Branch: 1 branch
BranchTrueFalseTotal
unless $Truncated 7 6 13
609 6 ▶ if ($Stuck) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Stuck) 1 5 6
610 1 push @Errors, "sync-collection of $Path truncated without a new sync-token";
611 1 last;
612 }
613 5 ▶ confess "sync-collection of $Path still truncated after $Round rounds"
Branch: 1 branch
BranchTrueFalseTotal
if $Round >= $MaxRounds 1 4 5
614 if $Round >= $MaxRounds;
615 }
616  
617 8 my @Removed = sort keys %Removed;
618 8 ▶ return wantarray ? (\%Added, \@Removed, \@Errors, $Token) : \%Added;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 8 0 8
619 }
620  
621 =head2 $Self->GetCurrentUserPrincipal()
622 =head2 $class->GetCurrentUserPrincipal(%Args)
623  
624 Can be called with the same args as new() as a class method, or
625 on an existing object. Either way it will use the .well-known
626 URI to find the path to the current-user-principal.
627  
628 Returns a string with the path.
629  
630 =cut
631  
632 0 ▶sub GetCurrentUserPrincipal {
Subroutine GetCurrentUserPrincipal: not called CC=6 SCAR=37.4
Pod documented
633 0 my ($Class, %Args) = @_;
634  
635 0 ▶ if (ref $Class) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Class) 0 0 0
636 0 %Args = %{$Class};
637 0 $Class = ref $Class;
638 }
639  
640 0 ▶ my $OriginalURL = $Args{url} || '';
Condition0%0/2
$Args{'url'} || ''
l!l
00
MC/DC0%0/1
$Args{'url'} || ''
$Args{'url'}
Truth table0%0/2
A
A= $Args{'url'}
Aresult
11
00
641 0 my $Self = $Class->new(%Args);
642 0 my $NS_D = $Self->ns('D');
643 0 my @BasePath = split '/', $Self->{basepath};
644  
645 0 ▶ @BasePath = ('', ".well-known/$Args{wellknown}") unless @BasePath;
Branch: 1 branch
BranchTrueFalseTotal
unless @BasePath 0 0 0
646  
647 0 PRINCIPAL: while(1) {
648 0 $Self->SetURL(join '/', @BasePath);
649  
650 0 ▶ if (my $Principal = $Self->GetProps('', [ 'D:current-user-principal', 'D:href' ])) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $Principal = $Self->GetProps("", ["D:current-user-principal", "D:href"])) 0 0 0
651 0 $Self->SetURL(uri_unescape($Principal));
652 0 return $Self->{url};
653 }
654  
655 0 pop @BasePath;
656 0 ▶ last unless @BasePath;
Branch: 1 branch
BranchTrueFalseTotal
unless @BasePath 0 0 0
657 }
658  
659 0 croak "Error finding current user principal at '$OriginalURL'";
660 }
661  
662 =head2 $Self->GetHomeSet
663 =head2 $class->GetHomeSet(%Args)
664  
665 Can be called with the same args as new() as a class method, or
666 on an existing object. Either way it assumes that the created
667 object has a 'url' parameter pointing at the current user principal
668 URL (see GetCurrentUserPrincipal above)
669  
670 Returns a string with the path to the home set.
671  
672 =cut
673  
674 0 ▶sub GetHomeSet {
Subroutine GetHomeSet: not called CC=4 SCAR=30.0
Pod documented
675 0 my ($Class, %Args) = @_;
676  
677 0 ▶ if (ref $Class) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Class) 0 0 0
678 0 %Args = %{$Class};
679 0 $Class = ref $Class;
680 }
681  
682 0 ▶ my $OriginalURL = $Args{url} || '';
Condition0%0/2
$Args{'url'} || ''
l!l
00
MC/DC0%0/1
$Args{'url'} || ''
$Args{'url'}
Truth table0%0/2
A
A= $Args{'url'}
Aresult
11
00
683 0 my $Self = $Class->new(%Args);
684 0 my $NS_D = $Self->ns('D');
685 0 my $NS_HS = $Self->ns($Args{homesetns});
686 0 my $HomeSet = $Args{homeset};
687  
688 0 ▶ if (my $Homeset = $Self->GetProps('', [ "$Args{homesetns}:$HomeSet", 'D:href' ])) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $Homeset = $Self->GetProps("", [qq[$Args{"homesetns"}:$HomeSet], "D:href"])) 0 0 0
689 0 $Self->SetURL(uri_unescape($Homeset));
690 0 return $Self->{url};
691 }
692  
693 0 croak "Error finding $HomeSet home set at '$OriginalURL'";
694 }
695  
696 =head2 $Self->genuuid()
697  
698 Helper to generate a uuid string. Returns a UUID, e.g.
699  
700 my $uuid = $DAVTalk->genuuid(); # 9b9d68af-ad13-46b8-b7ab-30ab70da14ac
701  
702 =cut
703  
704 0 ▶sub genuuid {
Subroutine genuuid: not called CC=1 SCAR=6.9
Pod documented
705 0 my $Self = shift;
706 0 return "$uuid";
707 }
708  
709 =head2 $Self->auth_header()
710  
711 Generate the authentication header to use on requests:
712  
713 e.g:
714  
715 $Headers{'Authorization'} = $Self->auth_header();
716  
717 =cut
718  
719 0 ▶sub auth_header {
Subroutine auth_header: not called CC=3 SCAR=24.8
Pod documented
720 0 my $Self = shift;
721  
722 0 ▶ if ($Self->{password}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"password"}) 0 0 0
723 0 return 'Basic ' . encode_base64("$Self->{user}:$Self->{password}", '');
724 }
725  
726 0 ▶ if ($Self->{access_token}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"access_token"}) 0 0 0
727 0 return "Bearer $Self->{access_token}";
728 }
729  
730 0 croak "Need a method to authenticate user (password or access_token)";
731 }
732  
733 =head2 $Self->request_url($Path)
734  
735 The URL to request for $Path. Paths are unescaped, as every href this
736 module and its subclasses return is: each segment is URI-escaped here.
737 A path starting with / is on the server of the connection's URL, one
738 starting with http:// or https:// (or a reference to such a string) is
739 absolute, and anything else is relative to the connection's URL.
740  
741 e.g:
742  
743 my $URL = $Self->request_url('/dav/calendars/user/a@b.com/Default/');
744 # https://dav.example.com/dav/calendars/user/a%40b.com/Default/
745  
746 =cut
747  
748 23 ▶sub request_url {
Subroutine request_url: called CC=6 SCAR=17.9
Pod documented
749 23 my $Self = shift;
750 23 my $Path = shift;
751  
752 23 my $URL = $Self->{url};
753  
754 # A reference, or a full URL (some servers give hrefs as those), is
755 # absolute
756 23 ▶ if (ref $Path) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $Path) { } 1 22 23
elsif (defined $Path and $Path =~ m[^https?://]i) { } 2 20 22
757 1 ($URL, $Path) = $$Path =~ m{(^https?://[^/]+)(.*)$};
758 }
759 ▶ elsif (defined $Path and $Path =~ m{^https?://}i) {
Condition66%2/3
defined $Path and $Path =~ m[^https?://]i
!ll&&!rl&&r
0202
MC/DC50%1/2
defined $Path and $Path =~ m[^https?://]i
defined $Path $Path =~ m[^https?://]i
Truth table66%2/3
A and B
A= defined $PathB= $Path =~ m[^https?://]i
ABresult
0X0
100
111
760 2 ($URL, $Path) = $Path =~ m{(^https?://[^/]+)(.*)$}i;
761 }
762  
763 23 ▶ if ($Path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Path) 22 1 23
764 22 $Path = join "/", map { uri_escape $_ } split m{/}, $Path, -1;
765 22 ▶ if ($Path =~ m{^/}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Path =~ m[^/]) { } 20 2 22
766 20 $URL =~ s{(^https?://[^/]+)(.*)}{$1$Path};
767 }
768 else {
769 2 $URL =~ s{/$}{};
770 2 $URL .= "/$Path";
771 }
772 }
773  
774 23 return $URL;
775 }
776  
777 =head2 $Self->request_href($Path)
778  
779 The href for $Path to put in a request body (e.g. the DAV:href elements
780 of a multiget): the escaped absolute path of request_url($Path). Hrefs
781 the module returns are unescaped, so one sent back as it came would not
782 be a valid URI wherever it has a space, a % or the like.
783  
784 =cut
785  
786 4 ▶sub request_href {
Subroutine request_href: called CC=2 SCAR=7.0
Pod documented
787 4 my ($Self, $Path) = @_;
788 4 my $URL = $Self->request_url($Path);
789 4 $URL =~ s{^https?://[^/]+}{}i;
790 4 ▶ return length $URL ? $URL : '/';
Branch: 1 branch
BranchTrueFalseTotal
length $URL ? : 4 0 4
791 }
792  
793 =head2 $Self->NS()
794  
795 Returns a hashref of the 'xmlns:shortname' => 'full namespace' items for use in XML::Spice body generation, e.g.
796  
797 $DAVTalk->Request(
798 'MKCALENDAR',
799 "$calendarId/",
800 x('C:mkcalendar', $Self->NS(),
801 x('D:set',
802 x('D:prop', @Properties),
803 ),
804 ),
805 );
806  
807 # { 'xmlns:C' => 'urn:ietf:params:xml:ns:caldav', 'xmlns:D' => 'DAV:' }
808  
809 =cut
810  
811 14 ▶sub NS {
Subroutine NS: called CC=1 SCAR=0.0
Pod documented
812 14 my $Self = shift;
813  
814 return {
815 14 map { ( "xmlns:$_" => $Self->ns($_) ) }
816 $Self->ns(),
817 };
818 }
819  
820  
821 =head2 $Self->ns($key, $value)
822  
823 Get or set namespace aliases, e.g
824  
825 $Self->ns(C => 'urn:ietf:params:xml:ns:caldav');
826 my $NS_C = $Self->ns('C'); # urn:ietf:params:xml:ns:caldav
827  
828 =cut
829  
830 48 ▶sub ns {
Subroutine ns: called CC=3 SCAR=11.0
Pod documented
831 48 my $Self = shift;
832  
833 # case: keys
834 48 ▶ return keys %{$Self->{ns}} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 14 34 48
835  
836 34 my $key = shift;
837 # case read one
838 34 ▶ return $Self->{ns}{$key} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 24 10 34
839  
840 # case write
841 10 my $prev = $Self->{ns}{$key};
842 10 $Self->{ns}{$key} = shift;
843 10 return $prev;
844 }
845  
846 =head2 function2
847  
848 =cut
849  
850 =head1 AUTHOR
851  
852 Bron Gondwana, C<< <brong at cpan.org> >>
853  
854 =head1 BUGS
855  
856 Please report any bugs or feature requests to C<bug-net-davtalk at rt.cpan.org>, or through
857 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-DAVTalk>. I will be notified, and then you'll
858 automatically be notified of progress on your bug as I make changes.
859  
860  
861  
862  
863 =head1 SUPPORT
864  
865 You can find documentation for this module with the perldoc command.
866  
867 perldoc Net::DAVTalk
868  
869  
870 You can also look for information at:
871  
872 =over 4
873  
874 =item * RT: CPAN's request tracker (report bugs here)
875  
876 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-DAVTalk>
877  
878 =item * AnnoCPAN: Annotated CPAN documentation
879  
880 L<http://annocpan.org/dist/Net-DAVTalk>
881  
882 =item * CPAN Ratings
883  
884 L<http://cpanratings.perl.org/d/Net-DAVTalk>
885  
886 =item * Search CPAN
887  
888 L<http://search.cpan.org/dist/Net-DAVTalk/>
889  
890 =back
891  
892  
893 =head1 ACKNOWLEDGEMENTS
894  
895  
896 =head1 LICENSE AND COPYRIGHT
897  
898 Copyright 2015-2026 Fastmail Pty Ltd.
899  
900 This program is free software; you can redistribute it and/or modify it
901 under the same terms as Perl itself; that is, either the GNU General
902 Public License as published by the Free Software Foundation (version 1,
903 or at your option any later version), or the Artistic License.
904  
905 See L<http://dev.perl.org/licenses/> and the LICENSE file included with
906 this distribution for more information.
907  
908 =cut
909  
910 4 1; # End of Net::DAVTalk
↑ Summary DAVTalk/XMLParser.pm »