File Coverage

File:C4/Items.pm
Coverage:3.6%

linestmtbrancondsubtimecode
1package C4::Items;
2
3# Copyright 2007 LibLime, Inc.
4# Parts Copyright Biblibre 2010
5#
6# This file is part of Koha.
7#
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
11# version.
12#
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.
16#
17# You should have received a copy of the GNU General Public License along
18# with Koha; if not, write to the Free Software Foundation, Inc.,
19# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21
30
30
30
48761
200
910
use strict;
22#use warnings; FIXME - Bug 2505
23
24
30
30
30
257
160
2467
use Carp;
25
30
30
30
703
196
498
use C4::Context;
26
30
30
30
764
151
14334
use C4::Koha;
27
30
30
30
1215
198
15378
use C4::Biblio;
28
30
30
30
284
167
1931
use C4::Dates qw/format_date format_date_in_iso/;
29
30
30
30
1799
169
1313
use MARC::Record;
30
30
30
30
232
191
4886
use C4::ClassSource;
31
30
30
30
248
98
3321
use C4::Log;
32
30
30
30
44745
50253
2646
use List::MoreUtils qw/any/;
33
30
30
30
271
120
1885
use Data::Dumper; # used as part of logging item record changes, not just for
34                  # debugging; so please don't remove this
35
36
30
30
30
204
139
4213
use vars qw($VERSION @ISA @EXPORT);
37
38BEGIN {
39
30
202
    $VERSION = 3.01;
40
41
30
215
        require Exporter;
42
30
386
    @ISA = qw( Exporter );
43
44    # function exports
45
30
392802
    @EXPORT = qw(
46        GetItem
47        AddItemFromMarc
48        AddItem
49        AddItemBatchFromMarc
50        ModItemFromMarc
51                Item2Marc
52        ModItem
53        ModDateLastSeen
54        ModItemTransfer
55        DelItem
56
57        CheckItemPreSave
58
59        GetItemStatus
60        GetItemLocation
61        GetLostItems
62        GetItemsForInventory
63        GetItemsCount
64        GetItemInfosOf
65        GetItemsByBiblioitemnumber
66        GetItemsInfo
67        GetItemsLocationInfo
68        GetHostItemsInfo
69        get_itemnumbers_of
70        get_hostitemnumbers_of
71        GetItemnumberFromBarcode
72        GetBarcodeFromItemnumber
73        GetHiddenItemnumbers
74                DelItemCheck
75                MoveItemFromBiblio
76                GetLatestAcquisitions
77        CartToShelf
78
79        GetAnalyticsCount
80        GetItemHolds
81
82
83        PrepareItemrecordDisplay
84
85    );
86}
87
88 - 127
=head1 NAME

C4::Items - item management functions

=head1 DESCRIPTION

This module contains an API for manipulating item 
records in Koha, and is used by cataloguing, circulation,
acquisitions, and serials management.

A Koha item record is stored in two places: the
items table and embedded in a MARC tag in the XML
version of the associated bib record in C<biblioitems.marcxml>.
This is done to allow the item information to be readily
indexed (e.g., by Zebra), but means that each item
modification transaction must keep the items table
and the MARC XML in sync at all times.

Consequently, all code that creates, modifies, or deletes
item records B<must> use an appropriate function from 
C<C4::Items>.  If no existing function is suitable, it is
better to add one to C<C4::Items> than to use add
one-off SQL statements to add or modify items.

The items table will be considered authoritative.  In other
words, if there is ever a discrepancy between the items
table and the MARC XML, the items table should be considered
accurate.

=head1 HISTORICAL NOTE

Most of the functions in C<C4::Items> were originally in
the C<C4::Biblio> module.

=head1 CORE EXPORTED FUNCTIONS

The following functions are meant for use by users
of C<C4::Items>

=cut
128
129 - 137
=head2 GetItem

  $item = GetItem($itemnumber,$barcode,$serial);

Return item information, for a given itemnumber or barcode.
The return value is a hashref mapping item column
names to values.  If C<$serial> is true, include serial publication data.

=cut
138
139sub GetItem {
140
0
    my ($itemnumber,$barcode, $serial) = @_;
141
0
    my $dbh = C4::Context->dbh;
142
0
        my $data;
143
0
    if ($itemnumber) {
144
0
        my $sth = $dbh->prepare("
145            SELECT * FROM items
146            WHERE itemnumber = ?");
147
0
        $sth->execute($itemnumber);
148
0
        $data = $sth->fetchrow_hashref;
149    } else {
150
0
        my $sth = $dbh->prepare("
151            SELECT * FROM items
152            WHERE barcode = ?"
153            );
154
0
        $sth->execute($barcode);
155
0
        $data = $sth->fetchrow_hashref;
156    }
157
0
    if ( $serial) {
158
0
    my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
159
0
        $ssth->execute($data->{'itemnumber'}) ;
160
0
        ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
161    }
162        #if we don't have an items.itype, use biblioitems.itemtype.
163
0
        if( ! $data->{'itype'} ) {
164
0
                my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
165
0
                $sth->execute($data->{'biblionumber'});
166
0
                ($data->{'itype'}) = $sth->fetchrow_array;
167        }
168
0
    return $data;
169} # sub GetItem
170
171 - 181
=head2 CartToShelf

  CartToShelf($itemnumber);

Set the current shelving location of the item record
to its stored permanent shelving location.  This is
primarily used to indicate when an item whose current
location is a special processing ('PROC') or shelving cart
('CART') location is back in the stacks.

=cut
182
183sub CartToShelf {
184
0
    my ( $itemnumber ) = @_;
185
186
0
    unless ( $itemnumber ) {
187
0
        croak "FAILED CartToShelf() - no itemnumber supplied";
188    }
189
190
0
    my $item = GetItem($itemnumber);
191
0
    $item->{location} = $item->{permanent_location};
192
0
    ModItem($item, undef, $itemnumber);
193}
194
195 - 203
=head2 AddItemFromMarc

  my ($biblionumber, $biblioitemnumber, $itemnumber) 
      = AddItemFromMarc($source_item_marc, $biblionumber);

Given a MARC::Record object containing an embedded item
record and a biblionumber, create a new item record.

=cut
204
205sub AddItemFromMarc {
206
0
    my ( $source_item_marc, $biblionumber ) = @_;
207
0
    my $dbh = C4::Context->dbh;
208
209    # parse item hash from MARC
210
0
    my $frameworkcode = GetFrameworkCode( $biblionumber );
211
0
        my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
212
213
0
        my $localitemmarc=MARC::Record->new;
214
0
        $localitemmarc->append_fields($source_item_marc->field($itemtag));
215
0
    my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
216
0
    my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
217
0
    return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
218}
219
220 - 239
=head2 AddItem

  my ($biblionumber, $biblioitemnumber, $itemnumber) 
      = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);

Given a hash containing item column names as keys,
create a new Koha item record.

The first two optional parameters (C<$dbh> and C<$frameworkcode>)
do not need to be supplied for general use; they exist
simply to allow them to be picked up from AddItemFromMarc.

The final optional parameter, C<$unlinked_item_subfields>, contains
an arrayref containing subfields present in the original MARC
representation of the item (e.g., from the item editor) that are
not mapped to C<items> columns directly but should instead
be stored in C<items.more_subfields_xml> and included in 
the biblio items tag for display and indexing.

=cut
240
241sub AddItem {
242
0
    my $item = shift;
243
0
    my $biblionumber = shift;
244
245
0
    my $dbh = @_ ? shift : C4::Context->dbh;
246
0
    my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
247
0
    my $unlinked_item_subfields;
248
0
    if (@_) {
249
0
        $unlinked_item_subfields = shift
250    };
251
252    # needs old biblionumber and biblioitemnumber
253
0
    $item->{'biblionumber'} = $biblionumber;
254
0
    my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
255
0
    $sth->execute( $item->{'biblionumber'} );
256
0
    ($item->{'biblioitemnumber'}) = $sth->fetchrow;
257
258
0
    _set_defaults_for_add($item);
259
0
    _set_derived_columns_for_add($item);
260
0
    $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
261    # FIXME - checks here
262
0
    unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
263
0
        my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
264
0
        $itype_sth->execute( $item->{'biblionumber'} );
265
0
        ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
266    }
267
268
0
        my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
269
0
    $item->{'itemnumber'} = $itemnumber;
270
271
0
    ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
272
273
0
    logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
274
275
0
    return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
276}
277
278 - 321
=head2 AddItemBatchFromMarc

  ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
             $biblionumber, $biblioitemnumber, $frameworkcode);

Efficiently create item records from a MARC biblio record with
embedded item fields.  This routine is suitable for batch jobs.

This API assumes that the bib record has already been
saved to the C<biblio> and C<biblioitems> tables.  It does
not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
are populated, but it will do so via a call to ModBibiloMarc.

The goal of this API is to have a similar effect to using AddBiblio
and AddItems in succession, but without inefficient repeated
parsing of the MARC XML bib record.

This function returns an arrayref of new itemsnumbers and an arrayref of item
errors encountered during the processing.  Each entry in the errors
list is a hashref containing the following keys:

=over

=item item_sequence

Sequence number of original item tag in the MARC record.

=item item_barcode

Item barcode, provide to assist in the construction of
useful error messages.

=item error_condition

Code representing the error condition.  Can be 'duplicate_barcode',
'invalid_homebranch', or 'invalid_holdingbranch'.

=item error_information

Additional information appropriate to the error condition.

=back

=cut
322
323sub AddItemBatchFromMarc {
324
0
    my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
325
0
    my $error;
326
0
    my @itemnumbers = ();
327
0
    my @errors = ();
328
0
    my $dbh = C4::Context->dbh;
329
330    # loop through the item tags and start creating items
331
0
    my @bad_item_fields = ();
332
0
    my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
333
0
    my $item_sequence_num = 0;
334
0
    ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
335
0
        $item_sequence_num++;
336        # we take the item field and stick it into a new
337        # MARC record -- this is required so far because (FIXME)
338        # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
339        # and there is no TransformMarcFieldToKoha
340
0
        my $temp_item_marc = MARC::Record->new();
341
0
        $temp_item_marc->append_fields($item_field);
342
343        # add biblionumber and biblioitemnumber
344
0
        my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
345
0
        my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
346
0
        $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
347
0
        $item->{'biblionumber'} = $biblionumber;
348
0
        $item->{'biblioitemnumber'} = $biblioitemnumber;
349
350        # check for duplicate barcode
351
0
        my %item_errors = CheckItemPreSave($item);
352
0
        if (%item_errors) {
353
0
            push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
354
0
            push @bad_item_fields, $item_field;
355
0
            next ITEMFIELD;
356        }
357
358
0
        _set_defaults_for_add($item);
359
0
        _set_derived_columns_for_add($item);
360
0
        my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
361
0
        warn $error if $error;
362
0
        push @itemnumbers, $itemnumber; # FIXME not checking error
363
0
        $item->{'itemnumber'} = $itemnumber;
364
365
0
        logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
366
367
0
        my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
368
0
        $item_field->replace_with($new_item_marc->field($itemtag));
369    }
370
371    # remove any MARC item fields for rejected items
372
0
    foreach my $item_field (@bad_item_fields) {
373
0
        $record->delete_field($item_field);
374    }
375
376    # update the MARC biblio
377 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
378
379
0
    return (\@itemnumbers, \@errors);
380}
381
382 - 406
=head2 ModItemFromMarc

  ModItemFromMarc($item_marc, $biblionumber, $itemnumber);

This function updates an item record based on a supplied
C<MARC::Record> object containing an embedded item field.
This API is meant for the use of C<additem.pl>; for 
other purposes, C<ModItem> should be used.

This function uses the hash %default_values_for_mod_from_marc,
which contains default values for item fields to
apply when modifying an item.  This is needed beccause
if an item field's value is cleared, TransformMarcToKoha
does not include the column in the
hash that's passed to ModItem, which without
use of this hash makes it impossible to clear
an item field's value.  See bug 2466.

Note that only columns that can be directly
changed from the cataloging and serials
item editors are included in this hash.

Returns item record

=cut
407
408my %default_values_for_mod_from_marc = (
409    barcode => undef,
410    booksellerid => undef,
411    ccode => undef,
412    'items.cn_source' => undef,
413    copynumber => undef,
414    damaged => 0,
415# dateaccessioned => undef,
416    enumchron => undef,
417    holdingbranch => undef,
418    homebranch => undef,
419    itemcallnumber => undef,
420    itemlost => 0,
421    itemnotes => undef,
422    itype => undef,
423    location => undef,
424    permanent_location => undef,
425    materials => undef,
426    notforloan => 0,
427    paidfor => undef,
428    price => undef,
429    replacementprice => undef,
430    replacementpricedate => undef,
431    restricted => undef,
432    stack => undef,
433    stocknumber => undef,
434    uri => undef,
435    wthdrawn => 0,
436);
437
438sub ModItemFromMarc {
439
0
    my $item_marc = shift;
440
0
    my $biblionumber = shift;
441
0
    my $itemnumber = shift;
442
443
0
    my $dbh = C4::Context->dbh;
444
0
    my $frameworkcode = GetFrameworkCode($biblionumber);
445
0
    my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
446
447
0
    my $localitemmarc = MARC::Record->new;
448
0
    $localitemmarc->append_fields( $item_marc->field($itemtag) );
449
0
    my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
450
0
    foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
451
0
        $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
452    }
453
0
    my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
454
455
0
    ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
456
0
    return $item;
457}
458
459 - 482
=head2 ModItem

  ModItem({ column => $newvalue }, $biblionumber, $itemnumber);

Change one or more columns in an item record and update
the MARC representation of the item.

The first argument is a hashref mapping from item column
names to the new values.  The second and third arguments
are the biblionumber and itemnumber, respectively.

The fourth, optional parameter, C<$unlinked_item_subfields>, contains
an arrayref containing subfields present in the original MARC
representation of the item (e.g., from the item editor) that are
not mapped to C<items> columns directly but should instead
be stored in C<items.more_subfields_xml> and included in 
the biblio items tag for display and indexing.

If one of the changed columns is used to calculate
the derived value of a column such as C<items.cn_sort>, 
this routine will perform the necessary calculation
and set the value.

=cut
483
484sub ModItem {
485
0
    my $item = shift;
486
0
    my $biblionumber = shift;
487
0
    my $itemnumber = shift;
488
489    # if $biblionumber is undefined, get it from the current item
490
0
    unless (defined $biblionumber) {
491
0
        $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
492    }
493
494
0
    my $dbh = @_ ? shift : C4::Context->dbh;
495
0
    my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
496
497
0
    my $unlinked_item_subfields;
498
0
    if (@_) {
499
0
        $unlinked_item_subfields = shift;
500
0
        $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
501    };
502
503
0
    $item->{'itemnumber'} = $itemnumber or return undef;
504
505
0
    $item->{onloan} = undef if $item->{itemlost};
506
507
0
    _set_derived_columns_for_mod($item);
508
0
    _do_column_fixes_for_mod($item);
509    # FIXME add checks
510    # duplicate barcode
511    # attempt to change itemnumber
512    # attempt to change biblionumber (if we want
513    # an API to relink an item to a different bib,
514    # it should be a separate function)
515
516    # update items table
517
0
    _koha_modify_item($item);
518
519    # request that bib be reindexed so that searching on current
520    # item status is possible
521
0
    ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
522
523
0
    logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
524}
525
526 - 533
=head2 ModItemTransfer

  ModItemTransfer($itenumber, $frombranch, $tobranch);

Marks an item as being transferred from one branch
to another.

=cut
534
535sub ModItemTransfer {
536
0
    my ( $itemnumber, $frombranch, $tobranch ) = @_;
537
538
0
    my $dbh = C4::Context->dbh;
539
540    #new entry in branchtransfers....
541
0
    my $sth = $dbh->prepare(
542        "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
543        VALUES (?, ?, NOW(), ?)");
544
0
    $sth->execute($itemnumber, $frombranch, $tobranch);
545
546
0
    ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
547
0
    ModDateLastSeen($itemnumber);
548
0
    return;
549}
550
551 - 558
=head2 ModDateLastSeen

  ModDateLastSeen($itemnum);

Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
C<$itemnum> is the item number

=cut
559
560sub ModDateLastSeen {
561
0
    my ($itemnumber) = @_;
562
563
0
    my $today = C4::Dates->new();
564
0
    ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
565}
566
567 - 573
=head2 DelItem

  DelItem($dbh, $biblionumber, $itemnumber);

Exported function (core API) for deleting an item record in Koha.

=cut
574
575sub DelItem {
576
0
    my ( $dbh, $biblionumber, $itemnumber ) = @_;
577
578    # FIXME check the item has no current issues
579
580
0
    _koha_delete_item( $dbh, $itemnumber );
581
582    # get the MARC record
583
0
    my $record = GetMarcBiblio($biblionumber);
584
0
    ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
585
586    # backup the record
587
0
    my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
588
0
    $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
589    # This last update statement makes that the timestamp column in deleteditems is updated too. If you remove these lines, please add a line to update the timestamp separately. See Bugzilla report 7146 and Biblio.pm (DelBiblio).
590
591    #search item field code
592
0
    logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
593}
594
595 - 635
=head2 CheckItemPreSave

    my $item_ref = TransformMarcToKoha($marc, 'items');
    # do stuff
    my %errors = CheckItemPreSave($item_ref);
    if (exists $errors{'duplicate_barcode'}) {
        print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
    } elsif (exists $errors{'invalid_homebranch'}) {
        print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
    } elsif (exists $errors{'invalid_holdingbranch'}) {
        print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
    } else {
        print "item is OK";
    }

Given a hashref containing item fields, determine if it can be
inserted or updated in the database.  Specifically, checks for
database integrity issues, and returns a hash containing any
of the following keys, if applicable.

=over 2

=item duplicate_barcode

Barcode, if it duplicates one already found in the database.

=item invalid_homebranch

Home branch, if not defined in branches table.

=item invalid_holdingbranch

Holding branch, if not defined in branches table.

=back

This function does NOT implement any policy-related checks,
e.g., whether current operator is allowed to save an
item that has a given branch code.

=cut
636
637sub CheckItemPreSave {
638
0
    my $item_ref = shift;
639
0
    require C4::Branch;
640
641
0
    my %errors = ();
642
643    # check for duplicate barcode
644
0
    if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
645
0
        my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
646
0
        if ($existing_itemnumber) {
647
0
            if (!exists $item_ref->{'itemnumber'} # new item
648                or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
649
0
                $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
650            }
651        }
652    }
653
654    # check for valid home branch
655
0
    if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
656
0
        my $branch_name = GetBranchName($item_ref->{'homebranch'});
657
0
        unless (defined $branch_name) {
658            # relies on fact that branches.branchname is a non-NULL column,
659            # so GetBranchName returns undef only if branch does not exist
660
0
            $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
661        }
662    }
663
664    # check for valid holding branch
665
0
    if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
666
0
        my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
667
0
        unless (defined $branch_name) {
668            # relies on fact that branches.branchname is a non-NULL column,
669            # so GetBranchName returns undef only if branch does not exist
670
0
            $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
671        }
672    }
673
674
0
    return %errors;
675
676}
677
678 - 689
=head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS

The following functions provide various ways of 
getting an item record, a set of item records, or
lists of authorized values for certain item fields.

Some of the functions in this group are candidates
for refactoring -- for example, some of the code
in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
has copy-and-paste work.

=cut
690
691 - 727
=head2 GetItemStatus

  $itemstatushash = GetItemStatus($fwkcode);

Returns a list of valid values for the
C<items.notforloan> field.

NOTE: does B<not> return an individual item's
status.

Can be MARC dependant.
fwkcode is optional.
But basically could be can be loan or not
Create a status selector with the following code

=head3 in PERL SCRIPT

 my $itemstatushash = getitemstatus;
 my @itemstatusloop;
 foreach my $thisstatus (keys %$itemstatushash) {
     my %row =(value => $thisstatus,
                 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
             );
     push @itemstatusloop, \%row;
 }
 $template->param(statusloop=>\@itemstatusloop);

=head3 in TEMPLATE

 <select name="statusloop">
     <option value="">Default</option>
 <!-- TMPL_LOOP name="statusloop" -->
     <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
 <!-- /TMPL_LOOP -->
 </select>

=cut
728
729sub GetItemStatus {
730
731    # returns a reference to a hash of references to status...
732
0
    my ($fwk) = @_;
733
0
    my %itemstatus;
734
0
    my $dbh = C4::Context->dbh;
735
0
    my $sth;
736
0
    $fwk = '' unless ($fwk);
737
0
    my ( $tag, $subfield ) =
738      GetMarcFromKohaField( "items.notforloan", $fwk );
739
0
    if ( $tag and $subfield ) {
740
0
        my $sth =
741          $dbh->prepare(
742            "SELECT authorised_value
743            FROM marc_subfield_structure
744            WHERE tagfield=?
745                AND tagsubfield=?
746                AND frameworkcode=?
747            "
748          );
749
0
        $sth->execute( $tag, $subfield, $fwk );
750
0
        if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
751
0
            my $authvalsth =
752              $dbh->prepare(
753                "SELECT authorised_value,lib
754                FROM authorised_values
755                WHERE category=?
756                ORDER BY lib
757                "
758              );
759
0
            $authvalsth->execute($authorisedvaluecat);
760
0
            while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
761
0
                $itemstatus{$authorisedvalue} = $lib;
762            }
763
0
            return \%itemstatus;
764
0
            exit 1;
765        }
766        else {
767
768            #No authvalue list
769            # build default
770        }
771    }
772
773    #No authvalue list
774    #build default
775
0
    $itemstatus{"1"} = "Not For Loan";
776
0
    return \%itemstatus;
777}
778
779 - 815
=head2 GetItemLocation

  $itemlochash = GetItemLocation($fwk);

Returns a list of valid values for the
C<items.location> field.

NOTE: does B<not> return an individual item's
location.

where fwk stands for an optional framework code.
Create a location selector with the following code

=head3 in PERL SCRIPT

  my $itemlochash = getitemlocation;
  my @itemlocloop;
  foreach my $thisloc (keys %$itemlochash) {
      my $selected = 1 if $thisbranch eq $branch;
      my %row =(locval => $thisloc,
                  selected => $selected,
                  locname => $itemlochash->{$thisloc},
               );
      push @itemlocloop, \%row;
  }
  $template->param(itemlocationloop => \@itemlocloop);

=head3 in TEMPLATE

  <select name="location">
      <option value="">Default</option>
  <!-- TMPL_LOOP name="itemlocationloop" -->
      <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
  <!-- /TMPL_LOOP -->
  </select>

=cut
816
817sub GetItemLocation {
818
819    # returns a reference to a hash of references to location...
820
0
    my ($fwk) = @_;
821
0
    my %itemlocation;
822
0
    my $dbh = C4::Context->dbh;
823
0
    my $sth;
824
0
    $fwk = '' unless ($fwk);
825
0
    my ( $tag, $subfield ) =
826      GetMarcFromKohaField( "items.location", $fwk );
827
0
    if ( $tag and $subfield ) {
828
0
        my $sth =
829          $dbh->prepare(
830            "SELECT authorised_value
831            FROM marc_subfield_structure
832            WHERE tagfield=?
833                AND tagsubfield=?
834                AND frameworkcode=?"
835          );
836
0
        $sth->execute( $tag, $subfield, $fwk );
837
0
        if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
838
0
            my $authvalsth =
839              $dbh->prepare(
840                "SELECT authorised_value,lib
841                FROM authorised_values
842                WHERE category=?
843                ORDER BY lib"
844              );
845
0
            $authvalsth->execute($authorisedvaluecat);
846
0
            while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
847
0
                $itemlocation{$authorisedvalue} = $lib;
848            }
849
0
            return \%itemlocation;
850
0
            exit 1;
851        }
852        else {
853
854            #No authvalue list
855            # build default
856        }
857    }
858
859    #No authvalue list
860    #build default
861
0
    $itemlocation{"1"} = "Not For Loan";
862
0
    return \%itemlocation;
863}
864
865 - 897
=head2 GetLostItems

  $items = GetLostItems( $where, $orderby );

This function gets a list of lost items.

=over 2

=item input:

C<$where> is a hashref. it containts a field of the items table as key
and the value to match as value. For example:

{ barcode    => 'abc123',
  homebranch => 'CPL',    }

C<$orderby> is a field of the items table by which the resultset
should be orderd.

=item return:

C<$items> is a reference to an array full of hashrefs with columns
from the "items" table as keys.

=item usage in the perl script:

  my $where = { barcode => '0001548' };
  my $items = GetLostItems( $where, "homebranch" );
  $template->param( itemsloop => $items );

=back

=cut
898
899sub GetLostItems {
900    # Getting input args.
901
0
    my $where = shift;
902
0
    my $orderby = shift;
903
0
    my $dbh = C4::Context->dbh;
904
905
0
    my $query = "
906        SELECT *
907        FROM items
908            LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
909            LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
910            LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
911        WHERE
912         authorised_values.category = 'LOST'
913           AND itemlost IS NOT NULL
914          AND itemlost <> 0
915    ";
916
0
    my @query_parameters;
917
0
    foreach my $key (keys %$where) {
918
0
        $query .= " AND $key LIKE ?";
919
0
        push @query_parameters, "%$where->{$key}%";
920    }
921
0
    my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
922
923
0
    if ( defined $orderby && grep($orderby, @ordervalues)) {
924
0
        $query .= ' ORDER BY '.$orderby;
925    }
926
927
0
    my $sth = $dbh->prepare($query);
928
0
    $sth->execute( @query_parameters );
929
0
    my $items = [];
930
0
    while ( my $row = $sth->fetchrow_hashref ){
931
0
        push @$items, $row;
932    }
933
0
    return $items;
934}
935
936 - 953
=head2 GetItemsForInventory

  $itemlist = GetItemsForInventory($minlocation, $maxlocation, 
                 $location, $itemtype $datelastseen, $branch, 
                 $offset, $size, $statushash);

Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.

The sub returns a reference to a list of hashes, each containing
itemnumber, author, title, barcode, item callnumber, and date last
seen. It is ordered by callnumber then title.

The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
the datelastseen can be used to specify that you want to see items not seen since a past date only.
offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
$statushash requires a hashref that has the authorized values fieldname (intems.notforloan, etc...) as keys, and an arrayref of statuscodes we are searching for as values.

=cut
954
955sub GetItemsForInventory {
956
0
    my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
957
0
    my $dbh = C4::Context->dbh;
958
0
    my ( @bind_params, @where_strings );
959
960
0
    my $query = <<'END_SQL';
961SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
962FROM items
963  LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
964  LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
965END_SQL
966
0
    if ($statushash){
967
0
        for my $authvfield (keys %$statushash){
968
0
0
            if ( scalar @{$statushash->{$authvfield}} > 0 ){
969
0
0
                my $joinedvals = join ',', @{$statushash->{$authvfield}};
970
0
                push @where_strings, "$authvfield in (" . $joinedvals . ")";
971            }
972        }
973    }
974
975
0
    if ($minlocation) {
976
0
        push @where_strings, 'itemcallnumber >= ?';
977
0
        push @bind_params, $minlocation;
978    }
979
980
0
    if ($maxlocation) {
981
0
        push @where_strings, 'itemcallnumber <= ?';
982
0
        push @bind_params, $maxlocation;
983    }
984
985
0
    if ($datelastseen) {
986
0
        $datelastseen = format_date_in_iso($datelastseen);
987
0
        push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
988
0
        push @bind_params, $datelastseen;
989    }
990
991
0
    if ( $location ) {
992
0
        push @where_strings, 'items.location = ?';
993
0
        push @bind_params, $location;
994    }
995
996
0
    if ( $branchcode ) {
997
0
        if($branch eq "homebranch"){
998
0
        push @where_strings, 'items.homebranch = ?';
999        }else{
1000
0
            push @where_strings, 'items.holdingbranch = ?';
1001        }
1002
0
        push @bind_params, $branchcode;
1003    }
1004
1005
0
    if ( $itemtype ) {
1006
0
        push @where_strings, 'biblioitems.itemtype = ?';
1007
0
        push @bind_params, $itemtype;
1008    }
1009
1010
0
    if ( $ignoreissued) {
1011
0
        $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1012
0
        push @where_strings, 'issues.date_due IS NULL';
1013    }
1014
1015
0
    if ( @where_strings ) {
1016
0
        $query .= 'WHERE ';
1017
0
        $query .= join ' AND ', @where_strings;
1018    }
1019
0
    $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1020
0
    my $sth = $dbh->prepare($query);
1021
0
    $sth->execute( @bind_params );
1022
1023
0
    my @results;
1024
0
    $size--;
1025
0
    while ( my $row = $sth->fetchrow_hashref ) {
1026
0
        $offset-- if ($offset);
1027
0
        $row->{datelastseen}=format_date($row->{datelastseen});
1028
0
        if ( ( !$offset ) && $size ) {
1029
0
            push @results, $row;
1030
0
            $size--;
1031        }
1032    }
1033
0
    return \@results;
1034}
1035
1036 - 1042
=head2 GetItemsCount

  $count = &GetItemsCount( $biblionumber);

This function return count of item with $biblionumber

=cut
1043
1044sub GetItemsCount {
1045
0
    my ( $biblionumber ) = @_;
1046
0
    my $dbh = C4::Context->dbh;
1047
0
    my $query = "SELECT count(*)
1048          FROM items
1049          WHERE biblionumber=?";
1050
0
    my $sth = $dbh->prepare($query);
1051
0
    $sth->execute($biblionumber);
1052
0
    my $count = $sth->fetchrow;
1053
0
    return ($count);
1054}
1055
1056 - 1060
=head2 GetItemInfosOf

  GetItemInfosOf(@itemnumbers);

=cut
1061
1062sub GetItemInfosOf {
1063
0
    my @itemnumbers = @_;
1064
1065
0
    my $query = '
1066        SELECT *
1067        FROM items
1068        WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1069    ';
1070
0
    return get_infos_of( $query, 'itemnumber' );
1071}
1072
1073 - 1080
=head2 GetItemsByBiblioitemnumber

  GetItemsByBiblioitemnumber($biblioitemnumber);

Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
Called by C<C4::XISBN>

=cut
1081
1082sub GetItemsByBiblioitemnumber {
1083
0
    my ( $bibitem ) = @_;
1084
0
    my $dbh = C4::Context->dbh;
1085
0
    my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1086    # Get all items attached to a biblioitem
1087
0
    my $i = 0;
1088
0
    my @results;
1089
0
    $sth->execute($bibitem) || die $sth->errstr;
1090
0
    while ( my $data = $sth->fetchrow_hashref ) {
1091        # Foreach item, get circulation information
1092
0
        my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1093                                   WHERE itemnumber = ?
1094                                   AND issues.borrowernumber = borrowers.borrowernumber"
1095        );
1096
0
        $sth2->execute( $data->{'itemnumber'} );
1097
0
        if ( my $data2 = $sth2->fetchrow_hashref ) {
1098            # if item is out, set the due date and who it is out too
1099
0
            $data->{'date_due'} = $data2->{'date_due'};
1100
0
            $data->{'cardnumber'} = $data2->{'cardnumber'};
1101
0
            $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1102        }
1103        else {
1104            # set date_due to blank, so in the template we check itemlost, and wthdrawn
1105
0
            $data->{'date_due'} = '';
1106        } # else
1107        # Find the last 3 people who borrowed this item.
1108
0
        my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1109                      AND old_issues.borrowernumber = borrowers.borrowernumber
1110                      ORDER BY returndate desc,timestamp desc LIMIT 3";
1111
0
        $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1112
0
        $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1113
0
        my $i2 = 0;
1114
0
        while ( my $data2 = $sth2->fetchrow_hashref ) {
1115
0
            $data->{"timestamp$i2"} = $data2->{'timestamp'};
1116
0
            $data->{"card$i2"} = $data2->{'cardnumber'};
1117
0
            $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1118
0
            $i2++;
1119        }
1120
0
        push(@results,$data);
1121    }
1122
0
    return (\@results);
1123}
1124
1125 - 1165
=head2 GetItemsInfo

  @results = GetItemsInfo($biblionumber);

Returns information about items with the given biblionumber.

C<GetItemsInfo> returns a list of references-to-hash. Each element
contains a number of keys. Most of them are attributes from the
C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
Koha database. Other keys include:

=over 2

=item C<$data-E<gt>{branchname}>

The name (not the code) of the branch to which the book belongs.

=item C<$data-E<gt>{datelastseen}>

This is simply C<items.datelastseen>, except that while the date is
stored in YYYY-MM-DD format in the database, here it is converted to
DD/MM/YYYY format. A NULL date is returned as C<//>.

=item C<$data-E<gt>{datedue}>

=item C<$data-E<gt>{class}>

This is the concatenation of C<biblioitems.classification>, the book's
Dewey code, and C<biblioitems.subclass>.

=item C<$data-E<gt>{ocount}>

I think this is the number of copies of the book available.

=item C<$data-E<gt>{order}>

If this is set, it is set to C<One Order>.

=back

=cut
1166
1167sub GetItemsInfo {
1168
0
    my ( $biblionumber ) = @_;
1169
0
    my $dbh = C4::Context->dbh;
1170    # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1171
0
    my $query = "
1172    SELECT items.*,
1173           biblio.*,
1174           biblioitems.volume,
1175           biblioitems.number,
1176           biblioitems.itemtype,
1177           biblioitems.isbn,
1178           biblioitems.issn,
1179           biblioitems.publicationyear,
1180           biblioitems.publishercode,
1181           biblioitems.volumedate,
1182           biblioitems.volumedesc,
1183           biblioitems.lccn,
1184           biblioitems.url,
1185           items.notforloan as itemnotforloan,
1186           itemtypes.description,
1187           itemtypes.notforloan as notforloan_per_itemtype,
1188           branchurl
1189     FROM items
1190     LEFT JOIN branches ON items.holdingbranch = branches.branchcode
1191     LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1192     LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1193     LEFT JOIN itemtypes ON itemtypes.itemtype = "
1194     . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1195
0
    $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1196
0
    my $sth = $dbh->prepare($query);
1197
0
    $sth->execute($biblionumber);
1198
0
    my $i = 0;
1199
0
    my @results;
1200
0
    my $serial;
1201
1202
0
    my $isth = $dbh->prepare(
1203        "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1204        FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1205        WHERE itemnumber = ?"
1206       );
1207
0
        my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1208
0
        while ( my $data = $sth->fetchrow_hashref ) {
1209
0
        my $datedue = '';
1210
0
        $isth->execute( $data->{'itemnumber'} );
1211
0
        if ( my $idata = $isth->fetchrow_hashref ) {
1212
0
            $data->{borrowernumber} = $idata->{borrowernumber};
1213
0
            $data->{cardnumber} = $idata->{cardnumber};
1214
0
            $data->{surname} = $idata->{surname};
1215
0
            $data->{firstname} = $idata->{firstname};
1216
0
            $data->{lastreneweddate} = $idata->{lastreneweddate};
1217
0
            $datedue = $idata->{'date_due'};
1218
0
        if (C4::Context->preference("IndependantBranches")){
1219
0
        my $userenv = C4::Context->userenv;
1220
0
        if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1221
0
            $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1222        }
1223        }
1224        }
1225
0
                if ( $data->{'serial'}) {
1226
0
                        $ssth->execute($data->{'itemnumber'}) ;
1227
0
                        ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1228
0
                        $serial = 1;
1229        }
1230        #get branch information.....
1231
0
        my $bsth = $dbh->prepare(
1232            "SELECT * FROM branches WHERE branchcode = ?
1233        "
1234        );
1235
0
        $bsth->execute( $data->{'holdingbranch'} );
1236
0
        if ( my $bdata = $bsth->fetchrow_hashref ) {
1237
0
            $data->{'branchname'} = $bdata->{'branchname'};
1238        }
1239
0
        $data->{'datedue'} = $datedue;
1240
1241        # get notforloan complete status if applicable
1242
0
        my $sthnflstatus = $dbh->prepare(
1243            'SELECT authorised_value
1244            FROM marc_subfield_structure
1245            WHERE kohafield="items.notforloan"
1246        '
1247        );
1248
1249
0
        $sthnflstatus->execute;
1250
0
        my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1251
0
        if ($authorised_valuecode) {
1252
0
            $sthnflstatus = $dbh->prepare(
1253                "SELECT lib FROM authorised_values
1254                 WHERE category=?
1255                 AND authorised_value=?"
1256            );
1257
0
            $sthnflstatus->execute( $authorised_valuecode,
1258                $data->{itemnotforloan} );
1259
0
            my ($lib) = $sthnflstatus->fetchrow;
1260
0
            $data->{notforloanvalue} = $lib;
1261        }
1262
1263        # get restricted status and description if applicable
1264
0
        my $restrictedstatus = $dbh->prepare(
1265            'SELECT authorised_value
1266            FROM marc_subfield_structure
1267            WHERE kohafield="items.restricted"
1268        '
1269        );
1270
1271
0
        $restrictedstatus->execute;
1272
0
        ($authorised_valuecode) = $restrictedstatus->fetchrow;
1273
0
        if ($authorised_valuecode) {
1274
0
            $restrictedstatus = $dbh->prepare(
1275                "SELECT lib,lib_opac FROM authorised_values
1276                 WHERE category=?
1277                 AND authorised_value=?"
1278            );
1279
0
            $restrictedstatus->execute( $authorised_valuecode,
1280                $data->{restricted} );
1281
1282
0
            if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1283
0
                $data->{restricted} = $rstdata->{'lib'};
1284
0
                $data->{restrictedopac} = $rstdata->{'lib_opac'};
1285            }
1286        }
1287
1288        # my stack procedures
1289
0
        my $stackstatus = $dbh->prepare(
1290            'SELECT authorised_value
1291             FROM marc_subfield_structure
1292             WHERE kohafield="items.stack"
1293        '
1294        );
1295
0
        $stackstatus->execute;
1296
1297
0
        ($authorised_valuecode) = $stackstatus->fetchrow;
1298
0
        if ($authorised_valuecode) {
1299
0
            $stackstatus = $dbh->prepare(
1300                "SELECT lib
1301                 FROM authorised_values
1302                 WHERE category=?
1303                 AND authorised_value=?
1304            "
1305            );
1306
0
            $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1307
0
            my ($lib) = $stackstatus->fetchrow;
1308
0
            $data->{stack} = $lib;
1309        }
1310        # Find the last 3 people who borrowed this item.
1311
0
        my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1312                                    WHERE itemnumber = ?
1313                                    AND old_issues.borrowernumber = borrowers.borrowernumber
1314                                    ORDER BY returndate DESC
1315                                    LIMIT 3");
1316
0
        $sth2->execute($data->{'itemnumber'});
1317
0
        my $ii = 0;
1318
0
        while (my $data2 = $sth2->fetchrow_hashref()) {
1319
0
            $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1320
0
            $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1321
0
            $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1322
0
            $ii++;
1323        }
1324
1325
0
        $results[$i] = $data;
1326
0
        $i++;
1327    }
1328
0
        if($serial) {
1329
0
0
                return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1330        } else {
1331
0
     return (@results);
1332        }
1333}
1334
1335 - 1376
=head2 GetItemsLocationInfo

  my @itemlocinfo = GetItemsLocationInfo($biblionumber);

Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question

C<GetItemsInfo> returns a list of references-to-hash. Data returned:

=over 2

=item C<$data-E<gt>{homebranch}>

Branch Name of the item's homebranch

=item C<$data-E<gt>{holdingbranch}>

Branch Name of the item's holdingbranch

=item C<$data-E<gt>{location}>

Item's shelving location code

=item C<$data-E<gt>{location_intranet}>

The intranet description for the Shelving Location as set in authorised_values 'LOC'

=item C<$data-E<gt>{location_opac}>

The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
description is set.

=item C<$data-E<gt>{itemcallnumber}>

Item's itemcallnumber

=item C<$data-E<gt>{cn_sort}>

Item's call number normalized for sorting

=back
  
=cut
1377
1378sub GetItemsLocationInfo {
1379
0
        my $biblionumber = shift;
1380
0
        my @results;
1381
1382
0
        my $dbh = C4::Context->dbh;
1383
0
        my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1384                            location, itemcallnumber, cn_sort
1385                     FROM items, branches as a, branches as b
1386                     WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1387                     AND biblionumber = ?
1388                     ORDER BY cn_sort ASC";
1389
0
        my $sth = $dbh->prepare($query);
1390
0
        $sth->execute($biblionumber);
1391
1392
0
        while ( my $data = $sth->fetchrow_hashref ) {
1393
0
             $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1394
0
             $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1395
0
             push @results, $data;
1396        }
1397
0
        return @results;
1398}
1399
1400 - 1405
=head2 GetHostItemsInfo

	$hostiteminfo = GetHostItemsInfo($hostfield);
	Returns the iteminfo for items linked to records via a host field

=cut
1406
1407sub GetHostItemsInfo {
1408
0
        my ($record) = @_;
1409
0
        my @returnitemsInfo;
1410
1411
0
        if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1412        C4::Context->preference('marcflavour') eq 'NORMARC'){
1413
0
            foreach my $hostfield ( $record->field('773') ) {
1414
0
         my $hostbiblionumber = $hostfield->subfield("0");
1415
0
                my $linkeditemnumber = $hostfield->subfield("9");
1416
0
         my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1417
0
                foreach my $hostitemInfo (@hostitemInfos){
1418
0
                 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1419
0
                         push (@returnitemsInfo,$hostitemInfo);
1420
0
                                last;
1421                 }
1422         }
1423            }
1424        } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1425
0
            foreach my $hostfield ( $record->field('461') ) {
1426
0
         my $hostbiblionumber = $hostfield->subfield("0");
1427
0
                my $linkeditemnumber = $hostfield->subfield("9");
1428
0
         my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1429
0
                foreach my $hostitemInfo (@hostitemInfos){
1430
0
                 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1431
0
                         push (@returnitemsInfo,$hostitemInfo);
1432
0
                                last;
1433                 }
1434         }
1435            }
1436        }
1437
0
        return @returnitemsInfo;
1438}
1439
1440
1441 - 1446
=head2 GetLastAcquisitions

  my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
                                    'itemtypes' => ('BK','BD')}, 10);

=cut
1447
1448sub GetLastAcquisitions {
1449
0
        my ($data,$max) = @_;
1450
1451
0
        my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1452
1453
0
0
        my $number_of_branches = @{$data->{branches}};
1454
0
0
        my $number_of_itemtypes = @{$data->{itemtypes}};
1455
1456
1457
0
        my @where = ('WHERE 1 ');
1458
0
        $number_of_branches and push @where
1459           , 'AND holdingbranch IN ('
1460           , join(',', ('?') x $number_of_branches )
1461           , ')'
1462         ;
1463
1464
0
        $number_of_itemtypes and push @where
1465           , "AND $itemtype IN ("
1466           , join(',', ('?') x $number_of_itemtypes )
1467           , ')'
1468         ;
1469
1470
0
        my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1471                                 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1472                                    RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1473                                    @where
1474                                    GROUP BY biblio.biblionumber
1475                                    ORDER BY dateaccessioned DESC LIMIT $max";
1476
1477
0
        my $dbh = C4::Context->dbh;
1478
0
        my $sth = $dbh->prepare($query);
1479
1480
0
0
0
    $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1481
1482
0
        my @results;
1483
0
        while( my $row = $sth->fetchrow_hashref){
1484
0
                push @results, {date => $row->{dateaccessioned}
1485                                                , biblionumber => $row->{biblionumber}
1486                                                , title => $row->{title}};
1487        }
1488
1489
0
        return @results;
1490}
1491
1492 - 1502
=head2 get_itemnumbers_of

  my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);

Given a list of biblionumbers, return the list of corresponding itemnumbers
for each biblionumber.

Return a reference on a hash where keys are biblionumbers and values are
references on array of itemnumbers.

=cut
1503
1504sub get_itemnumbers_of {
1505
0
    my @biblionumbers = @_;
1506
1507
0
    my $dbh = C4::Context->dbh;
1508
1509
0
    my $query = '
1510        SELECT itemnumber,
1511            biblionumber
1512        FROM items
1513        WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1514    ';
1515
0
    my $sth = $dbh->prepare($query);
1516
0
    $sth->execute(@biblionumbers);
1517
1518
0
    my %itemnumbers_of;
1519
1520
0
    while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1521
0
0
        push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1522    }
1523
1524
0
    return \%itemnumbers_of;
1525}
1526
1527 - 1536
=head2 get_hostitemnumbers_of

  my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);

Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields

Return a reference on a hash where key is a biblionumber and values are
references on array of itemnumbers.

=cut
1537
1538
1539sub get_hostitemnumbers_of {
1540
0
        my ($biblionumber) = @_;
1541
0
        my $marcrecord = GetMarcBiblio($biblionumber);
1542
0
        my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1543
1544
0
        my $marcflavor = C4::Context->preference('marcflavour');
1545
0
        if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1546
0
        $tag='773';
1547
0
        $biblio_s='0';
1548
0
        $item_s='9';
1549    } elsif ($marcflavor eq 'UNIMARC') {
1550
0
        $tag='461';
1551
0
        $biblio_s='0';
1552
0
        $item_s='9';
1553    }
1554
1555
0
    foreach my $hostfield ( $marcrecord->field($tag) ) {
1556
0
        my $hostbiblionumber = $hostfield->subfield($biblio_s);
1557
0
        my $linkeditemnumber = $hostfield->subfield($item_s);
1558
0
        my @itemnumbers;
1559
0
        if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1560        {
1561
0
            @itemnumbers = @$itemnumbers;
1562        }
1563
0
        foreach my $itemnumber (@itemnumbers){
1564
0
            if ($itemnumber eq $linkeditemnumber){
1565
0
                push (@returnhostitemnumbers,$itemnumber);
1566
0
                last;
1567            }
1568        }
1569    }
1570
0
    return @returnhostitemnumbers;
1571}
1572
1573
1574 - 1578
=head2 GetItemnumberFromBarcode

  $result = GetItemnumberFromBarcode($barcode);

=cut
1579
1580sub GetItemnumberFromBarcode {
1581
0
    my ($barcode) = @_;
1582
0
    my $dbh = C4::Context->dbh;
1583
1584
0
    my $rq =
1585      $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1586
0
    $rq->execute($barcode);
1587
0
    my ($result) = $rq->fetchrow;
1588
0
    return ($result);
1589}
1590
1591 - 1595
=head2 GetBarcodeFromItemnumber

  $result = GetBarcodeFromItemnumber($itemnumber);

=cut
1596
1597sub GetBarcodeFromItemnumber {
1598
0
    my ($itemnumber) = @_;
1599
0
    my $dbh = C4::Context->dbh;
1600
1601
0
    my $rq =
1602      $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1603
0
    $rq->execute($itemnumber);
1604
0
    my ($result) = $rq->fetchrow;
1605
0
    return ($result);
1606}
1607
1608 - 1616
=head2 GetHiddenItemnumbers

=over 4

$result = GetHiddenItemnumbers(@items);

=back

=cut
1617
1618sub GetHiddenItemnumbers {
1619
0
    my (@items) = @_;
1620
0
    my @resultitems;
1621
1622
0
    my $yaml = C4::Context->preference('OpacHiddenItems');
1623
0
    $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1624
0
    my $hidingrules;
1625
0
    eval {
1626
0
        $hidingrules = YAML::Load($yaml);
1627    };
1628
0
    if ($@) {
1629
0
        warn "Unable to parse OpacHiddenItems syspref : $@";
1630
0
        return ();
1631    }
1632
0
    my $dbh = C4::Context->dbh;
1633
1634    # For each item
1635
0
    foreach my $item (@items) {
1636
1637        # We check each rule
1638
0
        foreach my $field (keys %$hidingrules) {
1639
0
            my $val;
1640
0
            if (exists $item->{$field}) {
1641
0
                $val = $item->{$field};
1642            }
1643            else {
1644
0
                my $query = "SELECT $field from items where itemnumber = ?";
1645
0
                $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1646            }
1647
0
            $val = '' unless defined $val;
1648
1649            # If the results matches the values in the yaml file
1650
0
0
0
            if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1651
1652                # We add the itemnumber to the list
1653
0
                push @resultitems, $item->{'itemnumber'};
1654
1655                # If at least one rule matched for an item, no need to test the others
1656
0
                last;
1657            }
1658        }
1659    }
1660
0
    return @resultitems;
1661}
1662
1663 - 1687
=head3 get_item_authorised_values

find the types and values for all authorised values assigned to this item.

parameters: itemnumber

returns: a hashref malling the authorised value to the value set for this itemnumber

    $authorised_values = {
             'CCODE'      => undef,
             'DAMAGED'    => '0',
             'LOC'        => '3',
             'LOST'       => '0'
             'NOT_LOAN'   => '0',
             'RESTRICTED' => undef,
             'STACK'      => undef,
             'WITHDRAWN'  => '0',
             'branches'   => 'CPL',
             'cn_source'  => undef,
             'itemtypes'  => 'SER',
           };

Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.

=cut
1688
1689sub get_item_authorised_values {
1690
0
    my $itemnumber = shift;
1691
1692    # assume that these entries in the authorised_value table are item level.
1693
0
    my $query = q(SELECT distinct authorised_value, kohafield
1694                    FROM marc_subfield_structure
1695                    WHERE kohafield like 'item%'
1696                      AND authorised_value != '' );
1697
1698
0
    my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1699
0
    my $iteminfo = GetItem( $itemnumber );
1700    # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1701
0
    my $return;
1702
0
    foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1703
0
        my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1704
0
        $field =~ s/^items\.//;
1705
0
        if ( exists $iteminfo->{ $field } ) {
1706
0
            $return->{ $this_authorised_value } = $iteminfo->{ $field };
1707        }
1708    }
1709    # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1710
0
    return $return;
1711}
1712
1713 - 1734
=head3 get_authorised_value_images

find a list of icons that are appropriate for display based on the
authorised values for a biblio.

parameters: listref of authorised values, such as comes from
get_item_authorised_values or
from C4::Biblio::get_biblio_authorised_values

returns: listref of hashrefs for each image. Each hashref looks like this:

      { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
        label    => '',
        category => '',
        value    => '', }

Notes: Currently, I put on the full path to the images on the staff
side. This should either be configurable or not done at all. Since I
have to deal with 'intranet' or 'opac' in
get_biblio_authorised_values, perhaps I should be passing it in.

=cut
1735
1736sub get_authorised_value_images {
1737
0
    my $authorised_values = shift;
1738
1739
0
    my @imagelist;
1740
1741
0
    my $authorised_value_list = GetAuthorisedValues();
1742    # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1743
0
    foreach my $this_authorised_value ( @$authorised_value_list ) {
1744
0
        if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1745             && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1746            # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1747
0
            if ( defined $this_authorised_value->{'imageurl'} ) {
1748
0
                push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1749                                   label => $this_authorised_value->{'lib'},
1750                                   category => $this_authorised_value->{'category'},
1751                                   value => $this_authorised_value->{'authorised_value'}, };
1752            }
1753        }
1754    }
1755
1756    # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1757
0
    return \@imagelist;
1758
1759}
1760
1761 - 1769
=head1 LIMITED USE FUNCTIONS

The following functions, while part of the public API,
are not exported.  This is generally because they are
meant to be used by only one script for a specific
purpose, and should not be used in any other context
without careful thought.

=cut
1770
1771 - 1780
=head2 GetMarcItem

  my $item_marc = GetMarcItem($biblionumber, $itemnumber);

Returns MARC::Record of the item passed in parameter.
This function is meant for use only in C<cataloguing/additem.pl>,
where it is needed to support that script's MARC-like
editor.

=cut
1781
1782sub GetMarcItem {
1783
0
    my ( $biblionumber, $itemnumber ) = @_;
1784
1785    # GetMarcItem has been revised so that it does the following:
1786    # 1. Gets the item information from the items table.
1787    # 2. Converts it to a MARC field for storage in the bib record.
1788    #
1789    # The previous behavior was:
1790    # 1. Get the bib record.
1791    # 2. Return the MARC tag corresponding to the item record.
1792    #
1793    # The difference is that one treats the items row as authoritative,
1794    # while the other treats the MARC representation as authoritative
1795    # under certain circumstances.
1796
1797
0
    my $itemrecord = GetItem($itemnumber);
1798
1799    # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1800    # Also, don't emit a subfield if the underlying field is blank.
1801
1802
1803
0
    return Item2Marc($itemrecord,$biblionumber);
1804
1805}
1806sub Item2Marc {
1807
0
        my ($itemrecord,$biblionumber)=@_;
1808
0
    my $mungeditem = {
1809        map {
1810
0
            defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1811
0
        } keys %{ $itemrecord }
1812    };
1813
0
    my $itemmarc = TransformKohaToMarc($mungeditem);
1814
0
    my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1815
1816
0
    my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1817
0
    if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1818
0
                foreach my $field ($itemmarc->field($itemtag)){
1819
0
            $field->add_subfields(@$unlinked_item_subfields);
1820        }
1821    }
1822
0
        return $itemmarc;
1823}
1824
1825 - 1831
=head1 PRIVATE FUNCTIONS AND VARIABLES

The following functions are not meant to be called
directly, but are documented in order to explain
the inner workings of C<C4::Items>.

=cut
1832
1833 - 1848
=head2 %derived_columns

This hash keeps track of item columns that
are strictly derived from other columns in
the item record and are not meant to be set
independently.

Each key in the hash should be the name of a
column (as named by TransformMarcToKoha).  Each
value should be hashref whose keys are the
columns on which the derived column depends.  The
hashref should also contain a 'BUILDER' key
that is a reference to a sub that calculates
the derived value.

=cut
1849
1850my %derived_columns = (
1851    'items.cn_sort' => {
1852        'itemcallnumber' => 1,
1853        'items.cn_source' => 1,
1854        'BUILDER' => \&_calc_items_cn_sort,
1855    }
1856);
1857
1858 - 1866
=head2 _set_derived_columns_for_add 

  _set_derived_column_for_add($item);

Given an item hash representing a new item to be added,
calculate any derived columns.  Currently the only
such column is C<items.cn_sort>.

=cut
1867
1868sub _set_derived_columns_for_add {
1869
0
    my $item = shift;
1870
1871
0
    foreach my $column (keys %derived_columns) {
1872
0
        my $builder = $derived_columns{$column}->{'BUILDER'};
1873
0
        my $source_values = {};
1874
0
0
        foreach my $source_column (keys %{ $derived_columns{$column} }) {
1875
0
            next if $source_column eq 'BUILDER';
1876
0
            $source_values->{$source_column} = $item->{$source_column};
1877        }
1878
0
        $builder->($item, $source_values);
1879    }
1880}
1881
1882 - 1901
=head2 _set_derived_columns_for_mod 

  _set_derived_column_for_mod($item);

Given an item hash representing a new item to be modified.
calculate any derived columns.  Currently the only
such column is C<items.cn_sort>.

This routine differs from C<_set_derived_columns_for_add>
in that it needs to handle partial item records.  In other
words, the caller of C<ModItem> may have supplied only one
or two columns to be changed, so this function needs to
determine whether any of the columns to be changed affect
any of the derived columns.  Also, if a derived column
depends on more than one column, but the caller is not
changing all of then, this routine retrieves the unchanged
values from the database in order to ensure a correct
calculation.

=cut
1902
1903sub _set_derived_columns_for_mod {
1904
0
    my $item = shift;
1905
1906
0
    foreach my $column (keys %derived_columns) {
1907
0
        my $builder = $derived_columns{$column}->{'BUILDER'};
1908
0
        my $source_values = {};
1909
0
        my %missing_sources = ();
1910
0
        my $must_recalc = 0;
1911
0
0
        foreach my $source_column (keys %{ $derived_columns{$column} }) {
1912
0
            next if $source_column eq 'BUILDER';
1913
0
            if (exists $item->{$source_column}) {
1914
0
                $must_recalc = 1;
1915
0
                $source_values->{$source_column} = $item->{$source_column};
1916            } else {
1917
0
                $missing_sources{$source_column} = 1;
1918            }
1919        }
1920
0
        if ($must_recalc) {
1921
0
            foreach my $source_column (keys %missing_sources) {
1922
0
                $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1923            }
1924
0
            $builder->($item, $source_values);
1925        }
1926    }
1927}
1928
1929 - 1940
=head2 _do_column_fixes_for_mod

  _do_column_fixes_for_mod($item);

Given an item hashref containing one or more
columns to modify, fix up certain values.
Specifically, set to 0 any passed value
of C<notforloan>, C<damaged>, C<itemlost>, or
C<wthdrawn> that is either undefined or
contains the empty string.

=cut
1941
1942sub _do_column_fixes_for_mod {
1943
0
    my $item = shift;
1944
1945
0
    if (exists $item->{'notforloan'} and
1946        (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1947
0
        $item->{'notforloan'} = 0;
1948    }
1949
0
    if (exists $item->{'damaged'} and
1950        (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1951
0
        $item->{'damaged'} = 0;
1952    }
1953
0
    if (exists $item->{'itemlost'} and
1954        (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1955
0
        $item->{'itemlost'} = 0;
1956    }
1957
0
    if (exists $item->{'wthdrawn'} and
1958        (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1959
0
        $item->{'wthdrawn'} = 0;
1960    }
1961
0
    if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1962
0
        $item->{'permanent_location'} = $item->{'location'};
1963    }
1964
0
    if (exists $item->{'timestamp'}) {
1965
0
        delete $item->{'timestamp'};
1966    }
1967}
1968
1969 - 1976
=head2 _get_single_item_column

  _get_single_item_column($column, $itemnumber);

Retrieves the value of a single column from an C<items>
row specified by C<$itemnumber>.

=cut
1977
1978sub _get_single_item_column {
1979
0
    my $column = shift;
1980
0
    my $itemnumber = shift;
1981
1982
0
    my $dbh = C4::Context->dbh;
1983
0
    my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1984
0
    $sth->execute($itemnumber);
1985
0
    my ($value) = $sth->fetchrow();
1986
0
    return $value;
1987}
1988
1989 - 1995
=head2 _calc_items_cn_sort

  _calc_items_cn_sort($item, $source_values);

Helper routine to calculate C<items.cn_sort>.

=cut
1996
1997sub _calc_items_cn_sort {
1998
0
    my $item = shift;
1999
0
    my $source_values = shift;
2000
2001
0
    $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2002}
2003
2004 - 2037
=head2 _set_defaults_for_add 

  _set_defaults_for_add($item_hash);

Given an item hash representing an item to be added, set
correct default values for columns whose default value
is not handled by the DBMS.  This includes the following
columns:

=over 2

=item * 

C<items.dateaccessioned>

=item *

C<items.notforloan>

=item *

C<items.damaged>

=item *

C<items.itemlost>

=item *

C<items.wthdrawn>

=back

=cut
2038
2039sub _set_defaults_for_add {
2040
0
    my $item = shift;
2041
0
    $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2042
0
0
    $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2043}
2044
2045 - 2051
=head2 _koha_new_item

  my ($itemnumber,$error) = _koha_new_item( $item, $barcode );

Perform the actual insert into the C<items> table.

=cut
2052
2053sub _koha_new_item {
2054
0
    my ( $item, $barcode ) = @_;
2055
0
    my $dbh=C4::Context->dbh;
2056
0
    my $error;
2057
0
    my $query =
2058           "INSERT INTO items SET
2059            biblionumber = ?,
2060            biblioitemnumber = ?,
2061            barcode = ?,
2062            dateaccessioned = ?,
2063            booksellerid = ?,
2064            homebranch = ?,
2065            price = ?,
2066            replacementprice = ?,
2067            replacementpricedate = ?,
2068            datelastborrowed = ?,
2069            datelastseen = ?,
2070            stack = ?,
2071            notforloan = ?,
2072            damaged = ?,
2073            itemlost = ?,
2074            wthdrawn = ?,
2075            itemcallnumber = ?,
2076            restricted = ?,
2077            itemnotes = ?,
2078            holdingbranch = ?,
2079            paidfor = ?,
2080            location = ?,
2081            permanent_location = ?,
2082            onloan = ?,
2083            issues = ?,
2084            renewals = ?,
2085            reserves = ?,
2086            cn_source = ?,
2087            cn_sort = ?,
2088            ccode = ?,
2089            itype = ?,
2090            materials = ?,
2091            uri = ?,
2092            enumchron = ?,
2093            more_subfields_xml = ?,
2094            copynumber = ?,
2095            stocknumber = ?
2096          ";
2097
0
    my $sth = $dbh->prepare($query);
2098
0
    my $today = C4::Dates->today('iso');
2099
0
   $sth->execute(
2100            $item->{'biblionumber'},
2101            $item->{'biblioitemnumber'},
2102            $barcode,
2103            $item->{'dateaccessioned'},
2104            $item->{'booksellerid'},
2105            $item->{'homebranch'},
2106            $item->{'price'},
2107            $item->{'replacementprice'},
2108            $item->{'replacementpricedate'} || $today,
2109            $item->{datelastborrowed},
2110            $item->{datelastseen} || $today,
2111            $item->{stack},
2112            $item->{'notforloan'},
2113            $item->{'damaged'},
2114            $item->{'itemlost'},
2115            $item->{'wthdrawn'},
2116            $item->{'itemcallnumber'},
2117            $item->{'restricted'},
2118            $item->{'itemnotes'},
2119            $item->{'holdingbranch'},
2120            $item->{'paidfor'},
2121            $item->{'location'},
2122            $item->{'permanent_location'},
2123            $item->{'onloan'},
2124            $item->{'issues'},
2125            $item->{'renewals'},
2126            $item->{'reserves'},
2127            $item->{'items.cn_source'},
2128            $item->{'items.cn_sort'},
2129            $item->{'ccode'},
2130            $item->{'itype'},
2131            $item->{'materials'},
2132            $item->{'uri'},
2133            $item->{'enumchron'},
2134            $item->{'more_subfields_xml'},
2135            $item->{'copynumber'},
2136            $item->{'stocknumber'},
2137    );
2138
2139
0
    my $itemnumber;
2140
0
    if ( defined $sth->errstr ) {
2141
0
        $error.="ERROR in _koha_new_item $query".$sth->errstr;
2142    }
2143    else {
2144
0
        $itemnumber = $dbh->{'mysql_insertid'};
2145    }
2146
2147
0
    return ( $itemnumber, $error );
2148}
2149
2150 - 2158
=head2 MoveItemFromBiblio

  MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);

Moves an item from a biblio to another

Returns undef if the move failed or the biblionumber of the destination record otherwise

=cut
2159
2160sub MoveItemFromBiblio {
2161
0
    my ($itemnumber, $frombiblio, $tobiblio) = @_;
2162
0
    my $dbh = C4::Context->dbh;
2163
0
    my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2164
0
    $sth->execute( $tobiblio );
2165
0
    my ( $tobiblioitem ) = $sth->fetchrow();
2166
0
    $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2167
0
    my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2168
0
    if ($return == 1) {
2169
0
        ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2170
0
        ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2171            # Checking if the item we want to move is in an order
2172
0
        require C4::Acquisition;
2173
0
        my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2174
0
            if ($order) {
2175                    # Replacing the biblionumber within the order if necessary
2176
0
                    $order->{'biblionumber'} = $tobiblio;
2177
0
                C4::Acquisition::ModOrder($order);
2178            }
2179
0
        return $tobiblio;
2180        }
2181
0
    return;
2182}
2183
2184 - 2190
=head2 DelItemCheck

   DelItemCheck($dbh, $biblionumber, $itemnumber);

Exported function (core API) for deleting an item record in Koha if there no current issue.

=cut
2191
2192sub DelItemCheck {
2193
0
    my ( $dbh, $biblionumber, $itemnumber ) = @_;
2194
0
    my $error;
2195
2196
0
        my $countanalytics=GetAnalyticsCount($itemnumber);
2197
2198
2199    # check that there is no issue on this item before deletion.
2200
0
    my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2201
0
    $sth->execute($itemnumber);
2202
2203
0
    my $item = GetItem($itemnumber);
2204
0
    my $onloan=$sth->fetchrow;
2205
2206
0
    if ($onloan){
2207
0
        $error = "book_on_loan"
2208    }
2209    elsif ( !(C4::Context->userenv->{flags} & 1) and
2210            C4::Context->preference("IndependantBranches") and
2211           (C4::Context->userenv->{branch} ne
2212             $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2213    {
2214
0
        $error = "not_same_branch";
2215    }
2216        else{
2217        # check it doesnt have a waiting reserve
2218
0
        $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2219
0
        $sth->execute($itemnumber);
2220
0
        my $reserve=$sth->fetchrow;
2221
0
        if ($reserve){
2222
0
            $error = "book_reserved";
2223        } elsif ($countanalytics > 0){
2224
0
                $error = "linked_analytics";
2225        } else {
2226
0
            DelItem($dbh, $biblionumber, $itemnumber);
2227
0
            return 1;
2228        }
2229    }
2230
0
    return $error;
2231}
2232
2233 - 2240
=head2 _koha_modify_item

  my ($itemnumber,$error) =_koha_modify_item( $item );

Perform the actual update of the C<items> row.  Note that this
routine accepts a hashref specifying the columns to update.

=cut
2241
2242sub _koha_modify_item {
2243
0
    my ( $item ) = @_;
2244
0
    my $dbh=C4::Context->dbh;
2245
0
    my $error;
2246
2247
0
    my $query = "UPDATE items SET ";
2248
0
    my @bind;
2249
0
    for my $key ( keys %$item ) {
2250
0
        $query.="$key=?,";
2251
0
        push @bind, $item->{$key};
2252    }
2253
0
    $query =~ s/,$//;
2254
0
    $query .= " WHERE itemnumber=?";
2255
0
    push @bind, $item->{'itemnumber'};
2256
0
    my $sth = C4::Context->dbh->prepare($query);
2257
0
    $sth->execute(@bind);
2258
0
    if ( C4::Context->dbh->errstr ) {
2259
0
        $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2260
0
        warn $error;
2261    }
2262
0
    return ($item->{'itemnumber'},$error);
2263}
2264
2265 - 2271
=head2 _koha_delete_item

  _koha_delete_item( $dbh, $itemnum );

Internal function to delete an item record from the koha tables

=cut
2272
2273sub _koha_delete_item {
2274
0
    my ( $dbh, $itemnum ) = @_;
2275
2276    # save the deleted item to deleteditems table
2277
0
    my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2278
0
    $sth->execute($itemnum);
2279
0
    my $data = $sth->fetchrow_hashref();
2280
0
    my $query = "INSERT INTO deleteditems SET ";
2281
0
    my @bind = ();
2282
0
    foreach my $key ( keys %$data ) {
2283
0
        $query .= "$key = ?,";
2284
0
        push( @bind, $data->{$key} );
2285    }
2286
0
    $query =~ s/\,$//;
2287
0
    $sth = $dbh->prepare($query);
2288
0
    $sth->execute(@bind);
2289
2290    # delete from items table
2291
0
    $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2292
0
    $sth->execute($itemnum);
2293
0
    return undef;
2294}
2295
2296 - 2309
=head2 _marc_from_item_hash

  my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);

Given an item hash representing a complete item record,
create a C<MARC::Record> object containing an embedded
tag representing that item.

The third, optional parameter C<$unlinked_item_subfields> is
an arrayref of subfields (not mapped to C<items> fields per the
framework) to be added to the MARC representation
of the item.

=cut
2310
2311sub _marc_from_item_hash {
2312
0
    my $item = shift;
2313
0
    my $frameworkcode = shift;
2314
0
    my $unlinked_item_subfields;
2315
0
    if (@_) {
2316
0
        $unlinked_item_subfields = shift;
2317    }
2318
2319    # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2320    # Also, don't emit a subfield if the underlying field is blank.
2321
0
0
    my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2322                                (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2323
0
                                : () } keys %{ $item } };
2324
2325
0
    my $item_marc = MARC::Record->new();
2326
0
0
    foreach my $item_field ( keys %{$mungeditem} ) {
2327
0
        my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2328
0
        next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2329
0
        my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2330
0
        foreach my $value (@values){
2331
0
            if ( my $field = $item_marc->field($tag) ) {
2332
0
                    $field->add_subfields( $subfield => $value );
2333            } else {
2334
0
                my $add_subfields = [];
2335
0
                if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2336
0
                    $add_subfields = $unlinked_item_subfields;
2337            }
2338
0
            $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2339            }
2340        }
2341    }
2342
2343
0
    return $item_marc;
2344}
2345
2346 - 2351
=head2 _repack_item_errors

Add an error message hash generated by C<CheckItemPreSave>
to a list of errors.

=cut
2352
2353sub _repack_item_errors {
2354
0
    my $item_sequence_num = shift;
2355
0
    my $item_ref = shift;
2356
0
    my $error_ref = shift;
2357
2358
0
    my @repacked_errors = ();
2359
2360
0
0
    foreach my $error_code (sort keys %{ $error_ref }) {
2361
0
        my $repacked_error = {};
2362
0
        $repacked_error->{'item_sequence'} = $item_sequence_num;
2363
0
        $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2364
0
        $repacked_error->{'error_code'} = $error_code;
2365
0
        $repacked_error->{'error_information'} = $error_ref->{$error_code};
2366
0
        push @repacked_errors, $repacked_error;
2367    }
2368
2369
0
    return @repacked_errors;
2370}
2371
2372 - 2376
=head2 _get_unlinked_item_subfields

  my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);

=cut
2377
2378sub _get_unlinked_item_subfields {
2379
0
    my $original_item_marc = shift;
2380
0
    my $frameworkcode = shift;
2381
2382
0
    my $marcstructure = GetMarcStructure(1, $frameworkcode);
2383
2384    # assume that this record has only one field, and that that
2385    # field contains only the item information
2386
0
    my $subfields = [];
2387
0
    my @fields = $original_item_marc->fields();
2388
0
    if ($#fields > -1) {
2389
0
        my $field = $fields[0];
2390
0
            my $tag = $field->tag();
2391
0
        foreach my $subfield ($field->subfields()) {
2392
0
            if (defined $subfield->[1] and
2393                $subfield->[1] ne '' and
2394                !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2395
0
                push @$subfields, $subfield->[0] => $subfield->[1];
2396            }
2397        }
2398    }
2399
0
    return $subfields;
2400}
2401
2402 - 2406
=head2 _get_unlinked_subfields_xml

  my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);

=cut
2407
2408sub _get_unlinked_subfields_xml {
2409
0
    my $unlinked_item_subfields = shift;
2410
2411
0
    my $xml;
2412
0
    if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2413
0
        my $marc = MARC::Record->new();
2414        # use of tag 999 is arbitrary, and doesn't need to match the item tag
2415        # used in the framework
2416
0
        $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2417
0
        $marc->encoding("UTF-8");
2418
0
        $xml = $marc->as_xml("USMARC");
2419    }
2420
2421
0
    return $xml;
2422}
2423
2424 - 2428
=head2 _parse_unlinked_item_subfields_from_xml

  my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):

=cut
2429
2430sub _parse_unlinked_item_subfields_from_xml {
2431
0
    my $xml = shift;
2432
0
    require C4::Charset;
2433
0
    return unless defined $xml and $xml ne "";
2434
0
    my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2435
0
    my $unlinked_subfields = [];
2436
0
    my @fields = $marc->fields();
2437
0
    if ($#fields > -1) {
2438
0
        foreach my $subfield ($fields[0]->subfields()) {
2439
0
            push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2440        }
2441    }
2442
0
    return $unlinked_subfields;
2443}
2444
2445 - 2451
=head2 GetAnalyticsCount

  $count= &GetAnalyticsCount($itemnumber)

counts Usage of itemnumber in Analytical bibliorecords. 

=cut
2452
2453sub GetAnalyticsCount {
2454
0
    my ($itemnumber) = @_;
2455
0
    if (C4::Context->preference('NoZebra')) {
2456        # Read the index Koha-Auth-Number for this authid and count the lines
2457
0
        my $result = C4::Search::NZanalyse("hi=$itemnumber");
2458
0
        my @tab = split /;/,$result;
2459
0
        return scalar @tab;
2460    } else {
2461        ### ZOOM search here
2462
0
        my $query;
2463
0
        $query= "hi=".$itemnumber;
2464
0
                my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2465
0
        return ($result);
2466    }
2467}
2468
2469 - 2478
=head2 GetItemHolds

=over 4
$holds = &GetItemHolds($biblionumber, $itemnumber);

=back

This function return the count of holds with $biblionumber and $itemnumber

=cut
2479
2480sub GetItemHolds {
2481
0
    my ($biblionumber, $itemnumber) = @_;
2482
0
    my $holds;
2483
0
    my $dbh = C4::Context->dbh;
2484
0
    my $query = "SELECT count(*)
2485        FROM reserves
2486        WHERE biblionumber=? AND itemnumber=?";
2487
0
    my $sth = $dbh->prepare($query);
2488
0
    $sth->execute($biblionumber, $itemnumber);
2489
0
    $holds = $sth->fetchrow;
2490
0
    return $holds;
2491}
2492 - 2507
=head1  OTHER FUNCTIONS

=head2 _find_value

  ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);

Find the given $subfield in the given $tag in the given
MARC::Record $record.  If the subfield is found, returns
the (indicators, value) pair; otherwise, (undef, undef) is
returned.

PROPOSITION :
Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
I suggest we export it from this module.

=cut
2508
2509sub _find_value {
2510
0
    my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2511
0
    my @result;
2512
0
    my $indicator;
2513
0
    if ( $tagfield < 10 ) {
2514
0
        if ( $record->field($tagfield) ) {
2515
0
            push @result, $record->field($tagfield)->data();
2516        } else {
2517
0
            push @result, "";
2518        }
2519    } else {
2520
0
        foreach my $field ( $record->field($tagfield) ) {
2521
0
            my @subfields = $field->subfields();
2522
0
            foreach my $subfield (@subfields) {
2523
0
                if ( @$subfield[0] eq $insubfield ) {
2524
0
                    push @result, @$subfield[1];
2525
0
                    $indicator = $field->indicator(1) . $field->indicator(2);
2526                }
2527            }
2528        }
2529    }
2530
0
    return ( $indicator, @result );
2531}
2532
2533
2534 - 2542
=head2 PrepareItemrecordDisplay

  PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);

Returns a hash with all the fields for Display a given item data in a template

The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided

=cut
2543
2544sub PrepareItemrecordDisplay {
2545
2546
0
    my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2547
2548
0
    my $dbh = C4::Context->dbh;
2549
0
    $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2550
0
    my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2551
0
    my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2552
2553    # return nothing if we don't have found an existing framework.
2554
0
    return q{} unless $tagslib;
2555
0
    my $itemrecord;
2556
0
    if ($itemnum) {
2557
0
        $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2558    }
2559
0
    my @loop_data;
2560
0
    my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2561
0
0
    foreach my $tag ( sort keys %{$tagslib} ) {
2562
0
        my $previous_tag = '';
2563
0
        if ( $tag ne '' ) {
2564
2565            # loop through each subfield
2566
0
            my $cntsubf;
2567
0
0
            foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2568
0
                next if ( subfield_is_koha_internal_p($subfield) );
2569
0
                next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2570
0
                my %subfield_data;
2571
0
                $subfield_data{tag} = $tag;
2572
0
                $subfield_data{subfield} = $subfield;
2573
0
                $subfield_data{countsubfield} = $cntsubf++;
2574
0
                $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2575
2576                # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2577
0
                $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2578
0
                $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2579
0
                $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2580
0
                $subfield_data{hidden} = "display:none"
2581                  if $tagslib->{$tag}->{$subfield}->{hidden};
2582
0
                my ( $x, $defaultvalue );
2583
0
                if ($itemrecord) {
2584
0
                    ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2585                }
2586
0
                $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2587
0
                if ( !defined $defaultvalue ) {
2588
0
                    $defaultvalue = q||;
2589                }
2590
0
                $defaultvalue =~ s/"/&quot;/g;
2591
2592                # search for itemcallnumber if applicable
2593
0
                if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2594                    && C4::Context->preference('itemcallnumber') ) {
2595
0
                    my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2596
0
                    my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2597
0
                    if ($itemrecord) {
2598
0
                        my $temp = $itemrecord->field($CNtag);
2599
0
                        if ($temp) {
2600
0
                            $defaultvalue = $temp->subfield($CNsubfield);
2601                        }
2602                    }
2603                }
2604
0
                if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2605                    && $defaultvalues
2606                    && $defaultvalues->{'callnumber'} ) {
2607
0
                    my $temp;
2608
0
                    if ($itemrecord) {
2609
0
                        $temp = $itemrecord->field($subfield);
2610                    }
2611
0
                    unless ($temp) {
2612
0
                        $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2613                    }
2614                }
2615
0
                if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2616                    && $defaultvalues
2617                    && $defaultvalues->{'branchcode'} ) {
2618
0
                    my $temp;
2619
0
                    if ($itemrecord) {
2620
0
                        $temp = $itemrecord->field($subfield);
2621                    }
2622
0
                    unless ($temp) {
2623
0
                        $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2624                    }
2625                }
2626
0
                if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2627                    && $defaultvalues
2628                    && $defaultvalues->{'location'} ) {
2629
0
                    my $temp = $itemrecord->field($subfield) if ($itemrecord);
2630
0
                    unless ($temp) {
2631
0
                        $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2632                    }
2633                }
2634
0
                if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2635
0
                    my @authorised_values;
2636
0
                    my %authorised_lib;
2637
2638                    # builds list, depending on authorised value...
2639                    #---- branch
2640
0
                    if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2641
0
                        if ( ( C4::Context->preference("IndependantBranches") )
2642                            && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2643
0
                            my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2644
0
                            $sth->execute( C4::Context->userenv->{branch} );
2645
0
                            push @authorised_values, ""
2646                              unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2647
0
                            while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2648
0
                                push @authorised_values, $branchcode;
2649
0
                                $authorised_lib{$branchcode} = $branchname;
2650                            }
2651                        } else {
2652
0
                            my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2653
0
                            $sth->execute;
2654
0
                            push @authorised_values, ""
2655                              unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2656
0
                            while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2657
0
                                push @authorised_values, $branchcode;
2658
0
                                $authorised_lib{$branchcode} = $branchname;
2659                            }
2660                        }
2661
2662                        #----- itemtypes
2663                    } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2664
0
                        my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2665
0
                        $sth->execute;
2666
0
                        push @authorised_values, ""
2667                          unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2668
0
                        while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2669
0
                            push @authorised_values, $itemtype;
2670
0
                            $authorised_lib{$itemtype} = $description;
2671                        }
2672                        #---- class_sources
2673                    } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2674
0
                        push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2675
2676
0
                        my $class_sources = GetClassSources();
2677
0
                        my $default_source = C4::Context->preference("DefaultClassificationSource");
2678
2679
0
                        foreach my $class_source (sort keys %$class_sources) {
2680
0
                            next unless $class_sources->{$class_source}->{'used'} or
2681                                        ($class_source eq $default_source);
2682
0
                            push @authorised_values, $class_source;
2683
0
                            $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2684                        }
2685
2686                        #---- "true" authorised value
2687                    } else {
2688
0
                        $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2689
0
                        push @authorised_values, ""
2690                          unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2691
0
                        while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2692
0
                            push @authorised_values, $value;
2693
0
                            $authorised_lib{$value} = $lib;
2694                        }
2695                    }
2696
0
                    $subfield_data{marc_value} = CGI::scrolling_list(
2697                        -name => 'field_value',
2698                        -values => \@authorised_values,
2699                        -default => "$defaultvalue",
2700                        -labels => \%authorised_lib,
2701                        -size => 1,
2702                        -tabindex => '',
2703                        -multiple => 0,
2704                    );
2705                } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2706                        # opening plugin
2707
0
                        my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2708
0
                        if (do $plugin) {
2709
0
                            my $temp;
2710
0
                            my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2711
0
                            my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2712
0
                            $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2713
0
                            my $index_subfield = int(rand(1000000));
2714
0
                            $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
2715
0
                            $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
2716                                onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2717                                 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2718                                <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2719                                $javascript];
2720                        } else {
2721
0
                            warn "Plugin Failed: $plugin";
2722
0
                            $subfield_data{marc_value} = qq(<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" />); # supply default input form
2723                        }
2724                }
2725                elsif ( $tag eq '' ) { # it's an hidden field
2726
0
                    $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
2727                }
2728                elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2729
0
                    $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
2730                }
2731                elsif ( length($defaultvalue) > 100
2732                            or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2733                                  300 <= $tag && $tag < 400 && $subfield eq 'a' )
2734                            or (C4::Context->preference("marcflavour") eq "MARC21" and
2735                                  500 <= $tag && $tag < 600 )
2736                          ) {
2737                    # oversize field (textarea)
2738
0
                    $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255">$defaultvalue</textarea>\n");
2739                } else {
2740
0
                    $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2741                }
2742
0
                push( @loop_data, \%subfield_data );
2743            }
2744        }
2745    }
2746
0
    my $itemnumber;
2747
0
    if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2748
0
        $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2749    }
2750    return {
2751
0
        'itemtagfield' => $itemtagfield,
2752        'itemtagsubfield' => $itemtagsubfield,
2753        'itemnumber' => $itemnumber,
2754        'iteminformation' => \@loop_data
2755    };
2756}
2757
27581;