3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use MARC
::File
::USMARC
;
30 use C4
::Dates qw
/format_date/;
31 use C4
::Log
; # logaction
34 use vars
qw($VERSION @ISA @EXPORT);
40 @ISA = qw( Exporter );
54 &GetBiblioItemByBiblioNumber
55 &GetBiblioFromItemNumber
66 &GetAuthorisedValueDesc
70 &GetPublisherNameFromIsbn
85 # those functions are exported but should not be used
86 # they are usefull is few circumstances, so are exported.
87 # but don't use them unless you're a core developer ;-)
97 &PrepareItemrecordDisplay
104 C4::Biblio - cataloging management functions
108 Biblio.pm contains functions for managing storage and editing of bibliographic data within Koha. Most of the functions in this module are used for cataloging records: adding, editing, or removing biblios, biblioitems, or items. Koha's stores bibliographic information in three places:
112 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
114 =item 2. as raw MARC in the Zebra index and storage engine
116 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
120 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
122 Because the data isn't completely normalized there's a chance for information to get out of sync. The design choice to go with a un-normalized schema was driven by performance and stability concerns. However, if this occur, it can be considered as a bug : The API is (or should be) complete & the only entry point for all biblio/items managements.
126 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
128 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
132 Because of this design choice, the process of managing storage and editing is a bit convoluted. Historically, Biblio.pm's grown to an unmanagable size and as a result we have several types of functions currently:
136 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
138 =item 2. _koha_* - low-level internal functions for managing the koha tables
140 =item 3. Marc management function : as the MARC record is stored in biblioitems.marc(xml), some subs dedicated to it's management are in this package. They should be used only internally by Biblio.pm, the only official entry points being AddBiblio, AddItem, ModBiblio, ModItem.
142 =item 4. Zebra functions used to update the Zebra index
144 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
148 The MARC record (in biblioitems.marcxml) contains the complete marc record, including items. It also contains the biblionumber. That is the reason why it is not stored directly by AddBiblio, with all other fields . To save a biblio, we need to :
152 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
154 =item 2. add the biblionumber and biblioitemnumber into the MARC records
156 =item 3. save the marc record
160 When dealing with items, we must :
164 =item 1. save the item in items table, that gives us an itemnumber
166 =item 2. add the itemnumber to the item MARC field
168 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
170 When modifying a biblio or an item, the behaviour is quite similar.
174 =head1 EXPORTED FUNCTIONS
180 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
184 Exported function (core API) for adding a new biblio to koha.
186 The first argument is a C<MARC::Record> object containing the
187 bib to add, while the second argument is the desired MARC
190 This function also accepts a third, optional argument: a hashref
191 to additional options. The only defined option is C<defer_marc_save>,
192 which if present and mapped to a true value, causes C<AddBiblio>
193 to omit the call to save the MARC in C<bibilioitems.marc>
194 and C<biblioitems.marcxml> This option is provided B<only>
195 for the use of scripts such as C<bulkmarcimport.pl> that may need
196 to do some manipulation of the MARC record for item parsing before
197 saving it and which cannot afford the performance hit of saving
198 the MARC record twice. Consequently, do not use that option
199 unless you can guarantee that C<ModBiblioMarc> will be called.
205 my $frameworkcode = shift;
206 my $options = @_ ?
shift : undef;
207 my $defer_marc_save = 0;
208 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
209 $defer_marc_save = 1;
212 my ($biblionumber,$biblioitemnumber,$error);
213 my $dbh = C4
::Context
->dbh;
214 # transform the data into koha-table style data
215 my $olddata = TransformMarcToKoha
( $dbh, $record, $frameworkcode );
216 ($biblionumber,$error) = _koha_add_biblio
( $dbh, $olddata, $frameworkcode );
217 $olddata->{'biblionumber'} = $biblionumber;
218 ($biblioitemnumber,$error) = _koha_add_biblioitem
( $dbh, $olddata );
220 _koha_marc_update_bib_ids
($record, $frameworkcode, $biblionumber, $biblioitemnumber);
223 $biblionumber = ModBiblioMarc
( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
225 &logaction
(C4
::Context
->userenv->{'number'},"CATALOGUING","ADD",$biblionumber,"biblio")
226 if C4
::Context
->preference("CataloguingLog");
228 return ( $biblionumber, $biblioitemnumber );
233 ModBiblio( $record,$biblionumber,$frameworkcode);
234 Exported function (core API) to modify a biblio
239 my ( $record, $biblionumber, $frameworkcode ) = @_;
240 if (C4
::Context
->preference("CataloguingLog")) {
241 my $newrecord = GetMarcBiblio
($biblionumber);
242 &logaction
(C4
::Context
->userenv->{'number'},"CATALOGUING","MODIFY",$biblionumber,"BEFORE=>".$newrecord->as_formatted);
245 my $dbh = C4
::Context
->dbh;
247 $frameworkcode = "" unless $frameworkcode;
249 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
250 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
251 my $oldRecord = GetMarcBiblio
( $biblionumber );
253 # parse each item, and, for an unknown reason, re-encode each subfield
254 # if you don't do that, the record will have encoding mixed
255 # and the biblio will be re-encoded.
256 # strange, I (Paul P.) searched more than 1 day to understand what happends
257 # but could only solve the problem this way...
258 my @fields = $oldRecord->field( $itemtag );
259 foreach my $fielditem ( @fields ){
261 foreach ($fielditem->subfields()) {
263 $field->add_subfields(Encode
::encode
('utf-8',$_->[0]) => Encode
::encode
('utf-8',$_->[1]));
265 $field = MARC
::Field
->new("$itemtag",'','',Encode
::encode
('utf-8',$_->[0]) => Encode
::encode
('utf-8',$_->[1]));
268 $record->append_fields($field);
271 # update biblionumber and biblioitemnumber in MARC
272 # FIXME - this is assuming a 1 to 1 relationship between
273 # biblios and biblioitems
274 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
275 $sth->execute($biblionumber);
276 my ($biblioitemnumber) = $sth->fetchrow;
278 _koha_marc_update_bib_ids
($record, $frameworkcode, $biblionumber, $biblioitemnumber);
280 # update the MARC record (that now contains biblio and items) with the new record data
281 &ModBiblioMarc
( $record, $biblionumber, $frameworkcode );
283 # load the koha-table data object
284 my $oldbiblio = TransformMarcToKoha
( $dbh, $record, $frameworkcode );
286 # modify the other koha tables
287 _koha_modify_biblio
( $dbh, $oldbiblio, $frameworkcode );
288 _koha_modify_biblioitem_nonmarc
( $dbh, $oldbiblio );
292 =head2 ModBiblioframework
294 ModBiblioframework($biblionumber,$frameworkcode);
295 Exported function to modify a biblio framework
299 sub ModBiblioframework
{
300 my ( $biblionumber, $frameworkcode ) = @_;
301 my $dbh = C4
::Context
->dbh;
302 my $sth = $dbh->prepare(
303 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
305 $sth->execute($frameworkcode, $biblionumber);
313 my $error = &DelBiblio($dbh,$biblionumber);
314 Exported function (core API) for deleting a biblio in koha.
315 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
316 Also backs it up to deleted* tables
317 Checks to make sure there are not issues on any of the items
319 C<$error> : undef unless an error occurs
326 my ( $biblionumber ) = @_;
327 my $dbh = C4
::Context
->dbh;
328 my $error; # for error handling
330 # First make sure this biblio has no items attached
331 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
332 $sth->execute($biblionumber);
333 if (my $itemnumber = $sth->fetchrow){
334 # Fix this to use a status the template can understand
335 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
338 return $error if $error;
340 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
341 # for at least 2 reasons :
342 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
343 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
344 # and we would have no way to remove it (except manually in zebra, but I bet it would be very hard to handle the problem)
345 ModZebra
($biblionumber, "recordDelete", "biblioserver", undef);
347 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
350 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
351 $sth->execute($biblionumber);
352 while ( my $biblioitemnumber = $sth->fetchrow ) {
354 # delete this biblioitem
355 $error = _koha_delete_biblioitems
( $dbh, $biblioitemnumber );
356 return $error if $error;
359 # delete biblio from Koha tables and save in deletedbiblio
360 # must do this *after* _koha_delete_biblioitems, otherwise
361 # delete cascade will prevent deletedbiblioitems rows
362 # from being generated by _koha_delete_biblioitems
363 $error = _koha_delete_biblio
( $dbh, $biblionumber );
365 &logaction
(C4
::Context
->userenv->{'number'},"CATALOGUING","DELETE",$biblionumber,"")
366 if C4
::Context
->preference("CataloguingLog");
374 $data = &GetBiblioData($biblionumber);
375 Returns information about the book with the given biblionumber.
376 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
377 the C<biblio> and C<biblioitems> tables in the
379 In addition, C<$data-E<gt>{subject}> is the list of the book's
380 subjects, separated by C<" , "> (space, comma, space).
381 If there are multiple biblioitems with the given biblionumber, only
382 the first one is considered.
390 my $dbh = C4
::Context
->dbh;
392 # my $query = C4::Context->preference('item-level_itypes') ?
393 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
395 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
396 # WHERE biblio.biblionumber = ?
397 # AND biblioitems.biblionumber = biblio.biblionumber
400 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
402 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
403 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
404 WHERE biblio.biblionumber = ?
405 AND biblioitems.biblionumber = biblio.biblionumber ";
407 my $sth = $dbh->prepare($query);
408 $sth->execute($bibnum);
410 $data = $sth->fetchrow_hashref;
414 } # sub GetBiblioData
416 =head2 &GetBiblioItemData
420 $itemdata = &GetBiblioItemData($biblioitemnumber);
422 Looks up the biblioitem with the given biblioitemnumber. Returns a
423 reference-to-hash. The keys are the fields from the C<biblio>,
424 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
425 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
432 sub GetBiblioItemData
{
433 my ($biblioitemnumber) = @_;
434 my $dbh = C4
::Context
->dbh;
435 my $query = "SELECT *,biblioitems.notes AS bnotes
436 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblioitemnumber ";
437 unless(C4
::Context
->preference('item-level_itypes')) {
438 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
440 $query .= " WHERE biblioitemnumber = ? ";
441 my $sth = $dbh->prepare($query);
443 $sth->execute($biblioitemnumber);
444 $data = $sth->fetchrow_hashref;
447 } # sub &GetBiblioItemData
449 =head2 GetBiblioItemByBiblioNumber
453 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
459 sub GetBiblioItemByBiblioNumber
{
460 my ($biblionumber) = @_;
461 my $dbh = C4
::Context
->dbh;
462 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
466 $sth->execute($biblionumber);
468 while ( my $data = $sth->fetchrow_hashref ) {
469 push @results, $data;
476 =head2 GetBiblioFromItemNumber
480 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
482 Looks up the item with the given itemnumber. if undef, try the barcode.
484 C<&itemnodata> returns a reference-to-hash whose keys are the fields
485 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
493 sub GetBiblioFromItemNumber
{
494 my ( $itemnumber, $barcode ) = @_;
495 my $dbh = C4
::Context
->dbh;
498 $sth=$dbh->prepare( "SELECT * FROM items
499 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
500 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
501 WHERE items.itemnumber = ?") ;
502 $sth->execute($itemnumber);
504 $sth=$dbh->prepare( "SELECT * FROM items
505 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
506 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
507 WHERE items.barcode = ?") ;
508 $sth->execute($barcode);
510 my $data = $sth->fetchrow_hashref;
519 ( $count, @results ) = &GetBiblio($biblionumber);
526 my ($biblionumber) = @_;
527 my $dbh = C4
::Context
->dbh;
528 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
531 $sth->execute($biblionumber);
532 while ( my $data = $sth->fetchrow_hashref ) {
533 $results[$count] = $data;
537 return ( $count, @results );
540 =head2 GetBiblioItemInfosOf
544 GetBiblioItemInfosOf(@biblioitemnumbers);
550 sub GetBiblioItemInfosOf
{
551 my @biblioitemnumbers = @_;
554 SELECT biblioitemnumber,
558 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
560 return get_infos_of
( $query, 'biblioitemnumber' );
563 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
565 =head2 GetMarcStructure
569 $res = GetMarcStructure($forlibrarian,$frameworkcode);
571 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
572 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
573 $frameworkcode : the framework code to read
579 sub GetMarcStructure
{
580 my ( $forlibrarian, $frameworkcode ) = @_;
581 my $dbh=C4
::Context
->dbh;
582 $frameworkcode = "" unless $frameworkcode;
584 my $libfield = ( $forlibrarian eq 1 ) ?
'liblibrarian' : 'libopac';
586 # check that framework exists
589 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
590 $sth->execute($frameworkcode);
591 my ($total) = $sth->fetchrow;
592 $frameworkcode = "" unless ( $total > 0 );
595 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
596 FROM marc_tag_structure
597 WHERE frameworkcode=?
600 $sth->execute($frameworkcode);
601 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
603 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
606 $res->{$tag}->{lib
} =
607 ( $forlibrarian or !$libopac ) ?
$liblibrarian : $libopac;
608 $res->{$tab}->{tab
} = "";
609 $res->{$tag}->{mandatory
} = $mandatory;
610 $res->{$tag}->{repeatable
} = $repeatable;
615 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
616 FROM marc_subfield_structure
617 WHERE frameworkcode=?
618 ORDER BY tagfield,tagsubfield
622 $sth->execute($frameworkcode);
625 my $authorised_value;
637 $tag, $subfield, $liblibrarian,
639 $mandatory, $repeatable, $authorised_value,
640 $authtypecode, $value_builder, $kohafield,
641 $seealso, $hidden, $isurl,
647 $res->{$tag}->{$subfield}->{lib
} =
648 ( $forlibrarian or !$libopac ) ?
$liblibrarian : $libopac;
649 $res->{$tag}->{$subfield}->{tab
} = $tab;
650 $res->{$tag}->{$subfield}->{mandatory
} = $mandatory;
651 $res->{$tag}->{$subfield}->{repeatable
} = $repeatable;
652 $res->{$tag}->{$subfield}->{authorised_value
} = $authorised_value;
653 $res->{$tag}->{$subfield}->{authtypecode
} = $authtypecode;
654 $res->{$tag}->{$subfield}->{value_builder
} = $value_builder;
655 $res->{$tag}->{$subfield}->{kohafield
} = $kohafield;
656 $res->{$tag}->{$subfield}->{seealso
} = $seealso;
657 $res->{$tag}->{$subfield}->{hidden
} = $hidden;
658 $res->{$tag}->{$subfield}->{isurl
} = $isurl;
659 $res->{$tag}->{$subfield}->{'link'} = $link;
660 $res->{$tag}->{$subfield}->{defaultvalue
} = $defaultvalue;
665 =head2 GetUsedMarcStructure
667 the same function as GetMarcStructure expcet it just take field
668 in tab 0-9. (used field)
670 my $results = GetUsedMarcStructure($frameworkcode);
672 L<$results> is a ref to an array which each case containts a ref
673 to a hash which each keys is the columns from marc_subfield_structure
675 L<$frameworkcode> is the framework code.
679 sub GetUsedMarcStructure
($){
680 my $frameworkcode = shift || '';
681 my $dbh = C4
::Context
->dbh;
684 FROM marc_subfield_structure
686 AND frameworkcode
= ?
689 my $sth = $dbh->prepare($query);
690 $sth->execute($frameworkcode);
691 while (my $row = $sth->fetchrow_hashref){
697 =head2 GetMarcFromKohaField
701 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
702 Returns the MARC fields & subfields mapped to the koha field
703 for the given frameworkcode
709 sub GetMarcFromKohaField
{
710 my ( $kohafield, $frameworkcode ) = @_;
711 return 0, 0 unless $kohafield;
712 my $relations = C4
::Context
->marcfromkohafield;
714 $relations->{$frameworkcode}->{$kohafield}->[0],
715 $relations->{$frameworkcode}->{$kohafield}->[1]
723 Returns MARC::Record of the biblionumber passed in parameter.
724 the marc record contains both biblio & item datas
731 my $biblionumber = shift;
732 my $dbh = C4
::Context
->dbh;
734 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
735 $sth->execute($biblionumber);
736 my ($marcxml) = $sth->fetchrow;
737 MARC
::File
::XML
->default_record_format(C4
::Context
->preference('marcflavour'));
738 $marcxml =~ s/\x1e//g;
739 $marcxml =~ s/\x1f//g;
740 $marcxml =~ s/\x1d//g;
741 $marcxml =~ s/\x0f//g;
742 $marcxml =~ s/\x0c//g;
744 my $record = MARC
::Record
->new();
746 $record = eval {MARC
::Record
::new_from_xml
( $marcxml, "utf8", C4
::Context
->preference('marcflavour'))};
747 if ($@
) {warn " problem with :$biblionumber : $@ \n$marcxml";}
748 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
759 my $marcxml = GetXmlBiblio($biblionumber);
761 Returns biblioitems.marcxml of the biblionumber passed in parameter.
762 The XML contains both biblio & item datas
769 my ( $biblionumber ) = @_;
770 my $dbh = C4
::Context
->dbh;
772 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
773 $sth->execute($biblionumber);
774 my ($marcxml) = $sth->fetchrow;
778 =head2 GetAuthorisedValueDesc
782 my $subfieldvalue =get_authorised_value_desc(
783 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
784 Retrieve the complete description for a given authorised value.
786 Now takes $category and $value pair too.
787 my $auth_value_desc =GetAuthorisedValueDesc(
788 '','', 'DVD' ,'','','CCODE');
794 sub GetAuthorisedValueDesc
{
795 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
796 my $dbh = C4
::Context
->dbh;
800 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
801 return C4
::Branch
::GetBranchName
($value);
805 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
806 return getitemtypeinfo
($value)->{description
};
809 #---- "true" authorized value
810 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
813 if ( $category ne "" ) {
816 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
818 $sth->execute( $category, $value );
819 my $data = $sth->fetchrow_hashref;
820 return $data->{'lib'};
823 return $value; # if nothing is found return the original value
831 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
832 Get all notes from the MARC record and returns them in an array.
833 The note are stored in differents places depending on MARC flavour
840 my ( $record, $marcflavour ) = @_;
842 if ( $marcflavour eq "MARC21" ) {
845 else { # assume unimarc if not marc21
852 foreach my $field ( $record->field($scope) ) {
853 my $value = $field->as_string();
855 $marcnote = { marcnote
=> $note, };
856 push @marcnotes, $marcnote;
859 if ( $note ne $value ) {
860 $note = $note . " " . $value;
865 $marcnote = { marcnote
=> $note };
866 push @marcnotes, $marcnote; #load last tag into array
871 =head2 GetMarcSubjects
875 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
876 Get all subjects from the MARC record and returns them in an array.
877 The subjects are stored in differents places depending on MARC flavour
883 sub GetMarcSubjects
{
884 my ( $record, $marcflavour ) = @_;
885 my ( $mintag, $maxtag );
886 if ( $marcflavour eq "MARC21" ) {
890 else { # assume unimarc if not marc21
900 foreach my $field ( $record->field('6..' )) {
901 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
903 my @subfields = $field->subfields();
906 # if there is an authority link, build the link with an= subfield9
907 my $subfield9 = $field->subfield('9');
908 for my $subject_subfield (@subfields ) {
909 # don't load unimarc subfields 3,4,5
910 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ (3|4|5) ) );
911 my $code = $subject_subfield->[0];
912 my $value = $subject_subfield->[1];
913 my $linkvalue = $value;
914 $linkvalue =~ s/(\(|\))//g;
915 my $operator = " and " unless $counter==0;
917 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
919 push @link_loop, {'limit' => 'su', link => $linkvalue, operator
=> $operator };
921 my $separator = C4
::Context
->preference("authoritysep") unless $counter==0;
923 my @this_link_loop = @link_loop;
924 push @subfields_loop, {code
=> $code, value
=> $value, link_loop
=> \
@this_link_loop, separator
=> $separator} unless ($subject_subfield->[0] == 9 );
928 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP
=> \
@subfields_loop };
931 return \
@marcsubjects;
932 } #end getMARCsubjects
934 =head2 GetMarcAuthors
938 authors = GetMarcAuthors($record,$marcflavour);
939 Get all authors from the MARC record and returns them in an array.
940 The authors are stored in differents places depending on MARC flavour
947 my ( $record, $marcflavour ) = @_;
948 my ( $mintag, $maxtag );
949 # tagslib useful for UNIMARC author reponsabilities
950 my $tagslib = &GetMarcStructure
( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be bugguy on some setups, will be usually correct.
951 if ( $marcflavour eq "MARC21" ) {
955 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
964 foreach my $field ( $record->fields ) {
965 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
968 my @subfields = $field->subfields();
970 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
971 my $subfield9 = $field->subfield('9');
972 for my $authors_subfield (@subfields) {
973 # don't load unimarc subfields 3, 5
974 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ (3|5) ) );
975 my $subfieldcode = $authors_subfield->[0];
976 my $value = $authors_subfield->[1];
977 my $linkvalue = $value;
978 $linkvalue =~ s/(\(|\))//g;
979 my $operator = " and " unless $count_auth==0;
980 # if we have an authority link, use that as the link, otherwise use standard searching
982 @link_loop = ({'limit' => 'Koha-Auth-Number' ,link => "$subfield9" });
985 # reset $linkvalue if UNIMARC author responsibility
986 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq '4')) {
987 $linkvalue = "(".GetAuthorisedValueDesc
( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
989 push @link_loop, {'limit' => 'au', link => $linkvalue, operator
=> $operator };
991 my @this_link_loop = @link_loop;
992 my $separator = C4
::Context
->preference("authoritysep") unless $count_auth==0;
993 push @subfields_loop, {code
=> $subfieldcode, value
=> $value, link_loop
=> \
@this_link_loop, separator
=> $separator} unless ($authors_subfield->[0] == 9 );
996 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP
=> \
@subfields_loop };
998 return \
@marcauthors;
1005 $marcurls = GetMarcUrls($record,$marcflavour);
1006 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1007 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1014 my ($record, $marcflavour) = @_;
1017 for my $field ($record->field('856')) {
1018 my $url = $field->subfield('u');
1020 for my $note ( $field->subfield('z')) {
1021 push @notes , {note
=> $note};
1023 $marcurl = { MARCURL
=> $url,
1026 if($marcflavour eq 'MARC21') {
1027 my $s3 = $field->subfield('3');
1028 my $link = $field->subfield('y');
1029 $marcurl->{'linktext'} = $link || $s3 || $url ;;
1030 $marcurl->{'part'} = $s3 if($link);
1031 $marcurl->{'toc'} = 1 if($s3 =~ /^[Tt]able/) ;
1033 $marcurl->{'linktext'} = $url;
1035 push @marcurls, $marcurl;
1040 =head2 GetMarcSeries
1044 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1045 Get all series from the MARC record and returns them in an array.
1046 The series are stored in differents places depending on MARC flavour
1053 my ($record, $marcflavour) = @_;
1054 my ($mintag, $maxtag);
1055 if ($marcflavour eq "MARC21") {
1058 } else { # assume unimarc if not marc21
1068 foreach my $field ($record->field('440'), $record->field('490')) {
1070 #my $value = $field->subfield('a');
1071 #$marcsubjct = {MARCSUBJCT => $value,};
1072 my @subfields = $field->subfields();
1073 #warn "subfields:".join " ", @$subfields;
1076 for my $series_subfield (@subfields) {
1078 undef $volume_number;
1079 # see if this is an instance of a volume
1080 if ($series_subfield->[0] eq 'v') {
1084 my $code = $series_subfield->[0];
1085 my $value = $series_subfield->[1];
1086 my $linkvalue = $value;
1087 $linkvalue =~ s/(\(|\))//g;
1088 my $operator = " and " unless $counter==0;
1089 push @link_loop, {link => $linkvalue, operator
=> $operator };
1090 my $separator = C4
::Context
->preference("authoritysep") unless $counter==0;
1091 if ($volume_number) {
1092 push @subfields_loop, {volumenum
=> $value};
1095 push @subfields_loop, {code
=> $code, value
=> $value, link_loop
=> \
@link_loop, separator
=> $separator, volumenum
=> $volume_number};
1099 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP
=> \
@subfields_loop };
1100 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1101 #push @marcsubjcts, $marcsubjct;
1105 my $marcseriessarray=\
@marcseries;
1106 return $marcseriessarray;
1107 } #end getMARCseriess
1109 =head2 GetFrameworkCode
1113 $frameworkcode = GetFrameworkCode( $biblionumber )
1119 sub GetFrameworkCode
{
1120 my ( $biblionumber ) = @_;
1121 my $dbh = C4
::Context
->dbh;
1122 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1123 $sth->execute($biblionumber);
1124 my ($frameworkcode) = $sth->fetchrow;
1125 return $frameworkcode;
1128 =head2 GetPublisherNameFromIsbn
1130 $name = GetPublishercodeFromIsbn($isbn);
1137 sub GetPublisherNameFromIsbn
($){
1139 $isbn =~ s/[- _]//g;
1141 my @codes = (split '-', DisplayISBN
($isbn));
1142 my $code = $codes[0].$codes[1].$codes[2];
1143 my $dbh = C4
::Context
->dbh;
1145 SELECT distinct publishercode
1148 AND publishercode IS NOT NULL
1151 my $sth = $dbh->prepare($query);
1152 $sth->execute("$code%");
1153 my $name = $sth->fetchrow;
1154 return $name if length $name;
1158 =head2 TransformKohaToMarc
1162 $record = TransformKohaToMarc( $hash )
1163 This function builds partial MARC::Record from a hash
1164 Hash entries can be from biblio or biblioitems.
1165 This function is called in acquisition module, to create a basic catalogue entry from user entry
1171 sub TransformKohaToMarc
{
1174 my $dbh = C4
::Context
->dbh;
1177 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1179 my $record = MARC
::Record
->new();
1180 foreach (keys %{$hash}) {
1181 &TransformKohaToMarcOneField
( $sth, $record, $_,
1187 =head2 TransformKohaToMarcOneField
1191 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1197 sub TransformKohaToMarcOneField
{
1198 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1199 $frameworkcode='' unless $frameworkcode;
1203 if ( !defined $sth ) {
1204 my $dbh = C4
::Context
->dbh;
1205 $sth = $dbh->prepare(
1206 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1209 $sth->execute( $frameworkcode, $kohafieldname );
1210 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1211 my $tag = $record->field($tagfield);
1213 $tag->update( $tagsubfield => $value );
1214 $record->delete_field($tag);
1215 $record->insert_fields_ordered($tag);
1218 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1224 =head2 TransformHtmlToXml
1228 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1230 $auth_type contains :
1231 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1232 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1233 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1239 sub TransformHtmlToXml
{
1240 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1241 my $xml = MARC
::File
::XML
::header
('UTF-8');
1242 $auth_type = C4
::Context
->preference('marcflavour') unless $auth_type;
1243 MARC
::File
::XML
->default_record_format($auth_type);
1244 # in UNIMARC, field 100 contains the encoding
1245 # check that there is one, otherwise the
1246 # MARC::Record->new_from_xml will fail (and Koha will die)
1247 my $unimarc_and_100_exist=0;
1248 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1253 for ( my $i = 0 ; $i <= @
$tags ; $i++ ) {
1254 if (C4
::Context
->preference('marcflavour') eq 'UNIMARC' and @
$tags[$i] eq "100" and @
$subfields[$i] eq "a") {
1255 # if we have a 100 field and it's values are not correct, skip them.
1256 # if we don't have any valid 100 field, we will create a default one at the end
1257 my $enc = substr( @
$values[$i], 26, 2 );
1258 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1259 $unimarc_and_100_exist=1;
1264 @
$values[$i] =~ s/&/&/g;
1265 @
$values[$i] =~ s/</</g;
1266 @
$values[$i] =~ s/>/>/g;
1267 @
$values[$i] =~ s/"/"/g;
1268 @
$values[$i] =~ s/'/'/g;
1269 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1270 # utf8::decode( @$values[$i] );
1272 if ( ( @
$tags[$i] ne $prevtag ) ) {
1273 $j++ unless ( @
$tags[$i] eq "" );
1275 $xml .= "</datafield>\n";
1276 if ( ( @
$tags[$i] && @
$tags[$i] > 10 )
1277 && ( @
$values[$i] ne "" ) )
1279 my $ind1 = substr( @
$indicator[$j], 0, 1 );
1281 if ( @
$indicator[$j] ) {
1282 $ind2 = substr( @
$indicator[$j], 1, 1 );
1285 warn "Indicator in @$tags[$i] is empty";
1289 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1291 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1299 if ( @
$values[$i] ne "" ) {
1302 if ( @
$tags[$i] eq "000" ) {
1303 $xml .= "<leader>@$values[$i]</leader>\n";
1306 # rest of the fixed fields
1308 elsif ( @
$tags[$i] < 10 ) {
1310 "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1314 my $ind1 = substr( @
$indicator[$j], 0, 1 );
1315 my $ind2 = substr( @
$indicator[$j], 1, 1 );
1317 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1319 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1325 else { # @$tags[$i] eq $prevtag
1326 if ( @
$values[$i] eq "" ) {
1330 my $ind1 = substr( @
$indicator[$j], 0, 1 );
1331 my $ind2 = substr( @
$indicator[$j], 1, 1 );
1333 "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1337 "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1340 $prevtag = @
$tags[$i];
1342 if (C4
::Context
->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1343 # warn "SETTING 100 for $auth_type";
1344 use POSIX
qw(strftime);
1345 my $string = strftime
( "%Y%m%d", localtime(time) );
1346 # set 50 to position 26 is biblios, 13 if authorities
1348 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1349 $string = sprintf( "%-*s", 35, $string );
1350 substr( $string, $pos , 6, "50" );
1351 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1352 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1353 $xml .= "</datafield>\n";
1355 $xml .= MARC
::File
::XML
::footer
();
1359 =head2 TransformHtmlToMarc
1361 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1362 L<$params> is a ref to an array as below:
1364 'tag_010_indicator_531951' ,
1365 'tag_010_code_a_531951_145735' ,
1366 'tag_010_subfield_a_531951_145735' ,
1367 'tag_200_indicator_873510' ,
1368 'tag_200_code_a_873510_673465' ,
1369 'tag_200_subfield_a_873510_673465' ,
1370 'tag_200_code_b_873510_704318' ,
1371 'tag_200_subfield_b_873510_704318' ,
1372 'tag_200_code_e_873510_280822' ,
1373 'tag_200_subfield_e_873510_280822' ,
1374 'tag_200_code_f_873510_110730' ,
1375 'tag_200_subfield_f_873510_110730' ,
1377 L<$cgi> is the CGI object which containts the value.
1378 L<$record> is the MARC::Record object.
1382 sub TransformHtmlToMarc
{
1386 # creating a new record
1387 my $record = MARC
::Record
->new();
1390 while ($params->[$i]){ # browse all CGI params
1391 my $param = $params->[$i];
1393 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1394 if ($param eq 'biblionumber') {
1395 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1396 &GetMarcFromKohaField
( "biblio.biblionumber", '' );
1397 if ($biblionumbertagfield < 10) {
1398 $newfield = MARC
::Field
->new(
1399 $biblionumbertagfield,
1400 $cgi->param($param),
1403 $newfield = MARC
::Field
->new(
1404 $biblionumbertagfield,
1407 "$biblionumbertagsubfield" => $cgi->param($param),
1410 push @fields,$newfield if($newfield);
1412 elsif ($param =~ /^tag_(\d*)_indicator_/){ # new field start when having 'input name="..._indicator_..."
1415 my $ind1 = substr($cgi->param($param),0,1);
1416 my $ind2 = substr($cgi->param($param),1,1);
1420 if($tag < 10){ # no code for theses fields
1421 # in MARC editor, 000 contains the leader.
1422 if ($tag eq '000' ) {
1423 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1424 # between 001 and 009 (included)
1426 $newfield = MARC
::Field
->new(
1428 $cgi->param($params->[$j+1]),
1431 # > 009, deal with subfields
1433 while($params->[$j] =~ /_code_/){ # browse all it's subfield
1434 my $inner_param = $params->[$j];
1436 if($cgi->param($params->[$j+1])){ # only if there is a value (code => value)
1437 $newfield->add_subfields(
1438 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1442 if ( $cgi->param($params->[$j+1]) ) { # creating only if there is a value (code => value)
1443 $newfield = MARC
::Field
->new(
1447 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1454 push @fields,$newfield if($newfield);
1459 $record->append_fields(@fields);
1463 # cache inverted MARC field map
1464 our $inverted_field_map;
1466 =head2 TransformMarcToKoha
1470 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1474 Extract data from a MARC bib record into a hashref representing
1475 Koha biblio, biblioitems, and items fields.
1478 sub TransformMarcToKoha
{
1479 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1483 unless (defined $inverted_field_map) {
1484 $inverted_field_map = _get_inverted_marc_field_map
();
1488 if ($limit_table eq 'items') {
1489 $tables{'items'} = 1;
1491 $tables{'items'} = 1;
1492 $tables{'biblio'} = 1;
1493 $tables{'biblioitems'} = 1;
1496 # traverse through record
1497 MARCFIELD
: foreach my $field ($record->fields()) {
1498 my $tag = $field->tag();
1499 next MARCFIELD
unless exists $inverted_field_map->{$frameworkcode}->{$tag};
1500 if ($field->is_control_field()) {
1501 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list
};
1502 ENTRY
: foreach my $entry (@
{ $kohafields }) {
1503 my ($subfield, $table, $column) = @
{ $entry };
1504 next ENTRY
unless exists $tables{$table};
1505 my $key = _disambiguate
($table, $column);
1506 if ($result->{$key}) {
1507 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
1508 $result->{$key} .= " | " . $field->data();
1511 $result->{$key} = $field->data();
1515 # deal with subfields
1516 MARCSUBFIELD
: foreach my $sf ($field->subfields()) {
1517 my $code = $sf->[0];
1518 next MARCSUBFIELD
unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs
}->{$code};
1519 my $value = $sf->[1];
1520 SFENTRY
: foreach my $entry (@
{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs
}->{$code} }) {
1521 my ($table, $column) = @
{ $entry };
1522 next SFENTRY
unless exists $tables{$table};
1523 my $key = _disambiguate
($table, $column);
1524 if ($result->{$key}) {
1525 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
1526 $result->{$key} .= " | " . $value;
1529 $result->{$key} = $value;
1536 # modify copyrightdate to keep only the 1st year found
1537 if (exists $result->{'copyrightdate'}) {
1538 my $temp = $result->{'copyrightdate'};
1539 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1541 $result->{'copyrightdate'} = $1;
1543 else { # if no cYYYY, get the 1st date.
1544 $temp =~ m/(\d\d\d\d)/;
1545 $result->{'copyrightdate'} = $1;
1549 # modify publicationyear to keep only the 1st year found
1550 if (exists $result->{'publicationyear'}) {
1551 my $temp = $result->{'publicationyear'};
1552 $temp =~ m/c(\d\d\d\d)/; # search cYYYY first
1554 $result->{'publicationyear'} = $1;
1556 else { # if no cYYYY, get the 1st date.
1557 $temp =~ m/(\d\d\d\d)/;
1558 $result->{'publicationyear'} = $1;
1565 sub _get_inverted_marc_field_map
{
1567 my $relations = C4
::Context
->marcfromkohafield;
1569 foreach my $frameworkcode (keys %{ $relations }) {
1570 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
1571 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
1572 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
1573 my ($table, $column) = split /[.]/, $kohafield, 2;
1574 push @
{ $field_map->{$frameworkcode}->{$tag}->{list
} }, [ $subfield, $table, $column ];
1575 push @
{ $field_map->{$frameworkcode}->{$tag}->{sfs
}->{$subfield} }, [ $table, $column ];
1581 =head2 _disambiguate
1585 $newkey = _disambiguate($table, $field);
1587 This is a temporary hack to distinguish between the
1588 following sets of columns when using TransformMarcToKoha.
1590 items.cn_source & biblioitems.cn_source
1591 items.cn_sort & biblioitems.cn_sort
1593 Columns that are currently NOT distinguished (FIXME
1594 due to lack of time to fully test) are:
1596 biblio.notes and biblioitems.notes
1601 FIXME - this is necessary because prefixing each column
1602 name with the table name would require changing lots
1603 of code and templates, and exposing more of the DB
1604 structure than is good to the UI templates, particularly
1605 since biblio and bibloitems may well merge in a future
1606 version. In the future, it would also be good to
1607 separate DB access and UI presentation field names
1615 my ($table, $column) = @_;
1616 if ($column eq "cn_sort" or $column eq "cn_source") {
1617 return $table . '.' . $column;
1624 =head2 get_koha_field_from_marc
1628 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
1630 Internal function to map data from the MARC record to a specific non-MARC field.
1631 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
1637 sub get_koha_field_from_marc
{
1638 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
1639 my ( $tagfield, $subfield ) = GetMarcFromKohaField
( $koha_table.'.'.$koha_column, $frameworkcode );
1641 foreach my $field ( $record->field($tagfield) ) {
1642 if ( $field->tag() < 10 ) {
1644 $kohafield .= " | " . $field->data();
1647 $kohafield = $field->data();
1651 if ( $field->subfields ) {
1652 my @subfields = $field->subfields();
1653 foreach my $subfieldcount ( 0 .. $#subfields ) {
1654 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1657 " | " . $subfields[$subfieldcount][1];
1661 $subfields[$subfieldcount][1];
1672 =head2 TransformMarcToKohaOneField
1676 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
1682 sub TransformMarcToKohaOneField
{
1684 # FIXME ? if a field has a repeatable subfield that is used in old-db,
1685 # only the 1st will be retrieved...
1686 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
1688 my ( $tagfield, $subfield ) =
1689 GetMarcFromKohaField
( $kohatable . "." . $kohafield,
1691 foreach my $field ( $record->field($tagfield) ) {
1692 if ( $field->tag() < 10 ) {
1693 if ( $result->{$kohafield} ) {
1694 $result->{$kohafield} .= " | " . $field->data();
1697 $result->{$kohafield} = $field->data();
1701 if ( $field->subfields ) {
1702 my @subfields = $field->subfields();
1703 foreach my $subfieldcount ( 0 .. $#subfields ) {
1704 if ( $subfields[$subfieldcount][0] eq $subfield ) {
1705 if ( $result->{$kohafield} ) {
1706 $result->{$kohafield} .=
1707 " | " . $subfields[$subfieldcount][1];
1710 $result->{$kohafield} =
1711 $subfields[$subfieldcount][1];
1721 =head1 OTHER FUNCTIONS
1724 =head2 PrepareItemrecordDisplay
1728 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
1730 Returns a hash with all the fields for Display a given item data in a template
1736 sub PrepareItemrecordDisplay
{
1738 my ( $bibnum, $itemnum ) = @_;
1740 my $dbh = C4
::Context
->dbh;
1741 my $frameworkcode = &GetFrameworkCode
( $bibnum );
1742 my ( $itemtagfield, $itemtagsubfield ) =
1743 &GetMarcFromKohaField
( "items.itemnumber", $frameworkcode );
1744 my $tagslib = &GetMarcStructure
( 1, $frameworkcode );
1745 my $itemrecord = C4
::Items
::GetMarcItem
( $bibnum, $itemnum) if ($itemnum);
1747 my $authorised_values_sth =
1749 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
1751 foreach my $tag ( sort keys %{$tagslib} ) {
1752 my $previous_tag = '';
1754 # loop through each subfield
1756 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
1757 next if ( subfield_is_koha_internal_p
($subfield) );
1758 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
1760 $subfield_data{tag
} = $tag;
1761 $subfield_data{subfield
} = $subfield;
1762 $subfield_data{countsubfield
} = $cntsubf++;
1763 $subfield_data{kohafield
} =
1764 $tagslib->{$tag}->{$subfield}->{'kohafield'};
1766 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1767 $subfield_data{marc_lib
} =
1768 "<span id=\"error\" title=\""
1769 . $tagslib->{$tag}->{$subfield}->{lib
} . "\">"
1770 . substr( $tagslib->{$tag}->{$subfield}->{lib
}, 0, 12 )
1772 $subfield_data{mandatory
} =
1773 $tagslib->{$tag}->{$subfield}->{mandatory
};
1774 $subfield_data{repeatable
} =
1775 $tagslib->{$tag}->{$subfield}->{repeatable
};
1776 $subfield_data{hidden
} = "display:none"
1777 if $tagslib->{$tag}->{$subfield}->{hidden
};
1779 ( $x, $value ) = _find_value
( $tag, $subfield, $itemrecord )
1781 $value =~ s/"/"/g;
1783 # search for itemcallnumber if applicable
1784 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq
1785 'items.itemcallnumber'
1786 && C4
::Context
->preference('itemcallnumber') )
1789 substr( C4
::Context
->preference('itemcallnumber'), 0, 3 );
1791 substr( C4
::Context
->preference('itemcallnumber'), 3, 1 );
1792 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
1794 $value = $temp->subfield($CNsubfield);
1797 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
1798 my @authorised_values;
1801 # builds list, depending on authorised value...
1803 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
1806 if ( ( C4
::Context
->preference("IndependantBranches") )
1807 && ( C4
::Context
->userenv->{flags
} != 1 ) )
1811 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
1813 $sth->execute( C4
::Context
->userenv->{branch
} );
1814 push @authorised_values, ""
1816 $tagslib->{$tag}->{$subfield}->{mandatory
} );
1817 while ( my ( $branchcode, $branchname ) =
1818 $sth->fetchrow_array )
1820 push @authorised_values, $branchcode;
1821 $authorised_lib{$branchcode} = $branchname;
1827 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
1830 push @authorised_values, ""
1832 $tagslib->{$tag}->{$subfield}->{mandatory
} );
1833 while ( my ( $branchcode, $branchname ) =
1834 $sth->fetchrow_array )
1836 push @authorised_values, $branchcode;
1837 $authorised_lib{$branchcode} = $branchname;
1843 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq
1848 "SELECT itemtype,description FROM itemtypes ORDER BY description"
1851 push @authorised_values, ""
1852 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
1853 while ( my ( $itemtype, $description ) =
1854 $sth->fetchrow_array )
1856 push @authorised_values, $itemtype;
1857 $authorised_lib{$itemtype} = $description;
1860 #---- "true" authorised value
1863 $authorised_values_sth->execute(
1864 $tagslib->{$tag}->{$subfield}->{authorised_value
} );
1865 push @authorised_values, ""
1866 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
1867 while ( my ( $value, $lib ) =
1868 $authorised_values_sth->fetchrow_array )
1870 push @authorised_values, $value;
1871 $authorised_lib{$value} = $lib;
1874 $subfield_data{marc_value
} = CGI
::scrolling_list
(
1875 -name
=> 'field_value',
1876 -values => \
@authorised_values,
1877 -default => "$value",
1878 -labels
=> \
%authorised_lib,
1884 elsif ( $tagslib->{$tag}->{$subfield}->{thesaurus_category
} ) {
1885 $subfield_data{marc_value
} =
1886 "<input type=\"text\" name=\"field_value\" size=47 maxlength=255> <a href=\"javascript:Dopop('cataloguing/thesaurus_popup.pl?category=$tagslib->{$tag}->{$subfield}->{thesaurus_category}&index=',)\">...</a>";
1889 # COMMENTED OUT because No $i is provided with this API.
1890 # And thus, no value_builder can be activated.
1891 # BUT could be thought over.
1892 # } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
1893 # my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
1895 # my $extended_param = plugin_parameters($dbh,$itemrecord,$tagslib,$i,0);
1896 # my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
1897 # $subfield_data{marc_value}="<input type=\"text\" value=\"$value\" name=\"field_value\" size=47 maxlength=255 DISABLE READONLY OnFocus=\"javascript:Focus$function_name()\" OnBlur=\"javascript:Blur$function_name()\"> <a href=\"javascript:Clic$function_name()\">...</a> $javascript";
1900 $subfield_data{marc_value
} =
1901 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
1903 push( @loop_data, \
%subfield_data );
1907 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
1908 if ( $itemrecord && $itemrecord->field($itemtagfield) );
1910 'itemtagfield' => $itemtagfield,
1911 'itemtagsubfield' => $itemtagsubfield,
1912 'itemnumber' => $itemnumber,
1913 'iteminformation' => \
@loop_data
1919 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
1921 # replaced by a zebraqueue table, that is filled with ModZebra to run.
1922 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
1923 # =head2 ModZebrafiles
1925 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
1929 # sub ModZebrafiles {
1931 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
1935 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
1936 # unless ( opendir( DIR, "$zebradir" ) ) {
1937 # warn "$zebradir not found";
1941 # my $filename = $zebradir . $biblionumber;
1944 # open( OUTPUT, ">", $filename . ".xml" );
1945 # print OUTPUT $record;
1954 ModZebra( $biblionumber, $op, $server, $newRecord );
1956 $biblionumber is the biblionumber we want to index
1957 $op is specialUpdate or delete, and is used to know what we want to do
1958 $server is the server that we want to update
1959 $newRecord is the MARC::Record containing the new record. It is usefull only when NoZebra=1, and is used to know what to add to the nozebra database. (the record in mySQL being, if it exist, the previous record, the one just before the modif. We need both : the previous and the new one.
1966 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
1967 my ( $biblionumber, $op, $server, $newRecord ) = @_;
1968 my $dbh=C4
::Context
->dbh;
1970 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
1972 # replaced by a zebraqueue table, that is filled with ModZebra to run.
1973 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
1975 if (C4
::Context
->preference("NoZebra")) {
1976 # lock the nozebra table : we will read index lines, update them in Perl process
1977 # and write everything in 1 transaction.
1978 # lock the table to avoid someone else overwriting what we are doing
1979 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE');
1980 my %result; # the result hash that will be builded by deletion / add, and written on mySQL at the end, to improve speed
1982 if ($server eq 'biblioserver') {
1983 $record= GetMarcBiblio
($biblionumber);
1985 $record= C4
::AuthoritiesMarc
::GetAuthority
($biblionumber);
1987 if ($op eq 'specialUpdate') {
1988 # OK, we have to add or update the record
1989 # 1st delete (virtually, in indexes), if record actually exists
1991 %result = _DelBiblioNoZebra
($biblionumber,$record,$server);
1993 # ... add the record
1994 %result=_AddBiblioNoZebra
($biblionumber,$newRecord, $server, %result);
1996 # it's a deletion, delete the record...
1997 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
1998 %result=_DelBiblioNoZebra
($biblionumber,$record,$server);
2000 # ok, now update the database...
2001 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2002 foreach my $key (keys %result) {
2003 foreach my $index (keys %{$result{$key}}) {
2004 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2007 $dbh->do('UNLOCK TABLES');
2011 # we use zebra, just fill zebraqueue table
2013 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2014 $sth->execute($biblionumber,$server,$op);
2019 =head2 GetNoZebraIndexes
2021 %indexes = GetNoZebraIndexes;
2023 return the data from NoZebraIndexes syspref.
2027 sub GetNoZebraIndexes
{
2028 my $index = C4
::Context
->preference('NoZebraIndexes');
2030 foreach my $line (split /('|"),/,$index) {
2031 $line =~ /(.*)=>(.*)/;
2032 my $index = substr($1,1); # get the index, don't forget to remove initial ' or "
2034 $index =~ s/'|"|\s//g;
2037 $fields =~ s/'|"|\s//g;
2038 $indexes{$index}=$fields;
2043 =head1 INTERNAL FUNCTIONS
2045 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2047 function to delete a biblio in NoZebra indexes
2048 This function does NOT delete anything in database : it reads all the indexes entries
2049 that have to be deleted & delete them in the hash
2050 The SQL part is done either :
2051 - after the Add if we are modifying a biblio (delete + add again)
2052 - immediatly after this sub if we are doing a true deletion.
2053 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2058 sub _DelBiblioNoZebra
{
2059 my ($biblionumber, $record, $server)=@_;
2062 my $dbh = C4
::Context
->dbh;
2066 if ($server eq 'biblioserver') {
2067 %index=GetNoZebraIndexes
;
2068 # get title of the record (to store the 10 first letters with the index)
2069 my ($titletag,$titlesubfield) = GetMarcFromKohaField
('biblio.title');
2070 $title = lc($record->subfield($titletag,$titlesubfield));
2072 # for authorities, the "title" is the $a mainentry
2073 my $authref = C4
::AuthoritiesMarc
::GetAuthType
($record->subfield(152,'b'));
2074 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2075 $title = $record->subfield($authref->{auth_tag_to_report
},'a');
2076 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2077 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2078 $index{'auth_type'} = '152b';
2082 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2083 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2084 # limit to 10 char, should be enough, and limit the DB size
2085 $title = substr($title,0,10);
2087 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2088 foreach my $field ($record->fields()) {
2089 #parse each subfield
2090 next if $field->tag <10;
2091 foreach my $subfield ($field->subfields()) {
2092 my $tag = $field->tag();
2093 my $subfieldcode = $subfield->[0];
2095 # check each index to see if the subfield is stored somewhere
2096 # otherwise, store it in __RAW__ index
2097 foreach my $key (keys %index) {
2098 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2099 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2101 my $line= lc $subfield->[1];
2102 # remove meaningless value in the field...
2103 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g
;
2104 # ... and split in words
2105 foreach (split / /,$line) {
2106 next unless $_; # skip empty values (multiple spaces)
2107 # if the entry is already here, do nothing, the biblionumber has already be removed
2108 unless ($result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2109 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2110 $sth2->execute($server,$key,$_);
2111 my $existing_biblionumbers = $sth2->fetchrow;
2113 if ($existing_biblionumbers) {
2114 # warn " existing for $key $_: $existing_biblionumbers";
2115 $result{$key}->{$_} =$existing_biblionumbers;
2116 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2122 # the subfield is not indexed, store it in __RAW__ index anyway
2124 my $line= lc $subfield->[1];
2125 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g
;
2126 # ... and split in words
2127 foreach (split / /,$line) {
2128 next unless $_; # skip empty values (multiple spaces)
2129 # if the entry is already here, do nothing, the biblionumber has already be removed
2130 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2131 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2132 $sth2->execute($server,'__RAW__',$_);
2133 my $existing_biblionumbers = $sth2->fetchrow;
2135 if ($existing_biblionumbers) {
2136 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2137 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2147 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2149 function to add a biblio in NoZebra indexes
2153 sub _AddBiblioNoZebra
{
2154 my ($biblionumber, $record, $server, %result)=@_;
2155 my $dbh = C4
::Context
->dbh;
2159 if ($server eq 'biblioserver') {
2160 %index=GetNoZebraIndexes
;
2161 # get title of the record (to store the 10 first letters with the index)
2162 my ($titletag,$titlesubfield) = GetMarcFromKohaField
('biblio.title');
2163 $title = lc($record->subfield($titletag,$titlesubfield));
2165 # warn "server : $server";
2166 # for authorities, the "title" is the $a mainentry
2167 my $authref = C4
::AuthoritiesMarc
::GetAuthType
($record->subfield(152,'b'));
2168 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2169 $title = $record->subfield($authref->{auth_tag_to_report
},'a');
2170 $index{'mainmainentry'} = $authref->{auth_tag_to_report
}.'a';
2171 $index{'mainentry'} = $authref->{auth_tag_to_report
}.'*';
2172 $index{'auth_type'} = '152b';
2175 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2176 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2177 # limit to 10 char, should be enough, and limit the DB size
2178 $title = substr($title,0,10);
2180 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2181 foreach my $field ($record->fields()) {
2182 #parse each subfield
2183 next if $field->tag <10;
2184 foreach my $subfield ($field->subfields()) {
2185 my $tag = $field->tag();
2186 my $subfieldcode = $subfield->[0];
2188 # check each index to see if the subfield is stored somewhere
2189 # otherwise, store it in __RAW__ index
2190 foreach my $key (keys %index) {
2191 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2192 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2194 my $line= lc $subfield->[1];
2195 # remove meaningless value in the field...
2196 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g
;
2197 # ... and split in words
2198 foreach (split / /,$line) {
2199 next unless $_; # skip empty values (multiple spaces)
2200 # if the entry is already here, improve weight
2201 # warn "managing $_";
2202 if ($result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2204 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2205 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2207 # get the value if it exist in the nozebra table, otherwise, create it
2208 $sth2->execute($server,$key,$_);
2209 my $existing_biblionumbers = $sth2->fetchrow;
2211 if ($existing_biblionumbers) {
2212 $result{$key}->{"$_"} =$existing_biblionumbers;
2214 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2215 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2216 # create a new ligne for this entry
2218 # warn "INSERT : $server / $key / $_";
2219 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2220 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2226 # the subfield is not indexed, store it in __RAW__ index anyway
2228 my $line= lc $subfield->[1];
2229 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g
;
2230 # ... and split in words
2231 foreach (split / /,$line) {
2232 next unless $_; # skip empty values (multiple spaces)
2233 # if the entry is already here, improve weight
2234 if ($result{'__RAW__'}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d);/) {
2236 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2237 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2239 # get the value if it exist in the nozebra table, otherwise, create it
2240 $sth2->execute($server,'__RAW__',$_);
2241 my $existing_biblionumbers = $sth2->fetchrow;
2243 if ($existing_biblionumbers) {
2244 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2246 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d);//;
2247 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2248 # create a new ligne for this entry
2250 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2251 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2266 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2268 Find the given $subfield in the given $tag in the given
2269 MARC::Record $record. If the subfield is found, returns
2270 the (indicators, value) pair; otherwise, (undef, undef) is
2274 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2275 I suggest we export it from this module.
2282 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2285 if ( $tagfield < 10 ) {
2286 if ( $record->field($tagfield) ) {
2287 push @result, $record->field($tagfield)->data();
2294 foreach my $field ( $record->field($tagfield) ) {
2295 my @subfields = $field->subfields();
2296 foreach my $subfield (@subfields) {
2297 if ( @
$subfield[0] eq $insubfield ) {
2298 push @result, @
$subfield[1];
2299 $indicator = $field->indicator(1) . $field->indicator(2);
2304 return ( $indicator, @result );
2307 =head2 _koha_marc_update_bib_ids
2311 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2313 Internal function to add or update biblionumber and biblioitemnumber to
2320 sub _koha_marc_update_bib_ids
{
2321 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2323 # we must add bibnum and bibitemnum in MARC::Record...
2324 # we build the new field with biblionumber and biblioitemnumber
2325 # we drop the original field
2326 # we add the new builded field.
2327 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField
("biblio.biblionumber",$frameworkcode);
2328 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField
("biblioitems.biblioitemnumber",$frameworkcode);
2330 if ($biblio_tag != $biblioitem_tag) {
2331 # biblionumber & biblioitemnumber are in different fields
2333 # deal with biblionumber
2334 my ($new_field, $old_field);
2335 if ($biblio_tag < 10) {
2336 $new_field = MARC
::Field
->new( $biblio_tag, $biblionumber );
2339 MARC
::Field
->new( $biblio_tag, '', '',
2340 "$biblio_subfield" => $biblionumber );
2343 # drop old field and create new one...
2344 $old_field = $record->field($biblio_tag);
2345 $record->delete_field($old_field);
2346 $record->append_fields($new_field);
2348 # deal with biblioitemnumber
2349 if ($biblioitem_tag < 10) {
2350 $new_field = MARC
::Field
->new( $biblioitem_tag, $biblioitemnumber, );
2353 MARC
::Field
->new( $biblioitem_tag, '', '',
2354 "$biblioitem_subfield" => $biblioitemnumber, );
2356 # drop old field and create new one...
2357 $old_field = $record->field($biblioitem_tag);
2358 $record->delete_field($old_field);
2359 $record->insert_fields_ordered($new_field);
2362 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2363 my $new_field = MARC
::Field
->new(
2364 $biblio_tag, '', '',
2365 "$biblio_subfield" => $biblionumber,
2366 "$biblioitem_subfield" => $biblioitemnumber
2369 # drop old field and create new one...
2370 my $old_field = $record->field($biblio_tag);
2371 $record->delete_field($old_field);
2372 $record->insert_fields_ordered($new_field);
2376 =head2 _koha_add_biblio
2380 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2382 Internal function to add a biblio ($biblio is a hash with the values)
2388 sub _koha_add_biblio
{
2389 my ( $dbh, $biblio, $frameworkcode ) = @_;
2393 # set the series flag
2395 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2399 SET frameworkcode = ?,
2410 my $sth = $dbh->prepare($query);
2413 $biblio->{'author'},
2415 $biblio->{'unititle'},
2418 $biblio->{'seriestitle'},
2419 $biblio->{'copyrightdate'},
2420 $biblio->{'abstract'}
2423 my $biblionumber = $dbh->{'mysql_insertid'};
2424 if ( $dbh->errstr ) {
2425 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
2430 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2431 return ($biblionumber,$error);
2434 =head2 _koha_modify_biblio
2438 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2440 Internal function for updating the biblio table
2446 sub _koha_modify_biblio
{
2447 my ( $dbh, $biblio, $frameworkcode ) = @_;
2452 SET frameworkcode = ?,
2461 WHERE biblionumber = ?
2464 my $sth = $dbh->prepare($query);
2468 $biblio->{'author'},
2470 $biblio->{'unititle'},
2472 $biblio->{'serial'},
2473 $biblio->{'seriestitle'},
2474 $biblio->{'copyrightdate'},
2475 $biblio->{'abstract'},
2476 $biblio->{'biblionumber'}
2477 ) if $biblio->{'biblionumber'};
2479 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2480 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
2483 return ( $biblio->{'biblionumber'},$error );
2486 =head2 _koha_modify_biblioitem_nonmarc
2490 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2492 Updates biblioitems row except for marc and marcxml, which should be changed
2499 sub _koha_modify_biblioitem_nonmarc
{
2500 my ( $dbh, $biblioitem ) = @_;
2503 # re-calculate the cn_sort, it may have changed
2504 my ($cn_sort) = GetClassSort
($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2508 SET biblionumber = ?,
2514 publicationyear = ?,
2518 collectiontitle = ?,
2520 collectionvolume= ?,
2521 editionstatement= ?,
2522 editionresponsibility = ?,
2536 where biblioitemnumber = ?
2538 my $sth = $dbh->prepare($query);
2540 $biblioitem->{'biblionumber'},
2541 $biblioitem->{'volume'},
2542 $biblioitem->{'number'},
2543 $biblioitem->{'itemtype'},
2544 $biblioitem->{'isbn'},
2545 $biblioitem->{'issn'},
2546 $biblioitem->{'publicationyear'},
2547 $biblioitem->{'publishercode'},
2548 $biblioitem->{'volumedate'},
2549 $biblioitem->{'volumedesc'},
2550 $biblioitem->{'collectiontitle'},
2551 $biblioitem->{'collectionissn'},
2552 $biblioitem->{'collectionvolume'},
2553 $biblioitem->{'editionstatement'},
2554 $biblioitem->{'editionresponsibility'},
2555 $biblioitem->{'illus'},
2556 $biblioitem->{'pages'},
2557 $biblioitem->{'bnotes'},
2558 $biblioitem->{'size'},
2559 $biblioitem->{'place'},
2560 $biblioitem->{'lccn'},
2561 $biblioitem->{'url'},
2562 $biblioitem->{'biblioitems.cn_source'},
2563 $biblioitem->{'cn_class'},
2564 $biblioitem->{'cn_item'},
2565 $biblioitem->{'cn_suffix'},
2567 $biblioitem->{'totalissues'},
2568 $biblioitem->{'biblioitemnumber'}
2570 if ( $dbh->errstr ) {
2571 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
2574 return ($biblioitem->{'biblioitemnumber'},$error);
2577 =head2 _koha_add_biblioitem
2581 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
2583 Internal function to add a biblioitem
2589 sub _koha_add_biblioitem
{
2590 my ( $dbh, $biblioitem ) = @_;
2593 my ($cn_sort) = GetClassSort
($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2595 "INSERT INTO biblioitems SET
2602 publicationyear = ?,
2606 collectiontitle = ?,
2608 collectionvolume= ?,
2609 editionstatement= ?,
2610 editionresponsibility = ?,
2626 my $sth = $dbh->prepare($query);
2628 $biblioitem->{'biblionumber'},
2629 $biblioitem->{'volume'},
2630 $biblioitem->{'number'},
2631 $biblioitem->{'itemtype'},
2632 $biblioitem->{'isbn'},
2633 $biblioitem->{'issn'},
2634 $biblioitem->{'publicationyear'},
2635 $biblioitem->{'publishercode'},
2636 $biblioitem->{'volumedate'},
2637 $biblioitem->{'volumedesc'},
2638 $biblioitem->{'collectiontitle'},
2639 $biblioitem->{'collectionissn'},
2640 $biblioitem->{'collectionvolume'},
2641 $biblioitem->{'editionstatement'},
2642 $biblioitem->{'editionresponsibility'},
2643 $biblioitem->{'illus'},
2644 $biblioitem->{'pages'},
2645 $biblioitem->{'bnotes'},
2646 $biblioitem->{'size'},
2647 $biblioitem->{'place'},
2648 $biblioitem->{'lccn'},
2649 $biblioitem->{'marc'},
2650 $biblioitem->{'url'},
2651 $biblioitem->{'biblioitems.cn_source'},
2652 $biblioitem->{'cn_class'},
2653 $biblioitem->{'cn_item'},
2654 $biblioitem->{'cn_suffix'},
2656 $biblioitem->{'totalissues'}
2658 my $bibitemnum = $dbh->{'mysql_insertid'};
2659 if ( $dbh->errstr ) {
2660 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
2664 return ($bibitemnum,$error);
2667 =head2 _koha_delete_biblio
2671 $error = _koha_delete_biblio($dbh,$biblionumber);
2673 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2675 C<$dbh> - the database handle
2676 C<$biblionumber> - the biblionumber of the biblio to be deleted
2682 # FIXME: add error handling
2684 sub _koha_delete_biblio
{
2685 my ( $dbh, $biblionumber ) = @_;
2687 # get all the data for this biblio
2688 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2689 $sth->execute($biblionumber);
2691 if ( my $data = $sth->fetchrow_hashref ) {
2693 # save the record in deletedbiblio
2694 # find the fields to save
2695 my $query = "INSERT INTO deletedbiblio SET ";
2697 foreach my $temp ( keys %$data ) {
2698 $query .= "$temp = ?,";
2699 push( @bind, $data->{$temp} );
2702 # replace the last , by ",?)"
2704 my $bkup_sth = $dbh->prepare($query);
2705 $bkup_sth->execute(@bind);
2709 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2710 $del_sth->execute($biblionumber);
2717 =head2 _koha_delete_biblioitems
2721 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2723 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2725 C<$dbh> - the database handle
2726 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2732 # FIXME: add error handling
2734 sub _koha_delete_biblioitems
{
2735 my ( $dbh, $biblioitemnumber ) = @_;
2737 # get all the data for this biblioitem
2739 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2740 $sth->execute($biblioitemnumber);
2742 if ( my $data = $sth->fetchrow_hashref ) {
2744 # save the record in deletedbiblioitems
2745 # find the fields to save
2746 my $query = "INSERT INTO deletedbiblioitems SET ";
2748 foreach my $temp ( keys %$data ) {
2749 $query .= "$temp = ?,";
2750 push( @bind, $data->{$temp} );
2753 # replace the last , by ",?)"
2755 my $bkup_sth = $dbh->prepare($query);
2756 $bkup_sth->execute(@bind);
2759 # delete the biblioitem
2761 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2762 $del_sth->execute($biblioitemnumber);
2769 =head1 UNEXPORTED FUNCTIONS
2771 =head2 ModBiblioMarc
2773 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
2775 Add MARC data for a biblio to koha
2777 Function exported, but should NOT be used, unless you really know what you're doing
2783 # pass the MARC::Record to this function, and it will create the records in the marc field
2784 my ( $record, $biblionumber, $frameworkcode ) = @_;
2785 my $dbh = C4
::Context
->dbh;
2786 my @fields = $record->fields();
2787 if ( !$frameworkcode ) {
2788 $frameworkcode = "";
2791 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
2792 $sth->execute( $frameworkcode, $biblionumber );
2794 my $encoding = C4
::Context
->preference("marcflavour");
2796 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2797 if ( $encoding eq "UNIMARC" ) {
2799 if ( length($record->subfield( 100, "a" )) == 35 ) {
2800 $string = $record->subfield( 100, "a" );
2801 my $f100 = $record->field(100);
2802 $record->delete_field($f100);
2805 $string = POSIX
::strftime
( "%Y%m%d", localtime );
2807 $string = sprintf( "%-*s", 35, $string );
2809 substr( $string, 22, 6, "frey50" );
2810 unless ( $record->subfield( 100, "a" ) ) {
2811 $record->insert_grouped_field(
2812 MARC
::Field
->new( 100, "", "", "a" => $string ) );
2815 ModZebra
($biblionumber,"specialUpdate","biblioserver",$record);
2818 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
2819 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
2822 return $biblionumber;
2825 =head2 z3950_extended_services
2827 z3950_extended_services($serviceType,$serviceOptions,$record);
2829 z3950_extended_services is used to handle all interactions with Zebra's extended serices package, which is employed to perform all management of the MARC data stored in Zebra.
2831 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
2833 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
2835 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
2839 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
2840 syntax => the record syntax (transfer syntax)
2841 databaseName = Database from connection object
2843 To set serviceOptions, call set_service_options($serviceType)
2845 C<$record> the record, if one is needed for the service type
2847 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
2851 sub z3950_extended_services
{
2852 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
2854 # get our connection object
2855 my $Zconn = C4
::Context
->Zconn( $server, 0, 1 );
2857 # create a new package object
2858 my $Zpackage = $Zconn->package();
2861 $Zpackage->option( action
=> $action );
2863 if ( $serviceOptions->{'databaseName'} ) {
2864 $Zpackage->option( databaseName
=> $serviceOptions->{'databaseName'} );
2866 if ( $serviceOptions->{'recordIdNumber'} ) {
2868 recordIdNumber
=> $serviceOptions->{'recordIdNumber'} );
2870 if ( $serviceOptions->{'recordIdOpaque'} ) {
2872 recordIdOpaque
=> $serviceOptions->{'recordIdOpaque'} );
2875 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
2876 #if ($serviceType eq 'itemorder') {
2877 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
2878 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
2879 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
2880 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
2883 if ( $serviceOptions->{record
} ) {
2884 $Zpackage->option( record
=> $serviceOptions->{record
} );
2886 # can be xml or marc
2887 if ( $serviceOptions->{'syntax'} ) {
2888 $Zpackage->option( syntax
=> $serviceOptions->{'syntax'} );
2892 # send the request, handle any exception encountered
2893 eval { $Zpackage->send($serviceType) };
2894 if ( $@
&& $@
->isa("ZOOM::Exception") ) {
2895 return "error: " . $@
->code() . " " . $@
->message() . "\n";
2898 # free up package resources
2899 $Zpackage->destroy();
2902 =head2 set_service_options
2904 my $serviceOptions = set_service_options($serviceType);
2906 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
2908 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
2912 sub set_service_options
{
2913 my ($serviceType) = @_;
2916 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
2917 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
2919 if ( $serviceType eq 'commit' ) {
2923 if ( $serviceType eq 'create' ) {
2927 if ( $serviceType eq 'drop' ) {
2928 die "ERROR: 'drop' not currently supported (by Zebra)";
2930 return $serviceOptions;
2939 Koha Developement team <info@koha.org>
2941 Paul POULAIN paul.poulain@free.fr
2943 Joshua Ferraro jmf@liblime.com