TABOO/Data.pm untested

filter: Statementstmt 0.0% 0 / 247 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 19 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 380 CC 32 SCAR 35.2
CC
32
Cov
0%
write_xml
90.0
save
90.0
_load
20.0
CRAP 33.8
1 package AxKit::App::TABOO::Data;
2 use strict;
3 use warnings;
4 use Carp;
5 use Encode;
6  
7  
8  
9 use Data::Dumper;
10 use Class::Data::Inheritable;
11 use base qw(Class::Data::Inheritable);
12  
13  
14 our $VERSION = '0.52';
15  
16  
17 use DBI;
18 use Exception::Class::DBI;
19  
20 use XML::LibXML;
21 use HTML::StripScripts::LibXML;
22  
23  
24 =head1 NAME
25  
26 AxKit::App::TABOO::Data - Base class of abstracted Data objects for TABOO
27  
28 =head1 DESCRIPTION
29  
30 You would rarely if ever use this class directly. Instead, you would
31 call a subclass of this class, depending on what kind of data you are
32 operating on. This class does, however, define some very useful
33 methods that its subclasses can use unaltered.
34  
35 It is to be noted that I have not, neither in this class nor in the
36 subclasses, created methods to access or set every field. Instead, I
37 rely mainly on methods that will manipulate internal data based on the
38 for example objects that are passed as arguments. For example, the
39 C<write_xml>-method (below), will create XML based on all the
40 available data in the object. This is usually all you want anyway.
41  
42 In some subclasses, you will have some degree of control of what is
43 loaded into the object data structure in the first place, by sending
44 the names of the fields of the storage medium (e.g. database in the
45 present implementation).
46  
47 Similarly, if data is sent from a web application, the present
48 implementation makes it possible to pass an L<Apache::Request> object
49 to a Data object, and it is up to a method of the Data object to take
50 what it wants from the Apache::Request object, and intelligently store
51 it.
52  
53 Some methods to access data will be implemented on an ad hoc basis,
54 notably C<timestamp()>-methods, that will be important in determining
55 the validity of cached data.
56  
57 Sometimes you might want to retrieve more than one object from the
58 data store, and do stuff on these objects as a whole. Furthermore,
59 the load methods used to retrieve multiple objects may be optimized.
60 For this, TABOO also has Plural classes.
61  
62  
63 =head2 Methods
64  
65 =over
66  
67 =item C<new()>
68  
69 The constructor of this class. Rarely used.
70  
71 =cut
72  
73 sub new {
74 my $that = shift;
75 my $class = ref($that) || $that;
76 my $self = {
77 ONFILE => undef,
78 DBCONNECTARGS => [],
79 XMLPREFIX => 'taboo',
80 XMLELEMENT => 'taboo',
81 XMLNS => 'http://www.kjetil.kjernsmo.net/software/TABOO/NS/Output'
82 };
83  
84 bless($self, $class);
85 return $self;
86 }
87  
88  
89 =item C<load(what =E<gt> fields, limit =E<gt> {key =E<gt> value, [...]})>
90  
91 Will load and populate the data structure of an object with the data
92 from a data store. It uses named parameters, the first C<what> is used
93 to determine which fields to retrieve. It is a string consisting of a
94 commaseparated list of fields, as specified in the data store. If not
95 given, all fields will be fetched. The C<limit> argument is to be used
96 to determine which records to retrieve, and must be used to identify a
97 record uniquely. It is itself a reference to a hash, containing data
98 store field values as keys and values are corresponding values to
99 retrieve. These will be combined by logical AND.
100  
101 If there is no data that corresponds to the given arguments, this
102 method will return C<undef>.
103  
104 =cut
105  
106 sub load {
107 my ($self, %args) = @_;
108 my $data = $self->_load(%args);
109 if ($data) {
110 ${$self}{'ONFILE'} = 1;
111 } else {
112 return undef;
113 }
114 foreach my $key (keys(%{$data})) {
115 ${$self}{$key} = Encode::decode_utf8(${$data}{$key})
116 }
117 return $self;
118 }
119  
120  
121 =item C<_load(what =E<gt> fields, limit =E<gt> {key =E<gt> value, [...]})>
122  
123 As the underscore implies this is B<for internal use only>! It is
124 intended to do the hard work for this class and its subclasses. It
125 returns a hashref of the data from the datastore.
126  
127  
128 See the documentation for the C<load> method for the details on the
129 parameters.
130  
131 =cut
132  
133 sub _load {
134 my ($self, %args) = @_;
135 my $what = $args{'what'} || '*';
136 my %arg = %{$args{'limit'}};
137 my $dbh = DBI->connect($self->dbconnectargs());
138 # The subclass should give the dbfrom.
139 my $query = "SELECT " . $what . " FROM " . $self->dbfrom() . " WHERE ";
140 my $i=0;
141 my $nothing=1;
142 my @keys = keys(%arg);
143 foreach my $key (@keys) {
144 $i++;
145 next unless ($arg{$key});
146 $nothing = 0;
147 $query .= $key . "=?";
148 if ($i <= $#keys) {
149 $query .= " AND ";
150 }
151 }
152 # warn $query;
153 if ($nothing) {
154 # Then, none of the fields were actually sent with a value, so
155 # load won't return anything sensible...
156 carp "No fields were sent with value, so no unique record can be found";
157 return undef;
158 }
159 my $sth = $dbh->prepare($query);
160 $i=1;
161 foreach my $key (@keys) {
162 $sth->bind_param($i, $arg{$key});
163 $i++;
164 }
165 $sth->execute();
166 return $sth->fetchrow_hashref;
167 }
168  
169 =item C<write_xml($doc, $parent)>
170  
171 Takes arguments C<$doc>, which must be an L<XML::LibXML::Document>
172 object, and C<$parent>, a reference to the parent node. The method
173 will append the object it is handed it with the data contained in the
174 data structure of the class in XML. This method is the jewel of this
175 class, it should be sufficiently generic to rarely require
176 subclassing. References to subclasses will be followed, and
177 C<write_xml> will call the C<write_xml> of that object. Arrays will be
178 represented with multiple instances of the same element. Fields that
179 have undefined values will not be included. It will also parse fields
180 indicated by C<elementneedsparse()>, see below. Currently, we get HTML
181 from TinyMCE, which we let XML::LibXML parse.
182  
183 =cut
184  
185  
186 sub write_xml {
187 my $self = shift;
188 my $doc = shift;
189 my $parent = shift;
190 my $topel = $doc->createElementNS($self->xmlns(),
191 $self->xmlprefix() .':'. $self->xmlelement());
192 if ((defined($self->dbprimkey)) && (defined(${$self}{$self->dbprimkey()}))) {
193 $topel->setAttributeNS($self->xmlns(),
194 $self->xmlprefix() .':key',
195 ${$self}{$self->dbprimkey()});
196 }
197 $parent->appendChild($topel);
198 foreach my $key (split(/,\s*/, $self->elementorder())) {
199 if (defined(${$self}{$key})) {
200 my $content = ${$self}{$key};
201 if (ref($content) =~ m/^AxKit::App::TABOO::Data/) {
202 # The content is a reference to one of our subclasses, it
203 # should write itself
204 $content->write_xml($doc, $topel);
205 }
206 elsif (ref($content) eq '') {
207 my $element = $doc->createElementNS($self->xmlns(), $self->xmlprefix() .':'. $key);
208 if (($content) && (defined($self->elementneedsparse)) && ($self->elementneedsparse =~ m/\b$key\b/)) {
209 my $hss=HTML::StripScripts::LibXML->new(
210 {Context=>'Flow',
211 BanList => [qw( style font center blink marquee ) ],
212 AllowHref => 1,
213 AllowSrc => 1,
214 AllowMailto => 1,
215 Rules => {
216 'caption' => \&_style_callback,
217 'input' => \&_style_callback,
218 'legend' => \&_style_callback,
219 'table' => \&_style_callback,
220 'hr' => \&_style_callback,
221 'div' => \&_style_callback,
222 'p' => \&_style_callback,
223 'h1' => \&_style_callback,
224 'h2' => \&_style_callback,
225 'h3' => \&_style_callback,
226 'h4' => \&_style_callback,
227 'h5' => \&_style_callback,
228 'h6' => \&_style_callback,
229 }
230 }, # HSS options
231 strict_comment =>1, # HTML::Parser options
232 strict_names => 1
233 );
234 $hss->parse($content);
235 $hss->eof;
236 my $div = $doc->createElement('div');
237 $div->appendChild($hss->filtered_document);
238 $element->appendChild($div);
239 } else {
240 my $text = XML::LibXML::Text->new($content);
241 $element->appendChild($text);
242 }
243 $topel->appendChild($element);
244 } elsif (ref($content) eq "ARRAY") {
245 # The content is an array, we must go through it and add an element for each.
246 foreach (@{$content}) {
247 if (ref($_) eq '') {
248 my $element = $doc->createElementNS($self->xmlns(), $self->xmlprefix() .':'. $key);
249 my $text = XML::LibXML::Text->new($_);
250 $element->appendChild($text);
251 $topel->appendChild($element);
252 } else {
253 if (ref($_) =~ m/^AxKit::App::TABOO::Data/) {
254 # An element in the array contained a reference to one of our subclasses, it must be written too.
255 $_->write_xml($doc, $topel);
256 }
257 }
258 }
259 } else {
260 my $element = $doc->createElementNS($self->xmlns(), $self->xmlprefix() .':'. $key);
261 my $text = XML::LibXML::Text->new($content);
262 $element->appendChild($text);
263 $topel->appendChild($element);
264 }
265 }
266 }
267 return $doc;
268 }
269  
270 # Dispatch table for what CSS to use to replace a particular attribute
271 my %replace = (
272 hspace => sub { "margin-left:$_[0]px;margin-right:$_[0]px" },
273 vspace => sub { "margin-top:$_[0]px;margin-bottom:$_[0]px" },
274 border => sub { "border-width:$_[0]px" },
275 align => sub { "text-align:$_[0]" },
276 );
277  
278 sub _style_callback {
279 my ($filter,$element) = @_;
280
281 my $attrs = $element->{attr};
282 my $style = delete $attrs->{style} || '';
283
284 # loops through the existing attributes
285 # and, if appropriate, replaces them with a style
286 foreach my $key (keys %$attrs) {
287 next unless exists $replace{$key};
288 $style.= $replace{$key}->($attrs->{$key}).";";
289 delete $attrs->{$key}
290 }
291 $attrs->{style} = $style
292 if $style;
293 return 1;
294 }
295  
296  
297  
298 =item C<populate(\%args)>
299  
300 This method takes as argument a reference to a hash and will populate
301 the data object by adding any data from a key having the same name as
302 is used in the data storage. Fields that are not specified by the data
303 object or that has uppercase letters are ignored.
304  
305 It may be used to insert data from a request by first noting that in a
306 HTTP request, the Request object is available as C<$r>, so you may
307 create the hash to hand to this method by
308  
309 my %args = $r->args;
310  
311 Note that this only the case for HTTP GET, in the case of POST, you
312 may have to construct the hash by e.g.
313  
314 my %args = map { $_ => join('', $cgi->param($_)) } $cgi->param;
315  
316 =cut
317  
318  
319 sub populate {
320 my $self = shift;
321 my $args = shift;
322 foreach my $key (keys(%{$self})) {
323 next if ($key =~ m/[A-Z]/); # Uppercase keys are not in db
324 ${$self}{$key} = Encode::decode_utf8(${$args}{$key});
325 }
326 return $self;
327 }
328  
329 =item C<apache_request_changed(\%args)>
330  
331 Like the above method, this method takes as argument a reference to
332 the args hash of a L<Apache::Request> object. Instead of populating
333 the Data object, it will compare the C<\%args> with the contents of
334 the object and return an array of fields that differs between the
335 two. Fields that are not specified by the data object, that has
336 uppercase letters or has no value, are ignored.
337  
338  
339 =cut
340  
341  
342 sub apache_request_changed {
343 my $self = shift;
344 my $args = shift;
345 my @keys;
346 foreach my $key (keys(%{$self})) {
347 next if ($key =~ m/[A-Z]/); # Uppercase keys are not in db
348 next unless defined(${$args}{$key}); # if it isn't there, we don't care.
349 if (${$self}{$key} ne ${$args}{$key}) {
350 push(@keys, $key);
351 }
352 }
353 return @keys;
354 }
355  
356  
357 =item C<save([$olddbkey])>
358  
359 This is a generic save method, that will write a new record to the
360 data store, or update an old one. It may have to be subclassed for
361 certain classes. It takes an optional argument C<$olddbkey>, which is
362 the primary key of an existing record in the data store. You may
363 supply this in the case if you want to update the record with a new
364 key. In that case, you'd better be sure it actually exists, because
365 the method will trust you do.
366  
367 It is not yet a very rigorous implementation: It may well fail badly
368 if it is given something with a reference to other Data objects, which
369 is the case if you have a full story with all comments. Or it may
370 cope. Only time will tell! Expect to see funny warnings in your logs
371 if you try.
372  
373  
374 =cut
375  
376 sub save {
377 my $self = shift;
378 my $olddbkey = shift;
379 my $dbh = DBI->connect($self->dbconnectargs());
380 my @fields;
381 my $i=0;
382 foreach my $key (keys(%{$self})) {
383 next if ($key =~ m/[A-Z]/); # Uppercase keys are not in db
384 next unless defined(${$self}{$key}); # No need to insert something that isn't there
385 push(@fields, $key);
386 $i++;
387 }
388 if ($i == 0) {
389 carp "No data fields with anything to save";
390 } else {
391 my $sth;
392 my $dbkey = ${$self}{$self->dbprimkey()};
393 # First we check if we should update rather than insert
394 if (($olddbkey) || ($self->stored)) {
395 ${$self}{'ONFILE'} = 1;
396 # Yep, we update, but do we change the primary key?
397 if ($olddbkey) {
398 $dbkey = $olddbkey;
399 }
400 $sth = $dbh->prepare("UPDATE ". $self->dbtable() . " SET " . join('=?,', @fields) . "=? WHERE " . $self->dbprimkey() . "=?");
401
402 } else {
403 $sth = $dbh->prepare("INSERT INTO ". $self->dbtable() . " (" . join(',', @fields) . ") VALUES (" . '?,' x ($i-1) . '?)');
404 }
405 $i = 1;
406 foreach my $key (@fields) {
407 my $content = ${$self}{$key};
408 if (ref($content) eq '') {
409 $sth->bind_param($i, $content);
410 } elsif (ref($content) eq "ARRAY") {
411 # The content is an array, save it as such, ad hoc SQL3 for now.
412 $sth->bind_param($i, "{" . join(',', @{$content}) . "}");
413 } else {
414 # Actually, I should never get here, but anyway...:
415 warn "Advanced forms of references aren't implemented meaningfully yet. Don't be surprised if I crash or corrupt something.";
416 $content->save(); # IOW: Panic!! Everybody save yourselves if you can! :-)
417 }
418 $i++;
419 }
420 if (${$self}{'ONFILE'}) {
421 $sth->bind_param($i, $dbkey);
422 }
423 $sth->execute();
424 }
425 return $self;
426 }
427  
428  
429 =item C<exist(%limitargs)>
430  
431 This method can be used to check if a record allready exists. The
432 argument is the hash you would give to C<limit> in the load method.
433  
434 =cut
435  
436 sub exist {
437 my $self = shift;
438 my %args = @_;
439 my $data = $self->_load(what => 1, limit => \%args);
440 return scalar($data);
441 }
442  
443  
444 =item C<stored()>
445  
446 Checks if a record with the present object's identifier is allready
447 present in the datastore. Returns 1 if this is so.
448  
449 =cut
450  
451 # TODO, this needs to be more generic, should probably use _load.
452 sub stored {
453 my $self = shift;
454 return 1 if ${$self}{'ONFILE'};
455 my $dbh = DBI->connect($self->dbconnectargs());
456 my $check = scalar($dbh->selectrow_array("SELECT 1 FROM " . $self->dbtable() . " WHERE " . $self->dbprimkey() . "=?", {}, ${$self}{$self->dbprimkey()}));
457 ${$self}{'ONFILE'} = $check;
458 return $check;
459 }
460  
461  
462  
463 =item C<onfile>
464  
465 Method to set a flag to indicate that the record is in the data store.
466  
467 =cut
468  
469
470 sub onfile {
471 my $self = shift;
472 ${$self}{'ONFILE'} = 1;
473 return $self;
474 }
475  
476 =item C<dbconnectargs(@args)>
477  
478 This method will set or retrieve the arguments that are passed to
479 L<DBI>'s C<connect> method. Since this needs to be done for every
480 object, you may also pass these arguments to the C<new> constructor of
481 each subclass. However, it is recommended that you use environment
482 variables instead.
483  
484 =cut
485  
486 sub dbconnectargs {
487 my $self = shift;
488 if (@_) {
489 ${$self}{'DBCONNECTARGS'} = \@_;
490 }
491 return @{${$self}{'DBCONNECTARGS'}};
492 }
493  
494  
495 =item C<elementneedsparse($string)>
496  
497 User-supplied formatting may not be valid XHTML, and so needs to be
498 validated and parsed. This method takes a string consisting of a
499 comma-separated list of fields that needs parsing as argument, or will
500 return such a list if it is not given.
501  
502 =item C<xmlelement($string)>
503  
504 This method is I<intended> for internal use, but if you can use it
505 without shooting somebody in the foot (including yourself), fine by
506 me... It sets the root element that will enclose an
507 object's data to C<$string>, or return it if not given.
508  
509 =cut
510  
511  
512 sub xmlelement {
513 my $self = shift;
514 if (@_) {
515 ${$self}{'XMLELEMENT'} = shift;
516 }
517 return ${$self}{'XMLELEMENT'};
518 }
519  
520  
521 =item C<xmlns($string)>
522  
523 Like C<xmlelement()>, this method is I<intended> for internal
524 use. It sets the namespace URI of the XML representation of an object
525 to C<$string>, or return it if not given.
526  
527 =cut
528  
529  
530  
531 sub xmlns {
532 my $self = shift;
533 if (@_) {
534 ${$self}{'XMLNS'} = shift;
535 }
536 return ${$self}{'XMLNS'};
537 }
538  
539  
540 =item C<xmlprefix($string)>
541  
542 Alse like C<xmlelement()>, this method is I<intended> for internal
543 use. It sets the namespace prefix of the XML representation of an
544 object to C<$string>, to allow using QNames, or return it if not given.
545  
546  
547 =back
548  
549 =cut
550  
551  
552  
553 sub xmlprefix {
554 my $self = shift;
555 if (@_) {
556 ${$self}{'XMLPREFIX'} = shift;
557 }
558 return ${$self}{'XMLPREFIX'};
559 }
560  
561  
562  
563 #=item C<elementorder($string)>
564  
565 #This string contains a comma-separated list of all fields of a class that will be included in the XML, and in the order specified.
566  
567  
568 # Some inheritable methods and defaults
569 AxKit::App::TABOO::Data->mk_classdata('dbfrom');
570 AxKit::App::TABOO::Data->mk_classdata('dbtable');
571 AxKit::App::TABOO::Data->mk_classdata('dbprimkey');
572 AxKit::App::TABOO::Data->mk_classdata('elementorder');
573 AxKit::App::TABOO::Data->mk_classdata('elementneedsparse');
574  
575  
576  
577 =head1 STORED DATA
578  
579 The data is stored in named fields, currently in a database, but there
580 is nothing stopping you from subclassing the Data classes and storing
581 it somewhere else. TABOO should work well, but if you want to make it
582 less painful for yourself, you should use the same names or provide
583 some kind of mapping between your names and the names in these Data
584 classes. Note that any similarity between these names and the internal
585 names of this class is purely coincidential (eh, not really).
586  
587 Consult the documentation for each individual Data class for the names
588 of the stored data.
589  
590  
591 =head1 BUGS/TODO
592  
593 There is the issue with the handling of references to other objects in
594 the C<save()> method. I think it may actually cope in most cases, but
595 it definately could use some more attention.
596  
597  
598 =head1 FORMALITIES
599  
600 See L<AxKit::App::TABOO>.
601  
602 =cut
603  
604 1;
605