1 package File
::KDBX
::Object
;
2 # ABSTRACT: A KDBX database object
7 use Devel
::GlobalDestruction
;
8 use File
::KDBX
::Constants
qw(:bool);
10 use File
::KDBX
::Util
qw(:uuid);
11 use Hash
::Util
::FieldHash
qw(fieldhashes);
12 use List
::Util
qw(any first);
13 use Ref
::Util
qw(is_arrayref is_plain_arrayref is_plain_hashref is_ref);
14 use Scalar
::Util
qw(blessed weaken);
17 our $VERSION = '999.999'; # VERSION
19 fieldhashes \
my (%KDBX, %PARENT, %TXNS, %REFS, %SIGNALS);
23 $object = File
::KDBX
::Object-
>new;
24 $object = File
::KDBX
::Object-
>new(%attributes);
25 $object = File
::KDBX
::Object-
>new(\
%data);
26 $object = File
::KDBX
::Object-
>new(\
%data, $kdbx);
28 Construct a new KDBX object
.
30 There
is a subtlety to
take note of
. There
is a significant difference between
:
32 File
::KDBX
::Entry-
>new(username
=> 'iambatman');
36 File
::KDBX
::Entry-
>new({username
=> 'iambatman'}); # WRONG
38 In the first
, an empty object
is first created
and then initialized with whatever I
<attributes
> are
given. In
39 the second
, a hashref
is blessed
and essentially becomes the object
. The significance
is that the hashref
40 key-value pairs will remain as-is so the structure
is expected to adhere to the shape of a raw B
<Object
>
41 (which varies based on the type of object
), whereas with the first the attributes will set the structure
in
42 the correct way
(just like using the object accessors
/ getters / setters
).
44 The second example isn
't I<generally> wrong -- this type of construction is supported for a reason, to allow
45 for working with KDBX objects at a low level -- but it is wrong in this specific case only because
46 C<< {username => $str} >> isn't a valid raw KDBX entry object
. The L
</username
> attribute
is really a proxy
47 for the C
<UserName
> string
, so the equivalent raw entry object should be
48 C
<< {strings
=> {UserName
=> {value
=> $str}}} >>. These are roughly equivalent
:
50 File
::KDBX
::Entry-
>new(username
=> 'iambatman');
51 File
::KDBX
::Entry-
>new({strings
=> {UserName
=> {value
=> 'iambatman'}}});
53 If this explanation went over your head
, that
's fine. Just stick with the attributes since they are typically
54 easier to use correctly and provide the most convenience. If in the future you think of some kind of KDBX
55 object manipulation you want to do that isn't supported by the accessors
and methods
, just know you I
<can
>
56 access an object
's data directly.
64 return $_[0]->clone if @_ == 1 && blessed $_[0] && $_[0]->isa($class);
67 $data = shift if is_plain_hashref($_[0]);
70 $kdbx = shift if @_ % 2 == 1;
73 $args{kdbx} //= $kdbx if defined $kdbx;
75 my $self = bless $data // {}, $class;
77 $self->_set_nonlazy_attributes if !$data;
81 sub _set_nonlazy_attributes { die 'Not implemented
' }
85 $object = $object->init(%attributes);
87 Called by the constructor to set attributes. You normally should not call this.
95 while (my ($key, $val) = each %args) {
96 if (my $method = $self->can($key)) {
106 $object = File::KDBX::Object->wrap($object);
108 Ensure that a KDBX object is blessed.
115 return $object if blessed $object && $object->isa($class);
116 return $class->new(@_, @$object) if is_arrayref($object);
117 return $class->new($object, @_);
122 $label = $object->label;
123 $object->label($label);
125 Get or set the object's label
, a text string that can act as a non-unique identifier
. For an entry
, the label
126 is its title string
. For a group
, the label
is its name
.
130 sub label
{ die 'Not implemented' }
134 $object_copy = $object->clone(%options);
135 $object_copy = File
::KDBX
::Object-
>new($object);
137 Make a clone of an object
. By
default the clone
is indeed an exact copy that
is connected to the same database
138 but
not actually included
in the object tree
(i
.e
. it
has no parent group
). Some options are allowed to get
142 * C<new_uuid> - If set, generate a new UUID for the copy (default: false)
143 * C<parent> - If set, add the copy to the same parent group, if any (default: false)
144 * C<relabel> - If set, append " - Copy" to the object's title or name (default: false)
145 * C<entries> - If set, copy child entries, if any (default: true)
146 * C<groups> - If set, copy child groups, if any (default: true)
147 * C<history> - If set, copy entry history, if any (default: true)
148 * C<reference_password> - Toggle whether or not cloned entry's Password string should be set as a field
149 reference to the original entry's Password string (default: false)
150 * C<reference_username> - Toggle whether or not cloned entry's UserName string should be set as a field
151 reference to the original entry's UserName string (default: false)
155 my %CLONE = (entries
=> 1, groups
=> 1, history
=> 1);
160 local $CLONE{new_uuid
} = $args{new_uuid
} // $args{parent
} // 0;
161 local $CLONE{entries
} = $args{entries
} // 1;
162 local $CLONE{groups
} = $args{groups
} // 1;
163 local $CLONE{history
} = $args{history
} // 1;
164 local $CLONE{reference_password
} = $args{reference_password
} // 0;
165 local $CLONE{reference_username
} = $args{reference_username
} // 0;
168 my $copy = Storable
::dclone
($self);
170 if ($args{relabel
} and my $label = $self->label) {
171 $copy->label("$label - Copy");
173 if ($args{parent
} and my $parent = $self->group) {
174 $parent->add_object($copy);
180 sub STORABLE_freeze
{
185 delete $copy->{entries
} if !$CLONE{entries
};
186 delete $copy->{groups
} if !$CLONE{groups
};
187 delete $copy->{history
} if !$CLONE{history
};
189 return ($cloning ? Hash
::Util
::FieldHash
::id
($self) : ''), $copy;
198 @$self{keys %$copy} = values %$copy;
201 my $kdbx = $KDBX{$addr};
202 $self->kdbx($kdbx) if $kdbx;
205 if (defined $self->{uuid
}) {
206 if (($CLONE{reference_password
} || $CLONE{reference_username
}) && $self->can('strings')) {
207 my $uuid = format_uuid
($self->{uuid
});
209 local $CLONE{new_uuid
} = 0;
210 local $CLONE{entries
} = 1;
211 local $CLONE{groups
} = 1;
212 local $CLONE{history
} = 1;
213 local $CLONE{reference_password
} = 0;
214 local $CLONE{reference_username
} = 0;
215 # Clone only the entry's data and manually bless to avoid infinite recursion.
216 bless Storable
::dclone
({%$copy}), 'File::KDBX::Entry';
218 my $txn = $self->begin_work(snapshot
=> $clone_obj);
219 if ($CLONE{reference_password
}) {
220 $self->password("{REF:P\@I:$uuid}");
222 if ($CLONE{reference_username
}) {
223 $self->username("{REF:U\@I:$uuid}");
227 $self->uuid(generate_uuid
) if $CLONE{new_uuid
};
230 # Dualvars aren't cloned as dualvars, so dualify the icon.
231 $self->icon_id($self->{icon_id
}) if defined $self->{icon_id
};
236 $kdbx = $object->kdbx;
237 $object->kdbx($kdbx);
239 Get
or set the L
<File
::KDBX
> instance connected with this object
.
245 $self = $self->new if !ref $self;
247 if (my $kdbx = shift) {
248 $KDBX{$self} = $kdbx;
255 $KDBX{$self} or throw
'Object is disconnected', object
=> $self;
260 $bool = $object->is_connected;
262 Determine whether
or not an object
is connected to a database
.
268 return !!eval { $self->kdbx };
273 $string_uuid = $object->id;
274 $string_uuid = $object->id($delimiter);
276 Get the unique identifier
for this object as a B
<formatted
> UUID string
, typically
for display purposes
. You
277 could
use this to compare with other identifiers formatted with the same delimiter
, but it
is more efficient
278 to
use the raw UUID
for that purpose
(see L
</uuid
>).
280 A delimiter can optionally be provided to
break up the UUID string visually
. See
281 L
<File
::KDBX
::Util
/format_uuid
>.
285 sub id
{ format_uuid
(shift-
>uuid, @_) }
289 $parent_group = $object->group;
290 $object->group($parent_group);
292 Get
or set the parent group to which an object belongs
or C
<undef> if it belongs to
no group
.
299 if (my $new_group = shift) {
300 my $old_group = $self->group;
301 return $new_group if Hash
::Util
::FieldHash
::id
($old_group) == Hash
::Util
::FieldHash
::id
($new_group);
302 # move to a new parent
303 $self->remove(signal
=> 0) if $old_group;
304 $new_group->add_object($self);
307 my $id = Hash
::Util
::FieldHash
::id
($self);
308 if (my $group = $PARENT{$self}) {
309 my $method = $self->_parent_container;
310 return $group if first
{ $id == Hash
::Util
::FieldHash
::id
($_) } @{$group->$method};
311 delete $PARENT{$self};
313 # always get lineage from root to leaf because the other way requires parent, so it would be recursive
314 my $lineage = $self->kdbx->_trace_lineage($self) or return;
315 my $group = pop @$lineage or return;
316 $PARENT{$self} = $group; weaken
$PARENT{$self};
322 if (my $parent = shift) {
323 $PARENT{$self} = $parent;
324 weaken
$PARENT{$self};
327 delete $PARENT{$self};
332 ### Name of the parent attribute expected to contain the object
333 sub _parent_container
{ die 'Not implemented' }
337 \
@lineage = $object->lineage;
338 \
@lineage = $object->lineage($base_group);
340 Get the direct line of ancestors from C
<$base_group> (default: the root group
) to an object
. The lineage
341 includes the base group but I
<not> the target object
. Returns C
<undef> if the target
is not in the database
342 structure
. Returns an empty arrayref
is the object itself
is a root group
.
350 my $base_addr = $base ? Hash
::Util
::FieldHash
::id
($base) : 0;
355 while ($object = $object->group) {
356 unshift @path, $object;
357 last if $base_addr == Hash
::Util
::FieldHash
::id
($object);
359 return \
@path if @path && ($base_addr == Hash
::Util
::FieldHash
::id
($path[0]) || $path[0]->is_root);
362 return $self->kdbx->_trace_lineage($self, $base);
367 $object = $object->remove(%options);
369 Remove an object from its parent
. If the object
is a group
, all contained objects stay with the object
and so
370 are removed as well
. Options
:
373 * C<signal> Whether or not to signal the removal to the connected database (default: true)
379 my $parent = $self->group;
380 $parent->remove_object($self, @_) if $parent;
381 $self->_set_group(undef);
387 $object = $object->recycle;
389 Remove an object from its parent
and add it to the connected database
's recycle bin group.
395 return $self->group($self->kdbx->recycle_bin);
398 =method recycle_or_remove
400 $object = $object->recycle_or_remove;
402 Recycle or remove an object, depending on the connected database's L
<File
::KDBX
/recycle_bin_enabled
>. If the
403 object
is not connected to a database
or is already
in the recycle bin
, remove it
.
407 sub recycle_or_remove
{
409 my $kdbx = eval { $self->kdbx };
410 if ($kdbx && $kdbx->recycle_bin_enabled && !$self->is_recycled) {
420 $bool = $object->is_recycled;
422 Get whether
or not an object
is in a recycle bin
.
428 eval { $self->kdbx } or return FALSE
;
429 return !!($self->group && any
{ $_->is_recycle_bin } @{$self->lineage});
432 ##############################################################################
436 @tags = $entry->tag_list;
438 Get a list of tags
, split from L
</tag
> using delimiters C
<,>, C
<.>, C
<:>, C
<;> and whitespace
.
444 return grep { $_ ne '' } split(/[,\.:;]|\s+/, trim
($self->tags) // '');
449 $image_data = $object->custom_icon;
450 $image_data = $object->custom_icon($image_data, %attributes);
452 Get
or set an icon image
. Returns C
<undef> if there
is no custom icon set
. Setting a custom icon will change
453 the L
</custom_icon_uuid
> attribute
.
455 Custom icon attributes
(supported
in KDBX4
.1
and greater
):
458 * C<name> - Name of the icon (text)
459 * C<last_modification_time> - Just what it says (datetime)
465 my $kdbx = $self->kdbx;
468 my $uuid = defined $img ? $kdbx->add_custom_icon($img, @_) : undef;
469 $self->icon_id(0) if $uuid;
470 $self->custom_icon_uuid($uuid);
473 return $kdbx->custom_icon_data($self->custom_icon_uuid);
478 \
%all_data = $object->custom_data;
479 $object->custom_data(\
%all_data);
481 \
%data = $object->custom_data($key);
482 $object->custom_data($key => \
%data);
483 $object->custom_data(%data);
484 $object->custom_data(key
=> $value, %data);
486 Get
and set custom data
. Custom data
is metadata associated with an object
.
488 Each data item can have a few attributes associated with it
.
491 * C<key> - A unique text string identifier used to look up the data item (required)
492 * C<value> - A text string value (required)
493 * C<last_modification_time> (optional, KDBX4.1+)
499 $self->{custom_data
} = shift if @_ == 1 && is_plain_hashref
($_[0]);
500 return $self->{custom_data
} //= {} if !@_;
502 my %args = @_ == 2 ? (key
=> shift, value
=> shift)
503 : @_ % 2 == 1 ? (key
=> shift, @_) : @_;
505 if (!$args{key
} && !$args{value
}) {
506 my %standard = (key
=> 1, value
=> 1, last_modification_time
=> 1);
507 my @other_keys = grep { !$standard{$_} } keys %args;
508 if (@other_keys == 1) {
509 my $key = $args{key
} = $other_keys[0];
510 $args{value
} = delete $args{$key};
514 my $key = $args{key
} or throw
'Must provide a custom_data key to access';
516 return $self->{custom_data
}{$key} = $args{value
} if is_plain_hashref
($args{value
});
518 while (my ($field, $value) = each %args) {
519 $self->{custom_data
}{$key}{$field} = $value;
521 return $self->{custom_data
}{$key};
524 =method custom_data_value
526 $value = $object->custom_data_value($key);
528 Exactly the same as L
</custom_data
> except returns just the custom data
's value rather than a structure of
529 attributes. This is a shortcut for:
531 my $data = $object->custom_data($key);
532 my $value = defined $data ? $data->{value} : undef;
536 sub custom_data_value {
538 my $data = $self->custom_data(@_) // return undef;
539 return $data->{value};
542 ##############################################################################
546 $txn = $object->begin_work(%options);
547 $object->begin_work(%options);
549 Begin a new transaction. Returns a L<File::KDBX::Transaction> object that can be scoped to ensure a rollback
550 occurs if exceptions are thrown. Alternatively, if called in void context, there will be no
551 B<File::KDBX::Transaction> and it is instead your responsibility to call L</commit> or L</rollback> as
552 appropriate. It is undefined behavior to call these if a B<File::KDBX::Transaction> exists. Recursive
553 transactions are allowed.
555 Signals created during a transaction are delayed until all transactions are resolved. If the outermost
556 transaction is committed, then the signals are de-duplicated and delivered. Otherwise the signals are dropped.
557 This means that the KDBX database will not fix broken references or mark itself dirty until after the
558 transaction is committed.
560 How it works: With the beginning of a transaction, a snapshot of the object is created. In the event of
561 a rollback, the object's data
is replaced with data from the snapshot
.
563 By
default, the snapshot
is shallow
(i
.e
. does not include subroups
, entries
or historical entries
). This
564 means that only modifications to the object itself
(its data
, fields
, strings
, etc
.) are atomic
; modifications
565 to subroups etc
., including adding
or removing items
, are auto-committed instantly
and will persist regardless
566 of the result of the pending transaction
. You can override this
for groups
, entries
and history independently
570 * C<entries> - If set, snapshot entries within a group, deeply (default: false)
571 * C<groups> - If set, snapshot subroups within a group, deeply (default: false)
572 * C<history> - If set, snapshot historical entries within an entry (default: false)
574 For example, if you begin a transaction on a group object using the C<entries> option, like this:
576 $group->begin_work(entries => 1);
578 Then if you modify any of the group's entries OR add new entries OR delete entries, all of that will be undone
579 if the transaction is rolled back. With a default-configured transaction, however, changes to entries are kept
580 even if the transaction is rolled back.
587 if (defined wantarray) {
588 require File
::KDBX
::Transaction
;
589 return File
::KDBX
::Transaction-
>new($self, @_);
593 my $orig = $args{snapshot
} // do {
594 my $c = $self->clone(
595 entries
=> $args{entries
} // 0,
596 groups
=> $args{groups
} // 0,
597 history
=> $args{history
} // 0,
599 $c->{entries
} = $self->{entries
} if !$args{entries
};
600 $c->{groups
} = $self->{groups
} if !$args{groups
};
601 $c->{history
} = $self->{history
} if !$args{history
};
605 my $id = Hash
::Util
::FieldHash
::id
($orig);
606 _save_references
($id, $self, $orig);
608 $self->_signal_begin_work;
610 push @{$self->_txns}, $orig;
617 Commit a transaction
, making updates to C
<$object> permanent
. Returns itself to allow
method chaining
.
623 my $orig = pop @{$self->_txns} or return $self;
624 $self->_commit($orig);
625 my $signals = $self->_signal_commit;
626 $self->_signal_send($signals) if !$self->_in_txn;
634 Roll back the most recent transaction
, throwing away any updates to the L
</object
> made since the transaction
635 began
. Returns itself to allow
method chaining
.
642 my $orig = pop @{$self->_txns} or return $self;
644 my $id = Hash
::Util
::FieldHash
::id
($orig);
645 _restore_references
($id, $orig);
647 $self->_signal_rollback;
652 # Get whether or not there is at least one pending transaction.
653 sub _in_txn
{ scalar @{$_[0]->_txns} }
655 # Get an array ref of pending transactions.
656 sub _txns
{ $TXNS{$_[0]} //= [] }
658 # The _commit hook notifies subclasses that a commit has occurred.
659 sub _commit
{ die 'Not implemented' }
661 # Get a reference to an object that represents an object's committed state. If there is no pending
662 # transaction, this is just $self. If there is a transaction, this is the snapshot take before the transaction
663 # began. This method is private because it provides direct access to the actual snapshot. It is important that
664 # the snapshot not be changed or a rollback would roll back to an altered state.
665 # This is used by File::KDBX::Dumper::XML so as to not dump uncommitted changes.
668 my ($orig) = @{$self->_txns};
669 return $orig // $self;
672 # In addition to cloning an object when beginning work, we also keep track its hashrefs and arrayrefs
673 # internally so that we can restore to the very same structures in the case of a rollback.
674 sub _save_references
{
679 if (is_plain_arrayref
($orig)) {
680 for (my $i = 0; $i < @$orig; ++$i) {
681 _save_references
($id, $self->[$i], $orig->[$i]);
683 $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig)} = $self;
685 elsif (is_plain_hashref
($orig) || (blessed
$orig && $orig->isa(__PACKAGE__
))) {
686 for my $key (keys %$orig) {
687 _save_references
($id, $self->{$key}, $orig->{$key});
689 $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig)} = $self;
693 # During a rollback, copy data from the snapshot back into the original internal structures.
694 sub _restore_references
{
696 my $orig = shift // return;
697 my $self = delete $REFS{$id}{Hash
::Util
::FieldHash
::id
($orig) // ''} // return $orig;
699 if (is_plain_arrayref
($orig)) {
700 @$self = map { _restore_references
($id, $_) } @$orig;
702 elsif (is_plain_hashref
($orig) || (blessed
$orig && $orig->isa(__PACKAGE__
))) {
703 for my $key (keys %$orig) {
704 # next if is_ref($orig->{$key}) &&
705 # (Hash::Util::FieldHash::id($self->{$key}) // 0) == Hash::Util::FieldHash::id($orig->{$key});
706 $self->{$key} = _restore_references
($id, $orig->{$key});
713 ##############################################################################
719 if ($self->_in_txn) {
720 my $stack = $self->_signal_stack;
721 my $queue = $stack->[-1];
722 push @$queue, [$type, @_];
725 $self->_signal_send([[$type, @_]]);
730 sub _signal_stack
{ $SIGNALS{$_[0]} //= [] }
732 sub _signal_begin_work
{
734 push @{$self->_signal_stack}, [];
739 my $signals = pop @{$self->_signal_stack};
740 my $previous = $self->_signal_stack->[-1] // [];
741 push @$previous, @$signals;
745 sub _signal_rollback
{
747 pop @{$self->_signal_stack};
752 my $signals = shift // [];
754 my $kdbx = $KDBX{$self} or return;
756 # de-duplicate, keeping the most recent signal for each type
758 my @signals = grep { !$seen{$_->[0]}++ } reverse @$signals;
760 for my $sig (reverse @signals) {
761 $kdbx->_handle_signal($self, @$sig);
765 ##############################################################################
770 require File
::KDBX
::Group
;
771 return File
::KDBX
::Group-
>wrap($group, $KDBX{$self});
777 require File
::KDBX
::Entry
;
778 return File
::KDBX
::Entry-
>wrap($entry, $KDBX{$self});
781 sub TO_JSON
{ +{%{$_[0]}} }
786 =for Pod::Coverage STORABLE_freeze STORABLE_thaw TO_JSON
790 KDBX is an object database. This abstract class represents an object. You should not use this class directly
791 but instead use its subclasses:
794 * L<File::KDBX::Entry>
795 * L<File::KDBX::Group>
797 There is some functionality shared by both types of objects, and that's what this class provides.
799 Each object can be connected with a L<File::KDBX> database or be disconnected. A disconnected object exists in
800 memory but will not be persisted when dumping a database. It is also possible for an object to be connected
801 with a database but not be part of the object tree (i.e. is not the root group or any subroup or entry).
802 A disconnected object or an object not part of the object tree of a database can be added to a database using
806 * L<File::KDBX/add_entry>
807 * L<File::KDBX/add_group>
808 * L<File::KDBX::Group/add_entry>
809 * L<File::KDBX::Group/add_group>
810 * L<File::KDBX::Entry/add_historical_entry>
812 It is possible to copy or move objects between databases, but B<DO NOT> include the same object in more
813 than one database at once or there could be some strange aliasing effects (i.e. changes in one database might
814 effect another in unexpected ways). This could lead to difficult-to-debug problems. It is similarly not safe
815 or valid to add the same object multiple times to the same database. For example:
817 my $entry = File::KDBX::Entry->(title => 'Whatever');
820 $kdbx->add_entry($entry);
821 $another_kdbx->add_entry($entry);
824 $kdbx->add_entry($entry);
825 $kdbx->add_entry($entry); # again
829 # Copy an entry to multiple databases:
830 $kdbx->add_entry($entry);
831 $another_kdbx->add_entry($entry->clone);
833 # OR move an existing entry from one database to another:
834 $another_kdbx->add_entry($entry->remove);