TABOO/Data/Article.pm untested

filter: Statementstmt 0.0% 0 / 275 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 393 CC 29 SCAR 40.9
CC
29
Cov
0%
save
210.0
date
20.0
load
12.0
CRAP 59.5
1 package AxKit::App::TABOO::Data::Article;
2 use strict;
3 use warnings;
4 use Carp;
5 use Encode;
6  
7  
8 use Data::Dumper;
9 use AxKit::App::TABOO::Data;
10 use vars qw/@ISA/;
11  
12 @ISA = qw(AxKit::App::TABOO::Data);
13 use AxKit::App::TABOO::Data::User;
14 use AxKit::App::TABOO::Data::Category;
15 use AxKit::App::TABOO::Data::MediaType;
16 use AxKit::App::TABOO::Data::Plurals::Users;
17 use AxKit::App::TABOO::Data::Plurals::Categories;
18 use Time::Piece;
19 use MIME::Types;
20  
21 use DBI;
22  
23  
24 our $VERSION = '0.3';
25  
26  
27 =head1 NAME
28  
29 AxKit::App::TABOO::Data::Article - Article Data object for TABOO
30  
31 =head1 SYNOPSIS
32  
33 use AxKit::App::TABOO::Data::Article;
34 [etc ... similar as for other Data objects]
35  
36 =head1 DESCRIPTION
37  
38 This Data class contains an mainly metadata for an article. These
39 articles are of a more static nature than typical news stories.
40  
41 =head1 METHODS
42  
43 This class implements several methods, reimplements the load method,
44 but inherits some from L<AxKit::App::TABOO::Data>.
45  
46 =over
47  
48 =item C<new(@dbconnectargs)>
49  
50 The constructor. Nothing special.
51  
52 =cut
53  
54 AxKit::App::TABOO::Data::Article->dbtable("articles");
55 AxKit::App::TABOO::Data::Article->dbfrom("articles JOIN languages ON (languages.ID = articles.lang_ID) JOIN mediatypes ON (mediatypes.ID = articles.format_ID)");
56 AxKit::App::TABOO::Data::Article->dbprimkey("filename");
57 AxKit::App::TABOO::Data::Article->elementorder("filename, lang, primcat, seccat, freesubject, editorok, authorok, title, description, AUTHORS, date, publisher, type, format, coverage, rights");
58  
59  
60 sub new {
61 my $that = shift;
62 my $class = ref($that) || $that;
63 my $self = {
64 filename => undef,
65 primcat => undef,
66 seccat => [],
67 freesubject => [],
68 angles => [],
69 authorok => undef,
70 editorok => undef,
71 title => undef,
72 description => undef,
73 publisher => undef,
74 date => undef,
75 type => undef,
76 format => undef,
77 lang => undef,
78 coverage => undef,
79 rights => [],
80 authorids => [],
81 AUTHORS => undef,
82 DBCONNECTARGS => \@_,
83 XMLELEMENT => 'article',
84 XMLPREFIX => 'art',
85 XMLNS => 'http://www.kjetil.kjernsmo.net/software/TABOO/NS/Article/Output',
86 ONFILE => undef,
87 };
88 bless($self, $class);
89 return $self;
90 }
91  
92  
93 =item C<load(what =E<gt> fields, limit =E<gt> {filename =E<gt> value, primcat =E<gt> value, [...]})>
94  
95 This is a reimplementation of the load method, see the parent class
96 for details. It needs to get the category and user information, which
97 is not currently done very rigorously and will happen regardless of
98 the C<what> parameter. In the current implementation, C<filename> is
99 sufficient to identify an article uniquely, that may change in the
100 future, so you may want to supply C<primcat> too.
101  
102 =cut
103  
104 sub load
105 {
106 my ($self, %args) = @_;
107 my $what = $args{'what'} || '*';
108 if ($what eq '*') {
109 $what = 'articles.ID,articles.filename,articles.authorok,articles.editorok,articles.title,articles.description,articles.publisher,articles.date,articles.type,articles.identifieruri,articles.identifierurn,articles.coverage,articles.rights,mediatypes.mimetype,languages.code';
110 }
111 $args{'what'} = $what;
112 my $data = $self->_load(%args);
113 warn Dumper($data);
114 return undef unless ($data);
115 ${$self}{'ONFILE'} = 1;
116 my $dbh = DBI->connect($self->dbconnectargs());
117 # TODO: check 'what'
118 my $categories = $dbh->selectall_arrayref("SELECT categories.catname, articlecats.field FROM categories JOIN articlecats ON (categories.ID = Cat_ID) JOIN articles ON (articlecats.Article_ID=articles.ID) WHERE articlecats.Article_ID=?", {}, (${$data}{'id'}));
119  
120 my $users = $dbh->selectcol_arrayref("SELECT users.username FROM users JOIN articleusers ON (users.ID = Users_ID) JOIN articles ON (articleusers.Article_ID=articles.ID) WHERE articleusers.Article_ID=? ORDER BY articleusers.Users_ID", {}, (${$data}{'id'}));
121  
122 $self->populate($data,$categories,$users);
123 warn Dumper($self);
124 return $self;
125 }
126  
127 =item C<populate($articles, $categories, $users)>
128  
129 This class reimplements the C<populate> method and gives it a new
130 interface. C<$articles> must be a hashref where the keys correspond to
131 that of the data store. C<categories> must be an arrayref where the
132 elements contain another arrayref, where the first element is the
133 C<catname>, i.e. identifier for the category, and the second is the
134 field type, i.e. whether it is a primary category, free subject words,
135 etc. C<$users> must contain an arrayref with the C<username>s of the
136 authors.
137  
138 =cut
139  
140  
141 sub populate {
142 my $self = shift;
143 my $articles = shift;
144 my $categories = shift;
145 my @keys = grep(/[a-z]+/, keys(%{$self})); # all the lower-case keys
146 foreach my $key (@keys) {
147 if (defined(${$articles}{$key}) && (${$articles}{$key} =~ m/^\{(\S+)\}$/)) { # Support SQL3 arrays ad hoc
148 my @arr = split(/\,/, $1);
149 ${$self}{$key} = \@arr;
150 } else {
151 ${$self}{$key} = Encode::decode_utf8(${$articles}{$key}, Encode::FB_HTMLCREF);
152 }
153 }
154 ${$self}{'authorids'} = shift;
155 ${$self}{'lang'} = ${$articles}{'code'};
156 ${$self}{'format'} = ${$articles}{'mimetype'};
157 foreach my $cat (@{$categories}) {
158 if (${$cat}[1] eq 'primcat') {
159 ${$self}{'primcat'} = ${$cat}[0];
160 } else {
161 push(@{${$self}{${$cat}[1]}}, ${$cat}[0]);
162 }
163 }
164 return $self;
165 }
166  
167 =item C<save()>
168  
169 The C<save()> method is reimplemented too, and it works similarly to
170 that of the parent class, so it is straightforward to use. Note,
171 however, that it is not able yet to update an existing record.
172  
173 =cut
174  
175 sub save {
176 my $self = shift;
177 my $dbh = DBI->connect($self->dbconnectargs());
178 my @fields;
179 my $i=0;
180 my $catsusers=0;
181 foreach my $key (keys(%{$self})) {
182 next if ($key =~ m/[A-Z]/); # Uppercase keys are not in db
183 next unless defined(${$self}{$key}); # No need to insert something that isn't there
184 if (grep(/^$key$/, qw(primcat seccat freesubject angles authorids))) {
185 # Needs to be dealt with specially
186 $catsusers=1;
187 next;
188 }
189 $key =~ s/^(format|lang)$/$1_id/;
190 push(@fields, $key);
191 $i++;
192 }
193 if (($i == 0) && ($catsusers == 0)) {
194 carp "No data fields with anything to save";
195 } else {
196 my $sth;
197 my ($articleid) = $dbh->selectrow_array("SELECT id FROM articles WHERE filename=?", {}, ${$self}{'filename'});
198 if ($articleid) {
199 die "Updating articles not yet implemented. Filename ${$self}{'filename'} exists";
200 } else {
201 ($articleid) = $dbh->selectrow_array("SELECT NEXTVAL('articles_id_seq')");
202 $sth = $dbh->prepare("INSERT INTO articles (id, " . join(',', @fields) . ") VALUES (" . '?,' x $i . '?)');
203 $sth->bind_param(1, $articleid);
204 $i = 2;
205 foreach my $key (@fields) {
206 my $content = ${$self}{$key};
207 if ($key eq 'format_id') {
208 my ($fid) = $dbh->selectrow_array("SELECT id FROM mediatypes WHERE mimetype=?", {}, ${$self}{'format'});
209 croak(${$self}{'format'} . " doesn't exist in database, insert first") unless ($fid);
210 $sth->bind_param($i, $fid);
211 } elsif ($key eq 'lang_id') {
212 my ($lid) = $dbh->selectrow_array("SELECT id FROM languages WHERE code=?", {}, ${$self}{'lang'});
213 croak(${$self}{'lang'} . " doesn't exist in database, insert first") unless ($lid);
214 $sth->bind_param($i, $lid);
215 } elsif (ref($content) eq '') {
216 $sth->bind_param($i, $content);
217 } elsif (ref($content) eq "ARRAY") {
218 # The content is an array, save it as such, ad hoc SQL3 for now.
219 $sth->bind_param($i, "{" . join(',', @{$content}) . "}");
220 } else {
221 # Actually, I should never get here, but anyway...:
222 warn "Advanced forms of references aren't implemented meaningfully yet. Don't be surprised if I crash or corrupt something.";
223 $content->save(); # IOW: Panic!! Everybody save yourselves if you can! :-)
224 }
225 $i++;
226 }
227 $sth->execute;
228  
229 foreach my $catfield (qw(primcat seccat freesubject angles)) {
230 if ((ref(${$self}{$catfield}) eq 'ARRAY') && scalar(@{${$self}{$catfield}})) {
231 warn Dumper(($articleid, $catfield, @{${$self}{$catfield}}));
232 $dbh->do("INSERT INTO articlecats (article_id, field, cat_id) SELECT ?,?,id FROM categories WHERE catname IN (?" . ',?' x (scalar(@{${$self}{$catfield}})-1) . ')', {}, ($articleid, $catfield, @{${$self}{$catfield}}));
233 } elsif (defined(${$self}{$catfield})) {
234 $dbh->do("INSERT INTO articlecats (article_id, field, cat_id) SELECT ?,?,id FROM categories WHERE catname=?", {}, ($articleid, $catfield, ${$self}{$catfield}));
235  
236 }
237 }
238 $dbh->do("INSERT INTO articleusers (article_id, role_id, enabled, users_id) SELECT ?,1,true,id FROM users WHERE username IN (?" . ',?' x (scalar(@{${$self}{'authorids'}})-1) . ')', {}, ($articleid, @{${$self}{'authorids'}}));
239 }
240 }
241 return $self;
242 }
243  
244  
245 =item C<adduserinfo()>
246  
247 When data has been loaded into an object of this class, it will
248 contain a string only identifying a user, the authors of the article.
249 This method will replace those strings with a reference to a
250 L<AxKit::App::TABOO::Data::User>-object, containing the needed user
251 information.
252  
253 =cut
254  
255 sub adduserinfo {
256 my $self = shift;
257 my $users = AxKit::App::TABOO::Data::Plurals::Users->new($self->dbconnectargs());
258 foreach my $username (@{${$self}{'authorids'}}) {
259 my $user = AxKit::App::TABOO::Data::User->new($self->dbconnectargs());
260 $user->xmlelement("author");
261 $user->load(what => 'username,name', limit => {username => $username});
262 $users->Push($user);
263 }
264 ${$self}{'AUTHORS'} = $users;
265 return $self;
266 }
267  
268 =item C<addcatinfo()>
269  
270 Similarly to adding user info, this method will also add category
271 information, for different types of categories, again by creating a
272 reference to a L<AxKit::App::TABOO::Data::Category>-object and calling
273 its C<load>-method with the string from the data loaded by the article
274 as argument.
275  
276 =cut
277  
278 sub addcatinfo {
279 my $self = shift;
280 my @cattypes = qw(primcat seccat freesubject angles);
281 foreach my $cattype (@cattypes) {
282 # warn $cattype . ": ". ref(${$self}{$cattype});
283 if (ref(${$self}{$cattype}) eq 'ARRAY') {
284 my $cats = AxKit::App::TABOO::Data::Plurals::Categories->new($self->dbconnectargs());
285 $cats->xmlelement($cattype);
286 foreach my $catname (@{${$self}{$cattype}}) {
287 my $cat = AxKit::App::TABOO::Data::Category->new($self->dbconnectargs());
288 $cat->load(limit => {catname => $catname});
289 $cats->Push($cat);
290 }
291 ${$self}{$cattype} = $cats;
292 } elsif (defined(${$self}{$cattype})) {
293 my $cat = AxKit::App::TABOO::Data::Category->new($self->dbconnectargs());
294 $cat->xmlelement($cattype);
295 $cat->load(limit => {catname => ${$self}{$cattype}});
296 ${$self}{$cattype} = $cat;
297 } else {
298 # Actually, this is where we have an empty list
299 ${$self}{$cattype} = [];
300 }
301 }
302
303 return $self;
304 }
305  
306 =item C<addformatinfo()>
307  
308 Similarly to adding user info, this method will also add format
309 (i.e. MIME type) information, for different types of categories, again
310 by creating a reference to a
311 L<AxKit::App::TABOO::Data::MediaType>-object and calling its
312 C<load>-method with the string from the data loaded by the article as
313 argument.
314  
315 =cut
316  
317 sub addformatinfo {
318 my $self = shift;
319 my $type = AxKit::App::TABOO::Data::MediaType->new($self->dbconnectargs());
320 $type->load(limit => {mimetype => ${$self}{'format'}});
321 ${$self}{'format'} = $type;
322 return $self;
323 }
324  
325 =item C<date([$filename|Time::Piece])>
326  
327 The date method will retrieve or set the date of the
328 article. If the date has been loaded earlier from the data storage
329 (for example by the load method), you need not supply any
330 arguments. If the date is not available, you must supply the
331 filename identifier, the method will then load it into
332 the data structure first.
333  
334 The date method will return a L<Time::Piece> object with the
335 requested time information.
336  
337 To set the date, you must supply a L<Time::Piece> object, the
338 date is set to the time given by that object.
339  
340 =cut
341  
342 sub date {
343 my $self = shift;
344 my $arg = shift;
345 if (ref($arg) eq 'Time::Piece') {
346 ${$self}{'date'} = $arg->datetime;
347 return $self;
348 }
349 if (! ${$self}{'date'}) {
350 my $filename = shift;
351 $self->load(what => 'date', limit => {filename => $arg});
352 }
353 unless (${$self}{'date'}) { return undef; }
354 (my $tmp = ${$self}{'date'}) =~ s/\+\d{2}$//;
355 return Time::Piece->strptime($tmp, "%Y-%m-%d");
356 }
357  
358  
359 =item C<editorok([($filename)])>
360  
361 This is similar to the date method in interface, but can't be
362 used to set the value, only retrieves it. It returns the C<editorok>,
363 which is a boolean variable that can be used to see if an editor
364 has approved a article.
365  
366 It takes arguments like the date method does, and it will return
367 1 if the article has been approved, 0 if not.
368  
369  
370 =cut
371  
372 sub editorok {
373 my $self = shift;
374 unless (defined(${$self}{'editorok'})) {
375 my ($filename) = @_;
376 croak "No filename given to editorok and no earlier record" unless ($filename);
377 $self->load(what => 'editorok', limit => {filename => $filename});
378 }
379 return ${$self}{'editorok'};
380 }
381  
382 =item C<authorok([($filename)])>
383  
384 Identical to the C<editorok> method, but will return 1 if the article
385 has been approved by its I<authors>, 0 if not.
386  
387 =cut
388  
389 sub authorok {
390 my $self = shift;
391 unless (defined(${$self}{'authorok'})) {
392 my ($filename) = @_;
393 croak "No filename given to authorok and no earlier record" unless ($filename);
394 $self->load(what => 'authorok', limit => {filename => $filename});
395 }
396 return ${$self}{'authorok'};
397 }
398  
399 =item C<mimetype>
400  
401 Will return a L<MIME::Type> object representing the MIME-type of the
402 content of the article. In the present implementation, that's all it
403 is does, it can't be used to set the MIME-type, also it has to be
404 loaded allready before this method is called.
405  
406 =cut
407  
408 sub mimetype {
409 my $self = shift;
410 if (ref(${$self}{'format'}) eq 'MIME::Type') {
411 return ${$self}{'format'};
412 }
413 elsif (ref(${$self}{'format'}) eq 'AxKit::App::TABOO::Data::MediaType') {
414 return ${$self}{'format'}->mimetype;
415 }
416 my $mimetypes = MIME::Types->new(only_complete => 1);
417 my MIME::Type $type = $mimetypes->type(${$self}{'format'});
418 return $type;
419 }
420  
421 =item C<authorids>
422  
423 Will return an array containing the usernames of the authors of the
424 article, if they have been loaded.
425  
426 =cut
427  
428 sub authorids {
429 my $self = shift;
430 return @{$self}{'authorids'};
431 }
432  
433  
434 =back
435  
436 =head1 STORED DATA
437  
438 The data is stored in named fields, and for certain uses, it is good
439 to know them. If you want to subclass this class, you might want to
440 use the same names, see the documentation of
441 L<AxKit::App::TABOO::Data> for more about this.
442  
443 For those who didn't take my word for that the similarity between the
444 named fields and column names in the database was a coincidence, well,
445 too bad. The data of this class is more complex, and so this isn't
446 true anymore here.
447  
448 Nevertheless, it isn't less useful to know the names, so here goes:
449  
450 =over
451  
452 =item * filename - The filename of the content stored in the file system.
453  
454 =item * primcat - Primary categorization.
455  
456 =item * seccat - Secondary categorization, an array.
457  
458 =item * freesubject - Categorization in free subject terms, an array.
459  
460 =item * angles - Categorization in different viewing angles, an array.
461  
462 =item * authorok - If the authors have approved the article for publication, boolean.
463  
464 =item * editorok - If the editors have approved the article for publication, boolean.
465  
466 =item * authorids - The usernames of the article's author(s), an array.
467  
468 =item * title - Title of the article.
469  
470 =item * description - A description of the article.
471  
472 =item * publisher - URI (preferably) identifying the publisher.
473  
474 =item * date - Date of publication.
475  
476 =item * type - "The nature or genre of the content of the resource."
477  
478 =item * format - The MIME type of the content.
479  
480 =item * lang - Natural resource of the content.
481  
482 =item * coverage - "The extent or scope of the content of the resource."
483  
484 =item * rights - URIs describing copyright policy, e.g. Creative Commons.
485  
486 =back
487  
488 See L<AxKit::App::TABOO::Data::Category> for more about the different
489 category types. Also, note that many of these fields are taken from
490 the terms of the Dublin Core, including some of the labels.
491  
492  
493 =head1 XML representation
494  
495 The C<write_xml()> method, implemented in the parent class, can be
496 used to create an XML representation of the data in the object. The
497 above names will be used as element names. The C<xmlelement()>,
498 C<xmlns()> and C<xmlprefix()> methods can be used to set the name of
499 the root element, the namespace URI and namespace prefix
500 respectively. Usually, it doesn't make sense to change the defaults,
501 that are
502  
503  
504 =over
505  
506 =item * C<article>
507  
508 =item * C<http://www.kjetil.kjernsmo.net/software/TABOO/NS/Article/Output>
509  
510 =item * C<art>
511  
512 =back
513  
514 =head1 BUGS/TODO
515  
516 This class is rather experimental at this point, and has not seen the
517 same level of testing as the rest of TABOO. The C<save> method needs
518 the ability to update records, and the C<load> method should check the
519 C<what> parameter properly.
520  
521 =head1 FORMALITIES
522  
523 See L<AxKit::App::TABOO>.
524  
525 =cut
526  
527 1;