1 package C4::Labels::Label;
3 # Copyright 2006 Katipo Communications.
4 # Some parts Copyright 2009 Foundations Bible College.
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA 02111-1307 USA
24 use Sys::Syslog qw(syslog);
26 use Algorithm::CheckDigits;
35 use version; our $VERSION = qv('1.0.0_1');
39 my ( $llx, $lly, $width, $height ) = @_;
40 my $obj_stream = "q\n"; # save the graphic state
41 $obj_stream .= "0.5 w\n"; # border line width
42 $obj_stream .= "1.0 0.0 0.0 RG\n"; # border color red
43 $obj_stream .= "1.0 1.0 1.0 rg\n"; # fill color white
44 $obj_stream .= "$llx $lly $width $height re\n"; # a rectangle
45 $obj_stream .= "B\n"; # fill (and a little more)
46 $obj_stream .= "Q\n"; # restore the graphic state
51 my $item_number = shift;
52 my $barcode_only = shift || 0;
53 my $dbh = C4::Context->dbh;
55 # FIXME This makes for a very bulky data structure; data from tables w/duplicate col names also gets overwritten.
56 # Something like this, perhaps, but this also causes problems because we need more fields sometimes.
57 # SELECT i.barcode, i.itemcallnumber, i.itype, bi.isbn, bi.issn, b.title, b.author
58 "SELECT bi.*, i.*, b.*
59 FROM items AS i, biblioitems AS bi ,biblio AS b
60 WHERE itemnumber=? AND i.biblioitemnumber=bi.biblioitemnumber AND bi.biblionumber=b.biblionumber";
61 my $sth = $dbh->prepare($query);
62 $sth->execute($item_number);
64 syslog("LOG_ERR", "C4::Labels::Label::_get_label_item : Database returned the following error: %s", $sth->errstr);
66 my $data = $sth->fetchrow_hashref;
67 # Replaced item's itemtype with the more user-friendly description...
68 my $sth1 = $dbh->prepare("SELECT itemtype,description FROM itemtypes WHERE itemtype = ?");
69 $sth1->execute($data->{itemtype});
71 syslog("LOG_ERR", "C4::Labels::Label::_get_label_item : Database returned the following error: %s", $sth1->errstr);
73 my $data1 = $sth->fetchrow_hashref;
74 $data->{'itemtype'} = $data1->{'description'};
75 $data->{'itype'} = $data1->{'description'};
76 $barcode_only ? return $data->{'barcode'} : return $data;
79 sub _get_text_fields {
80 my $format_string = shift;
81 my $csv = Text::CSV_XS->new({allow_whitespace => 1});
82 my $status = $csv->parse($format_string);
83 my @sorted_fields = map {{ 'code' => $_, desc => $_ }} $csv->fields();
84 my $error = $csv->error_input();
85 syslog("LOG_ERR", "C4::Labels::Label::_get_text_fields : Text field sort failed with this error: %s", $error) if $error;
86 return \@sorted_fields;
91 my ($ll, $wnl, $dec, $cutter, $pubdate) = (0, 0, 0, 0, 0);
93 # lccn example 'HE8700.7 .P6T44 1983';
96 ([0-9]+\.*[0-9]*) # 8700.7
98 (\.*[a-zA-Z0-9]*) # P6T44
103 # strip something occuring spaces too
104 $splits[0] =~ s/\s+$//;
105 $splits[1] =~ s/\s+$//;
106 $splits[2] =~ s/\s+$//;
113 $ddcn =~ s/\///g; # in theory we should be able to simply remove all segmentation markers and arrive at the correct call number...
115 # ddcn example R220.3 H2793Z H32 c.2
116 my @splits = m/^([A-Z]{0,3}) # R (OS, REF, etc. up do three letters)
117 ([0-9]+\.[0-9]*) # 220.3
118 \s? # space (not requiring anything beyond the call number)
119 ([a-zA-Z0-9]*\.?[a-zA-Z0-9])# cutter number... maybe, but if so it is in this position (Z indicates literary criticism)
120 \s? # space if it exists
121 ([a-zA-Z]*\.?[0-9]*) # other indicators such as cutter for author of literary criticism in this example if it exists
122 \s? # space if ie exists
123 ([a-zA-Z]*\.?[0-9]*) # other indicators such as volume number, copy number, edition date, etc. if it exists
131 # Split fiction call numbers based on spaces
134 if ($fcn =~ m/([A-Za-z0-9]+\.?[0-9]?)(\W?).*?/x) {
135 push (@fcn_split, $1);
139 last SPLIT_FCN; # No match, break out of the loop
146 my ( $layout_id, $sorttype ) = @_;
148 my $sortorder = get_layout($layout_id);
150 return $sortorder->{'formatstring'};
153 my $csv = Text::CSV_XS->new( { allow_whitespace => 1 } );
154 my $line = $sortorder->{'formatstring'};
155 my $status = $csv->parse($line);
157 map { { 'code' => $_, desc => $_ } } $csv->fields();
158 if (my $error = $csv->error_input()) {
159 syslog("LOG_ERR", "C4::Labels::Label::_get_fields : Text::CSV_XS returned the following error: %s", $error);
164 sub _get_item_fields {
174 sub _get_barcode_data {
175 my ( $f, $item, $record ) = @_;
176 my $kohatables = _desc_koha_tables();
178 my $match_kohatable = join(
181 @{ $kohatables->{biblio} },
182 @{ $kohatables->{biblioitems} },
183 @{ $kohatables->{items} }
190 if ( $f =~ /^'(.*)'.*/ ) {
191 # single quotes indicate a static text string.
196 elsif ( $f =~ /^($match_kohatable).*/ ) {
198 $datastring .= $item->{$f};
201 syslog("LOG_ERR", "C4::Labels::Label::_get_barcode_data : The '%s' field contains no data.", $f);
206 elsif ( $f =~ /^([0-9a-z]{3})(\w)(\W?).*?/ ) {
207 my ($field,$subf,$ws) = ($1,$2,$3);
209 my ($itemtag, $itemsubfieldcode) = &GetMarcFromKohaField("items.itemnumber",'');
210 my @marcfield = $record->field($field);
212 if($field eq $itemtag) { # item-level data, we need to get the right item.
214 foreach my $itemfield (@marcfield) {
215 if ( $itemfield->subfield($itemsubfieldcode) eq $item->{'itemnumber'} ) {
216 if ($itemfield->subfield($subf)) {
217 $datastring .= $itemfield->subfield($subf) . $ws;
220 syslog("LOG_ERR", "C4::Labels::Label::_get_barcode_data : The '%s' field contains no data.", $f);
225 } else { # bib-level data, we'll take the first matching tag/subfield.
226 if ($marcfield[0]->subfield($subf)) {
227 $datastring .= $marcfield[0]->subfield($subf) . $ws;
230 syslog("LOG_ERR", "C4::Labels::Label::_get_barcode_data : The '%s' field contains no data.", $f);
238 syslog("LOG_ERR", "C4::Labels::Label::_get_barcode_data : Failed to parse label format string: %s", $f);
239 last FIELD_LIST; # Failed to match
245 sub _desc_koha_tables {
246 my $dbh = C4::Context->dbh();
248 for my $table ( 'biblio','biblioitems','items' ) {
249 my $sth = $dbh->column_info(undef,undef,$table,'%');
250 while (my $info = $sth->fetchrow_hashref()){
251 push @{$kohatables->{$table}} , $info->{'COLUMN_NAME'} ;
259 my ($invocant, %params) = @_;
260 my $type = ref($invocant) || $invocant;
261 my $layout = C4::Labels::Layout->retrieve(layout_id => $params{'layout_id'});
263 batch_id => $params{'batch_id'},
264 layout_id => $params{'layout_id'},
265 item_number => $params{'item_number'},
266 height => $params{'height'},
267 width => $params{'width'},
268 top_text_margin => $params{'top_text_margin'},
269 left_text_margin => $params{'left_text_margin'},
270 font => $params{'font'},
271 font_size => $params{'font_size'},
272 justify => $params{'justify'},
273 text_wrap_cols => $params{'text_wrap_cols'},
278 if ($layout->get_attr('guidebox')) {
279 $self->{'guidebox'} = _guide_box($self->{'llx'}, $self->{'lly'}, $self->{'width'}, $self->{'height'});
281 bless ($self, $type);
287 return $self->{'layout'}->get_attr('printing_type');
290 =head2 $label->draw_label_text()
292 Invoking the I<draw_label_text> method generates the label text for the label object.
294 $label->draw_label_text(
297 top_text_margin => $label_top_text_margin,
298 line_spacer => $text_leading,
300 font_size => $text_font_size,
301 justify => $text_justification,
305 sub draw_label_text {
306 my ($self, %params) = @_;
309 my $text_lly = $params{'lly'};
310 my $font = $self->{'font'};
311 my $item = _get_label_item($self->{item_number});
312 my $label_fields = _get_text_fields($self->{layout}->get_attr('format_string'));
313 my $record = GetMarcBiblio($item->{biblionumber});
314 # FIXME - returns all items, so you can't get data from an embedded holdings field.
315 # TODO - add a GetMarcBiblio1item(bibnum,itemnum) or a GetMarcItem(itemnum).
316 my $cn_source = ($item->{'cn_source'} ? $item->{'cn_source'} : C4::Context->preference('DefaultClassificationSource'));
317 LABEL_FIELDS: # process data for requested fields on current label
318 for my $field (@$label_fields) {
319 if ($field->{'code'} eq 'itemtype') {
320 $field->{'data'} = C4::Context->preference('item-level_itypes') ? $item->{'itype'} : $item->{'itemtype'};
323 $field->{'data'} = _get_barcode_data($field->{'code'},$item,$record);
325 ($field->{'code'} eq 'title') ? (($font =~ /T/) ? ($font = 'TI') : ($font = ($font . 'O'))) : ($font = $font);
326 my $field_data = $field->{'data'};
327 $field_data =~ s/\n//g;
328 $field_data =~ s/\r//g;
330 my @callnumber_list = ('itemcallnumber', '050a', '050b', '082a', '952o'); # Fields which hold call number data FIXME: ( 060? 090? 092? 099? )
331 if ((grep {$field->{'code'} =~ m/$_/} @callnumber_list) and ($self->{layout}->get_attr('printing_type') eq 'BIB') and ($self->{layout}->get_attr('callnum_split'))) { # If the field contains the call number, we do some sp
332 if ($cn_source eq 'lcc') {
333 @label_lines = _split_lccn($field_data);
334 @label_lines = _split_fcn($field_data) if !@label_lines; # If it was not a true lccn, try it as a fiction call number
335 push (@label_lines, $field_data) if !@label_lines; # If it was not that, send it on unsplit
336 } elsif ($cn_source eq 'ddc') {
337 @label_lines = _split_ddcn($field_data);
338 @label_lines = _split_fcn($field_data) if !@label_lines;
339 push (@label_lines, $field_data) if !@label_lines;
341 syslog("LOG_ERR", "C4::Labels::Label->draw_label_text : Call number splitting failed for: %s. Please add this call number to bug #2500 at bugs.koha.org", $field_data);
342 push @label_lines, $field_data;
346 $field_data =~ s/\/$//g; # Here we will strip out all trailing '/' in fields other than the call number...
347 $field_data =~ s/\(/\\\(/g; # Escape '(' and ')' for the pdf object stream...
348 $field_data =~ s/\)/\\\)/g;
349 eval{local($Text::Wrap::columns) = $self->{'text_wrap_cols'};};
350 my @line = split(/\n/ ,wrap('', '', $field_data));
351 # If this is a title field, limit to two lines; all others limit to one... FIXME: this is rather arbitrary
352 if ($field->{'code'} eq 'title' && scalar(@line) >= 2) {
353 while (scalar(@line) > 2) {
357 while (scalar(@line) > 1) {
361 push(@label_lines, @line);
363 LABEL_LINES: # generate lines of label text for current field
364 foreach my $line (@label_lines) {
365 next LABEL_LINES if $line eq '';
366 my $string_width = C4::Labels::PDF->StrWidth($line, $font, $self->{'font_size'});
367 if ($self->{'justify'} eq 'R') {
368 $text_llx = $params{'llx'} + $self->{'width'} - ($self->{'left_text_margin'} + $string_width);
369 } elsif($self->{'justify'} eq 'C') {
370 # some code to try and center each line on the label based on font size and string point width...
371 my $whitespace = ($self->{'width'} - ($string_width + (2 * $self->{'left_text_margin'})));
372 $text_llx = (($whitespace / 2) + $params{'llx'} + $self->{'left_text_margin'});
374 $text_llx = ($params{'llx'} + $self->{'left_text_margin'});
377 text_llx => $text_llx,
378 text_lly => $text_lly,
380 font_size => $self->{'font_size'},
383 $text_lly = $text_lly - $params{'line_spacer'};
385 $font = $self->{'font'}; # reset font for next field
390 =head2 $label->barcode()
392 Invoking the I<barcode> method generates a barcode for the label object and inserts it into the current pdf stream. C<barcode_data> is optional
393 and omitting it will cause the barcode from the current item to be used. C<barcode_type> is also optional. Omission results in the barcode
394 type of the current template being used.
400 width => $barcode_width,
401 y_scale_factor => $barcode_y_scale_factor,
402 barcode_data => $barcode,
403 barcode_type => $barcodetype,
410 $params{'barcode'} = _get_label_item($self->{'item_number'}, 1) if !$params{'barcode'};
411 $params{'barcode_type'} = $self->{'layout'}->get_attr('barcode_type') if !$params{'barcode_type'};
412 my $x_scale_factor = 1;
413 my $num_of_bars = length($params{'barcode'});
414 my $tot_bar_length = 0;
416 my $guard_length = 10;
417 my $hide_text = 'yes';
418 if ($params{'barcode_type'} =~ m/CODE39/) {
419 $bar_length = '17.5';
420 $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2);
421 $x_scale_factor = ($params{'width'} / $tot_bar_length);
422 if ($params{'barcode_type'} eq 'CODE39MOD') {
423 my $c39 = CheckDigits('visa'); # get modulo43 checksum
424 $params{'barcode'} = $c39->complete($params{'barcode'});
426 elsif ($params{'barcode_type'} eq 'CODE39MOD10') {
427 my $c39_10 = CheckDigits('visa'); # get modulo43 checksum
428 $params{'barcode'} = $c39_10->complete($params{'barcode'});
432 PDF::Reuse::Barcode::Code39(
435 value => "*$params{barcode}*",
436 xSize => $x_scale_factor,
437 ySize => $params{'y_scale_factor'},
444 syslog("LOG_ERR", "Barcode generation failed for item %s with this error: %s", $self->{'item_number'}, $@);
447 elsif ($params{'barcode_type'} eq 'COOP2OF5') {
448 $bar_length = '9.43333333333333';
449 $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2);
450 $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9;
452 PDF::Reuse::Barcode::COOP2of5(
455 value => "*$params{barcode}*",
456 xSize => $x_scale_factor,
457 ySize => $params{'y_scale_factor'},
462 syslog("LOG_ERR", "Barcode generation failed for item %s with this error: %s", $self->{'item_number'}, $@);
465 elsif ( $params{'barcode_type'} eq 'INDUSTRIAL2OF5' ) {
466 $bar_length = '13.1333333333333';
467 $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2);
468 $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9;
470 PDF::Reuse::Barcode::Industrial2of5(
473 value => "*$params{barcode}*",
474 xSize => $x_scale_factor,
475 ySize => $params{'y_scale_factor'},
480 syslog("LOG_ERR", "Barcode generation failed for item %s with this error: %s", $self->{'item_number'}, $@);
490 Mason James <mason@katipo.co.nz>
491 Chris Nighswonger <cnighswonger AT foundations DOT edu>